text
stringlengths 2
1.04M
| meta
dict |
---|---|
<?php
return [
'stripeSecretKey' => getenv('SWIPE_STRIPE_SECRET_KEY'),
'stripePublicKey' => getenv('SWIPE_STRIPE_PUBLIC_KEY'),
'usernameBlacklist' => include 'swipe-username-disallow.php',
];
| {
"content_hash": "3263529d13bca7eb15db5516d5dde9be",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 65,
"avg_line_length": 29.857142857142858,
"alnum_prop": 0.6650717703349283,
"repo_name": "craftx/craftx.io",
"id": "6df0643058f9b3ced8b45140400eaa55688b3fac",
"size": "209",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "config/swipe.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "330"
},
{
"name": "CSS",
"bytes": "15192"
},
{
"name": "HTML",
"bytes": "109234"
},
{
"name": "JavaScript",
"bytes": "16050"
},
{
"name": "PHP",
"bytes": "41007"
},
{
"name": "Vue",
"bytes": "6171"
}
],
"symlink_target": ""
} |
package RQ2.Table6;
import java.io.*;
import java.util.*;
/*
* RQ2-2
* Goal: extract buggy snippets for FilterdPatches with repeated fixes
*
*/
public class BuggySnippetCollector {
String filteredNewPatchFolderPath = null, buggySnippetFolderPath = null;
int diffCount = 0, fixCount = 0, contextLineNum = 20;
String hunkSuffix = null;
String pathSep = File.separator;
String lineBreak = System.getProperty("line.separator");
public BuggySnippetCollector(String filteredNewPatchFolderPath, String buggySnippetFolderPath) {
this.filteredNewPatchFolderPath = filteredNewPatchFolderPath;
this.buggySnippetFolderPath = buggySnippetFolderPath;
File buggySnippetDir = new File(buggySnippetFolderPath);
if (!buggySnippetDir.exists() && !buggySnippetDir.isDirectory()) {
buggySnippetDir.mkdir();
}
File filteredNewPatchFileDir = new File(filteredNewPatchFolderPath);
for (File file : filteredNewPatchFileDir.listFiles()) {
if (file.getName().equals(".DS_Store"))
continue;
patchToBuggySnippets(file.getAbsolutePath());
}
}
public void patchToBuggySnippets(String filteredNewPatchfilePath) {
try {
File file = new File(filteredNewPatchfilePath);
Scanner input = new Scanner(file);
diffCount = 0;// diff count in current patch
fixCount = 0;// continuous change(fix) count in current patch
Vector<String> hunkContent = new Vector<String>();
boolean isBelowDiffAndAboveAt = false;
String sourceFileSuffix = null;
while (input.hasNext()) {
String text = input.nextLine();
// System.out.println(text);
if (text.startsWith("diff")) {
if (!hunkContent.isEmpty()) {// last @@ of previous diff
processSingleHunk(hunkContent, filteredNewPatchfilePath);
hunkContent.clear();
}
hunkSuffix = text.substring(text.lastIndexOf("."));
diffCount++;
fixCount = 0;
isBelowDiffAndAboveAt = true;
} else if (text.startsWith("@@")) {
if (!hunkContent.isEmpty()) {// previous @@
processSingleHunk(hunkContent, filteredNewPatchfilePath);
hunkContent.clear();
}
isBelowDiffAndAboveAt = false;
} else if (!isBelowDiffAndAboveAt) {
hunkContent.add(text);
}
}
input.close();
if (!hunkContent.isEmpty()) {
processSingleHunk(hunkContent, filteredNewPatchfilePath);
hunkContent.clear();
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private void processSingleHunk(Vector<String> hunkContent, String patchfilePath) {
int firstIndex = 0, lastIndex = 0;
int k = 0;
for (int i = 0; i < hunkContent.size(); i = lastIndex + 1) {
boolean isFirstEditedLineExist = false;
for (k = i; k < hunkContent.size(); k++) {
if (hunkContent.get(k).startsWith("+") || hunkContent.get(k).startsWith("-")) {
if (!isFirstEditedLineExist) {
firstIndex = k;
isFirstEditedLineExist = true;
}
} else {
if (isFirstEditedLineExist) {
lastIndex = k - 1;
break;
}
} // end of else
}
if (!isFirstEditedLineExist || k == hunkContent.size()) {
break;
}
fixCount++;
int countUp = 0;
String buggySnippetStr = "";
for (int j = firstIndex - 1; j >= 0 && countUp < contextLineNum; j--) {
if (!hunkContent.get(j).startsWith("+")) {
if (buggySnippetStr.equals("")) {
buggySnippetStr = hunkContent.get(j);
} else {
buggySnippetStr = hunkContent.get(j) + lineBreak + buggySnippetStr;
}
countUp++;
}
}
int addLineCount = 0;
int deleteLineCount = 0;
for (int j = firstIndex; j <= lastIndex; j++) {
if (hunkContent.get(j).startsWith("-")) {
if (buggySnippetStr.equals("")) {
buggySnippetStr = hunkContent.get(j);
} else {
buggySnippetStr = buggySnippetStr + lineBreak + hunkContent.get(j);
}
deleteLineCount++;
} else {
addLineCount++;
}
}
int countDown = 0;
for (int j = lastIndex + 1; countDown < contextLineNum && j < hunkContent.size(); j++) {
if (!hunkContent.get(j).startsWith("+")) {
if (buggySnippetStr.equals("")) {
buggySnippetStr = hunkContent.get(j);
} else {
buggySnippetStr = buggySnippetStr + lineBreak + hunkContent.get(j);
}
countDown++;
}
}
String buggySnippetFilePath = buggySnippetFolderPath
+ patchfilePath.substring(patchfilePath.lastIndexOf(pathSep) + 1, patchfilePath.lastIndexOf("."))
+ "_" + diffCount + "_" + fixCount + "-" + countUp + "-" + countDown + "-" + addLineCount + "-"
+ deleteLineCount + hunkSuffix;
File outputFile = new File(buggySnippetFilePath);
try {
if (!outputFile.exists()) {
outputFile.createNewFile();
}
FileWriter output = new FileWriter(outputFile);
output.write(buggySnippetStr);
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| {
"content_hash": "4d06386837ec05451a0948927c799518",
"timestamp": "",
"source": "github",
"line_count": 159,
"max_line_length": 102,
"avg_line_length": 30.50314465408805,
"alnum_prop": 0.6550515463917526,
"repo_name": "Yuerr14/RepeatedFixes",
"id": "758c47ef2548636556efecf79b23c63c96d3bcf2",
"size": "4850",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "RepeatedFixes/src/RQ2/Table6/BuggySnippetCollector.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "842"
},
{
"name": "Batchfile",
"bytes": "99"
},
{
"name": "C",
"bytes": "11113"
},
{
"name": "C++",
"bytes": "574724"
},
{
"name": "HTML",
"bytes": "1384"
},
{
"name": "Java",
"bytes": "5534781"
},
{
"name": "Makefile",
"bytes": "1351"
},
{
"name": "Perl",
"bytes": "6982"
}
],
"symlink_target": ""
} |
#ifndef STEXCEPTION_HPP
#define STEXCEPTION_HPP
#include <QString>
namespace Starstructor {
class Exception
{
public:
explicit Exception(const QString& message, const QString& exType = "General exception")
: m_message(message),
m_exType(exType)
{
}
virtual ~Exception()
{
}
QString what() const
{
return m_exType + ": " + m_message;
}
QString message() const
{
return m_message;
}
private:
QString m_message;
QString m_exType;
};
class FileNotFoundException : public Exception
{
public:
explicit FileNotFoundException(const QString& message)
: Exception(message, "File not found exception")
{
}
virtual ~FileNotFoundException()
{
}
};
class JsonInvalidFormatException : public Exception
{
public:
explicit JsonInvalidFormatException(const QString& message)
: Exception(message, "JSON invalid format exception")
{
}
virtual ~JsonInvalidFormatException()
{
}
};
class AssetLoadException : public Exception
{
public:
explicit AssetLoadException(const QString& message)
: Exception(message, "Asset load exception")
{
}
virtual ~AssetLoadException()
{
}
};
}
#endif // STEXCEPTION_HPP | {
"content_hash": "fff02e2e37b492ebc6dfbf86a68f4d20",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 92,
"avg_line_length": 16.341772151898734,
"alnum_prop": 0.6367157242447715,
"repo_name": "Starstructor/starstructor-cpp",
"id": "24918df22ac3f64f0020e6c391ecfd0c40ab2649",
"size": "1498",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/stexception.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "39023"
},
{
"name": "IDL",
"bytes": "1740"
}
],
"symlink_target": ""
} |
package org.apache.flink.table.api.stream.table.validation
import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment
import org.apache.flink.table.api._
import org.apache.flink.table.api.bridge.scala._
import org.apache.flink.table.api.internal.TableEnvironmentInternal
import org.apache.flink.table.runtime.stream.table.{TestAppendSink, TestUpsertSink}
import org.apache.flink.table.runtime.utils.StreamTestData
import org.apache.flink.table.utils.TableTestBase
import org.junit.Test
class TableSinkValidationTest extends TableTestBase {
@Test(expected = classOf[TableException])
def testAppendSinkOnUpdatingTable(): Unit = {
val env = StreamExecutionEnvironment.getExecutionEnvironment
val tEnv = StreamTableEnvironment.create(env)
val t = StreamTestData.get3TupleDataStream(env).toTable(tEnv, 'id, 'num, 'text)
tEnv.asInstanceOf[TableEnvironmentInternal]
.registerTableSinkInternal("testSink", new TestAppendSink)
t.groupBy('text)
.select('text, 'id.count, 'num.sum)
.insertInto("testSink")
// must fail because table is not append-only
env.execute()
}
@Test(expected = classOf[TableException])
def testUpsertSinkOnUpdatingTableWithoutFullKey(): Unit = {
val env = StreamExecutionEnvironment.getExecutionEnvironment
val tEnv = StreamTableEnvironment.create(env)
val t = StreamTestData.get3TupleDataStream(env)
.assignAscendingTimestamps(_._1.toLong)
.toTable(tEnv, 'id, 'num, 'text)
tEnv.asInstanceOf[TableEnvironmentInternal].registerTableSinkInternal(
"testSink", new TestUpsertSink(Array("len", "cTrue"), false))
t.select('id, 'num, 'text.charLength() as 'len, ('id > 0) as 'cTrue)
.groupBy('len, 'cTrue)
.select('len, 'id.count, 'num.sum)
.insertInto("testSink")
// must fail because table is updating table without full key
env.execute()
}
@Test(expected = classOf[TableException])
def testAppendSinkOnLeftJoin(): Unit = {
val env = StreamExecutionEnvironment.getExecutionEnvironment
val tEnv = StreamTableEnvironment.create(env)
val ds1 = StreamTestData.get3TupleDataStream(env).toTable(tEnv, 'a, 'b, 'c)
val ds2 = StreamTestData.get5TupleDataStream(env).toTable(tEnv, 'd, 'e, 'f, 'g, 'h)
tEnv.asInstanceOf[TableEnvironmentInternal]
.registerTableSinkInternal("testSink", new TestAppendSink)
ds1.leftOuterJoin(ds2, 'a === 'd && 'b === 'h)
.select('c, 'g)
.insertInto("testSink")
// must fail because table is not append-only
env.execute()
}
}
| {
"content_hash": "aae646d337cb058571e1087f34a08aa7",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 87,
"avg_line_length": 35.91549295774648,
"alnum_prop": 0.7321568627450981,
"repo_name": "rmetzger/flink",
"id": "773376a5f4eb13a86c311b9a5fd765f4e6cb1e80",
"size": "3355",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/api/stream/table/validation/TableSinkValidationTest.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1863"
},
{
"name": "C",
"bytes": "847"
},
{
"name": "Clojure",
"bytes": "93543"
},
{
"name": "Dockerfile",
"bytes": "6926"
},
{
"name": "FreeMarker",
"bytes": "82636"
},
{
"name": "GAP",
"bytes": "139514"
},
{
"name": "HTML",
"bytes": "135607"
},
{
"name": "HiveQL",
"bytes": "71445"
},
{
"name": "Java",
"bytes": "83684824"
},
{
"name": "JavaScript",
"bytes": "1829"
},
{
"name": "Less",
"bytes": "65918"
},
{
"name": "Makefile",
"bytes": "5134"
},
{
"name": "Python",
"bytes": "2468561"
},
{
"name": "Scala",
"bytes": "15030324"
},
{
"name": "Shell",
"bytes": "540331"
},
{
"name": "TypeScript",
"bytes": "288463"
},
{
"name": "q",
"bytes": "7939"
}
],
"symlink_target": ""
} |
<!DOCTYPE html><html><head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="description">
<meta name="keywords" content="static content generator,static site generator,static site,HTML,web development,.NET,C#,Razor,Markdown,YAML">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="/FunctionalSharp/assets/img/favicon.ico" type="image/x-icon">
<link rel="icon" href="/FunctionalSharp/assets/img/favicon.ico" type="image/x-icon">
<title>FunctionalSharp - API - DiscriminatedUnionWithBaseList<Type1, Type2, Type3, Type4, Type5, Type6, Type7, BaseType>.Add(Type3) Method</title>
<link href="/FunctionalSharp/assets/css/mermaid.css" rel="stylesheet">
<link href="/FunctionalSharp/assets/css/highlight.css" rel="stylesheet">
<link href="/FunctionalSharp/assets/css/bootstrap/bootstrap.css" rel="stylesheet">
<link href="/FunctionalSharp/assets/css/adminlte/AdminLTE.css" rel="stylesheet">
<link href="/FunctionalSharp/assets/css/theme/theme.css" rel="stylesheet">
<link href="//fonts.googleapis.com/css?family=Roboto+Mono:400,700|Roboto:400,400i,700,700i" rel="stylesheet">
<link href="/FunctionalSharp/assets/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="/FunctionalSharp/assets/css/override.css" rel="stylesheet">
<script src="/FunctionalSharp/assets/js/jquery-2.2.3.min.js"></script>
<script src="/FunctionalSharp/assets/js/bootstrap.min.js"></script>
<script src="/FunctionalSharp/assets/js/app.min.js"></script>
<script src="/FunctionalSharp/assets/js/highlight.pack.js"></script>
<script src="/FunctionalSharp/assets/js/jquery.slimscroll.min.js"></script>
<script src="/FunctionalSharp/assets/js/jquery.sticky-kit.min.js"></script>
<script src="/FunctionalSharp/assets/js/mermaid.min.js"></script>
<!--[if lt IE 9]>
<script src="/FunctionalSharp/assets/js/html5shiv.min.js"></script>
<script src="/FunctionalSharp/assets/js/respond.min.js"></script>
<![endif]-->
</head>
<body class="hold-transition wyam layout-boxed ">
<div class="top-banner"></div>
<div class="wrapper with-container">
<!-- Header -->
<header class="main-header">
<a href="/FunctionalSharp/" class="logo">
<!-- mini logo for sidebar mini 50x50 pixels -->
<span class="logo-mini"><img src="/FunctionalSharp/assets/img/logo.png"></span>
<!-- logo for regular state and mobile devices -->
<span class="logo-lg"><img src="/FunctionalSharp/assets/img/logo.png"></span>
</a>
<nav class="navbar navbar-static-top" role="navigation">
<!-- Sidebar toggle button-->
<a href="#" class="sidebar-toggle visible-xs-block" data-toggle="offcanvas" role="button">
<span class="sr-only">Toggle side menu</span>
<i class="fa fa-chevron-circle-right"></i>
</a>
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse">
<span class="sr-only">Toggle side menu</span>
<i class="fa fa-chevron-circle-down"></i>
</button>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse pull-left" id="navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="/FunctionalSharp/docs">Docs</a></li>
<li class="active"><a href="/FunctionalSharp/api">API</a></li>
</ul>
</div>
<!-- /.navbar-collapse -->
<!-- Navbar Right Menu -->
</nav>
</header>
<!-- Left side column. contains the logo and sidebar -->
<aside class="main-sidebar ">
<section class="infobar" data-spy="affix" data-offset-top="60" data-offset-bottom="200">
<div id="infobar-headings"><h6>On This Page</h6><p><a href="#Summary">Summary</a></p>
<p><a href="#Syntax">Syntax</a></p>
<p><a href="#Parameters">Parameters</a></p>
<p><a href="#ReturnValue">Return Value</a></p>
<hr class="infobar-hidden">
</div>
</section>
<section class="sidebar">
<script src="/assets/js/lunr.min.js"></script>
<script src="/assets/js/searchIndex.js"></script>
<div class="sidebar-form">
<div class="input-group">
<input type="text" name="search" id="search" class="form-control" placeholder="Search Types...">
<span class="input-group-btn">
<button class="btn btn-flat"><i class="fa fa-search"></i></button>
</span>
</div>
</div>
<div id="search-results">
</div>
<script>
function runSearch(query){
$("#search-results").empty();
if( query.length < 2 ){
return;
}
var results = searchModule.search("*" + query + "*");
var listHtml = "<ul class='sidebar-menu'>";
listHtml += "<li class='header'>Type Results</li>";
if(results.length == 0 ){
listHtml += "<li>No results found</li>";
} else {
for(var i = 0; i < results.length; ++i){
var res = results[i];
listHtml += "<li><a href='" + res.url + "'>" + res.title + "</a></li>";
}
}
listHtml += "</ul>";
$("#search-results").append(listHtml);
}
$(document).ready(function(){
$("#search").on('input propertychange paste', function() {
runSearch($("#search").val());
});
});
</script>
<hr>
<ul class="sidebar-menu">
<li class="header">Namespace</li>
<li><a href="/FunctionalSharp/api/FunctionalSharp.DiscriminatedUnions">FunctionalSharp<wbr>.DiscriminatedUnions</a></li>
<li class="header">Type</li>
<li><a href="/FunctionalSharp/api/FunctionalSharp.DiscriminatedUnions/DiscriminatedUnionWithBaseList_8">Discriminated<wbr>Union<wbr>With<wbr>Base<wbr>List<wbr><Type1, <wbr>Type2, <wbr>Type3, <wbr>Type4, <wbr>Type5, <wbr>Type6, <wbr>Type7, <wbr>BaseType><wbr></a></li>
<li role="separator" class="divider"></li>
<li class="header">Method Members</li>
<li><a href="/FunctionalSharp/api/FunctionalSharp.DiscriminatedUnions/DiscriminatedUnionWithBaseList_8/C07F2492">Add<wbr>(Type1)<wbr></a></li>
<li><a href="/FunctionalSharp/api/FunctionalSharp.DiscriminatedUnions/DiscriminatedUnionWithBaseList_8/814E3F8B">Add<wbr>(Type2)<wbr></a></li>
<li class="selected"><a href="/FunctionalSharp/api/FunctionalSharp.DiscriminatedUnions/DiscriminatedUnionWithBaseList_8/421D12A0">Add<wbr>(Type3)<wbr></a></li>
<li><a href="/FunctionalSharp/api/FunctionalSharp.DiscriminatedUnions/DiscriminatedUnionWithBaseList_8/032C09B9">Add<wbr>(Type4)<wbr></a></li>
<li><a href="/FunctionalSharp/api/FunctionalSharp.DiscriminatedUnions/DiscriminatedUnionWithBaseList_8/C4BA48F6">Add<wbr>(Type5)<wbr></a></li>
<li><a href="/FunctionalSharp/api/FunctionalSharp.DiscriminatedUnions/DiscriminatedUnionWithBaseList_8/858B53EF">Add<wbr>(Type6)<wbr></a></li>
<li><a href="/FunctionalSharp/api/FunctionalSharp.DiscriminatedUnions/DiscriminatedUnionWithBaseList_8/46D87EC4">Add<wbr>(Type7)<wbr></a></li>
<li><a href="/FunctionalSharp/api/FunctionalSharp.DiscriminatedUnions/DiscriminatedUnionWithBaseList_8/A8834542">AddRange<wbr>(IEnumerable<wbr><Type1><wbr>)<wbr></a></li>
<li><a href="/FunctionalSharp/api/FunctionalSharp.DiscriminatedUnions/DiscriminatedUnionWithBaseList_8/9FE98743">AddRange<wbr>(IEnumerable<wbr><Type2><wbr>)<wbr></a></li>
<li><a href="/FunctionalSharp/api/FunctionalSharp.DiscriminatedUnions/DiscriminatedUnionWithBaseList_8/C657C141">AddRange<wbr>(IEnumerable<wbr><Type3><wbr>)<wbr></a></li>
<li><a href="/FunctionalSharp/api/FunctionalSharp.DiscriminatedUnions/DiscriminatedUnionWithBaseList_8/F13D0340">AddRange<wbr>(IEnumerable<wbr><Type4><wbr>)<wbr></a></li>
<li><a href="/FunctionalSharp/api/FunctionalSharp.DiscriminatedUnions/DiscriminatedUnionWithBaseList_8/742B4C45">AddRange<wbr>(IEnumerable<wbr><Type5><wbr>)<wbr></a></li>
<li><a href="/FunctionalSharp/api/FunctionalSharp.DiscriminatedUnions/DiscriminatedUnionWithBaseList_8/43418E44">AddRange<wbr>(IEnumerable<wbr><Type6><wbr>)<wbr></a></li>
<li><a href="/FunctionalSharp/api/FunctionalSharp.DiscriminatedUnions/DiscriminatedUnionWithBaseList_8/1AFFC846">AddRange<wbr>(IEnumerable<wbr><Type7><wbr>)<wbr></a></li>
<li><a href="/FunctionalSharp/api/FunctionalSharp.DiscriminatedUnions/DiscriminatedUnionWithBaseList_8/EE6D35D0">Merge<wbr><TypeToMerge><wbr><wbr>(IEnumerable<wbr><TypeToMerge><wbr>)<wbr></a></li>
</ul>
</section>
</aside>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<section class="content-header">
<h3><a href="/FunctionalSharp/api/FunctionalSharp.DiscriminatedUnions/DiscriminatedUnionWithBaseList_8">Discriminated<wbr>Union<wbr>With<wbr>Base<wbr>List<wbr><Type1, <wbr>Type2, <wbr>Type3, <wbr>Type4, <wbr>Type5, <wbr>Type6, <wbr>Type7, <wbr>BaseType><wbr></a>.</h3>
<h1>Add<wbr>(Type3)<wbr> <small>Method</small></h1>
</section>
<section class="content">
<h1 id="Summary">Summary</h1>
<div class="lead">
Adds the object to the end of the DiscriminatedUnionList
</div>
<div class="panel panel-default">
<div class="panel-body">
<dl class="dl-horizontal">
<dt>Namespace</dt>
<dd><a href="/FunctionalSharp/api/FunctionalSharp.DiscriminatedUnions">FunctionalSharp<wbr>.DiscriminatedUnions</a></dd>
<dt>Containing Type</dt>
<dd><a href="/FunctionalSharp/api/FunctionalSharp.DiscriminatedUnions/DiscriminatedUnionWithBaseList_8">Discriminated<wbr>Union<wbr>With<wbr>Base<wbr>List<wbr><Type1, <wbr>Type2, <wbr>Type3, <wbr>Type4, <wbr>Type5, <wbr>Type6, <wbr>Type7, <wbr>BaseType><wbr></a></dd>
</dl>
</div>
</div>
<h1 id="Syntax">Syntax</h1>
<pre><code>public void Add(Type3 item)</code></pre>
<h1 id="Parameters">Parameters</h1>
<div class="box">
<div class="box-body no-padding table-responsive">
<table class="table table-striped table-hover three-cols">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody><tr>
<td>item</td>
<td><a href="/FunctionalSharp/api/FunctionalSharp.DiscriminatedUnions/DiscriminatedUnionWithBaseList_8#typeparam-Type3">Type3</a></td>
<td></td>
</tr>
</tbody></table>
</div>
</div>
<h1 id="ReturnValue">Return Value</h1>
<div class="box">
<div class="box-body no-padding table-responsive">
<table class="table table-striped table-hover two-cols">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody><tr>
<td>void</td>
<td></td>
</tr>
</tbody></table>
</div>
</div>
</section>
</div>
<!-- Footer -->
<footer class="main-footer">
</footer>
</div>
<div class="wrapper bottom-wrapper">
<footer class="bottom-footer">
Generated by <a href="https://wyam.io">Wyam</a>
</footer>
</div>
<a href="javascript:" id="return-to-top"><i class="fa fa-chevron-up"></i></a>
<script>
// Close the sidebar if we select an anchor link
$(".main-sidebar a[href^='#']:not('.expand')").click(function(){
$(document.body).removeClass('sidebar-open');
});
$(document).load(function() {
mermaid.initialize(
{
flowchart:
{
htmlLabels: false,
useMaxWidth:false
}
});
mermaid.init(undefined, ".mermaid")
$('svg').addClass('img-responsive');
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
});
hljs.initHighlightingOnLoad();
// Back to top
$(window).scroll(function() {
if ($(this).scrollTop() >= 200) { // If page is scrolled more than 50px
$('#return-to-top').fadeIn(1000); // Fade in the arrow
} else {
$('#return-to-top').fadeOut(1000); // Else fade out the arrow
}
});
$('#return-to-top').click(function() { // When arrow is clicked
$('body,html').animate({
scrollTop : 0 // Scroll to top of body
}, 500);
});
</script>
</body></html> | {
"content_hash": "ce8eb3c976f8cd82bb5f4f74daabf00d",
"timestamp": "",
"source": "github",
"line_count": 293,
"max_line_length": 281,
"avg_line_length": 48.153583617747444,
"alnum_prop": 0.5668722092281523,
"repo_name": "Patrickkk/FunctionalSharp",
"id": "a41f818f65880ad07e1a41b719b5b76adcfd36e0",
"size": "14109",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/api/FunctionalSharp.DiscriminatedUnions/DiscriminatedUnionWithBaseList_8/421D12A0.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "91"
},
{
"name": "C#",
"bytes": "538428"
}
],
"symlink_target": ""
} |
const path = require('path');
const cpx = require('cpx2');
const { spawnSync } = require('child_process');
const fs = require('fs');
const rimraf = require('rimraf');
const fixture = path.join(__dirname, 'fixture');
const bin = path.resolve(__dirname, 'index.js');
function getTmpDirectory(prefix) {
const date = new Date();
const tmp = path.join(
__dirname,
`tmp-${prefix}-${date.toLocaleDateString().replace(/\//g, '-')}`,
);
cpx.copySync(path.join(fixture, '**'), tmp);
return tmp;
}
describe('talend-scripts', () => {
afterAll(() => {
rimraf.sync(path.join(__dirname, 'tmp*'));
});
describe('build:lib:umd', () => {
it('should by default create a dist folder', () => {
const tmp = getTmpDirectory('build-lib-umd');
const output = spawnSync('node', [bin, 'build:lib:umd'], { cwd: tmp });
const logs = output.stdout.toString();
expect(output.error).toBeUndefined();
expect(logs).toContain('CONFIGURATION -----');
expect(logs).toContain('Running command: build:lib:umd With options: ');
expect(logs).toContain('Talend scripts mode : production');
expect(logs).toContain('Talend scripts configuration file found and loaded');
expect(logs).toContain('RUN ------------');
expect(output.stderr.toString()).toBe('');
fs.existsSync(path.join(tmp, 'dist', 'TalendTestScriptsCore.min.js'));
fs.existsSync(path.join(tmp, 'dist', 'TalendTestScriptsCore.min.js.dependencies.json'));
fs.existsSync(path.join(tmp, 'dist', 'TalendTestScriptsCore.min.js.map'));
});
});
describe('build:lib', () => {
it('should by default put build output in lib folder', () => {
const tmp = getTmpDirectory('build-lib');
const output = spawnSync('node', [bin, 'build:lib'], { cwd: tmp });
const logs = output.stdout.toString();
expect(output.error).toBeUndefined();
expect(logs).toContain('CONFIGURATION -----');
expect(logs).toContain('Running command: build:lib With options: ');
expect(logs).toContain('Talend scripts mode : production');
expect(logs).toContain('Talend scripts configuration file found and loaded');
expect(logs).toContain('RUN ------------');
expect(output.stderr.toString()).toBe('');
fs.existsSync(path.join(tmp, 'lib', 'index.js'));
fs.existsSync(path.join(tmp, 'lib', 'index.js.map'));
});
});
});
| {
"content_hash": "cdbd0105a72de9dcac0a31ba02319138",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 91,
"avg_line_length": 40.280701754385966,
"alnum_prop": 0.6533101045296167,
"repo_name": "Talend/ui",
"id": "e1457e8f2e282cedf4d3ca0e219ef04af6be80a1",
"size": "2296",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tools/scripts-core/index.test.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "809"
},
{
"name": "Groovy",
"bytes": "9150"
},
{
"name": "HTML",
"bytes": "183895"
},
{
"name": "Java",
"bytes": "338"
},
{
"name": "JavaScript",
"bytes": "4781212"
},
{
"name": "SCSS",
"bytes": "699775"
},
{
"name": "Shell",
"bytes": "62"
},
{
"name": "TypeScript",
"bytes": "1291286"
}
],
"symlink_target": ""
} |
import os
import json
import requests
from requests.auth import HTTPDigestAuth
from collections import OrderedDict
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
def get_solr_json(solr_url,
query,
api_key=None,
digest_user=None,
digest_pswd=None):
'''get the solr json response for the given URL.
Use the requests library. The production API uses headers for auth,
while the ingest environment uses http digest auth
Returns an python object created from the json response.
Query is a dictionary of parameters
'''
solr_auth = { 'X-Authentication-Token': api_key } if api_key else None
digest_auth = HTTPDigestAuth(
digest_user, digest_pswd) if digest_user else None
return json.loads(requests.get(solr_url,
headers=solr_auth,
auth=digest_auth,
params=query,
verify=False).text)
def create_facet_dict(json_results, facet_field):
'''Create a dictionary consisting of keys = facet_field_values, values =
facet_field coutns
Takes a json result that must have the given facet field in it & the
'''
results = json_results.get('facet_counts').get('facet_fields').get(facet_field)
#zip into array with elements of ('collection_data_value', count)
facet_list = zip(*[iter(results)]*2)
d = OrderedDict()
for val, count in facet_list:
if count > 0: #reject ones that have 0 records?
d[val] = count
return d
# Copyright © 2016, Regents of the University of California
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# - Neither the name of the University of California nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
| {
"content_hash": "15ecdf83f1e61e059fc571c701785e53",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 83,
"avg_line_length": 48.343283582089555,
"alnum_prop": 0.715961716579191,
"repo_name": "mredar/ucldc_api_data_quality",
"id": "37975406d6be9d06e98f62b42559b45eb0fe8120",
"size": "3264",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "reporting/get_solr_json.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Gherkin",
"bytes": "1161"
},
{
"name": "HTML",
"bytes": "115349"
},
{
"name": "Jupyter Notebook",
"bytes": "28608"
},
{
"name": "Python",
"bytes": "70303"
},
{
"name": "Ruby",
"bytes": "794"
},
{
"name": "Shell",
"bytes": "273"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Create an empty dictionary using the memory functions associated with a context.</title>
</head>
<body><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="function.php-getdns-convert-ulabel-to-alabel.html">php_getdns_convert_ulabel_to_alabel</a></div>
<div class="next" style="text-align: right; float: right;"><a href="function.php-getdns-dict-create.html">php_getdns_dict_create</a></div>
<div class="up"><a href="ref.getdns.html">getdns Functions</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div><hr /><div id="function.php-getdns-dict-create-with-context" class="refentry">
<div class="refnamediv">
<h1 class="refname">php_getdns_dict_create_with_context</h1>
<p class="verinfo">(PECL getdns >= 0.11.0)</p><p class="refpurpose"><span class="refname">php_getdns_dict_create_with_context</span> — <span class="dc-title">Create an empty dictionary using the memory functions associated with a context.</span></p>
</div>
<div class="refsect1 description" id="refsect1-function.php-getdns-dict-create-with-context-description">
<h3 class="title">Description</h3>
<div class="methodsynopsis dc-description">
<span class="type">int</span> <span class="methodname"><strong>php_getdns_dict_create_with_context</strong></span>
( <span class="methodparam"><span class="type">int</span> <code class="parameter">$context</code></span>
)</div>
<p class="para rdfs-comment">
This function creates an empty dictionary using the memory functions associated
with an existing context. As currently implemented for PHP, this function uses
the default memory functions provided by the getdns library.
</p>
</div>
<div class="refsect1 parameters" id="refsect1-function.php-getdns-dict-create-with-context-parameters">
<h3 class="title">Parameters</h3>
<dl>
<dt>
<code class="parameter">context</code></dt>
<dd>
<p class="para">
The previously created DNS context that is to be used with this request.
</p>
</dd>
</dl>
</div>
<div class="refsect1 returnvalues" id="refsect1-function.php-getdns-dict-create-with-context-returnvalues">
<h3 class="title">Return Values</h3>
<p class="para">
This function returns an integer representation of an empty dictionary. The
dictionary must eventually be freed using php_getdns_dict_destroy(). The
return value will be 0 (zero) if an error occurred.
</p>
</div>
</div><hr /><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="function.php-getdns-convert-ulabel-to-alabel.html">php_getdns_convert_ulabel_to_alabel</a></div>
<div class="next" style="text-align: right; float: right;"><a href="function.php-getdns-dict-create.html">php_getdns_dict_create</a></div>
<div class="up"><a href="ref.getdns.html">getdns Functions</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div></body></html>
| {
"content_hash": "d6d2bf6fe7c7464661f458d315f9b964",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 260,
"avg_line_length": 44.791666666666664,
"alnum_prop": 0.703875968992248,
"repo_name": "getdnsapi/getdns-php-bindings",
"id": "734be66a8652f8f92a13b17d7956a9ebc8f3242a",
"size": "3225",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc-out/php-chunked-xhtml/function.php-getdns-dict-create-with-context.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "177492"
},
{
"name": "HTML",
"bytes": "594001"
},
{
"name": "PHP",
"bytes": "95626"
}
],
"symlink_target": ""
} |
#ifndef __OPENCV_CONDENS_HPP__
#define __OPENCV_CONDENS_HPP__
#ifdef __cplusplus
extern "C" {
#endif
/************************************************************************/
/************************ Copy from compat.cpp **************************/
/************************************************************************/
typedef struct CvRandState
{
CvRNG state; /* RNG state (the current seed and carry)*/
int disttype; /* distribution type */
CvScalar param[2]; /* parameters of RNG */
} CvRandState;
/* Changes RNG range while preserving RNG state */
CV_EXPORTS void cvRandSetRange( CvRandState* state, double param1,
double param2, int index CV_DEFAULT(-1));
CV_EXPORTS void cvRandInit( CvRandState* state, double param1,
double param2, int seed,
int disttype CV_DEFAULT(CV_RAND_UNI));
/* Fills array with random numbers */
CV_EXPORTS void cvRand( CvRandState* state, CvArr* arr );
#define cvRandNext( _state ) cvRandInt( &(_state)->state )
CV_EXPORTS void cvbRand( CvRandState* state, float* dst, int len );
/************************************************************************/
typedef struct CvConDensation
{
int MP;
int DP;
float* DynamMatr; /* Matrix of the linear Dynamics system */
float* State; /* Vector of State */
int SamplesNum; /* Number of the Samples */
float** flSamples; /* arr of the Sample Vectors */
float** flNewSamples; /* temporary array of the Sample Vectors */
float* flConfidence; /* Confidence for each Sample */
float* flCumulative; /* Cumulative confidence */
float* Temp; /* Temporary vector */
float* RandomSample; /* RandomVector to update sample set */
struct CvRandState* RandS; /* Array of structures to generate random vectors */
} CvConDensation;
/* Creates ConDensation filter state */
CVAPI(CvConDensation*) cvCreateConDensation( int dynam_params,
int measure_params,
int sample_count );
/* Releases ConDensation filter state */
CVAPI(void) cvReleaseConDensation( CvConDensation** condens );
/* Updates ConDensation filter by time (predict future state of the system) */
CVAPI(void) cvConDensUpdateByTime( CvConDensation* condens);
/* Initializes ConDensation filter samples */
CVAPI(void) cvConDensInitSampleSet( CvConDensation* condens, CvMat* lower_bound, CvMat* upper_bound );
CV_INLINE int iplWidth( const IplImage* img )
{
return !img ? 0 : !img->roi ? img->width : img->roi->width;
}
CV_INLINE int iplHeight( const IplImage* img )
{
return !img ? 0 : !img->roi ? img->height : img->roi->height;
}
#ifdef __cplusplus
}
#endif
#endif
/* End of file. */
| {
"content_hash": "1e1ead06360cae763ae677fec1984625",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 103,
"avg_line_length": 35.17857142857143,
"alnum_prop": 0.5560067681895093,
"repo_name": "irvs/ros_tms",
"id": "45b08e45d14d16c3c790df4d0cccf49c0d576408",
"size": "5040",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "tms_ss/tms_ss_pot/include/condens/condens.hpp",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "75"
},
{
"name": "C",
"bytes": "1105412"
},
{
"name": "C#",
"bytes": "8112"
},
{
"name": "C++",
"bytes": "5839153"
},
{
"name": "CMake",
"bytes": "94659"
},
{
"name": "CSS",
"bytes": "30956"
},
{
"name": "HTML",
"bytes": "982020"
},
{
"name": "Inno Setup",
"bytes": "3254"
},
{
"name": "Java",
"bytes": "419664"
},
{
"name": "JavaScript",
"bytes": "68803"
},
{
"name": "M4",
"bytes": "1180"
},
{
"name": "MATLAB",
"bytes": "6958"
},
{
"name": "Makefile",
"bytes": "102553"
},
{
"name": "Max",
"bytes": "49936"
},
{
"name": "Objective-C",
"bytes": "80085"
},
{
"name": "Python",
"bytes": "591691"
},
{
"name": "SWIG",
"bytes": "1336"
},
{
"name": "Shell",
"bytes": "2654"
},
{
"name": "TSQL",
"bytes": "15032971"
},
{
"name": "TeX",
"bytes": "5590"
}
],
"symlink_target": ""
} |
<?php
namespace Dellaert\DCIMBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints as DoctrineAssert;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* @ORM\Entity
* @ORM\Table(name="dcim_issues")
*/
class Issue
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*
* @var integer
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="User")
*
* @var \DateTime
*/
protected $createdBy;
/**
* @ORM\Column(type="datetime", nullable=true)
*
* @var \DateTime
*/
protected $createdAt;
/**
* @ORM\Column(type="datetime", nullable=true)
*
* @var \DateTime
*/
protected $updatedAt;
/**
* @ORM\Column(type="boolean")
*
* @var boolean
*/
protected $enabled;
/**
* @ORM\ManyToOne(targetEntity="Project",inversedBy="issues")
*/
protected $project;
/**
* @ORM\OneToMany(targetEntity="WorkEntry", mappedBy="issue")
*/
protected $workentries;
/**
* @ORM\Column(type="string", length=255)
* @Assert\NotBlank()
*/
protected $title;
/**
* @ORM\Column(type="text", nullable=true)
*/
protected $description;
/**
* @ORM\Column(type="float", nullable=true)
*/
protected $rate;
/**
* @ORM\Column(type="boolean")
*
* @var boolean
*/
protected $statsShowListOnly;
public function __construct() {
$this->workentries = new ArrayCollection();
}
public function preInsert()
{
$this->createdAt = new \DateTime();
$this->preUpdate();
}
public function preUpdate()
{
$this->updatedAt = new \DateTime();
}
/**
* Get total of amount worked
*
* @return float
*/
public function getTotalWorkEntryAmount()
{
$total = 0;
$workentries = $this->getWorkEntries();
foreach( $workentries as $entry ) {
$total += $entry->getAmount();
}
return number_format($total,2,'.','');
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set createdAt
*
* @param \DateTime $createdAt
* @return Issue
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* @param \DateTime $updatedAt
* @return Issue
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* @return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Set enabled
*
* @param boolean $enabled
* @return Issue
*/
public function setEnabled($enabled)
{
$this->enabled = $enabled;
return $this;
}
/**
* Get enabled
*
* @return boolean
*/
public function getEnabled()
{
return $this->enabled;
}
/**
* Set title
*
* @param string $title
* @return Issue
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description
*
* @param string $description
* @return Issue
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set rate
*
* @param float $rate
* @return Issue
*/
public function setRate($rate)
{
$this->rate = $rate;
return $this;
}
/**
* Get rate
*
* @return float
*/
public function getRate()
{
return $this->rate;
}
/**
* Set statsShowListOnly
*
* @param boolean $statsShowListOnly
* @return Issue
*/
public function setStatsShowListOnly($statsShowListOnly)
{
$this->statsShowListOnly = $statsShowListOnly;
return $this;
}
/**
* Get statsShowListOnly
*
* @return boolean
*/
public function getStatsShowListOnly()
{
return $this->statsShowListOnly;
}
/**
* Set createdBy
*
* @param \Dellaert\DCIMBundle\Entity\User $createdBy
* @return Issue
*/
public function setCreatedBy(\Dellaert\DCIMBundle\Entity\User $createdBy = null)
{
$this->createdBy = $createdBy;
return $this;
}
/**
* Get createdBy
*
* @return \Dellaert\DCIMBundle\Entity\User
*/
public function getCreatedBy()
{
return $this->createdBy;
}
/**
* Set project
*
* @param \Dellaert\DCIMBundle\Entity\Project $project
* @return Issue
*/
public function setProject(\Dellaert\DCIMBundle\Entity\Project $project = null)
{
$this->project = $project;
return $this;
}
/**
* Get project
*
* @return \Dellaert\DCIMBundle\Entity\Project
*/
public function getProject()
{
return $this->project;
}
/**
* Add workentries
*
* @param \Dellaert\DCIMBundle\Entity\WorkEntry $workentries
* @return Issue
*/
public function addWorkentrie(\Dellaert\DCIMBundle\Entity\WorkEntry $workentries)
{
$this->workentries[] = $workentries;
return $this;
}
/**
* Remove workentries
*
* @param \Dellaert\DCIMBundle\Entity\WorkEntry $workentries
*/
public function removeWorkentrie(\Dellaert\DCIMBundle\Entity\WorkEntry $workentries)
{
$this->workentries->removeElement($workentries);
}
/**
* Get workentries
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getWorkentries()
{
return $this->workentries;
}
/**
* Add workentries
*
* @param \Dellaert\DCIMBundle\Entity\WorkEntry $workentries
* @return Issue
*/
public function addWorkentry(\Dellaert\DCIMBundle\Entity\WorkEntry $workentries)
{
$this->workentries[] = $workentries;
return $this;
}
/**
* Remove workentries
*
* @param \Dellaert\DCIMBundle\Entity\WorkEntry $workentries
*/
public function removeWorkentry(\Dellaert\DCIMBundle\Entity\WorkEntry $workentries)
{
$this->workentries->removeElement($workentries);
}
}
| {
"content_hash": "1a2b7f7b5912319f7252890e4e702b33",
"timestamp": "",
"source": "github",
"line_count": 388,
"max_line_length": 87,
"avg_line_length": 15.876288659793815,
"alnum_prop": 0.6301948051948052,
"repo_name": "pdellaert/DCIMBundle",
"id": "5f68414b4b6117d8840b682cc6d91c616bd890b4",
"size": "6160",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Entity/Issue.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "19041"
},
{
"name": "JavaScript",
"bytes": "74764"
},
{
"name": "PHP",
"bytes": "252368"
}
],
"symlink_target": ""
} |
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
namespace Microsoft.DotNet.Cli.Build
{
public static class Utils
{
public static void CleanNuGetTempCache()
{
// Clean NuGet Temp Cache on Linux (seeing some issues on Linux)
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && Directory.Exists("/tmp/NuGet"))
{
Directory.Delete("/tmp/NuGet", recursive: true);
}
}
public static string GetOSName()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return "win";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return "osx";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
throw new NotImplementedException();
}
else
{
throw new PlatformNotSupportedException();
}
}
// Generate a Version 5 (SHA1 Name Based) Guid from a name.
public static Guid GenerateGuidFromName(string name)
{
// Any fixed GUID will do for a namespace.
Guid namespaceId = new Guid("28F1468D-672B-489A-8E0C-7C5B3030630C");
using (SHA1 hasher = SHA1.Create())
{
var nameBytes = System.Text.Encoding.UTF8.GetBytes(name ?? string.Empty);
var namespaceBytes = namespaceId.ToByteArray();
SwapGuidByteOrder(namespaceBytes);
var streamToHash = new byte[namespaceBytes.Length + nameBytes.Length];
Array.Copy(namespaceBytes, streamToHash, namespaceBytes.Length);
Array.Copy(nameBytes, 0, streamToHash, namespaceBytes.Length, nameBytes.Length);
var hashResult = hasher.ComputeHash(streamToHash);
var res = new byte[16];
Array.Copy(hashResult, res, res.Length);
unchecked { res[6] = (byte)(0x50 | (res[6] & 0x0F)); }
unchecked { res[8] = (byte)(0x40 | (res[8] & 0x3F)); }
SwapGuidByteOrder(res);
return new Guid(res);
}
}
// Do a byte order swap, .NET GUIDs store multi byte components in little
// endian.
private static void SwapGuidByteOrder(byte[] b)
{
Swap(b, 0, 3);
Swap(b, 1, 2);
Swap(b, 5, 6);
Swap(b, 7, 8);
}
private static void Swap(byte[] b, int x, int y)
{
byte t = b[x];
b[x] = b[y];
b[y] = t;
}
public static void DeleteDirectory(string path)
{
if (Directory.Exists(path))
{
string[] files = Directory.GetFiles(path, "*", SearchOption.AllDirectories);
foreach (string file in files)
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
var retry = 5;
while (retry >= 0)
{
try
{
Directory.Delete(path, true);
return;
}
catch (IOException ex)
{
if (retry == 0)
{
throw;
}
System.Threading.Thread.Sleep(200);
retry--;
}
}
}
}
public static void CopyDirectoryRecursively(string path, string destination, bool keepParentDir = false)
{
if (keepParentDir)
{
path = path.TrimEnd(Path.DirectorySeparatorChar);
destination = Path.Combine(destination, Path.GetFileName(path));
Directory.CreateDirectory(destination);
}
foreach (var file in Directory.GetFiles(path, "*", SearchOption.AllDirectories))
{
string destFile = file.Replace(path, destination);
Directory.CreateDirectory(Path.GetDirectoryName(destFile));
File.Copy(file, destFile, true);
}
}
}
}
| {
"content_hash": "73b74a2d1a7235afb29c36405d31af74",
"timestamp": "",
"source": "github",
"line_count": 137,
"max_line_length": 112,
"avg_line_length": 32.627737226277375,
"alnum_prop": 0.4894854586129754,
"repo_name": "danquirk/cli",
"id": "799bda56fd9b1261a4f873e064a12db2c692bb75",
"size": "4472",
"binary": false,
"copies": "3",
"ref": "refs/heads/rel/1.0.0",
"path": "scripts/dotnet-cli-build/Utils/Utils.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "7545"
},
{
"name": "C",
"bytes": "4424"
},
{
"name": "C#",
"bytes": "2108410"
},
{
"name": "C++",
"bytes": "566329"
},
{
"name": "CMake",
"bytes": "7669"
},
{
"name": "F#",
"bytes": "1999"
},
{
"name": "Groovy",
"bytes": "2309"
},
{
"name": "HTML",
"bytes": "51884"
},
{
"name": "PowerShell",
"bytes": "54928"
},
{
"name": "Shell",
"bytes": "85799"
}
],
"symlink_target": ""
} |
function redirect(url){
document.location = url;
}
$jQuery(document).ready(function($){
$jQuery('.call-age-status').popover({
placement: 'left'
});
$jQuery(document).on('change', 'input:file', function (){
if (this.files[0]){
var fileName = this.files[0].name;
var ext = fileName.substr(fileName.lastIndexOf('.')+1).toLowerCase();
var reset = false;
var fileSize = false;
var invalidFileType = false;
if (this.files[0].size > 3145728){
var fileSize = true;
var reset = true;
}
if (ext != 'doc' && ext != 'docx' && ext != 'gif' && ext != 'jpg' && ext != 'pdf' && ext != 'png' && ext != 'txt' && ext != 'xls' && ext != 'xlsx'){
var invalidFileType = true;
var reset = true;
}
if (fileSize && invalidFileType){
alert('The file size is too large, and there was an invalid file type.');
}
else if (fileSize){
alert('The file size is too large.');
}
else if(invalidFileType){
alert('An invalid file type was supplied.');
}
if (reset){
$jQuery('#attach_files').replaceWith('<input type="file" name="attachment" id="attach_files"/>');
}
}
});
$jQuery('.box .replace-toggle').on('click', function(e) {
e.preventDefault();
$jQuery(this).next().show();
$jQuery(this).remove();
});
$jQuery('#search_string').focus();
$jQuery('#its-group-help').colorbox({
width: 1000,
height: 800
});
$jQuery(document).delegate('.print-balance a', 'click',function(){
$jQuery('.print-funds .error').hide();
$jQuery('.print-funds .add-funds').slideDown('fast');
return false;
});
$jQuery(document).delegate('.add-funds button', 'click',function(){
$jQuery('.add-funds').hide();
$jQuery('.add-funds-throbber').show();
var amount = $jQuery('.add-funds select').val();
var pidm = $jQuery('#caller_pidm').val();
$jQuery.get( BASE_URL + '/print_balance.php?pidm=' + pidm + '&fund_increase=' + amount + '&action=update', function(data){
data = $jQuery.trim(data);
$jQuery('.add-funds-throbber').slideUp('fast');
if(data == 'no_record' || data == 'invalid_privs' || data == 'too_small') {
$jQuery('.add-funds-' + data).slideDown('fast');
}//end if
else {
var updated_value = '$' + amount + '.00';
$jQuery('.add-funds-success span').html(updated_value.replace(/\$\-/,'-$'));
$jQuery('.add-funds-success').slideDown('fast');
$jQuery('.print-balance .balance').html(data);
}//end esle
});
});
// make the Open Call tables clickable
$jQuery(document).delegate('#open_calls_main_div .call', 'click', function(){
var $link = $jQuery('.view', this).attr('href');
$jQuery(this).closest('table').find('.highlight').removeClass('highlight');
$jQuery(this).addClass('highlight');
document.location = $link;
});
////// BEGIN handle Ticket Checklists
function getValue( $el, depth ) {
var val = $el.val();
var append_text = '';
var temp_value = '';
if( $el.is('input[type=radio]:not(:checked)') ) {
return append_text;
}
if( $.trim(val) != '' ) {
var $label = $el.siblings('label');
var rel = $label.attr('rel');
var label_text = rel ? rel : $label.html();
append_text = append_text + label_text + " " + val;
var $extra = $el.siblings('.sub:visible').children('li select,li textarea,li input');
if( $extra.length > 0 ) {
temp_value = getValue( $($extra.get(0)), depth+1 );
if( $.trim( temp_value ) !== '' ) {
append_text = append_text + "\r";
for(var i = 0; i < depth; i++) {
append_text = append_text + "-";
}//end for
append_text = append_text + " " + temp_value;
}//end if
}//end if
}//end if
return append_text;
}//end get Value
$('#new_call,#edit_call').bind('submit', function(){
var append_text = '';
var $details = $('#problem_details');
var details = $details.val();
var temp_value = '';
$('#checklists ul:visible li > select,#checklists ul:visible li > input,#checklists ul:visible li > textarea').each(function(){
temp_value = getValue( $(this), 1 );
if( append_text !== '' && temp_value) {
append_text = append_text + "\r";
}//end if
append_text = append_text + temp_value;
});
if( $.trim( append_text ) != '' ) {
append_text = "*****************\rTicket Details (" + $('select[name=checklist] option:selected').html() + "):\r------------------\r" + append_text + "\r*****************";
if( $.trim( $details.val() ) != '' ) {
append_text = "\r\r" + append_text;
}//end if
} else if( $('#new_call').length > 0 ) {
if( !confirm( 'You haven\'t answered the provided questions about your ticket. Are you sure you wish to submit the call?') ) {
return false;
}//end if
}//end else
if( $.trim( details ) == '' ) {
if( !confirm('You have not filled out a problem description. Do you still want to submit the call?') ) {
return false;
}//end if
}//end if
$details.val( $details.val() + append_text );
return true;
});
$('#checklists select').bind('change', function(){
var select = $(this).val();
$(this).siblings('.sub').each(function(){
var $extra = $(this);
var rel = $extra.attr('rel');
if( rel !== undefined ) {
try{
rel = rel.split('|');
} catch( e ) {
rel = [ rel ];
}
} else {
rel = false;
}//end else
if( select && (rel === false || $.inArray(select, rel) !== -1) ) {
$extra.slideDown('fast');
} else {
$extra.slideUp('fast');
}//end else
});
});
/////// end handle ticket checklists
$jQuery('body').delegate('#call-history', 'hover', function() {
setTimeout( add_focused_history, 250 );
});
$jQuery('body').delegate('#call-history', 'mouseleave', function() {
setTimeout( remove_focused_history, 500 );
});
});
function add_focused_history() {
if( $jQuery('#call-history').is(':hover') ) {
$jQuery('#call-history').addClass('focused-block');
}//end if
}//end add_focused_history
function remove_focused_history() {
if( ! $jQuery('#call-history').is(':hover') ) {
$jQuery('#call-history').removeClass('focused-block');
}//end if
}//end add_focused_history
| {
"content_hash": "9cd42f50e9c0b3c2fe3ca3a347af8a07",
"timestamp": "",
"source": "github",
"line_count": 200,
"max_line_length": 175,
"avg_line_length": 30.225,
"alnum_prop": 0.5849462365591398,
"repo_name": "borkweb/plymouth-webapp",
"id": "9e2080314d87fba1d64c25681eee66b03632c99e",
"size": "6046",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "webapp/calllog/js/main.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "6794914"
},
{
"name": "PHP",
"bytes": "29886910"
},
{
"name": "Perl",
"bytes": "209785"
},
{
"name": "Racket",
"bytes": "4313"
},
{
"name": "Shell",
"bytes": "528689"
},
{
"name": "XML",
"bytes": "58623"
}
],
"symlink_target": ""
} |
class GaloisFieldElement(object):
"""
Element of a finite field
"""
def __init__(self):
pass
def __eq__(self, other):
return self.__dict__ == other.__dict__
class GaloisFieldArithmetic(object):
"""
A collection of arithmetic operators for finite field elements
"""
def __init__(self, add_identity, mul_identity):
self.add_identity = add_identity # additive identity
self.mul_identity = mul_identity # multiplicative identity
def add(self, a, b):
"""
a + b
"""
pass
def neg(self, a):
"""
-a
"""
pass
def sub(self, a, b):
"""
a - b
"""
pass
def mul(self, a, b):
"""
a * b
"""
pass
def invert(self, a):
"""
a^(-1)
"""
pass
def div(self, a, b):
"""
a / b
"""
pass
def pow(self, a, e):
"""
a^e
"""
pass
def get_add_identity(self):
return self.add_identity
def get_mul_identity(self):
return self.mul_identity
| {
"content_hash": "e4dbc091ff04d0de4125af4cd4f22ebf",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 69,
"avg_line_length": 17.176470588235293,
"alnum_prop": 0.4460616438356164,
"repo_name": "FederatedAI/FATE",
"id": "2c452790ef60fa6130810f619f1779261009a4a8",
"size": "1833",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "python/federatedml/secureprotol/number_theory/field/base_galois_field.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Lua",
"bytes": "19716"
},
{
"name": "Python",
"bytes": "5121767"
},
{
"name": "Rust",
"bytes": "3971"
},
{
"name": "Shell",
"bytes": "19676"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<package name="accountItem" namespace="/accountItem" extends="json-default">
<action name="*" class="accountItemAction" method="{1}">
<result type="json"/>
</action>
</package>
</struts>
| {
"content_hash": "6c9088338858569bcf227f749b35c3e3",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 80,
"avg_line_length": 37.63636363636363,
"alnum_prop": 0.644927536231884,
"repo_name": "tycooc/ERP",
"id": "c470d14b013ad1dee4d4356127655b1f58e3a8cd",
"size": "414",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/main/webapp/WEB-INF/classes/struts2/accountItem-struts.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "278"
},
{
"name": "C#",
"bytes": "9414"
},
{
"name": "CSS",
"bytes": "948400"
},
{
"name": "HTML",
"bytes": "599338"
},
{
"name": "Java",
"bytes": "1666896"
},
{
"name": "JavaScript",
"bytes": "1715064"
},
{
"name": "PHP",
"bytes": "2982"
}
],
"symlink_target": ""
} |
package org.elasticsearch.xpack.ml.dataframe.process;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.lucene.util.SetOnce;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.xpack.core.ml.dataframe.DataFrameAnalyticsConfig;
import org.elasticsearch.xpack.core.ml.job.messages.Messages;
import org.elasticsearch.xpack.core.ml.job.persistence.AnomalyDetectorsIndex;
import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper;
import org.elasticsearch.xpack.ml.MachineLearning;
import org.elasticsearch.xpack.ml.dataframe.DataFrameAnalyticsTask;
import org.elasticsearch.xpack.ml.dataframe.extractor.DataFrameDataExtractor;
import org.elasticsearch.xpack.ml.dataframe.extractor.DataFrameDataExtractorFactory;
import org.elasticsearch.xpack.ml.dataframe.process.results.AnalyticsResult;
import org.elasticsearch.xpack.ml.dataframe.stats.DataCountsTracker;
import org.elasticsearch.xpack.ml.dataframe.stats.ProgressTracker;
import org.elasticsearch.xpack.ml.dataframe.stats.StatsPersister;
import org.elasticsearch.xpack.ml.dataframe.steps.StepResponse;
import org.elasticsearch.xpack.ml.extractor.ExtractedFields;
import org.elasticsearch.xpack.ml.inference.persistence.TrainedModelProvider;
import org.elasticsearch.xpack.ml.notifications.DataFrameAnalyticsAuditor;
import org.elasticsearch.xpack.ml.utils.persistence.ResultsPersisterService;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.function.Consumer;
import static org.elasticsearch.xpack.core.ClientHelper.ML_ORIGIN;
public class AnalyticsProcessManager {
private static final Logger LOGGER = LogManager.getLogger(AnalyticsProcessManager.class);
private final Settings settings;
private final Client client;
private final ExecutorService executorServiceForJob;
private final ExecutorService executorServiceForProcess;
private final AnalyticsProcessFactory<AnalyticsResult> processFactory;
private final ConcurrentMap<Long, ProcessContext> processContextByAllocation = new ConcurrentHashMap<>();
private final DataFrameAnalyticsAuditor auditor;
private final TrainedModelProvider trainedModelProvider;
private final ResultsPersisterService resultsPersisterService;
private final int numAllocatedProcessors;
public AnalyticsProcessManager(Settings settings,
Client client,
ThreadPool threadPool,
AnalyticsProcessFactory<AnalyticsResult> analyticsProcessFactory,
DataFrameAnalyticsAuditor auditor,
TrainedModelProvider trainedModelProvider,
ResultsPersisterService resultsPersisterService,
int numAllocatedProcessors) {
this(
settings,
client,
threadPool.executor(MachineLearning.UTILITY_THREAD_POOL_NAME),
threadPool.executor(MachineLearning.JOB_COMMS_THREAD_POOL_NAME),
analyticsProcessFactory,
auditor,
trainedModelProvider,
resultsPersisterService,
numAllocatedProcessors);
}
// Visible for testing
public AnalyticsProcessManager(Settings settings,
Client client,
ExecutorService executorServiceForJob,
ExecutorService executorServiceForProcess,
AnalyticsProcessFactory<AnalyticsResult> analyticsProcessFactory,
DataFrameAnalyticsAuditor auditor,
TrainedModelProvider trainedModelProvider,
ResultsPersisterService resultsPersisterService,
int numAllocatedProcessors) {
this.settings = Objects.requireNonNull(settings);
this.client = Objects.requireNonNull(client);
this.executorServiceForJob = Objects.requireNonNull(executorServiceForJob);
this.executorServiceForProcess = Objects.requireNonNull(executorServiceForProcess);
this.processFactory = Objects.requireNonNull(analyticsProcessFactory);
this.auditor = Objects.requireNonNull(auditor);
this.trainedModelProvider = Objects.requireNonNull(trainedModelProvider);
this.resultsPersisterService = Objects.requireNonNull(resultsPersisterService);
this.numAllocatedProcessors = numAllocatedProcessors;
}
public void runJob(DataFrameAnalyticsTask task, DataFrameAnalyticsConfig config, DataFrameDataExtractorFactory dataExtractorFactory,
ActionListener<StepResponse> listener) {
executorServiceForJob.execute(() -> {
ProcessContext processContext = new ProcessContext(config);
synchronized (processContextByAllocation) {
if (task.isStopping()) {
LOGGER.debug("[{}] task is stopping. Marking as complete before creating process context.",
task.getParams().getId());
// The task was requested to stop before we created the process context
auditor.info(config.getId(), Messages.DATA_FRAME_ANALYTICS_AUDIT_FINISHED_ANALYSIS);
listener.onResponse(new StepResponse(true));
return;
}
if (processContextByAllocation.putIfAbsent(task.getAllocationId(), processContext) != null) {
listener.onFailure(ExceptionsHelper.serverError(
"[" + config.getId() + "] Could not create process as one already exists"));
return;
}
}
// Fetch existing model state (if any)
final boolean hasState = hasModelState(config);
boolean isProcessStarted;
try {
isProcessStarted = processContext.startProcess(dataExtractorFactory, task, hasState);
} catch (Exception e) {
processContext.stop();
processContextByAllocation.remove(task.getAllocationId());
listener.onFailure(processContext.getFailureReason() == null ?
e : ExceptionsHelper.serverError(processContext.getFailureReason()));
return;
}
if (isProcessStarted) {
executorServiceForProcess.execute(() -> processContext.resultProcessor.get().process(processContext.process.get()));
executorServiceForProcess.execute(() -> processData(task, processContext, hasState, listener));
} else {
processContextByAllocation.remove(task.getAllocationId());
auditor.info(config.getId(), Messages.DATA_FRAME_ANALYTICS_AUDIT_FINISHED_ANALYSIS);
listener.onResponse(new StepResponse(true));
}
});
}
private boolean hasModelState(DataFrameAnalyticsConfig config) {
if (config.getAnalysis().persistsState() == false) {
return false;
}
try (ThreadContext.StoredContext ignore = client.threadPool().getThreadContext().stashWithOrigin(ML_ORIGIN)) {
SearchResponse searchResponse = client.prepareSearch(AnomalyDetectorsIndex.jobStateIndexPattern())
.setSize(1)
.setFetchSource(false)
.setQuery(QueryBuilders.idsQuery().addIds(config.getAnalysis().getStateDocIdPrefix(config.getId()) + "1"))
.get();
return searchResponse.getHits().getHits().length == 1;
}
}
private void processData(DataFrameAnalyticsTask task, ProcessContext processContext, boolean hasState,
ActionListener<StepResponse> listener) {
LOGGER.info("[{}] Started loading data", processContext.config.getId());
auditor.info(processContext.config.getId(), Messages.getMessage(Messages.DATA_FRAME_ANALYTICS_AUDIT_STARTED_LOADING_DATA));
DataFrameAnalyticsConfig config = processContext.config;
DataFrameDataExtractor dataExtractor = processContext.dataExtractor.get();
AnalyticsProcess<AnalyticsResult> process = processContext.process.get();
AnalyticsResultProcessor resultProcessor = processContext.resultProcessor.get();
try {
writeHeaderRecord(dataExtractor, process, task);
writeDataRows(dataExtractor, process, task);
process.writeEndOfDataMessage();
LOGGER.debug(() -> new ParameterizedMessage("[{}] Flushing input stream", processContext.config.getId()));
process.flushStream();
LOGGER.debug(() -> new ParameterizedMessage("[{}] Flushing input stream completed", processContext.config.getId()));
restoreState(config, process, hasState);
LOGGER.info("[{}] Started analyzing", processContext.config.getId());
auditor.info(processContext.config.getId(), Messages.getMessage(Messages.DATA_FRAME_ANALYTICS_AUDIT_STARTED_ANALYZING));
LOGGER.info("[{}] Waiting for result processor to complete", config.getId());
resultProcessor.awaitForCompletion();
processContext.setFailureReason(resultProcessor.getFailure());
LOGGER.info("[{}] Result processor has completed", config.getId());
} catch (Exception e) {
if (task.isStopping()) {
// Errors during task stopping are expected but we still want to log them just in case.
String errorMsg =
new ParameterizedMessage(
"[{}] Error while processing data [{}]; task is stopping", config.getId(), e.getMessage()).getFormattedMessage();
LOGGER.debug(errorMsg, e);
} else {
String errorMsg =
new ParameterizedMessage("[{}] Error while processing data [{}]", config.getId(), e.getMessage()).getFormattedMessage();
LOGGER.error(errorMsg, e);
processContext.setFailureReason(errorMsg);
}
} finally {
closeProcess(task);
processContextByAllocation.remove(task.getAllocationId());
LOGGER.debug("Removed process context for task [{}]; [{}] processes still running", config.getId(),
processContextByAllocation.size());
if (processContext.getFailureReason() == null) {
auditor.info(config.getId(), Messages.DATA_FRAME_ANALYTICS_AUDIT_FINISHED_ANALYSIS);
listener.onResponse(new StepResponse(false));
} else {
LOGGER.error("[{}] Marking task failed; {}", config.getId(), processContext.getFailureReason());
listener.onFailure(ExceptionsHelper.serverError(processContext.getFailureReason()));
// Note: We are not marking the task as failed here as we want the user to be able to inspect the failure reason.
}
}
}
private void writeDataRows(DataFrameDataExtractor dataExtractor, AnalyticsProcess<AnalyticsResult> process,
DataFrameAnalyticsTask task) throws IOException {
ProgressTracker progressTracker = task.getStatsHolder().getProgressTracker();
DataCountsTracker dataCountsTracker = task.getStatsHolder().getDataCountsTracker();
// The extra fields are for the doc hash and the control field (should be an empty string)
String[] record = new String[dataExtractor.getFieldNames().size() + 2];
// The value of the control field should be an empty string for data frame rows
record[record.length - 1] = "";
long totalRows = process.getConfig().rows();
long rowsProcessed = 0;
while (dataExtractor.hasNext()) {
Optional<List<DataFrameDataExtractor.Row>> rows = dataExtractor.next();
if (rows.isPresent()) {
for (DataFrameDataExtractor.Row row : rows.get()) {
if (row.shouldSkip()) {
dataCountsTracker.incrementSkippedDocsCount();
} else {
String[] rowValues = row.getValues();
System.arraycopy(rowValues, 0, record, 0, rowValues.length);
record[record.length - 2] = String.valueOf(row.getChecksum());
if (row.isTraining()) {
dataCountsTracker.incrementTrainingDocsCount();
process.writeRecord(record);
}
}
}
rowsProcessed += rows.get().size();
progressTracker.updateLoadingDataProgress(rowsProcessed >= totalRows ? 100 : (int) (rowsProcessed * 100.0 / totalRows));
}
}
}
private void writeHeaderRecord(DataFrameDataExtractor dataExtractor,
AnalyticsProcess<AnalyticsResult> process,
DataFrameAnalyticsTask task) throws IOException {
List<String> fieldNames = dataExtractor.getFieldNames();
LOGGER.debug(() -> new ParameterizedMessage("[{}] header row fields {}", task.getParams().getId(), fieldNames));
// We add 2 extra fields, both named dot:
// - the document hash
// - the control message
String[] headerRecord = new String[fieldNames.size() + 2];
for (int i = 0; i < fieldNames.size(); i++) {
headerRecord[i] = fieldNames.get(i);
}
headerRecord[headerRecord.length - 2] = ".";
headerRecord[headerRecord.length - 1] = ".";
process.writeRecord(headerRecord);
}
private void restoreState(DataFrameAnalyticsConfig config, AnalyticsProcess<AnalyticsResult> process, boolean hasState) {
if (config.getAnalysis().persistsState() == false) {
LOGGER.debug("[{}] Analysis does not support state", config.getId());
return;
}
if (hasState == false) {
LOGGER.debug("[{}] No model state available to restore", config.getId());
return;
}
LOGGER.debug("[{}] Restoring from previous model state", config.getId());
auditor.info(config.getId(), Messages.DATA_FRAME_ANALYTICS_AUDIT_RESTORING_STATE);
try (ThreadContext.StoredContext ignore = client.threadPool().getThreadContext().stashWithOrigin(ML_ORIGIN)) {
process.restoreState(client, config.getAnalysis().getStateDocIdPrefix(config.getId()));
} catch (Exception e) {
LOGGER.error(new ParameterizedMessage("[{}] Failed to restore state", process.getConfig().jobId()), e);
throw ExceptionsHelper.serverError("Failed to restore state: " + e.getMessage());
}
}
private AnalyticsProcess<AnalyticsResult> createProcess(DataFrameAnalyticsTask task, DataFrameAnalyticsConfig config,
AnalyticsProcessConfig analyticsProcessConfig, boolean hasState) {
AnalyticsProcess<AnalyticsResult> process = processFactory.createAnalyticsProcess(
config, analyticsProcessConfig, hasState, executorServiceForProcess, onProcessCrash(task));
if (process.isProcessAlive() == false) {
throw ExceptionsHelper.serverError("Failed to start data frame analytics process");
}
return process;
}
private Consumer<String> onProcessCrash(DataFrameAnalyticsTask task) {
return reason -> {
ProcessContext processContext = processContextByAllocation.get(task.getAllocationId());
if (processContext != null) {
processContext.setFailureReason(reason);
processContext.stop();
}
};
}
private void closeProcess(DataFrameAnalyticsTask task) {
String configId = task.getParams().getId();
LOGGER.info("[{}] Closing process", configId);
ProcessContext processContext = processContextByAllocation.get(task.getAllocationId());
try {
processContext.process.get().close();
LOGGER.info("[{}] Closed process", configId);
} catch (Exception e) {
if (task.isStopping()) {
LOGGER.debug(() -> new ParameterizedMessage(
"[{}] Process closing was interrupted by kill request due to the task being stopped", configId), e);
LOGGER.info("[{}] Closed process", configId);
} else {
LOGGER.error("[" + configId + "] Error closing data frame analyzer process", e);
String errorMsg = new ParameterizedMessage(
"[{}] Error closing data frame analyzer process [{}]", configId, e.getMessage()).getFormattedMessage();
processContext.setFailureReason(errorMsg);
}
}
}
public void stop(DataFrameAnalyticsTask task) {
ProcessContext processContext;
synchronized (processContextByAllocation) {
processContext = processContextByAllocation.get(task.getAllocationId());
}
if (processContext != null) {
LOGGER.debug("[{}] Stopping process", task.getParams().getId());
processContext.stop();
} else {
LOGGER.debug("[{}] No process context to stop", task.getParams().getId());
}
}
// Visible for testing
int getProcessContextCount() {
return processContextByAllocation.size();
}
class ProcessContext {
private final DataFrameAnalyticsConfig config;
private final SetOnce<AnalyticsProcess<AnalyticsResult>> process = new SetOnce<>();
private final SetOnce<DataFrameDataExtractor> dataExtractor = new SetOnce<>();
private final SetOnce<AnalyticsResultProcessor> resultProcessor = new SetOnce<>();
private final SetOnce<String> failureReason = new SetOnce<>();
ProcessContext(DataFrameAnalyticsConfig config) {
this.config = Objects.requireNonNull(config);
}
String getFailureReason() {
return failureReason.get();
}
void setFailureReason(String failureReason) {
if (failureReason == null) {
return;
}
// Only set the new reason if there isn't one already as we want to keep the first reason (most likely the root cause).
this.failureReason.trySet(failureReason);
}
synchronized void stop() {
LOGGER.debug("[{}] Stopping process", config.getId());
if (dataExtractor.get() != null) {
dataExtractor.get().cancel();
}
if (resultProcessor.get() != null) {
resultProcessor.get().cancel();
}
if (process.get() != null) {
try {
process.get().kill(true);
} catch (IOException e) {
LOGGER.error(new ParameterizedMessage("[{}] Failed to kill process", config.getId()), e);
}
}
}
/**
* @return {@code true} if the process was started or {@code false} if it was not because it was stopped in the meantime
*/
synchronized boolean startProcess(DataFrameDataExtractorFactory dataExtractorFactory, DataFrameAnalyticsTask task,
boolean hasState) {
if (task.isStopping()) {
// The job was stopped before we started the process so no need to start it
return false;
}
dataExtractor.set(dataExtractorFactory.newExtractor(false));
AnalyticsProcessConfig analyticsProcessConfig =
createProcessConfig(dataExtractor.get(), dataExtractorFactory.getExtractedFields());
LOGGER.debug("[{}] creating analytics process with config [{}]", config.getId(), Strings.toString(analyticsProcessConfig));
// If we have no rows, that means there is no data so no point in starting the native process
// just finish the task
if (analyticsProcessConfig.rows() == 0) {
LOGGER.info("[{}] no data found to analyze. Will not start analytics native process.", config.getId());
return false;
}
process.set(createProcess(task, config, analyticsProcessConfig, hasState));
resultProcessor.set(createResultProcessor(task, dataExtractorFactory));
return true;
}
private AnalyticsProcessConfig createProcessConfig(DataFrameDataExtractor dataExtractor,
ExtractedFields extractedFields) {
DataFrameDataExtractor.DataSummary dataSummary = dataExtractor.collectDataSummary();
Set<String> categoricalFields = dataExtractor.getCategoricalFields(config.getAnalysis());
int threads = Math.min(config.getMaxNumThreads(), numAllocatedProcessors);
return new AnalyticsProcessConfig(
config.getId(),
dataSummary.rows,
dataSummary.cols,
config.getModelMemoryLimit(),
threads,
config.getDest().getResultsField(),
categoricalFields,
config.getAnalysis(),
extractedFields);
}
private AnalyticsResultProcessor createResultProcessor(DataFrameAnalyticsTask task,
DataFrameDataExtractorFactory dataExtractorFactory) {
DataFrameRowsJoiner dataFrameRowsJoiner =
new DataFrameRowsJoiner(config.getId(), settings, task.getParentTaskId(),
dataExtractorFactory.newExtractor(true), resultsPersisterService);
StatsPersister statsPersister = new StatsPersister(config.getId(), resultsPersisterService, auditor);
return new AnalyticsResultProcessor(
config, dataFrameRowsJoiner, task.getStatsHolder(), trainedModelProvider, auditor, statsPersister,
dataExtractor.get().getExtractedFields());
}
}
}
| {
"content_hash": "200422e26dfb0f39654f21b8b1086815",
"timestamp": "",
"source": "github",
"line_count": 449,
"max_line_length": 140,
"avg_line_length": 51.198218262806236,
"alnum_prop": 0.6367235079171741,
"repo_name": "robin13/elasticsearch",
"id": "e1feb5c52422176e909da169700ac362fcc99e57",
"size": "23240",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/dataframe/process/AnalyticsProcessManager.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "11082"
},
{
"name": "Batchfile",
"bytes": "14049"
},
{
"name": "Emacs Lisp",
"bytes": "3341"
},
{
"name": "FreeMarker",
"bytes": "45"
},
{
"name": "Groovy",
"bytes": "315863"
},
{
"name": "HTML",
"bytes": "3399"
},
{
"name": "Java",
"bytes": "40107206"
},
{
"name": "Perl",
"bytes": "7271"
},
{
"name": "Python",
"bytes": "54437"
},
{
"name": "Shell",
"bytes": "108937"
}
],
"symlink_target": ""
} |
package com.thomas.controllers;
import com.thomas.models.Booking;
import com.thomas.services.BookingService;
import com.thomas.utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import static com.thomas.utils.KeyConstants.RESOURCE;
/**
* Created by yougeshwar on 16/03/2017.
*/
@RestController
@RequestMapping("/booking")
public class BookingController
{
@Autowired
private BookingService bookingService;
@PostMapping
public ResponseEntity<?> add(@RequestBody Booking booking)
{
Response response = bookingService.add(booking);
if (response.isSuccess())
{
return new ResponseEntity(response, HttpStatus.OK);
}
else
{
return new ResponseEntity(response, HttpStatus.BAD_REQUEST);
}
}
@PutMapping
public ResponseEntity<?> update(@RequestBody Booking booking)
{
Response response = bookingService.update(booking);
if (response.isSuccess())
{
return new ResponseEntity(response, HttpStatus.OK);
}
else
{
return new ResponseEntity(response, HttpStatus.BAD_REQUEST);
}
}
@DeleteMapping("/{id}")
public ResponseEntity<?> delete(@PathVariable("id") Integer id)
{
Response response = bookingService.delete(id);
if (response.isSuccess())
{
return new ResponseEntity(response, HttpStatus.OK);
}
else
{
return new ResponseEntity(response, HttpStatus.BAD_REQUEST);
}
}
@SuppressWarnings("Duplicates")
@GetMapping("/{id}")
public ResponseEntity<?> get(@PathVariable("id") Integer id)
{
Response response = bookingService.get(id);
if (response.isSuccess())
{
if (response.get(RESOURCE) == null)
{
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
else
{
return new ResponseEntity(response, HttpStatus.OK);
}
}
else
{
return new ResponseEntity(response, HttpStatus.BAD_REQUEST);
}
}
@GetMapping("/customer/{customerId}")
public ResponseEntity<?> getAllByCustomer(@PathVariable("customerId") Integer customerId)
{
Response response = bookingService.getAllByCustomer(customerId);
if (response.isSuccess())
{
return new ResponseEntity(response, HttpStatus.OK);
}
else
{
return new ResponseEntity(response, HttpStatus.BAD_REQUEST);
}
}
@GetMapping("/status/{statusId}")
public ResponseEntity<?> getAllByStatus(@PathVariable("statusId") Integer statusId)
{
Response response = bookingService.getAllByStatus(statusId);
if (response.isSuccess())
{
return new ResponseEntity(response, HttpStatus.OK);
}
else
{
return new ResponseEntity(response, HttpStatus.BAD_REQUEST);
}
}
@GetMapping()
public ResponseEntity<?> getAll()
{
Response response = bookingService.getAll();
if (response.isSuccess())
{
return new ResponseEntity(response, HttpStatus.OK);
}
else
{
return new ResponseEntity(response, HttpStatus.BAD_REQUEST);
}
}
}
| {
"content_hash": "f9b3f215ee3b6d48fbde69c7679d8637",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 93,
"avg_line_length": 27.8125,
"alnum_prop": 0.6087078651685394,
"repo_name": "ThomasEvents/thomosevents",
"id": "aae29c1e0970fcc4536780517d43d2855513d994",
"size": "3560",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/thomas/controllers/BookingController.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "134158"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>write_at (2 of 8 overloads)</title>
<link rel="stylesheet" href="../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../../index.html" title="Asio">
<link rel="up" href="../write_at.html" title="write_at">
<link rel="prev" href="overload1.html" title="write_at (1 of 8 overloads)">
<link rel="next" href="overload3.html" title="write_at (3 of 8 overloads)">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr><td valign="top"><img alt="asio C++ library" width="250" height="60" src="../../../asio.png"></td></tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload1.html"><img src="../../../prev.png" alt="Prev"></a><a accesskey="u" href="../write_at.html"><img src="../../../up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../home.png" alt="Home"></a><a accesskey="n" href="overload3.html"><img src="../../../next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="asio.reference.write_at.overload2"></a><a class="link" href="overload2.html" title="write_at (2 of 8 overloads)">write_at (2 of 8
overloads)</a>
</h4></div></div></div>
<p>
Write all of the supplied data at the specified offset before returning.
</p>
<pre class="programlisting"><span class="keyword">template</span><span class="special"><</span>
<span class="keyword">typename</span> <a class="link" href="../SyncRandomAccessWriteDevice.html" title="Buffer-oriented synchronous random-access write device requirements">SyncRandomAccessWriteDevice</a><span class="special">,</span>
<span class="keyword">typename</span> <a class="link" href="../ConstBufferSequence.html" title="Constant buffer sequence requirements">ConstBufferSequence</a><span class="special">></span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <span class="identifier">write_at</span><span class="special">(</span>
<span class="identifier">SyncRandomAccessWriteDevice</span> <span class="special">&</span> <span class="identifier">d</span><span class="special">,</span>
<span class="identifier">uint64_t</span> <span class="identifier">offset</span><span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">ConstBufferSequence</span> <span class="special">&</span> <span class="identifier">buffers</span><span class="special">,</span>
<span class="identifier">asio</span><span class="special">::</span><span class="identifier">error_code</span> <span class="special">&</span> <span class="identifier">ec</span><span class="special">);</span>
</pre>
<p>
This function is used to write a certain number of bytes of data to a random
access device at a specified offset. The call will block until one of the
following conditions is true:
</p>
<div class="itemizedlist"><ul class="itemizedlist" type="disc">
<li class="listitem">
All of the data in the supplied buffers has been written. That is,
the bytes transferred is equal to the sum of the buffer sizes.
</li>
<li class="listitem">
An error occurred.
</li>
</ul></div>
<p>
This operation is implemented in terms of zero or more calls to the device's
write_some_at function.
</p>
<h6>
<a name="asio.reference.write_at.overload2.h0"></a>
<span><a name="asio.reference.write_at.overload2.parameters"></a></span><a class="link" href="overload2.html#asio.reference.write_at.overload2.parameters">Parameters</a>
</h6>
<div class="variablelist">
<p class="title"><b></b></p>
<dl>
<dt><span class="term">d</span></dt>
<dd><p>
The device to which the data is to be written. The type must support
the SyncRandomAccessWriteDevice concept.
</p></dd>
<dt><span class="term">offset</span></dt>
<dd><p>
The offset at which the data will be written.
</p></dd>
<dt><span class="term">buffers</span></dt>
<dd><p>
One or more buffers containing the data to be written. The sum of
the buffer sizes indicates the maximum number of bytes to write to
the device.
</p></dd>
<dt><span class="term">ec</span></dt>
<dd><p>
Set to indicate what error occurred, if any.
</p></dd>
</dl>
</div>
<h6>
<a name="asio.reference.write_at.overload2.h1"></a>
<span><a name="asio.reference.write_at.overload2.return_value"></a></span><a class="link" href="overload2.html#asio.reference.write_at.overload2.return_value">Return
Value</a>
</h6>
<p>
The number of bytes transferred.
</p>
<h6>
<a name="asio.reference.write_at.overload2.h2"></a>
<span><a name="asio.reference.write_at.overload2.example"></a></span><a class="link" href="overload2.html#asio.reference.write_at.overload2.example">Example</a>
</h6>
<p>
To write a single data buffer use the <a class="link" href="../buffer.html" title="buffer"><code class="computeroutput"><span class="identifier">buffer</span></code></a> function as follows:
</p>
<pre class="programlisting"><span class="identifier">asio</span><span class="special">::</span><span class="identifier">write_at</span><span class="special">(</span><span class="identifier">d</span><span class="special">,</span> <span class="number">42</span><span class="special">,</span>
<span class="identifier">asio</span><span class="special">::</span><span class="identifier">buffer</span><span class="special">(</span><span class="identifier">data</span><span class="special">,</span> <span class="identifier">size</span><span class="special">),</span> <span class="identifier">ec</span><span class="special">);</span>
</pre>
<p>
See the <a class="link" href="../buffer.html" title="buffer"><code class="computeroutput"><span class="identifier">buffer</span></code></a>
documentation for information on writing multiple buffers in one go, and
how to use it with arrays, boost::array or std::vector.
</p>
<h6>
<a name="asio.reference.write_at.overload2.h3"></a>
<span><a name="asio.reference.write_at.overload2.remarks"></a></span><a class="link" href="overload2.html#asio.reference.write_at.overload2.remarks">Remarks</a>
</h6>
<p>
This overload is equivalent to calling:
</p>
<pre class="programlisting"><span class="identifier">asio</span><span class="special">::</span><span class="identifier">write_at</span><span class="special">(</span>
<span class="identifier">d</span><span class="special">,</span> <span class="identifier">offset</span><span class="special">,</span> <span class="identifier">buffers</span><span class="special">,</span>
<span class="identifier">asio</span><span class="special">::</span><span class="identifier">transfer_all</span><span class="special">(),</span> <span class="identifier">ec</span><span class="special">);</span>
</pre>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2015 Christopher M.
Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload1.html"><img src="../../../prev.png" alt="Prev"></a><a accesskey="u" href="../write_at.html"><img src="../../../up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../home.png" alt="Home"></a><a accesskey="n" href="overload3.html"><img src="../../../next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "5dfe15871a647ef0c4efbe9811c3de27",
"timestamp": "",
"source": "github",
"line_count": 130,
"max_line_length": 339,
"avg_line_length": 63.253846153846155,
"alnum_prop": 0.6459929466131582,
"repo_name": "jeanleflambeur/silkopter",
"id": "db11039c28f45ba491dd97aa177cbd16a4b314e3",
"size": "8223",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "asio/doc/asio/reference/write_at/overload2.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "110"
},
{
"name": "C",
"bytes": "2221045"
},
{
"name": "C++",
"bytes": "24409548"
},
{
"name": "CMake",
"bytes": "216809"
},
{
"name": "CSS",
"bytes": "34635"
},
{
"name": "Cuda",
"bytes": "4881"
},
{
"name": "Fortran",
"bytes": "1315584"
},
{
"name": "HTML",
"bytes": "18916392"
},
{
"name": "JavaScript",
"bytes": "7839"
},
{
"name": "Lex",
"bytes": "3749"
},
{
"name": "Lua",
"bytes": "3762"
},
{
"name": "M4",
"bytes": "9302"
},
{
"name": "Objective-C",
"bytes": "2096"
},
{
"name": "Objective-C++",
"bytes": "168"
},
{
"name": "Perl",
"bytes": "6547"
},
{
"name": "Python",
"bytes": "8937"
},
{
"name": "QML",
"bytes": "10680"
},
{
"name": "QMake",
"bytes": "101603"
},
{
"name": "Shell",
"bytes": "73534"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "b1e2ae3bfb9b01b55341e4a7ea08af63",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "26f05e9b6a56db22e4afd486ea43032896a23dae",
"size": "188",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Tripogon/Tripogon loliiformis/Diplachne loliiformis loliiformis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package weixin.popular.client;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weixin.popular.util.JsonUtil;
public class JsonResponseHandler{
private static Logger logger = LoggerFactory.getLogger(JsonResponseHandler.class);
public static <T> ResponseHandler<T> createResponseHandler(final Class<T> clazz){
return new JsonResponseHandlerImpl<T>(null,clazz);
}
public static class JsonResponseHandlerImpl<T> extends LocalResponseHandler implements ResponseHandler<T> {
private Class<T> clazz;
public JsonResponseHandlerImpl(String uriId, Class<T> clazz) {
this.uriId = uriId;
this.clazz = clazz;
}
@Override
public T handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
String str = EntityUtils.toString(entity,"utf-8");
logger.info("URI[{}] elapsed time:{} ms RESPONSE DATA:{}",super.uriId,System.currentTimeMillis()-super.startTime,str);
return JsonUtil.parseObject(str, clazz);
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
}
}
| {
"content_hash": "46d0ff936a1003222403a622cfea3bfd",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 134,
"avg_line_length": 34.255319148936174,
"alnum_prop": 0.6944099378881987,
"repo_name": "liyiorg/weixin-popular",
"id": "515bb119756ac2818abe3e609be75c1556014451",
"size": "1610",
"binary": false,
"copies": "1",
"ref": "refs/heads/2.8.x",
"path": "src/main/java/weixin/popular/client/JsonResponseHandler.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1149657"
}
],
"symlink_target": ""
} |
namespace media {
#if !defined(OS_MACOSX)
// TODO(crogers): implement MIDIManager for other platforms.
MIDIManager* MIDIManager::Create() {
return NULL;
}
#endif
MIDIManager::MIDIManager()
: initialized_(false) {
}
MIDIManager::~MIDIManager() {}
bool MIDIManager::StartSession(MIDIManagerClient* client) {
// Lazily initialize the MIDI back-end.
if (!initialized_)
initialized_ = Initialize();
if (initialized_) {
base::AutoLock auto_lock(clients_lock_);
clients_.insert(client);
}
return initialized_;
}
void MIDIManager::EndSession(MIDIManagerClient* client) {
base::AutoLock auto_lock(clients_lock_);
ClientList::iterator i = clients_.find(client);
if (i != clients_.end())
clients_.erase(i);
}
void MIDIManager::AddInputPort(const MIDIPortInfo& info) {
input_ports_.push_back(info);
}
void MIDIManager::AddOutputPort(const MIDIPortInfo& info) {
output_ports_.push_back(info);
}
void MIDIManager::ReceiveMIDIData(
uint32 port_index,
const uint8* data,
size_t length,
double timestamp) {
base::AutoLock auto_lock(clients_lock_);
for (ClientList::iterator i = clients_.begin(); i != clients_.end(); ++i)
(*i)->ReceiveMIDIData(port_index, data, length, timestamp);
}
bool MIDIManager::CurrentlyOnMIDISendThread() {
return send_thread_->message_loop() == base::MessageLoop::current();
}
void MIDIManager::DispatchSendMIDIData(MIDIManagerClient* client,
uint32 port_index,
const std::vector<uint8>& data,
double timestamp) {
// Lazily create the thread when first needed.
if (!send_thread_) {
send_thread_.reset(new base::Thread("MIDISendThread"));
send_thread_->Start();
send_message_loop_ = send_thread_->message_loop_proxy();
}
send_message_loop_->PostTask(
FROM_HERE,
base::Bind(&MIDIManager::SendMIDIData, base::Unretained(this),
client, port_index, data, timestamp));
}
} // namespace media
| {
"content_hash": "913f665f9de255031d16c2492d1cdc6b",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 75,
"avg_line_length": 26.776315789473685,
"alnum_prop": 0.655036855036855,
"repo_name": "cvsuser-chromium/chromium",
"id": "b3262e4a034516ab8af46629bc3cfffa5b5d5ea7",
"size": "2377",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "media/midi/midi_manager.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Assembly",
"bytes": "36421"
},
{
"name": "C",
"bytes": "6924841"
},
{
"name": "C++",
"bytes": "179649999"
},
{
"name": "CSS",
"bytes": "812951"
},
{
"name": "Java",
"bytes": "3768838"
},
{
"name": "JavaScript",
"bytes": "8338074"
},
{
"name": "Makefile",
"bytes": "52980"
},
{
"name": "Objective-C",
"bytes": "819293"
},
{
"name": "Objective-C++",
"bytes": "6453781"
},
{
"name": "PHP",
"bytes": "61320"
},
{
"name": "Perl",
"bytes": "17897"
},
{
"name": "Python",
"bytes": "5640877"
},
{
"name": "Rebol",
"bytes": "262"
},
{
"name": "Shell",
"bytes": "648699"
},
{
"name": "XSLT",
"bytes": "418"
},
{
"name": "nesC",
"bytes": "15926"
}
],
"symlink_target": ""
} |
package org.geotools.filter.function;
/*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2005-2008, Open Source Geospatial Foundation (OSGeo)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
//this code is autogenerated - you shouldnt be modifying it!
import static org.geotools.filter.capability.FunctionNameImpl.*;
import org.geotools.filter.FunctionExpressionImpl;
import org.geotools.filter.capability.FunctionNameImpl;
import org.opengis.filter.capability.FunctionName;
import com.vividsolutions.jts.geom.Geometry;
/**
*
*
* @source $URL$
*/
public class FilterFunction_relate extends FunctionExpressionImpl {
public static FunctionName NAME = new FunctionNameImpl("relate", String.class,
parameter("geometry1", Geometry.class),
parameter("geometry2", Geometry.class));
public FilterFunction_relate() {
super(NAME);
}
public Object evaluate(Object feature) {
Geometry arg0;
Geometry arg1;
try { // attempt to get value and perform conversion
arg0 = getExpression(0).evaluate(feature, Geometry.class);
} catch (Exception e) // probably a type error
{
throw new IllegalArgumentException(
"Filter Function problem for function relate argument #0 - expected type Geometry");
}
try { // attempt to get value and perform conversion
arg1 = getExpression(1).evaluate(feature, Geometry.class);
} catch (Exception e) // probably a type error
{
throw new IllegalArgumentException(
"Filter Function problem for function relate argument #1 - expected type Geometry");
}
return (StaticGeometry.relate(arg0, arg1));
}
}
| {
"content_hash": "954f2d65d892bcb0d69c8b79320e10f6",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 104,
"avg_line_length": 34.15151515151515,
"alnum_prop": 0.6752440106477373,
"repo_name": "TerraMobile/TerraMobile",
"id": "f8767f0440911fa34ca740ecad4d83cc81046d79",
"size": "2254",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "sldparser/src/main/geotools/filter/function/FilterFunction_relate.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "11389"
},
{
"name": "Java",
"bytes": "5446921"
}
],
"symlink_target": ""
} |
using System;
using System.Runtime.Serialization;
namespace XCLCMS.Data.WebAPIEntity.RequestEntity.FileInfo
{
[DataContract]
[Serializable]
public class DiskFileListEntity
{
/// <summary>
/// 当前目录(物理路径)
/// </summary>
[DataMember]
public string CurrentDirectory { get; set; }
[DataMember]
public string RootPath { get; set; }
[DataMember]
public string WebRootPath { get; set; }
}
} | {
"content_hash": "4444bbd0ca1321369b4dd8c41cd4d536",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 57,
"avg_line_length": 21.727272727272727,
"alnum_prop": 0.602510460251046,
"repo_name": "xucongli1989/XCLCMS",
"id": "d718172be84514b6ec5e2324dba6ec321c5abf4e",
"size": "500",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "XCLCMS.Data/XCLCMS.Data.WebAPIEntity/RequestEntity/FileInfo/DiskFileListEntity.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "327"
},
{
"name": "Batchfile",
"bytes": "660"
},
{
"name": "C#",
"bytes": "1889339"
},
{
"name": "CSS",
"bytes": "909839"
},
{
"name": "HTML",
"bytes": "3753"
},
{
"name": "JavaScript",
"bytes": "885024"
},
{
"name": "PLpgSQL",
"bytes": "44712"
},
{
"name": "PowerShell",
"bytes": "8774"
},
{
"name": "SQLPL",
"bytes": "3916"
},
{
"name": "Smarty",
"bytes": "1704"
},
{
"name": "TypeScript",
"bytes": "98337"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RabbitMQ.Client;
using Newtonsoft.Json;
using Polly;
using Polly.Retry;
namespace RabbitHole
{
public class Publisher<T> : IPublisher<T>
where T : IMessage
{
public IMessage Message { get; private set; }
public string RoutingKey { get; private set; }
public IBasicProperties Properties { get; private set; }
public Func<T, Guid> CorrelationField { get; private set; }
private int _tryConnectAttempts = 15;
private RetryPolicy _policy;
private string _exchangeName;
public Publisher()
{
this.RoutingKey = string.Empty;
_policy = Policy
.Handle<Exception>()
.WaitAndRetry(
_tryConnectAttempts,
retryAttempt => TimeSpan.FromSeconds(Math.Pow(1.5, retryAttempt)),
(exception, timespan) =>
{
Console.WriteLine($"Unable to stablish a channel and/or publish the message. Trying again in {timespan.TotalSeconds} seconds.", exception);
//throw new UnableToCreateChannelException($"Unable to stablish a channel and/or publish the message. Trying again in {timespan.TotalSeconds} seconds.", exception);
});
}
public void Go(IConnection connection, IEnumerable<IExchange> exchanges, IDictionary<Type, IMessageConfigurator> messagesConfiguration)
{
try
{
var exchange = exchanges.FirstOrDefault(e => e.Name.Equals(_exchangeName));
if (exchange == null) throw new Exception($"No exchange with name '{_exchangeName}' was found.");
var routingKey = this.RoutingKey;
_policy.Execute(() =>
{
using (var channel = connection.RabbitConnection.CreateModel())
{
var correlationId = CorrelationField?.Invoke((T)Message) ?? Guid.Empty;
var properties = this.Properties ?? channel.CreateBasicProperties();
var messageType = this.Message.GetType();
properties.CorrelationId = (correlationId != Guid.Empty ? correlationId : Guid.NewGuid()).ToString();
if (messagesConfiguration.ContainsKey(messageType))
{
var messageConfiguration = messagesConfiguration[messageType] as IMessageConfiguration<T>;
if (messageConfiguration.Properties != null)
properties = messageConfiguration.Properties;
routingKey = messageConfiguration.RoutingKey;
//queueName = messageConfiguration.QueueName;
correlationId = messageConfiguration.CorrelationField((T)this.Message);
if(correlationId != Guid.Empty)
properties.CorrelationId = correlationId.ToString();
properties.Persistent = messageConfiguration.Persistent;
}
channel.ExchangeDeclare(exchange: exchange.Name,
type: exchange.Type.ToString().ToLower(),
durable: exchange.Durable,
autoDelete: exchange.AutoDelete);
var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(this.Message));
channel.BasicPublish(exchange: exchange.Name,
routingKey: routingKey ?? string.Empty,
basicProperties: properties,
body: body);
Console.WriteLine($"RabbitHole: Sent Message. Exchange: {exchange.Name}, CorrelationId:{properties.CorrelationId}");
}
});
}
catch (Exception ex)
{
///TODO logging
throw;
}
}
public IPublisher<T> WithMessage(IMessage message)
{
this.Message = message;
return this;
}
public IPublisher<T> WithProperties(IBasicProperties properties)
{
this.Properties = properties;
return this;
}
public IPublisher<T> WithRoutingKey(string routingKey)
{
this.RoutingKey = routingKey;
return this;
}
public IPublisher<T> WithCorrelationId(Func<T, Guid> correlationField)
{
this.CorrelationField = correlationField;
return this;
}
public IPublisher<T> WithExchange(string exchangeName)
{
_exchangeName = exchangeName;
return this;
}
}
}
| {
"content_hash": "8983492006cd4ac0b0e4b303416c0a44",
"timestamp": "",
"source": "github",
"line_count": 123,
"max_line_length": 188,
"avg_line_length": 41.32520325203252,
"alnum_prop": 0.5321660436749951,
"repo_name": "alvesdm/RabbitHole",
"id": "996100c6ff4ed51c085b5085ae84ad09009ab3b8",
"size": "5085",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Publisher.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "33248"
}
],
"symlink_target": ""
} |
cask 'rubymine' do
version '2018.1.3,181.4892.67'
sha256 'e7800ae4a5e6b21e9363c89a6cd513f926fe17e38e11a9dbb5fb69f9f9e2fe45'
url "https://download.jetbrains.com/ruby/RubyMine-#{version.before_comma}.dmg"
appcast 'https://data.services.jetbrains.com/products/releases?code=RM&latest=true&type=release',
checkpoint: '9e6636654a2a7923abc2b73834d7b61b7f1b73ab97b3fcb52f18081d8d1dce45'
name 'RubyMine'
homepage 'https://www.jetbrains.com/ruby/'
auto_updates true
app 'RubyMine.app'
uninstall_postflight do
ENV['PATH'].split(File::PATH_SEPARATOR).map { |path| File.join(path, 'mine') }.each { |path| File.delete(path) if File.exist?(path) && File.readlines(path).grep(%r{# see com.intellij.idea.SocketLock for the server side of this interface}).any? }
end
zap trash: [
"~/Library/Application Support/RubyMine#{version.major_minor}",
"~/Library/Caches/RubyMine#{version.major_minor}",
"~/Library/Logs/RubyMine#{version.major_minor}",
"~/Library/Preferences/RubyMine#{version.major_minor}",
]
end
| {
"content_hash": "de66de5dc748bb39b367e52d6182fd99",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 249,
"avg_line_length": 44.12,
"alnum_prop": 0.6962828649138713,
"repo_name": "jpmat296/homebrew-cask",
"id": "6f5289f16dc2ad7bfa646298a182ef56002c8cf2",
"size": "1103",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "Casks/rubymine.rb",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Ruby",
"bytes": "2312575"
},
{
"name": "Shell",
"bytes": "39510"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
namespace OpenSim.Framework.Servers.Tests
{
[TestFixture]
public class VersionInfoTests
{
[Test]
public void TestVersionLength()
{
Assert.AreEqual(VersionInfo.VERSIONINFO_VERSION_LENGTH, VersionInfo.Version.Length," VersionInfo.Version string not " + VersionInfo.VERSIONINFO_VERSION_LENGTH + " chars.");
}
[Test]
public void TestGetVersionStringLength()
{
foreach (VersionInfo.Flavour flavour in Enum.GetValues(typeof(VersionInfo.Flavour)))
{
Assert.AreEqual(VersionInfo.VERSIONINFO_VERSION_LENGTH, VersionInfo.GetVersionString("0.0.0", flavour).Length, "0.0.0/" + flavour + " failed");
}
}
}
}
| {
"content_hash": "4c490eab019afd7d12bc0d890cff8c62",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 184,
"avg_line_length": 29.75,
"alnum_prop": 0.6470588235294118,
"repo_name": "allquixotic/opensim-autobackup",
"id": "49e5061316f9450e937e53048908956f510b87a7",
"size": "2450",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "OpenSim/Framework/Servers/Tests/VersionInfoTests.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C#",
"bytes": "14971534"
},
{
"name": "JavaScript",
"bytes": "556"
},
{
"name": "PHP",
"bytes": "1640"
},
{
"name": "Perl",
"bytes": "3578"
},
{
"name": "Python",
"bytes": "5053"
},
{
"name": "Shell",
"bytes": "2243"
}
],
"symlink_target": ""
} |
8x8x8 LED Cube für Arduino Uno Rev3
[](https://github.com/fuchsalex/Smart-Mirror/blob/master/LICENSE)
## Beschreibung
Ein LED Cube ist eine kubische Anordnung von LEDs. Die Größenordnungen liegen bei 3x3x3 bis über 10x10x10.
Die Fertigung ist sehr Zeitaufwendig, da die Anschlüsse jeder LED in Form gebracht werden müssen. Desweiteren müssen die Lötarbeiten präzise durchgeführt werden, damit am Schluss der Cube gerade steht.
Die Ansteuerung der 512 LEDs erfolgt über den Arduino.
Die Kathoden werden über ein Darlington-Array auf Masse geschalten.
Die Anoden werden über 8 Schieberegister, die durch Kaskadierung miteinander verbunden sind, auf Vcc geschaltet.
Ein Demo vom fertigen Cube kann [:warning:in Arbeit...] betrachtet werden.
## Dokumentation
:warning: Inhalt in Arbeit...
## Simulation
Der Schaltungsaufbau inklusive Arduino Uno ist in Proteus simuliert.
Die Simulation ist auf 3 Seiten aufgeteilt:
- [Sheet 1] Platinenaufbau
- [Sheet 2] Analyse der Steuerleitungen
- [Sheet 3] Ansteuerung der 512 LEDs
[Simulation](https://github.com/fuchsalex/LED-Cube/tree/master/Simulation)
## Funktionstest
Um die Funktionalität der einzelnen LEDs zu überprüfen wird das [Testprogramm](https://github.com/fuchsalex/LED-Cube/blob/master/Sourcecode/LED_CUBE_Testprogramm.ino) in den Microcontroller geladen.
Dabei wird jede LED für kurze Dauer beschalten. Sollte hier eine LED nicht leuchten, so liegt entweder ein Fehler in der Platine vor oder die Leuchtdiode ist defekt.
## Programmcode
Ist der Cube auf funktionsfähigkeit geprüft, so kann der [Programmcode](https://github.com/fuchsalex/LED-Cube/blob/master/Sourcecode/LED_CUBE_source.ino) in den Microcontroller geladen werden.
### Autor

### Lizenz
MIT
### Info
Die Anfertigung eines eigenen LED Cube wurde inspiriert von [ChrisB](http://ledcubeblog.blogspot.co.at/).
| {
"content_hash": "3066ebd797d4984e58ce3498fb137bb1",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 201,
"avg_line_length": 42.148936170212764,
"alnum_prop": 0.7945482079757699,
"repo_name": "fuchsalex/LED-Cube",
"id": "3ecf47477cf39865d09e29ca21004b3aca881fae",
"size": "2012",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Arduino",
"bytes": "111912"
}
],
"symlink_target": ""
} |
FOUNDATION_EXPORT NSString * const kCALayerKeyPathTransformRotation;
FOUNDATION_EXPORT NSString * const kCALayerKeyPathTransformRotationX;
FOUNDATION_EXPORT NSString * const kCALayerKeyPathTransformRotationY;
FOUNDATION_EXPORT NSString * const kCALayerKeyPathTransformRotationZ;
FOUNDATION_EXPORT NSString * const kCALayerKeyPathTransformScale;
FOUNDATION_EXPORT NSString * const kCALayerKeyPathTransformScaleX;
FOUNDATION_EXPORT NSString * const kCALayerKeyPathTransformScaleY;
FOUNDATION_EXPORT NSString * const kCALayerKeyPathTransformScaleZ;
FOUNDATION_EXPORT NSString * const kCALayerKeyPathTransformTranslationX;
FOUNDATION_EXPORT NSString * const kCALayerKeyPathTransformTranslationY;
FOUNDATION_EXPORT NSString * const kCALayerKeyPathTransformTranslationZ;
@interface CALayer (BSCategory)
@property (assign, nonatomic) CGPoint bs_origin;
@property (assign, nonatomic) CGSize bs_size;
@property (assign, nonatomic) CGFloat bs_x;
@property (assign, nonatomic) CGFloat bs_y;
@property (assign, nonatomic) CGFloat bs_positionX;
@property (assign, nonatomic) CGFloat bs_positionY;
@property (assign, nonatomic) CGFloat bs_width;
@property (assign, nonatomic) CGFloat bs_height;
- (CGFloat)bs_minX;
- (CGFloat)bs_midX;
- (CGFloat)bs_maxX;
- (CGFloat)bs_minY;
- (CGFloat)bs_midY;
- (CGFloat)bs_maxY;
@end
| {
"content_hash": "e488ec97697b3b08b351eb62533357f0",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 72,
"avg_line_length": 34.6578947368421,
"alnum_prop": 0.8200455580865603,
"repo_name": "blurryssky/BSCategories",
"id": "619ba66c0f6af11171bbad101a40257c15759ced",
"size": "1508",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BSCategoriesSample/BSCategories/CALayer+BSCategory.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "134801"
},
{
"name": "Ruby",
"bytes": "6287"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Function papi_get_taxonomy_label</title>
<link rel="stylesheet" href="resources/bootstrap.min.css?973e37a8502921d56bc02bb55321f45b072b6f71">
<link rel="stylesheet" href="resources/style.css?04121df963d959d8cb6f3057fccf1e8067c675b0">
</head>
<body>
<nav id="navigation" class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<a href="index.html" class="navbar-brand">
<img src="https://avatars0.githubusercontent.com/u/6768662?s=200">
</a>
</div>
<div class="collapse navbar-collapse">
<form id="search" class="navbar-form navbar-left" role="search">
<input type="hidden" name="cx" value="">
<input type="hidden" name="ie" value="UTF-8">
<div class="form-group">
<input type="text" name="q" class="search-query form-control" placeholder="Search">
</div>
</form>
<ul class="nav navbar-nav">
<li class="active">
<span>Function</span> </li>
<li class="divider-vertical"></li>
<li>
<a href="tree.html" title="Tree view of classes, interfaces, traits and exceptions"><span>Tree</span></a>
</li>
<li>
<a href="annotation-group-deprecated.html" title="List of elements with deprecated annotation">
<span>Deprecated</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
<div id="left">
<div id="menu">
<div id="groups">
</div>
<div id="elements">
<h3>Classes</h3>
<ul>
<li><a href="class-Papi_Admin.html">Papi_Admin</a></li>
<li><a href="class-Papi_Admin_Ajax.html">Papi_Admin_Ajax</a></li>
<li><a href="class-Papi_Admin_Assets.html">Papi_Admin_Assets</a></li>
<li><a href="class-Papi_Admin_Columns.html">Papi_Admin_Columns</a></li>
<li><a href="class-Papi_Admin_Menu.html">Papi_Admin_Menu</a></li>
<li><a href="class-Papi_Admin_Meta_Box.html">Papi_Admin_Meta_Box</a></li>
<li><a href="class-Papi_Admin_Meta_Box_Tabs.html">Papi_Admin_Meta_Box_Tabs</a></li>
<li><a href="class-Papi_Admin_Meta_Handler.html">Papi_Admin_Meta_Handler</a></li>
<li><a href="class-Papi_Admin_Option_Handler.html">Papi_Admin_Option_Handler</a></li>
<li><a href="class-Papi_Admin_Taxonomy.html">Papi_Admin_Taxonomy</a></li>
<li><a href="class-Papi_Admin_View.html">Papi_Admin_View</a></li>
<li><a href="class-Papi_Attachment_Type.html">Papi_Attachment_Type</a></li>
<li><a href="class-Papi_CLI.html">Papi_CLI</a></li>
<li><a href="class-Papi_CLI_Command.html">Papi_CLI_Command</a></li>
<li><a href="class-Papi_CLI_Post_Command.html">Papi_CLI_Post_Command</a></li>
<li><a href="class-Papi_CLI_Term_Command.html">Papi_CLI_Term_Command</a></li>
<li><a href="class-Papi_CLI_Type_Command.html">Papi_CLI_Type_Command</a></li>
<li><a href="class-Papi_Conditional_Rules.html">Papi_Conditional_Rules</a></li>
<li><a href="class-Papi_Container.html">Papi_Container</a></li>
<li><a href="class-Papi_Core_Autoload.html">Papi_Core_Autoload</a></li>
<li><a href="class-Papi_Core_Box.html">Papi_Core_Box</a></li>
<li><a href="class-Papi_Core_Conditional.html">Papi_Core_Conditional</a></li>
<li><a href="class-Papi_Core_Conditional_Rule.html">Papi_Core_Conditional_Rule</a></li>
<li><a href="class-Papi_Core_Data_Handler.html">Papi_Core_Data_Handler</a></li>
<li><a href="class-Papi_Core_Meta_Store.html">Papi_Core_Meta_Store</a></li>
<li><a href="class-Papi_Core_Property.html">Papi_Core_Property</a></li>
<li><a href="class-Papi_Core_Tab.html">Papi_Core_Tab</a></li>
<li><a href="class-Papi_Core_Type.html">Papi_Core_Type</a></li>
<li><a href="class-Papi_Entry_Type.html">Papi_Entry_Type</a></li>
<li><a href="class-Papi_Loader.html">Papi_Loader</a></li>
<li><a href="class-Papi_Option_Store.html">Papi_Option_Store</a></li>
<li><a href="class-Papi_Option_Type.html">Papi_Option_Type</a></li>
<li><a href="class-Papi_Page_Type.html">Papi_Page_Type</a></li>
<li><a href="class-Papi_Porter.html">Papi_Porter</a></li>
<li><a href="class-Papi_Porter_Driver.html">Papi_Porter_Driver</a></li>
<li><a href="class-Papi_Porter_Driver_Core.html">Papi_Porter_Driver_Core</a></li>
<li><a href="class-Papi_Post_Store.html">Papi_Post_Store</a></li>
<li><a href="class-Papi_Property.html">Papi_Property</a></li>
<li><a href="class-Papi_Property_Bool.html">Papi_Property_Bool</a></li>
<li><a href="class-Papi_Property_Checkbox.html">Papi_Property_Checkbox</a></li>
<li><a href="class-Papi_Property_Color.html">Papi_Property_Color</a></li>
<li><a href="class-Papi_Property_Datetime.html">Papi_Property_Datetime</a></li>
<li><a href="class-Papi_Property_Divider.html">Papi_Property_Divider</a></li>
<li><a href="class-Papi_Property_Dropdown.html">Papi_Property_Dropdown</a></li>
<li><a href="class-Papi_Property_Editor.html">Papi_Property_Editor</a></li>
<li><a href="class-Papi_Property_Email.html">Papi_Property_Email</a></li>
<li><a href="class-Papi_Property_File.html">Papi_Property_File</a></li>
<li><a href="class-Papi_Property_Flexible.html">Papi_Property_Flexible</a></li>
<li><a href="class-Papi_Property_Gallery.html">Papi_Property_Gallery</a></li>
<li><a href="class-Papi_Property_Group.html">Papi_Property_Group</a></li>
<li><a href="class-Papi_Property_Hidden.html">Papi_Property_Hidden</a></li>
<li><a href="class-Papi_Property_Html.html">Papi_Property_Html</a></li>
<li><a href="class-Papi_Property_Image.html">Papi_Property_Image</a></li>
<li><a href="class-Papi_Property_Link.html">Papi_Property_Link</a></li>
<li><a href="class-Papi_Property_Number.html">Papi_Property_Number</a></li>
<li><a href="class-Papi_Property_Post.html">Papi_Property_Post</a></li>
<li><a href="class-Papi_Property_Radio.html">Papi_Property_Radio</a></li>
<li><a href="class-Papi_Property_Reference.html">Papi_Property_Reference</a></li>
<li><a href="class-Papi_Property_Relationship.html">Papi_Property_Relationship</a></li>
<li><a href="class-Papi_Property_Repeater.html">Papi_Property_Repeater</a></li>
<li><a href="class-Papi_Property_String.html">Papi_Property_String</a></li>
<li><a href="class-Papi_Property_Term.html">Papi_Property_Term</a></li>
<li><a href="class-Papi_Property_Text.html">Papi_Property_Text</a></li>
<li><a href="class-Papi_Property_Url.html">Papi_Property_Url</a></li>
<li><a href="class-Papi_Property_User.html">Papi_Property_User</a></li>
<li><a href="class-Papi_Taxonomy_Type.html">Papi_Taxonomy_Type</a></li>
<li><a href="class-Papi_Term_Store.html">Papi_Term_Store</a></li>
</ul>
<h3>Functions</h3>
<ul>
<li><a href="function-papi.html">papi</a></li>
<li><a href="function-papi_action_delete_value.html">papi_action_delete_value</a></li>
<li><a href="function-papi_append_post_type_query.html">papi_append_post_type_query</a></li>
<li><a href="function-papi_body_class.html">papi_body_class</a></li>
<li><a href="function-papi_cache_delete.html">papi_cache_delete</a></li>
<li><a href="function-papi_cache_get.html">papi_cache_get</a></li>
<li><a href="function-papi_cache_key.html">papi_cache_key</a></li>
<li><a href="function-papi_cache_set.html">papi_cache_set</a></li>
<li><a href="function-papi_camel_case.html">papi_camel_case</a></li>
<li><a href="function-papi_cast_string_value.html">papi_cast_string_value</a></li>
<li><a href="function-papi_convert_to_string.html">papi_convert_to_string</a></li>
<li><a href="function-papi_current_user_is_allowed.html">papi_current_user_is_allowed</a></li>
<li><a href="function-papi_delete_field.html">papi_delete_field</a></li>
<li><a href="function-papi_delete_option.html">papi_delete_option</a></li>
<li><a href="function-papi_delete_property_meta_value.html">papi_delete_property_meta_value</a></li>
<li><a href="function-papi_delete_term_field.html">papi_delete_term_field</a></li>
<li><a href="function-papi_display_page_type.html">papi_display_page_type</a></li>
<li><a href="function-papi_doing_ajax.html">papi_doing_ajax</a></li>
<li><a href="function-papi_entry_type_exists.html">papi_entry_type_exists</a></li>
<li><a href="function-papi_esc_html.html">papi_esc_html</a></li>
<li><a href="function-papi_f.html">papi_f</a></li>
<li><a href="function-papi_field_shortcode.html">papi_field_shortcode</a></li>
<li><a href="function-papi_field_value.html">papi_field_value</a></li>
<li><a href="function-papi_filter_conditional_rule_allowed.html">papi_filter_conditional_rule_allowed</a></li>
<li><a href="function-papi_filter_format_value.html">papi_filter_format_value</a></li>
<li><a href="function-papi_filter_load_value.html">papi_filter_load_value</a></li>
<li><a href="function-papi_filter_settings_directories.html">papi_filter_settings_directories</a></li>
<li><a href="function-papi_filter_settings_only_page_type.html">papi_filter_settings_only_page_type</a></li>
<li><a href="function-papi_filter_settings_only_taxonomy_type.html">papi_filter_settings_only_taxonomy_type</a></li>
<li><a href="function-papi_filter_settings_show_page_type.html">papi_filter_settings_show_page_type</a></li>
<li><a href="function-papi_filter_settings_show_standard_page_type.html">papi_filter_settings_show_standard_page_type</a></li>
<li><a href="function-papi_filter_settings_show_standard_page_type_in_filter.html">papi_filter_settings_show_standard_page_type_in_filter</a></li>
<li><a href="function-papi_filter_settings_show_standard_taxonomy_type.html">papi_filter_settings_show_standard_taxonomy_type</a></li>
<li><a href="function-papi_filter_settings_sort_order.html">papi_filter_settings_sort_order</a></li>
<li><a href="function-papi_filter_settings_standard_page_type_description.html">papi_filter_settings_standard_page_type_description</a></li>
<li><a href="function-papi_filter_settings_standard_page_type_name.html">papi_filter_settings_standard_page_type_name</a></li>
<li><a href="function-papi_filter_settings_standard_page_type_thumbnail.html">papi_filter_settings_standard_page_type_thumbnail</a></li>
<li><a href="function-papi_filter_settings_standard_taxonomy_type_name.html">papi_filter_settings_standard_taxonomy_type_name</a></li>
<li><a href="function-papi_filter_update_value.html">papi_filter_update_value</a></li>
<li><a href="function-papi_from_property_array_slugs.html">papi_from_property_array_slugs</a></li>
<li><a href="function-papi_get_all_core_type_files.html">papi_get_all_core_type_files</a></li>
<li><a href="function-papi_get_all_entry_types.html">papi_get_all_entry_types</a></li>
<li><a href="function-papi_get_all_files_in_directory.html">papi_get_all_files_in_directory</a></li>
<li><a href="function-papi_get_all_page_types.html">papi_get_all_page_types</a></li>
<li><a href="function-papi_get_class_name.html">papi_get_class_name</a></li>
<li><a href="function-papi_get_core_type_base_path.html">papi_get_core_type_base_path</a></li>
<li><a href="function-papi_get_core_type_file_path.html">papi_get_core_type_file_path</a></li>
<li><a href="function-papi_get_entry_type.html">papi_get_entry_type</a></li>
<li><a href="function-papi_get_entry_type_by_id.html">papi_get_entry_type_by_id</a></li>
<li><a href="function-papi_get_entry_type_by_meta_id.html">papi_get_entry_type_by_meta_id</a></li>
<li><a href="function-papi_get_entry_type_count.html">papi_get_entry_type_count</a></li>
<li><a href="function-papi_get_entry_type_css_class.html">papi_get_entry_type_css_class</a></li>
<li><a href="function-papi_get_entry_type_id.html">papi_get_entry_type_id</a></li>
<li><a href="function-papi_get_entry_type_template.html">papi_get_entry_type_template</a></li>
<li><a href="function-papi_get_field.html">papi_get_field</a></li>
<li><a href="function-papi_get_file_path.html">papi_get_file_path</a></li>
<li><a href="function-papi_get_meta_id.html">papi_get_meta_id</a></li>
<li><a href="function-papi_get_meta_id_column.html">papi_get_meta_id_column</a></li>
<li><a href="function-papi_get_meta_store.html">papi_get_meta_store</a></li>
<li><a href="function-papi_get_meta_type.html">papi_get_meta_type</a></li>
<li><a href="function-papi_get_only_objects.html">papi_get_only_objects</a></li>
<li><a href="function-papi_get_option.html">papi_get_option</a></li>
<li><a href="function-papi_get_options_and_properties.html">papi_get_options_and_properties</a></li>
<li><a href="function-papi_get_or_post.html">papi_get_or_post</a></li>
<li><a href="function-papi_get_page.html">papi_get_page</a></li>
<li><a href="function-papi_get_page_new_url.html">papi_get_page_new_url</a></li>
<li><a href="function-papi_get_page_type_id.html">papi_get_page_type_id</a></li>
<li><a href="function-papi_get_page_type_key.html">papi_get_page_type_key</a></li>
<li><a href="function-papi_get_page_type_name.html">papi_get_page_type_name</a></li>
<li><a href="function-papi_get_parent_post_id.html">papi_get_parent_post_id</a></li>
<li><a href="function-papi_get_post_id.html">papi_get_post_id</a></li>
<li><a href="function-papi_get_post_type.html">papi_get_post_type</a></li>
<li><a href="function-papi_get_post_type_label.html">papi_get_post_type_label</a></li>
<li><a href="function-papi_get_post_types.html">papi_get_post_types</a></li>
<li><a href="function-papi_get_property_class_name.html">papi_get_property_class_name</a></li>
<li><a href="function-papi_get_property_meta_value.html">papi_get_property_meta_value</a></li>
<li><a href="function-papi_get_property_type.html">papi_get_property_type</a></li>
<li><a href="function-papi_get_property_type_key.html">papi_get_property_type_key</a></li>
<li><a href="function-papi_get_property_type_key_f.html">papi_get_property_type_key_f</a></li>
<li><a href="function-papi_get_qs.html">papi_get_qs</a></li>
<li><a href="function-papi_get_sanitized_post.html">papi_get_sanitized_post</a></li>
<li><a href="function-papi_get_slugs.html">papi_get_slugs</a></li>
<li><a href="function-papi_get_taxonomies.html">papi_get_taxonomies</a></li>
<li><a href="function-papi_get_taxonomy.html">papi_get_taxonomy</a></li>
<li class="active"><a href="function-papi_get_taxonomy_label.html">papi_get_taxonomy_label</a></li>
<li><a href="function-papi_get_taxonomy_type_id.html">papi_get_taxonomy_type_id</a></li>
<li><a href="function-papi_get_taxonomy_type_name.html">papi_get_taxonomy_type_name</a></li>
<li><a href="function-papi_get_template_file_name.html">papi_get_template_file_name</a></li>
<li><a href="function-papi_get_term_field.html">papi_get_term_field</a></li>
<li><a href="function-papi_get_term_id.html">papi_get_term_id</a></li>
<li><a href="function-papi_get_term_slugs.html">papi_get_term_slugs</a></li>
<li><a href="function-papi_html_name.html">papi_html_name</a></li>
<li><a href="function-papi_html_tag.html">papi_html_tag</a></li>
<li><a href="function-papi_include_query_strings.html">papi_include_query_strings</a></li>
<li><a href="function-papi_include_template.html">papi_include_template</a></li>
<li><a href="function-papi_is_empty.html">papi_is_empty</a></li>
<li><a href="function-papi_is_json.html">papi_is_json</a></li>
<li><a href="function-papi_is_method.html">papi_is_method</a></li>
<li><a href="function-papi_is_option_type.html">papi_is_option_type</a></li>
<li><a href="function-papi_is_page_type.html">papi_is_page_type</a></li>
<li><a href="function-papi_is_property.html">papi_is_property</a></li>
<li><a href="function-papi_is_property_type_key.html">papi_is_property_type_key</a></li>
<li><a href="function-papi_is_rule.html">papi_is_rule</a></li>
<li><a href="function-papi_load_page_type_id.html">papi_load_page_type_id</a></li>
<li><a href="function-papi_load_taxonomy_type_id.html">papi_load_taxonomy_type_id</a></li>
<li><a href="function-papi_maybe_convert_to_array.html">papi_maybe_convert_to_array</a></li>
<li><a href="function-papi_maybe_convert_to_object.html">papi_maybe_convert_to_object</a></li>
<li><a href="function-papi_maybe_get_callable_value.html">papi_maybe_get_callable_value</a></li>
<li><a href="function-papi_maybe_json_decode.html">papi_maybe_json_decode</a></li>
<li><a href="function-papi_maybe_json_encode.html">papi_maybe_json_encode</a></li>
<li><a href="function-papi_nl2br.html">papi_nl2br</a></li>
<li><a href="function-papi_option_shortcode.html">papi_option_shortcode</a></li>
<li><a href="function-papi_option_type_exists.html">papi_option_type_exists</a></li>
<li><a href="function-papi_populate_properties.html">papi_populate_properties</a></li>
<li><a href="function-papi_property.html">papi_property</a></li>
<li><a href="function-papi_remove_trailing_quotes.html">papi_remove_trailing_quotes</a></li>
<li><a href="function-papi_render_html_tag.html">papi_render_html_tag</a></li>
<li><a href="function-papi_render_properties.html">papi_render_properties</a></li>
<li><a href="function-papi_render_property.html">papi_render_property</a></li>
<li><a href="function-papi_require_text.html">papi_require_text</a></li>
<li><a href="function-papi_required_html.html">papi_required_html</a></li>
<li><a href="function-papi_rule.html">papi_rule</a></li>
<li><a href="function-papi_santize_data.html">papi_santize_data</a></li>
<li><a href="function-papi_set_page_type_id.html">papi_set_page_type_id</a></li>
<li><a href="function-papi_set_taxonomy_type_id.html">papi_set_taxonomy_type_id</a></li>
<li><a href="function-papi_slugify.html">papi_slugify</a></li>
<li><a href="function-papi_sort_order.html">papi_sort_order</a></li>
<li><a href="function-papi_supports_term_meta.html">papi_supports_term_meta</a></li>
<li><a href="function-papi_tab.html">papi_tab</a></li>
<li><a href="function-papi_tabs_setup.html">papi_tabs_setup</a></li>
<li><a href="function-papi_taxonomy_shortcode.html">papi_taxonomy_shortcode</a></li>
<li><a href="function-papi_template.html">papi_template</a></li>
<li><a href="function-papi_template_include.html">papi_template_include</a></li>
<li><a href="function-papi_to_array.html">papi_to_array</a></li>
<li><a href="function-papi_to_property_array_slugs.html">papi_to_property_array_slugs</a></li>
<li><a href="function-papi_underscorify.html">papi_underscorify</a></li>
<li><a href="function-papi_update_field.html">papi_update_field</a></li>
<li><a href="function-papi_update_option.html">papi_update_option</a></li>
<li><a href="function-papi_update_property_meta_value.html">papi_update_property_meta_value</a></li>
<li><a href="function-papi_update_property_meta_value_cache_delete.html">papi_update_property_meta_value_cache_delete</a></li>
<li><a href="function-papi_update_term_field.html">papi_update_term_field</a></li>
<li><a href="function-papify.html">papify</a></li>
<li><a href="function-the_papi_field.html">the_papi_field</a></li>
<li><a href="function-the_papi_option.html">the_papi_option</a></li>
<li><a href="function-the_papi_page_type_name.html">the_papi_page_type_name</a></li>
<li><a href="function-the_papi_taxonomy_type_name.html">the_papi_taxonomy_type_name</a></li>
<li><a href="function-the_papi_term_field.html">the_papi_term_field</a></li>
<li><a href="function-unpapify.html">unpapify</a></li>
</ul>
</div>
</div>
</div>
<div id="splitter"></div>
<div id="right">
<div id="rightInner">
<div id="content" class="function">
<h1>Function papi_get_taxonomy_label</h1>
<div class="description">
<p>Get taxonomy label.</p>
</div>
<div class="alert alert-info">
<b>Located at</b>
<a href="source-function-papi_get_taxonomy_label.html#57-72" title="Go to source code">
lib/core/taxonomy.php
</a><br>
</div>
<div class="panel panel-default">
<div class="panel-heading"><h2>Parameters summary</h2></div>
<table class="summary table table-bordered table-striped" id="parameters">
<tr id="$taxonomy">
<td class="name"><code>string</code></td>
<td class="value"><code><var>$taxonomy</var></code></td>
<td></td>
</tr>
<tr id="$label">
<td class="name"><code>string</code></td>
<td class="value"><code><var>$label</var></code></td>
<td></td>
</tr>
<tr id="$default">
<td class="name"><code>string</code></td>
<td class="value"><code><var>$default</var> = <span class="php-quote">''</span></code></td>
<td></td>
</tr>
</table>
</div>
<div class="panel panel-default">
<div class="panel-heading"><h2>Return value summary</h2></div>
<table class="summary table table-bordered table-striped" id="returns">
<tr>
<td class="name"><code>
string
</code></td>
<td>
string
</td>
</tr>
</table>
</div>
</div>
</div>
<div id="footer">
API documentation generated by <a href="http://apigen.org">ApiGen</a>
</div>
</div>
<script src="resources/combined.js?9b8db01807155719f944ec714a0c3d3f91b613ef"></script>
<script src="elementlist.js?1e7a1dbe5a3ef66df9e86bd9a31fbfa70132e428"></script>
</body>
</html>
| {
"content_hash": "3243757ad7cb715131674cd93f5d8a0e",
"timestamp": "",
"source": "github",
"line_count": 358,
"max_line_length": 150,
"avg_line_length": 59.952513966480446,
"alnum_prop": 0.6714345618040348,
"repo_name": "wp-papi/wp-papi.github.io",
"id": "79a1d13cb9336e647be7a7aa12cdeccf2e9a67f5",
"size": "21463",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/apigen/function-papi_get_taxonomy_label.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "17584"
},
{
"name": "HTML",
"bytes": "12394"
},
{
"name": "JavaScript",
"bytes": "1223"
}
],
"symlink_target": ""
} |
package org.apache.hadoop.yarn.server.resourcemanager.scheduler;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.metrics2.MetricsSystem;
import org.apache.hadoop.metrics2.annotation.Metrics;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CSQueue;
@Metrics(context = "yarn")
public class PartitionQueueMetrics extends QueueMetrics {
private String partition;
protected PartitionQueueMetrics(MetricsSystem ms, String queueName,
Queue parent, boolean enableUserMetrics, Configuration conf,
String partition) {
super(ms, queueName, parent, enableUserMetrics, conf);
this.partition = partition;
if (getParentQueue() != null) {
String newQueueName = (getParentQueue() instanceof CSQueue)
? ((CSQueue) getParentQueue()).getQueuePath()
: getParentQueue().getQueueName();
String parentMetricName =
partition + METRIC_NAME_DELIMITER + newQueueName;
setParent(getQueueMetrics().get(parentMetricName));
}
}
/**
* Partition * Queue * User Metrics
*
* Computes Metrics at Partition (Node Label) * Queue * User Level.
*
* Sample JMX O/P Structure:
*
* PartitionQueueMetrics (labelX)
* QueueMetrics (A)
* usermetrics
* QueueMetrics (A1)
* usermetrics
* QueueMetrics (A2)
* usermetrics
* QueueMetrics (B)
* usermetrics
*
* @return QueueMetrics
*/
@Override
public synchronized QueueMetrics getUserMetrics(String userName) {
if (users == null) {
return null;
}
String partitionJMXStr =
(partition.equals(DEFAULT_PARTITION)) ? DEFAULT_PARTITION_JMX_STR
: partition;
QueueMetrics metrics = (PartitionQueueMetrics) users.get(userName);
if (metrics == null) {
metrics = new PartitionQueueMetrics(this.metricsSystem, this.queueName,
null, false, this.conf, this.partition);
users.put(userName, metrics);
metricsSystem.register(
pSourceName(partitionJMXStr).append(qSourceName(queueName))
.append(",user=").append(userName).toString(),
"Metrics for user '" + userName + "' in queue '" + queueName + "'",
((PartitionQueueMetrics) metrics.tag(PARTITION_INFO, partitionJMXStr)
.tag(QUEUE_INFO, queueName)).tag(USER_INFO, userName));
}
return metrics;
}
}
| {
"content_hash": "e9b6212f2ad6eb7033ac0d50091ef3db",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 80,
"avg_line_length": 32.76712328767123,
"alnum_prop": 0.6743311036789298,
"repo_name": "nandakumar131/hadoop",
"id": "f43131809a0caebd912051ffc3730cb486a0d72d",
"size": "3198",
"binary": false,
"copies": "4",
"ref": "refs/heads/trunk",
"path": "hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/PartitionQueueMetrics.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "78118"
},
{
"name": "C",
"bytes": "1963896"
},
{
"name": "C++",
"bytes": "2858990"
},
{
"name": "CMake",
"bytes": "114811"
},
{
"name": "CSS",
"bytes": "117127"
},
{
"name": "Dockerfile",
"bytes": "8160"
},
{
"name": "HTML",
"bytes": "401158"
},
{
"name": "Java",
"bytes": "91592443"
},
{
"name": "JavaScript",
"bytes": "1175143"
},
{
"name": "Python",
"bytes": "77552"
},
{
"name": "Roff",
"bytes": "8817"
},
{
"name": "Shell",
"bytes": "467526"
},
{
"name": "TLA",
"bytes": "14997"
},
{
"name": "TSQL",
"bytes": "30600"
},
{
"name": "TeX",
"bytes": "19322"
},
{
"name": "XSLT",
"bytes": "18026"
}
],
"symlink_target": ""
} |
package com.tec.os.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.tec.os.model.Procedimento;
public interface ProcedimentoRepository extends JpaRepository<Procedimento, Long> {
@Query("SELECT a FROM Procedimento a WHERE a.descricao LIKE %:descricao%")
List<Procedimento> findByDescricao(@Param("descricao")String descricao);
}
| {
"content_hash": "ded62076e7df844c9e3bf85185dfb694",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 83,
"avg_line_length": 25.75,
"alnum_prop": 0.8,
"repo_name": "alciosilva/ficha",
"id": "5b495c45aa7139a5ba08eab87c8649ae7540425f",
"size": "515",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ficha/src/main/java/com/tec/os/repository/ProcedimentoRepository.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "5006"
},
{
"name": "CSS",
"bytes": "229080"
},
{
"name": "HTML",
"bytes": "20265"
},
{
"name": "Java",
"bytes": "12309"
},
{
"name": "JavaScript",
"bytes": "465036"
},
{
"name": "Shell",
"bytes": "7058"
}
],
"symlink_target": ""
} |
API Conventions
===============
The conventions of the Kubernetes API (and related APIs in the ecosystem) are intended to ease client development and ensure that configuration mechanisms can be implemented that work across a diverse set of use cases consistently.
The general style of the Kubernetes API is RESTful - clients create, update, delete, or retrieve a description of an object via the standard HTTP verbs (POST, PUT, DELETE, and GET) - and those APIs preferentially accept and return JSON. Kubernetes also exposes additional endpoints for non-standard verbs and allows alternative content types.
The following terms are defined:
* **Endpoint** a URL on an HTTP server that modifies, retrieves, or transforms a Resource.
* **Resource** an object manipulated via an HTTP action in an API
* **Kind** a resource has a string that identifies the schema of the JSON used (e.g. a "Car" and a "Dog" would have different attributes and properties)
Types of Resources
------------------
All API resources are either:
1. **Objects** represents a physical or virtual construct in the system
An API object resource is a record of intent - once created, the system will work to ensure that resource exists. All API objects have common metadata intended for client use.
2. **Lists** are collections of **objects** of one or more types
Lists have a limited set of common metadata. All lists use the "items" field to contain the array of objects they return. Each resource kind should have an endpoint that returns the full set of resources, as well as zero or more endpoints that return subsets of the full list.
In addition, all lists that return objects with labels should support label filtering (see [labels.md](labels.md), and most lists should support filtering by fields.
TODO: Describe field filtering below or in a separate doc.
The standard REST verbs (defined below) MUST return singular JSON objects. Some API endpoints may deviate from the strict REST pattern and return resources that are not singular JSON objects, such as streams of JSON objects or unstructured text log data.
### Resources
All singular JSON resources returned by an API MUST have the following fields:
* kind: a string that identifies the schema this object should have
* apiVersion: a string that identifiers the version of the schema the object should have
### Objects
Every object MUST have the following metadata in a nested object field called "metadata":
* namespace: a namespace is a DNS compatible subdomain that objects are subdivided into. The default namespace is 'default'. See [namespaces.md](namespaces.md) for more.
* name: a string that uniquely identifies this object within the current namespace (see [identifiers.md](identifiers.md)). This value is used in the path when retrieving an individual object.
* uid: a unique in time and space value (typically an RFC 4122 generated identifier, see [identifiers.md](identifiers.md)) used to distinguish between objects with the same name that have been deleted and recreated
Every object SHOULD have the following metadata in a nested object field called "metadata":
* resourceVersion: a string that identifies the internal version of this object that can be used by clients to determine when objects have changed. This value MUST be treated as opaque by clients and passed unmodified back to the server. Clients should not assume that the resource version has meaning across namespaces, different kinds of resources, or different servers.
* creationTimestamp: a string representing an RFC 3339 date of the date and time an object was created
* labels: a map of string keys and values that can be used to organize and categorize objects (see [labels.md](labels.md))
* annotations: a map of string keys and values that can be used by external tooling to store and retrieve arbitrary metadata about this object (see [annotations.md](annotations.md))
Labels are intended for organizational purposes by end users (select the pods that match this label query). Annotations enable third party automation and tooling to decorate objects with additional metadata for their own use.
By convention, the Kubernetes API makes a distinction between the specification of a resource (a nested object field called "spec") and the status of the resource at the current time (a nested object field called "status"). The specification is persisted in stable storage with the API object and reflects user input. The status is generated at runtime and summarizes the current effect that the spec has on the system, and is ignored on user input. The PUT and POST verbs will ignore the "status" values.
For example, a pod object has a "spec" field that defines how the pod should be run. The pod also has a "status" field that shows details about what is happening on the host that is running the containers in the pod (if available) and a summarized "status" string that can guide callers as to the overall state of their pod.
### Lists
Every list SHOULD have the following metadata in a nested object field called "metadata":
* resourceVersion: a string that identifies the common version of the objects returned by in a list. This value MUST be treated as opaque by clients and passed unmodified back to the server. A resource version is only valid within a single namespace on a single kind of resource.
Special Resources
-----------------
Kubernetes MAY return two resources from any API endpoint in special circumstances. Clients SHOULD handle these types of objects when appropriate.
A "Status" object SHOULD be returned by an API when an operation is not successful (when the server would return a non 2xx HTTP status code). The status object contains fields for humans and machine consumers of the API to determine failures. The information in the status object supplements, but does not override, the HTTP status code's meaning.
An "Operation" object MAY be returned by any non-GET API if the operation may take a significant amount of time. The name of the Operation may be used to retrieve the final result of an operation at a later time.
TODO: Use SelfLink to retrieve operation instead.
Synthetic Resources
-------------------
An API may represent a single object in different ways for different clients, or transform an object after certain transitions in the system occur. In these cases, one request object may have two representations available as different resource kinds. An example is a Pod, which represents the intent of the user to run a container with certain parameters. When Kubernetes schedules the Pod, it creates a Binding object that ties that Pod to a single host in the system. After this occurs, the pod is represented by two distinct resources - under the original Pod resource the user created, as well as in a BoundPods object that the host may query but not update.
Verbs on Resources
------------------
API resources should use the traditional REST pattern:
* GET /<resourceNamePlural> - Retrieve a list of type <resourceName>, e.g. GET /pods returns a list of Pods
* POST /<resourceNamePlural> - Create a new resource from the JSON object provided by the client
* GET /<resourceNamePlural>/<name> - Retrieves a single resource with the given name, e.g. GET /pods/first returns a Pod named 'first'
* DELETE /<resourceNamePlural>/<name> - Delete the single resource with the given name
* PUT /<resourceNamePlural>/<name> - Update or create the resource with the given name with the JSON object provided by the client
Kubernetes by convention exposes additional verbs as new endpoints with singular names. Examples:
* GET /watch/<resourceNamePlural> - Receive a stream of JSON objects corresponding to changes made to any resource of the given kind over time.
* GET /watch/<resourceNamePlural>/<name> - Receive a stream of JSON objects corresponding to changes made to the named resource of the given kind over time
* GET /redirect/<resourceNamePlural>/<name> - If the named resource can be described by a URL, return an HTTP redirect to that URL instead of a JSON response. For example, a service exposes a port and IP address and a client could invoke the redirect verb to receive an HTTP 307 redirection to that port and IP.
Support of additional verbs is not required for all object types.
Idempotency
-----------
All compatible Kubernetes APIs MUST support "name idempotency" and respond with an HTTP status code 409 when a request is made to POST an object that has the same name as an existing object in the system. See [identifiers.md](identifiers.md) for details.
TODO: name generation
APIs SHOULD set resourceVersion on retrieved resources, and support PUT idempotency by rejecting HTTP requests with a 409 HTTP status code where an HTTP header `If-Match: resourceVersion=` or `?resourceVersion=` query parameter are set and do not match the currently stored version of the resource.
TODO: better syntax?
Serialization Format
--------------------
APIs may return alternative representations of any resource in response to an Accept header or under alternative endpoints, but the default serialization for input and output of API responses MUST be JSON.
All dates should be serialized as RFC3339 strings.
Selecting Fields
----------------
Some APIs may need to identify which field in a JSON object is invalid, or to reference a value to extract from a separate resource. The current recommendation is to use standard JavaScript syntax for accessing that field, assuming the JSON object was transformed into a JavaScript object.
Examples:
* Find the field "current" in the object "state" in the second item in the array "fields": `fields[0].state.current`
TODO: Plugins, extensions, nested kinds, headers | {
"content_hash": "b2b099682252e04fc41594ea12be5d98",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 662,
"avg_line_length": 72.17037037037036,
"alnum_prop": 0.7825105203736016,
"repo_name": "matttproud/kubernetes",
"id": "1ccd410cc8a4d56e0ce5a8fdbb18d9046cf3ea41",
"size": "9743",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/api-conventions.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package networks;
/**
*
* @author mars
*/
public class TestEmployee {
public static void main(String[] args) {
Employee SnEmployee = new Employee();
Employee JnEmployee = new Employee();
SnEmployee.setFirstName("Evanson");
System.out.println(SnEmployee.getFirstName());
SnEmployee.setLastName("Mwangi");
System.out.println(SnEmployee.getLastName());
SnEmployee.setMonthlySalary(500000);
System.out.println(SnEmployee.getMonthlySalary());
System.out.println(SnEmployee);
JnEmployee.setFirstName("Kelly");
System.out.println(JnEmployee.getFirstName());
JnEmployee.setLastName("Rowland");
System.out.println(JnEmployee.getLastName());
JnEmployee.setMonthlySalary(100000);
System.out.println(JnEmployee.getMonthlySalary());
System.out.println(JnEmployee);
}
}
| {
"content_hash": "147ac688a36c714247420e4c6a2b66f7",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 79,
"avg_line_length": 32.81818181818182,
"alnum_prop": 0.6777469990766389,
"repo_name": "devopsmwas/javapractice",
"id": "49d845852afee8ebc6970a9456e256ba48803227",
"size": "1083",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "NetBeansProjects/practice/src/networks/TestEmployee.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "880128"
}
],
"symlink_target": ""
} |
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('structure', '0016_customerpermissionreview'),
]
operations = [
migrations.RemoveField(model_name='customer', name='is_company',),
]
| {
"content_hash": "0b169104f49ea8ae8ede6a42e5720baf",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 74,
"avg_line_length": 21.583333333333332,
"alnum_prop": 0.6602316602316602,
"repo_name": "opennode/nodeconductor-assembly-waldur",
"id": "6ef428be3cfbd0720dad1f0fda08efa155103ee7",
"size": "309",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "src/waldur_core/structure/migrations/0017_remove_customer_is_company.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1624"
},
{
"name": "Python",
"bytes": "412263"
},
{
"name": "Shell",
"bytes": "2031"
}
],
"symlink_target": ""
} |
#include <cstring>
#include <iostream>
#include <iterator>
#include <memory>
#include <string>
#include <vector>
#include <tinyxml2.h>
#include "libutils/log.h"
#include "libutils/io/preferences.h"
#include "libutils/io/xml_preferences_loader.h"
#include "libutils/str/encode_utils.h"
#include "libutils/str/str_utils.h"
using namespace std;
#define LU_NS_TAG "utils::io::"
#define LU_TAG LU_NS_TAG "XmlPreferencesLoader::"
namespace utils
{
namespace io
{
namespace
{
template<typename T>
struct PrimitiveSerializer
{
static string Serialize(const T value);
static T Unserialize(const string &value);
};
template<>
string PrimitiveSerializer<bool>::Serialize(const bool value)
{
return value ? "true" : "false";
}
template<typename T>
string PrimitiveSerializer<T>::Serialize(const T value)
{
return str::StrUtils::Concat(value);
}
template<>
bool PrimitiveSerializer<bool>::Unserialize(const string &value)
{
return (value == "true");
}
template<typename T>
T PrimitiveSerializer<T>::Unserialize(const string &value)
{
stringstream ss(value);
T v;
ss >> v;
return v;
}
inline void PutPrimitive(const wstring &key, const bool v,
const unique_ptr<Preferences::Editor> &edit)
{
edit->PutBool(key, v);
}
inline void PutPrimitive(const wstring &key, const float v,
const unique_ptr<Preferences::Editor> &edit)
{
edit->PutFloat(key, v);
}
inline void PutPrimitive(const wstring &key, const int v,
const unique_ptr<Preferences::Editor> &edit)
{
edit->PutInt(key, v);
}
inline void PutPrimitive(const wstring &key, const long v,
const unique_ptr<Preferences::Editor> &edit)
{
edit->PutLong(key, v);
}
class Impl
{
public:
static bool Load(const unique_ptr<Preferences::Editor> &edit, istream *read);
private:
template<typename T>
static bool LoadPrimitive(const tinyxml2::XMLElement *element,
const unique_ptr<Preferences::Editor> &edit);
static bool LoadString(const tinyxml2::XMLElement *element,
const unique_ptr<Preferences::Editor> &edit);
static bool LoadStringSet(const tinyxml2::XMLElement *element,
const unique_ptr<Preferences::Editor> &edit);
};
bool Impl::Load(const unique_ptr<Preferences::Editor> &edit, istream *read)
{
using namespace tinyxml2;
string content{istreambuf_iterator<char>(*read),
istreambuf_iterator<char>()};
XMLDocument doc;
if (doc.Parse(content.c_str()) != XML_NO_ERROR)
{
LU_LOG_E(LU_TAG "Load", "Failed while Parse");
return false;
}
auto map = doc.FirstChildElement("map");
if (!map)
{
LU_LOG_E(LU_TAG "Load", "map not found");
return false;
}
for (auto element = map->FirstChildElement(); element;
element = element->NextSiblingElement())
{
const char *type = element->Value();
if (!strcmp(type, "boolean") && !LoadPrimitive<bool>(element, edit))
{
LU_LOG_E(LU_TAG "Load", "Failed while loading bool");
}
else if (!strcmp(type, "float") && !LoadPrimitive<float>(element, edit))
{
LU_LOG_E(LU_TAG "Load", "Failed while loading float");
}
else if (!strcmp(type, "int") && !LoadPrimitive<int>(element, edit))
{
LU_LOG_E(LU_TAG "Load", "Failed while loading int");
}
else if (!strcmp(type, "long") && !LoadPrimitive<long>(element, edit))
{
LU_LOG_E(LU_TAG "Load", "Failed while loading long");
}
else if (!strcmp(type, "string") && !LoadString(element, edit))
{
LU_LOG_E(LU_TAG "Load", "Failed while loading string");
}
else if (!strcmp(type, "set") && !LoadStringSet(element, edit))
{
LU_LOG_E(LU_TAG "Load", "Failed while loading string set");
}
}
edit->CommitAndInvalidate();
return true;
}
template<typename T>
bool Impl::LoadPrimitive(const tinyxml2::XMLElement *element,
const unique_ptr<Preferences::Editor> &edit)
{
wstring key;
T value{};
bool is_has_value = false;
for (auto attr = element->FirstAttribute(); attr; attr = attr->Next())
{
const char *name = attr->Name();
if (!strcmp(name, "name"))
{
key = str::EncodeUtils::U8ToU16(attr->Value());
}
else if (!strcmp(name, "value"))
{
value = PrimitiveSerializer<T>::Unserialize(attr->Value());
is_has_value = true;
}
}
if (!key.empty() && is_has_value)
{
PutPrimitive(key, value, edit);
return true;
}
else
{
LU_LOG_E(LU_TAG "LoadString", "Invalid key/value");
return false;
}
}
bool Impl::LoadString(const tinyxml2::XMLElement *element,
const unique_ptr<Preferences::Editor> &edit)
{
auto attr = element->FindAttribute("name");
const char *text = element->GetText();
if (!attr || !text)
{
LU_LOG_E(LU_TAG "LoadString", "Invalid node");
return false;
}
wstring key = str::EncodeUtils::U8ToU16(attr->Value());
wstring textStr = str::EncodeUtils::U8ToU16(text);
if (!key.empty())
{
edit->PutString(key, std::move(textStr));
return true;
}
else
{
LU_LOG_E(LU_TAG "LoadString", "Invalid key");
return false;
}
}
bool Impl::LoadStringSet(const tinyxml2::XMLElement *element,
const unique_ptr<Preferences::Editor> &edit)
{
auto attr = element->FindAttribute("name");
if (!attr)
{
LU_LOG_E(LU_TAG "LoadString", "Invalid node");
return false;
}
wstring key = str::EncodeUtils::U8ToU16(attr->Value());
if (key.empty())
{
LU_LOG_E(LU_TAG "LoadString", "Invalid key");
return false;
}
vector<wstring> set;
for (auto child = element->FirstChildElement(); child;
child = child->NextSiblingElement())
{
if (!strcmp(child->Name(), "string"))
{
const char *text = child->GetText();
if (text)
{
set.push_back(str::EncodeUtils::U8ToU16(text));
}
}
}
edit->PutStringSet(key, std::move(set));
return true;
}
}
XmlPreferencesLoader::XmlPreferencesLoader(std::istream *read)
: m_read(read)
{}
XmlPreferencesLoader::~XmlPreferencesLoader()
{}
bool XmlPreferencesLoader::Load(const unique_ptr<Preferences::Editor> &edit)
{
return Impl::Load(edit, m_read);
}
}
}
| {
"content_hash": "8e4543aa03e7393260e949315a01990b",
"timestamp": "",
"source": "github",
"line_count": 264,
"max_line_length": 78,
"avg_line_length": 21.992424242424242,
"alnum_prop": 0.6822252841887703,
"repo_name": "nkming2/libutils",
"id": "eb7b98a22dbca28081d158cc6c30bb75eb68f105",
"size": "5932",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/libutils/io/xml_preferences_loader.cpp",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1549"
},
{
"name": "C++",
"bytes": "173418"
},
{
"name": "HTML",
"bytes": "2846"
},
{
"name": "JavaScript",
"bytes": "3705"
},
{
"name": "Perl",
"bytes": "3342"
},
{
"name": "Shell",
"bytes": "107"
}
],
"symlink_target": ""
} |
package org.dita.dost.store;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.Serializer;
import net.sf.saxon.s9api.XdmNode;
import org.dita.dost.exception.DITAOTException;
import org.dita.dost.util.XMLUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.w3c.dom.Document;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class StreamStoreTest {
@Rule
public final TemporaryFolder temporaryFolder = new TemporaryFolder();
private XMLUtils xmlUtils;
private StreamStore store;
private File tmpDir;
@Before
public void setUp() throws Exception {
xmlUtils = new XMLUtils();
tmpDir = temporaryFolder.newFolder();
store = new StreamStore(tmpDir, xmlUtils);
}
@Test
public void getSerializer_subDirectory() throws IOException, SaxonApiException {
final Document doc = XMLUtils.getDocumentBuilder().newDocument();
doc.appendChild(doc.createElement("foo"));
final XdmNode source = xmlUtils.getProcessor().newDocumentBuilder().wrap(doc);
final Serializer serializer = store.getSerializer(tmpDir.toURI().resolve("foo/bar"));
serializer.serializeNode(source);
}
@Test
public void exists_WhenFileExists_ShouldReturnTrue() throws IOException {
Files.write(tmpDir.toPath().resolve("dummy.xml"), "<dummy/>".getBytes(UTF_8));
assertTrue(store.exists(tmpDir.toPath().resolve("dummy.xml").toUri()));
}
@Test
public void exists_WhenFileIsMissing_ShouldReturnFalse() {
assertFalse(store.exists(tmpDir.toPath().resolve("missing.xml").toUri()));
}
@Test
public void exists_WhenInputIsHttp_ShouldReturnFalse() {
assertFalse(store.exists(URI.create("http://abc/def")));
}
@Test
public void copy_WhenFileExists_ShouldCreateCopy() throws IOException {
Files.write(tmpDir.toPath().resolve("src.xml"), "<dummy/>".getBytes(UTF_8));
store.copy(tmpDir.toPath().resolve("src.xml").toUri(), tmpDir.toPath().resolve("dst.xml").toUri());
assertTrue(Files.exists(tmpDir.toPath().resolve("src.xml")));
assertTrue(Files.exists(tmpDir.toPath().resolve("dst.xml")));
}
@Test(expected = IOException.class)
public void copy_WhenFileIsMissing_ShouldThrowException() throws IOException {
store.copy(tmpDir.toPath().resolve("src.xml").toUri(), tmpDir.toPath().resolve("dst.xml").toUri());
}
@Test(expected = IOException.class)
public void copy_WhenSrcIsHttp_ShouldThrowException() throws IOException {
store.copy(URI.create("http://src.xml"), tmpDir.toPath().resolve("dst.xml").toUri());
}
@Test(expected = IOException.class)
public void copy_WhenDstIsHttp_ShouldThrowException() throws IOException {
store.copy(tmpDir.toPath().resolve("src.xml").toUri(), URI.create("http://dst.xml"));
}
@Test
public void move_WhenFileExists_ShouldCreateCopy() throws IOException {
Files.write(tmpDir.toPath().resolve("src.xml"), "<dummy/>".getBytes(UTF_8));
store.move(tmpDir.toPath().resolve("src.xml").toUri(), tmpDir.toPath().resolve("dst.xml").toUri());
assertFalse(Files.exists(tmpDir.toPath().resolve("src.xml")));
assertTrue(Files.exists(tmpDir.toPath().resolve("dst.xml")));
}
@Test(expected = IOException.class)
public void move_WhenFileIsMissing_ShouldThrowException() throws IOException {
store.move(tmpDir.toPath().resolve("src.xml").toUri(), tmpDir.toPath().resolve("dst.xml").toUri());
}
@Test(expected = IOException.class)
public void move_WhenSrcIsHttp_ShouldThrowException() throws IOException {
store.move(URI.create("http://src.xml"), tmpDir.toPath().resolve("dst.xml").toUri());
}
@Test(expected = IOException.class)
public void move_WhenDstIsHttp_ShouldThrowException() throws IOException {
store.move(tmpDir.toPath().resolve("src.xml").toUri(), URI.create("http://dst.xml"));
}
@Test
public void transformWithAnchorInURIPath() throws IOException, DITAOTException, URISyntaxException {
final Path target = Paths.get(tmpDir.getAbsolutePath(), "source.xml");
Files.write(target, "<root/>".getBytes(StandardCharsets.UTF_8));
final URI uri = new URI(target.toUri().toString() + "#abc");
store.transform(uri, Collections.emptyList());
}
} | {
"content_hash": "de3833edd9c149a8f7269c910ada7b77",
"timestamp": "",
"source": "github",
"line_count": 129,
"max_line_length": 107,
"avg_line_length": 37.263565891472865,
"alnum_prop": 0.6979405034324943,
"repo_name": "shaneataylor/dita-ot",
"id": "fadccc94d6247c6fb36ae8198fec2436a6cee70b",
"size": "4968",
"binary": false,
"copies": "4",
"ref": "refs/heads/develop",
"path": "src/test/java/org/dita/dost/store/StreamStoreTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "10738"
},
{
"name": "C",
"bytes": "4336"
},
{
"name": "CSS",
"bytes": "60188"
},
{
"name": "HTML",
"bytes": "795861"
},
{
"name": "Java",
"bytes": "2404278"
},
{
"name": "JavaScript",
"bytes": "2246"
},
{
"name": "Shell",
"bytes": "16323"
},
{
"name": "XSLT",
"bytes": "2106965"
}
],
"symlink_target": ""
} |
import unittest
from unittest import mock
import wikipedia
from orangecontrib.text.wikipedia import WikipediaAPI
from orangecontrib.text.corpus import Corpus
class StopingMock(mock.Mock):
def __init__(self, allow_calls=0):
super().__init__()
self.allow_calls = allow_calls
self.call_count = 0
def __call__(self, *args, **kwargs):
self.call_count += 1
if self.call_count > self.allow_calls:
return True
else:
return False
class WikipediaTests(unittest.TestCase):
def test_search(self):
on_progress = mock.MagicMock()
api = WikipediaAPI()
result = api.search('en', ['Clinton'], articles_per_query=2, on_progress=on_progress)
self.assertIsInstance(result, Corpus)
self.assertEquals(len(result.domain.attributes), 0)
self.assertEquals(len(result.domain.metas), 7)
self.assertEquals(len(result), 2)
self.assertEquals(on_progress.call_count, 2)
progress = 0
for arg in on_progress.call_args_list:
self.assertGreater(arg[0][0], progress)
progress = arg[0][0]
def test_search_disambiguation(self):
api = WikipediaAPI()
result = api.search('en', ['Scarf'], articles_per_query=3)
self.assertIsInstance(result, Corpus)
self.assertGreaterEqual(len(result), 3)
def test_search_break(self):
api = WikipediaAPI()
# stop immediately
result = api.search('en', ['Clinton'], articles_per_query=2,
should_break=mock.Mock(return_value=True))
self.assertEqual(len(result), 0)
# stop inside recursion
result = api.search('en', ['Scarf'], articles_per_query=3,
should_break=StopingMock(allow_calls=4))
self.assertEqual(len(result), 2)
def page(*args, **kwargs):
raise wikipedia.exceptions.PageError('1')
@mock.patch('wikipedia.page', page)
def test_page_error(self):
on_error = mock.MagicMock()
api = WikipediaAPI(on_error=on_error)
api.search('en', ['Barack Obama'])
self.assertEqual(on_error.call_count, 0)
def search(*args, **kwargs):
raise IOError('Network error')
@mock.patch('wikipedia.search', search)
def test_network_errors(self):
on_error = mock.MagicMock()
api = WikipediaAPI(on_error=on_error)
api.search('en', ['Barack Obama'])
self.assertEqual(on_error.call_count, 1)
| {
"content_hash": "0974b2d83a00f8f83374361f21a975a4",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 93,
"avg_line_length": 31.5125,
"alnum_prop": 0.6120587068623562,
"repo_name": "cheral/orange3-text",
"id": "b8c78e939aba6abd79648de743505698d501d01b",
"size": "2521",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "orangecontrib/text/tests/test_wikipedia.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "6578"
},
{
"name": "HTML",
"bytes": "613"
},
{
"name": "JavaScript",
"bytes": "39421"
},
{
"name": "Python",
"bytes": "378938"
}
],
"symlink_target": ""
} |
"use strict";
var _require = require('./index-esm'),
uncontrollable = _require.default,
useUncontrolled = _require.useUncontrolled;
module.exports = uncontrollable;
module.exports.useUncontrolled = useUncontrolled;
module.exports.uncontrollable = uncontrollable; | {
"content_hash": "f47febc516967ee35f38e2c428788340",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 49,
"avg_line_length": 30.22222222222222,
"alnum_prop": 0.7720588235294118,
"repo_name": "brett-harvey/Smart-Contracts",
"id": "e6e8b7e7f47221728b5a8cffeeba7ca7094974e7",
"size": "272",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Ethereum-based-Roll4Win/node_modules/uncontrollable/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "430"
}
],
"symlink_target": ""
} |
layout: post
categories: blog
title: Title
use_math: true
---
* Table of Contents
{:toc}
## Header
%include image
% 
% syntax highlighting
%{% highlight python %}
%import matplotlib as mpl
%mpl.use('Agg')
%{% endhighlight %}
| {
"content_hash": "4d5293a13eebc175583610d3e370bd7e",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 55,
"avg_line_length": 14.15,
"alnum_prop": 0.6784452296819788,
"repo_name": "brantr/brantr.github.io",
"id": "1886c71483c920e87ba5dc5326492442fcae747d",
"size": "287",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/blog/template/template.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8626"
},
{
"name": "HTML",
"bytes": "2687430"
},
{
"name": "JavaScript",
"bytes": "78211"
},
{
"name": "Jupyter Notebook",
"bytes": "2278986"
},
{
"name": "Ruby",
"bytes": "1087"
},
{
"name": "SCSS",
"bytes": "50701"
}
],
"symlink_target": ""
} |
import React, { Component } from 'react';
import styles from './Wrapper.css';
export default class Wrap extends Component {
render() {
return (
<div className={[styles.root, this.props.className].join(' ')}>
{this.props.children}
</div>
);
}
}
Wrap.propTypes = {
children: React.PropTypes.any,
className: React.PropTypes.string,
};
| {
"content_hash": "c2f3998b1b6e0de0df009905cb81c11c",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 69,
"avg_line_length": 20.61111111111111,
"alnum_prop": 0.6361185983827493,
"repo_name": "scott-riley/loggins",
"id": "ac18cc1037128f1f5a1073e5d2ea89274027c33f",
"size": "371",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "components/Wrapper/Wrapper.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "43494"
},
{
"name": "HTML",
"bytes": "343"
},
{
"name": "JavaScript",
"bytes": "98681"
}
],
"symlink_target": ""
} |
var file = require('../../lib/FileUtil');
var ModifyProperties = (function () {
function ModifyProperties() {
this.initProperties();
}
ModifyProperties.prototype.getProperties = function () {
return this.projectConfig;
};
ModifyProperties.prototype.initProperties = function () {
var projectPath = file.joinPath(egret.args.projectDir, "egretProperties.json");
var content = file.read(projectPath);
if (!content) {
this.projectConfig = {
"modules": [
{
"name": "core"
}
],
"native": {
"path_ignore": []
}
};
}
else {
this.projectConfig = JSON.parse(content);
}
if (!this.projectConfig.native) {
this.projectConfig.native = {};
}
};
ModifyProperties.prototype.save = function (version) {
if (version) {
this.projectConfig.egret_version = version;
}
var projectPath = file.joinPath(egret.args.projectDir, "egretProperties.json");
var content = JSON.stringify(this.projectConfig, null, "\t");
file.save(projectPath, content);
};
return ModifyProperties;
})();
var egretProjectConfig = egretProjectConfig || new ModifyProperties();
module.exports = egretProjectConfig;
//# sourceMappingURL=../../commands/upgrade/ModifyProperties.js.map | {
"content_hash": "6d8ca94fede396f99c662e587a281620",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 87,
"avg_line_length": 34,
"alnum_prop": 0.5561497326203209,
"repo_name": "jiangzhonghui/egret-core",
"id": "62b7275348464bcf4ff6230fd21c7b89013e1558",
"size": "1636",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "tools/commands/upgrade/ModifyProperties.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "5180887"
},
{
"name": "TypeScript",
"bytes": "4510137"
}
],
"symlink_target": ""
} |
#ifndef WASMINT_VARIABLE_H
#define WASMINT_VARIABLE_H
#include <cstdint>
#include <vector>
#include <types/Type.h>
namespace wasm_module {
class Type;
class InvalidDataSize : public std::exception {};
class Variable {
static const std::size_t size_ = 8;
const wasm_module::Type *type_;
uint8_t value_[size_] = {0, 0, 0, 0, 0, 0, 0, 0};
void setType(const wasm_module::Type* type);
Variable(uint32_t value);
Variable(int32_t value);
Variable(uint64_t value);
Variable(int64_t value);
Variable(float value);
Variable(double value);
public:
Variable();
static Variable createBool(bool value) {
return createUInt32(value == true ? 1u : 0u);
}
static Variable createUInt32(uint32_t value) {
return Variable(value);
}
static Variable createInt32(int32_t value) {
return Variable(value);
}
static Variable createUInt64(uint64_t value) {
return Variable(value);
}
static Variable createInt64(int64_t value) {
return Variable(value);
}
static Variable createFloat32(float value) {
return Variable(value);
}
static Variable createFloat64(double value) {
return Variable(value);
}
static Variable Void();
Variable(const wasm_module::Type *type);
const wasm_module::Type& type() const {
return *type_;
}
void* value() {
return (void *) value_;
}
const void* value() const {
return (const void *) value_;
}
uint64_t primitiveValue() const {
return *((uint64_t*)value_);
}
void setFromPrimitiveValue(uint64_t value) {
*((uint64_t*)value_) = value;
}
std::vector<uint8_t> data();
void setValue(std::vector<uint8_t> newData);
uint32_t uint32() const;
int32_t int32() const;
void uint32(uint32_t value);
void int32(int32_t value);
int64_t int64() const;
uint64_t uint64() const;
float float32() const;
double float64() const;
void float32(float value);
void float64(double value);
bool isVoid() const;
uint32_t uint32Reinterpret() const;
uint64_t uint64Reinterpret() const;
std::string toString() const;
bool operator==(const Variable& variable) const;
};
}
#endif //WASMINT_VARIABLE_H
| {
"content_hash": "521bbde7c1fedc0e20cca1dd767f836d",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 57,
"avg_line_length": 21.048387096774192,
"alnum_prop": 0.5532567049808429,
"repo_name": "Teemperor/wasmint",
"id": "0830beefad6850e180f9c0e3ceccfa568a3b3020",
"size": "3220",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "wasm-module/src/Variable.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "10699"
},
{
"name": "C++",
"bytes": "886100"
},
{
"name": "CMake",
"bytes": "20126"
},
{
"name": "Shell",
"bytes": "3188"
}
],
"symlink_target": ""
} |
title: com.virtlink.aesi.eclipse.debugging.model - aesi-eclipse
---
[aesi-eclipse](../index.html) / [com.virtlink.aesi.eclipse.debugging.model](.)
## Package com.virtlink.aesi.eclipse.debugging.model
### Types
| [AbstractDebugThread](-abstract-debug-thread/index.html) | `abstract class AbstractDebugThread : DebugElement, IThread`<br>Abstract base class for debug thread implementations. |
| [AesiBreakpoint](-aesi-breakpoint/index.html) | `open class AesiBreakpoint : Breakpoint` |
| [AesiBreakpointAdapterFactory](-aesi-breakpoint-adapter-factory/index.html) | `open class AesiBreakpointAdapterFactory : IAdapterFactory` |
| [AesiBreakpointManager](-aesi-breakpoint-manager/index.html) | `class AesiBreakpointManager`<br>Manages breakpoints. |
| [AesiDebugElement](-aesi-debug-element/index.html) | `open class AesiDebugElement : DebugElement`<br>A debug element. |
| [AesiLineBreakpointAdapter](-aesi-line-breakpoint-adapter/index.html) | `open class AesiLineBreakpointAdapter : IToggleBreakpointsTarget` |
| [AesiStackFrame](-aesi-stack-frame/index.html) | `open class AesiStackFrame : AbstractStackFrame`<br>A stack frame. |
| {
"content_hash": "9d0e7d8550b1741f6ee0c0adab7f3c16",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 180,
"avg_line_length": 66.82352941176471,
"alnum_prop": 0.7808098591549296,
"repo_name": "Virtlink/aesi",
"id": "eced136fd77f4dc9a14327d55e3082bf13b32b35",
"size": "1140",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/aesi-eclipse/com.virtlink.aesi.eclipse.debugging.model/index.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "3802"
},
{
"name": "HTML",
"bytes": "1865"
},
{
"name": "Java",
"bytes": "116648"
},
{
"name": "Kotlin",
"bytes": "297889"
},
{
"name": "Makefile",
"bytes": "7433"
},
{
"name": "Shell",
"bytes": "77"
}
],
"symlink_target": ""
} |
/*This file has been prepared for Doxygen automatic documentation generation.*/
/*! \file *********************************************************************
*
* \brief FreeRTOS port source for AVR32 UC3.
*
* - Compiler: GNU GCC for AVR32
* - Supported devices: All AVR32 devices can be used.
* - AppNote:
*
* \author Atmel Corporation: http://www.atmel.com \n
* Support and FAQ: http://support.atmel.no/
*
*****************************************************************************/
/*
FreeRTOS V8.0.1 - Copyright (C) 2014 Real Time Engineers Ltd.
All rights reserved
VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
***************************************************************************
* *
* FreeRTOS provides completely free yet professionally developed, *
* robust, strictly quality controlled, supported, and cross *
* platform software that has become a de facto standard. *
* *
* Help yourself get started quickly and support the FreeRTOS *
* project by purchasing a FreeRTOS tutorial book, reference *
* manual, or both from: http://www.FreeRTOS.org/Documentation *
* *
* Thank you! *
* *
***************************************************************************
This file is part of the FreeRTOS distribution.
FreeRTOS 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 >>!AND MODIFIED BY!<< the FreeRTOS exception.
>>! NOTE: The modification to the GPL is included to allow you to !<<
>>! distribute a combined work that includes FreeRTOS without being !<<
>>! obliged to provide the source code for proprietary components !<<
>>! outside of the FreeRTOS kernel. !<<
FreeRTOS 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. Full license text is available from the following
link: http://www.freertos.org/a00114.html
1 tab == 4 spaces!
***************************************************************************
* *
* Having a problem? Start by reading the FAQ "My application does *
* not run, what could be wrong?" *
* *
* http://www.FreeRTOS.org/FAQHelp.html *
* *
***************************************************************************
http://www.FreeRTOS.org - Documentation, books, training, latest versions,
license and Real Time Engineers Ltd. contact details.
http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
including FreeRTOS+Trace - an indispensable productivity tool, a DOS
compatible FAT file system, and our tiny thread aware UDP/IP stack.
http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High
Integrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOS
licenses offer ticketed support, indemnification and middleware.
http://www.SafeRTOS.com - High Integrity Systems also provide a safety
engineered and independently SIL3 certified version for use in safety and
mission critical applications that require provable dependability.
1 tab == 4 spaces!
*/
/* Standard includes. */
#include <sys/cpu.h>
#include <sys/usart.h>
#include <malloc.h>
/* Scheduler includes. */
#include "FreeRTOS.h"
#include "task.h"
/* AVR32 UC3 includes. */
#include <avr32/io.h>
#include "gpio.h"
#if( configTICK_USE_TC==1 )
#include "tc.h"
#endif
/* Constants required to setup the task context. */
#define portINITIAL_SR ( ( StackType_t ) 0x00400000 ) /* AVR32 : [M2:M0]=001 I1M=0 I0M=0, GM=0 */
#define portINSTRUCTION_SIZE ( ( StackType_t ) 0 )
/* Each task maintains its own critical nesting variable. */
#define portNO_CRITICAL_NESTING ( ( uint32_t ) 0 )
volatile uint32_t ulCriticalNesting = 9999UL;
#if( configTICK_USE_TC==0 )
static void prvScheduleNextTick( void );
#else
static void prvClearTcInt( void );
#endif
/* Setup the timer to generate the tick interrupts. */
static void prvSetupTimerInterrupt( void );
/*-----------------------------------------------------------*/
/*
* Low-level initialization routine called during startup, before the main
* function.
* This version comes in replacement to the default one provided by Newlib.
* Newlib's _init_startup only calls init_exceptions, but Newlib's exception
* vectors are not compatible with the SCALL management in the current FreeRTOS
* port. More low-level initializations are besides added here.
*/
void _init_startup(void)
{
/* Import the Exception Vector Base Address. */
extern void _evba;
#if configHEAP_INIT
extern void __heap_start__;
extern void __heap_end__;
BaseType_t *pxMem;
#endif
/* Load the Exception Vector Base Address in the corresponding system register. */
Set_system_register( AVR32_EVBA, ( int ) &_evba );
/* Enable exceptions. */
ENABLE_ALL_EXCEPTIONS();
/* Initialize interrupt handling. */
INTC_init_interrupts();
#if configHEAP_INIT
/* Initialize the heap used by malloc. */
for( pxMem = &__heap_start__; pxMem < ( BaseType_t * )&__heap_end__; )
{
*pxMem++ = 0xA5A5A5A5;
}
#endif
/* Give the used CPU clock frequency to Newlib, so it can work properly. */
set_cpu_hz( configCPU_CLOCK_HZ );
/* Code section present if and only if the debug trace is activated. */
#if configDBG
{
static const gpio_map_t DBG_USART_GPIO_MAP =
{
{ configDBG_USART_RX_PIN, configDBG_USART_RX_FUNCTION },
{ configDBG_USART_TX_PIN, configDBG_USART_TX_FUNCTION }
};
/* Initialize the USART used for the debug trace with the configured parameters. */
set_usart_base( ( void * ) configDBG_USART );
gpio_enable_module( DBG_USART_GPIO_MAP,
sizeof( DBG_USART_GPIO_MAP ) / sizeof( DBG_USART_GPIO_MAP[0] ) );
usart_init( configDBG_USART_BAUDRATE );
}
#endif
}
/*-----------------------------------------------------------*/
/*
* malloc, realloc and free are meant to be called through respectively
* pvPortMalloc, pvPortRealloc and vPortFree.
* The latter functions call the former ones from within sections where tasks
* are suspended, so the latter functions are task-safe. __malloc_lock and
* __malloc_unlock use the same mechanism to also keep the former functions
* task-safe as they may be called directly from Newlib's functions.
* However, all these functions are interrupt-unsafe and SHALL THEREFORE NOT BE
* CALLED FROM WITHIN AN INTERRUPT, because __malloc_lock and __malloc_unlock do
* not call portENTER_CRITICAL and portEXIT_CRITICAL in order not to disable
* interrupts during memory allocation management as this may be a very time-
* consuming process.
*/
/*
* Lock routine called by Newlib on malloc / realloc / free entry to guarantee a
* safe section as memory allocation management uses global data.
* See the aforementioned details.
*/
void __malloc_lock(struct _reent *ptr)
{
vTaskSuspendAll();
}
/*
* Unlock routine called by Newlib on malloc / realloc / free exit to guarantee
* a safe section as memory allocation management uses global data.
* See the aforementioned details.
*/
void __malloc_unlock(struct _reent *ptr)
{
xTaskResumeAll();
}
/*-----------------------------------------------------------*/
/* Added as there is no such function in FreeRTOS. */
void *pvPortRealloc( void *pv, size_t xWantedSize )
{
void *pvReturn;
vTaskSuspendAll();
{
pvReturn = realloc( pv, xWantedSize );
}
xTaskResumeAll();
return pvReturn;
}
/*-----------------------------------------------------------*/
/* The cooperative scheduler requires a normal IRQ service routine to
simply increment the system tick. */
/* The preemptive scheduler is defined as "naked" as the full context is saved
on entry as part of the context switch. */
__attribute__((__naked__)) static void vTick( void )
{
/* Save the context of the interrupted task. */
portSAVE_CONTEXT_OS_INT();
#if( configTICK_USE_TC==1 )
/* Clear the interrupt flag. */
prvClearTcInt();
#else
/* Schedule the COUNT&COMPARE match interrupt in (configCPU_CLOCK_HZ/configTICK_RATE_HZ)
clock cycles from now. */
prvScheduleNextTick();
#endif
/* Because FreeRTOS is not supposed to run with nested interrupts, put all OS
calls in a critical section . */
portENTER_CRITICAL();
xTaskIncrementTick();
portEXIT_CRITICAL();
/* Restore the context of the "elected task". */
portRESTORE_CONTEXT_OS_INT();
}
/*-----------------------------------------------------------*/
__attribute__((__naked__)) void SCALLYield( void )
{
/* Save the context of the interrupted task. */
portSAVE_CONTEXT_SCALL();
vTaskSwitchContext();
portRESTORE_CONTEXT_SCALL();
}
/*-----------------------------------------------------------*/
/* The code generated by the GCC compiler uses the stack in different ways at
different optimisation levels. The interrupt flags can therefore not always
be saved to the stack. Instead the critical section nesting level is stored
in a variable, which is then saved as part of the stack context. */
__attribute__((__noinline__)) void vPortEnterCritical( void )
{
/* Disable interrupts */
portDISABLE_INTERRUPTS();
/* Now interrupts are disabled ulCriticalNesting can be accessed
directly. Increment ulCriticalNesting to keep a count of how many times
portENTER_CRITICAL() has been called. */
ulCriticalNesting++;
}
/*-----------------------------------------------------------*/
__attribute__((__noinline__)) void vPortExitCritical( void )
{
if(ulCriticalNesting > portNO_CRITICAL_NESTING)
{
ulCriticalNesting--;
if( ulCriticalNesting == portNO_CRITICAL_NESTING )
{
/* Enable all interrupt/exception. */
portENABLE_INTERRUPTS();
}
}
}
/*-----------------------------------------------------------*/
/*
* Initialise the stack of a task to look exactly as if a call to
* portSAVE_CONTEXT had been called.
*
* See header file for description.
*/
StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )
{
/* Setup the initial stack of the task. The stack is set exactly as
expected by the portRESTORE_CONTEXT() macro. */
/* When the task starts, it will expect to find the function parameter in R12. */
pxTopOfStack--;
*pxTopOfStack-- = ( StackType_t ) 0x08080808; /* R8 */
*pxTopOfStack-- = ( StackType_t ) 0x09090909; /* R9 */
*pxTopOfStack-- = ( StackType_t ) 0x0A0A0A0A; /* R10 */
*pxTopOfStack-- = ( StackType_t ) 0x0B0B0B0B; /* R11 */
*pxTopOfStack-- = ( StackType_t ) pvParameters; /* R12 */
*pxTopOfStack-- = ( StackType_t ) 0xDEADBEEF; /* R14/LR */
*pxTopOfStack-- = ( StackType_t ) pxCode + portINSTRUCTION_SIZE; /* R15/PC */
*pxTopOfStack-- = ( StackType_t ) portINITIAL_SR; /* SR */
*pxTopOfStack-- = ( StackType_t ) 0xFF0000FF; /* R0 */
*pxTopOfStack-- = ( StackType_t ) 0x01010101; /* R1 */
*pxTopOfStack-- = ( StackType_t ) 0x02020202; /* R2 */
*pxTopOfStack-- = ( StackType_t ) 0x03030303; /* R3 */
*pxTopOfStack-- = ( StackType_t ) 0x04040404; /* R4 */
*pxTopOfStack-- = ( StackType_t ) 0x05050505; /* R5 */
*pxTopOfStack-- = ( StackType_t ) 0x06060606; /* R6 */
*pxTopOfStack-- = ( StackType_t ) 0x07070707; /* R7 */
*pxTopOfStack = ( StackType_t ) portNO_CRITICAL_NESTING; /* ulCriticalNesting */
return pxTopOfStack;
}
/*-----------------------------------------------------------*/
BaseType_t xPortStartScheduler( void )
{
/* Start the timer that generates the tick ISR. Interrupts are disabled
here already. */
prvSetupTimerInterrupt();
/* Start the first task. */
portRESTORE_CONTEXT();
/* Should not get here! */
return 0;
}
/*-----------------------------------------------------------*/
void vPortEndScheduler( void )
{
/* It is unlikely that the AVR32 port will require this function as there
is nothing to return to. */
}
/*-----------------------------------------------------------*/
/* Schedule the COUNT&COMPARE match interrupt in (configCPU_CLOCK_HZ/configTICK_RATE_HZ)
clock cycles from now. */
#if( configTICK_USE_TC==0 )
static void prvScheduleFirstTick(void)
{
uint32_t lCycles;
lCycles = Get_system_register(AVR32_COUNT);
lCycles += (configCPU_CLOCK_HZ/configTICK_RATE_HZ);
// If lCycles ends up to be 0, make it 1 so that the COMPARE and exception
// generation feature does not get disabled.
if(0 == lCycles)
{
lCycles++;
}
Set_system_register(AVR32_COMPARE, lCycles);
}
__attribute__((__noinline__)) static void prvScheduleNextTick(void)
{
uint32_t lCycles, lCount;
lCycles = Get_system_register(AVR32_COMPARE);
lCycles += (configCPU_CLOCK_HZ/configTICK_RATE_HZ);
// If lCycles ends up to be 0, make it 1 so that the COMPARE and exception
// generation feature does not get disabled.
if(0 == lCycles)
{
lCycles++;
}
lCount = Get_system_register(AVR32_COUNT);
if( lCycles < lCount )
{ // We missed a tick, recover for the next.
lCycles += (configCPU_CLOCK_HZ/configTICK_RATE_HZ);
}
Set_system_register(AVR32_COMPARE, lCycles);
}
#else
__attribute__((__noinline__)) static void prvClearTcInt(void)
{
AVR32_TC.channel[configTICK_TC_CHANNEL].sr;
}
#endif
/*-----------------------------------------------------------*/
/* Setup the timer to generate the tick interrupts. */
static void prvSetupTimerInterrupt(void)
{
#if( configTICK_USE_TC==1 )
volatile avr32_tc_t *tc = &AVR32_TC;
// Options for waveform genration.
tc_waveform_opt_t waveform_opt =
{
.channel = configTICK_TC_CHANNEL, /* Channel selection. */
.bswtrg = TC_EVT_EFFECT_NOOP, /* Software trigger effect on TIOB. */
.beevt = TC_EVT_EFFECT_NOOP, /* External event effect on TIOB. */
.bcpc = TC_EVT_EFFECT_NOOP, /* RC compare effect on TIOB. */
.bcpb = TC_EVT_EFFECT_NOOP, /* RB compare effect on TIOB. */
.aswtrg = TC_EVT_EFFECT_NOOP, /* Software trigger effect on TIOA. */
.aeevt = TC_EVT_EFFECT_NOOP, /* External event effect on TIOA. */
.acpc = TC_EVT_EFFECT_NOOP, /* RC compare effect on TIOA: toggle. */
.acpa = TC_EVT_EFFECT_NOOP, /* RA compare effect on TIOA: toggle (other possibilities are none, set and clear). */
.wavsel = TC_WAVEFORM_SEL_UP_MODE_RC_TRIGGER,/* Waveform selection: Up mode without automatic trigger on RC compare. */
.enetrg = FALSE, /* External event trigger enable. */
.eevt = 0, /* External event selection. */
.eevtedg = TC_SEL_NO_EDGE, /* External event edge selection. */
.cpcdis = FALSE, /* Counter disable when RC compare. */
.cpcstop = FALSE, /* Counter clock stopped with RC compare. */
.burst = FALSE, /* Burst signal selection. */
.clki = FALSE, /* Clock inversion. */
.tcclks = TC_CLOCK_SOURCE_TC2 /* Internal source clock 2. */
};
tc_interrupt_t tc_interrupt =
{
.etrgs=0,
.ldrbs=0,
.ldras=0,
.cpcs =1,
.cpbs =0,
.cpas =0,
.lovrs=0,
.covfs=0,
};
#endif
/* Disable all interrupt/exception. */
portDISABLE_INTERRUPTS();
/* Register the compare interrupt handler to the interrupt controller and
enable the compare interrupt. */
#if( configTICK_USE_TC==1 )
{
INTC_register_interrupt(&vTick, configTICK_TC_IRQ, INT0);
/* Initialize the timer/counter. */
tc_init_waveform(tc, &waveform_opt);
/* Set the compare triggers.
Remember TC counter is 16-bits, so counting second is not possible!
That's why we configure it to count ms. */
tc_write_rc( tc, configTICK_TC_CHANNEL, ( configPBA_CLOCK_HZ / 4) / configTICK_RATE_HZ );
tc_configure_interrupts( tc, configTICK_TC_CHANNEL, &tc_interrupt );
/* Start the timer/counter. */
tc_start(tc, configTICK_TC_CHANNEL);
}
#else
{
INTC_register_interrupt(&vTick, AVR32_CORE_COMPARE_IRQ, INT0);
prvScheduleFirstTick();
}
#endif
}
| {
"content_hash": "2b4fe28e094a3f5d90283570325d2a50",
"timestamp": "",
"source": "github",
"line_count": 473,
"max_line_length": 134,
"avg_line_length": 36.010570824524315,
"alnum_prop": 0.5963130393941173,
"repo_name": "miragecentury/M2_SE_RTOS_Project",
"id": "9607eef55d61de99081a905ab949dd08588b64b7",
"size": "17033",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Project/LPC1549_Keil/freertos/freertos/Source/portable/GCC/AVR32_UC3/port.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "3487996"
},
{
"name": "Batchfile",
"bytes": "24092"
},
{
"name": "C",
"bytes": "84242987"
},
{
"name": "C++",
"bytes": "11815227"
},
{
"name": "CSS",
"bytes": "228804"
},
{
"name": "D",
"bytes": "102276"
},
{
"name": "HTML",
"bytes": "97193"
},
{
"name": "JavaScript",
"bytes": "233480"
},
{
"name": "Makefile",
"bytes": "3365112"
},
{
"name": "Objective-C",
"bytes": "46531"
},
{
"name": "Python",
"bytes": "3237"
},
{
"name": "Shell",
"bytes": "13510"
}
],
"symlink_target": ""
} |
By default, you can specify configuration when you register CAP services into the IoC container for ASP.NET Core project.
```c#
services.AddCap(config=>
{
// config.XXX
});
```
`services` is `IServiceCollection` interface, which can be found in the `Microsoft.Extensions.DependencyInjection` package.
If you don't want to use Microsoft's IoC container, you can take a look at ASP.NET Core documentation [here](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.2#default-service-container-replacement) to learn how to replace the default container implementation.
## what is minimum configuration required for CAP
you have to configure at least a transport and a storage. If you want to get started quickly you can use the following configuration:
```C#
services.AddCap(capOptions =>
{
capOptions.UseInMemoryQueue();
capOptions.UseInmemoryStorage();
});
```
For specific transport and storage configuration, you can take a look at the configuration options provided by the specific components in the [Transports](../transport/general.md) section and the [Persistent](../storage/general.md) section.
## Custom configuration
The `CapOptions` is used to store configuration information. By default they have default values, sometimes you may need to customize them.
#### DefaultGroupName
> Default: cap.queue.{assembly name}
The default consumer group name, corresponds to different names in different Transports, you can customize this value to customize the names in Transports for easy viewing.
!!! info "Mapping"
Map to [Queue Names](https://www.rabbitmq.com/queues.html#names) in RabbitMQ.
Map to [Consumer Group Id](http://kafka.apache.org/documentation/#group.id) in Apache Kafka.
Map to Subscription Name in Azure Service Bus.
Map to [Queue Group Name](https://docs.nats.io/nats-concepts/queue) in NATS.
Map to [Consumer Group](https://redis.io/topics/streams-intro#creating-a-consumer-group) in Redis Streams.
#### GroupNamePrefix
> Default: Null
Add unified prefixes for consumer group. https://github.com/dotnetcore/CAP/pull/780
#### TopicNamePrefix
> Default: Null
Add unified prefixes for topic/queue name. https://github.com/dotnetcore/CAP/pull/780
#### Versioning
> Default: v1
This is a new configuration option introduced in the CAP v2.4 version. It is used to specify a version of a message to isolate messages of different versions of the service. It is often used in A/B testing or multi-service version scenarios. Following are application scenarios that needs versioning:
!!! info "Business Iterative and compatible"
Due to the rapid iteration of services, the data structure of the message is not fixed during each service integration process. Sometimes we add or modify certain data structures to accommodate the newly introduced requirements. If you have a brand new system, there's no problem, but if your system is already deployed to a production environment and serves customers, this will cause new features to be incompatible with the old data structure when they go online, and then these changes can cause serious problems. To work around this issue, you can only clean up message queues and persistent messages before starting the application, which is obviously not acceptable for production environments.
!!! info "Multiple versions of the server"
Sometimes, the server's server needs to provide multiple sets of interfaces to support different versions of the app. Data structures of the same interface and server interaction of these different versions of the app may be different, so usually server does not provide the same routing addresses to adapt to different versions of App calls.
!!! info "Using the same persistent table/collection in different instance"
If you want multiple different instance services to use the same database, in versions prior to 2.4, we could isolate database tables for different instances by specifying different table names. After version 2.4 this can be achived through CAP configuration, by configuring different table name prefixes.
> Check out the blog to learn more about the Versioning feature: https://www.cnblogs.com/savorboard/p/cap-2-4.html
#### FailedRetryInterval
> Default: 60 sec
During the message sending process if message transport fails, CAP will try to send the message again. This configuration option is used to configure the interval between each retry.
During the message sending process if consumption method fails, CAP will try to execute the method again. This configuration option is used to configure the interval between each retry.
!!! WARNING "Retry & Interval"
By default if failure occurs on send or consume, retry will start after **4 minutes** in order to avoid possible problems caused by setting message state delays.
Failures in the process of sending and consuming messages will be retried 3 times immediately, and will be retried polling after 3 times, at which point the FailedRetryInterval configuration will take effect.
#### CollectorCleaningInterval
> Default: 300 sec
The interval of the collector processor deletes expired messages.
#### ConsumerThreadCount
> Default: 1
Number of consumer threads, when this value is greater than 1, the order of message execution cannot be guaranteed.
#### FailedRetryCount
> Default: 50
Maximum number of retries. When this value is reached, retry will stop and the maximum number of retries will be modified by setting this parameter.
#### FailedThresholdCallback
> Default: NULL
Type: `Action<FailedInfo>`
Failure threshold callback. This action is called when the retry reaches the value set by `FailedRetryCount`, you can receive notification by specifying this parameter to make a manual intervention. For example, send an email or notification.
#### SucceedMessageExpiredAfter
> Default: 24*3600 sec (1 days)
The expiration time (in seconds) of the success message. When the message is sent or consumed successfully, it will be removed from database storage when the time reaches `SucceedMessageExpiredAfter` seconds. You can set the expiration time by specifying this value.
#### FailedMessageExpiredAfter
> Default: 15*24*3600 sec(15 days)
The expiration time (in seconds) of the failed message. When the message is sent or consumed failed, it will be removed from database storage when the time reaches `FailedMessageExpiredAfter` seconds. You can set the expiration time by specifying this value.
#### UseDispatchingPerGroup
> Default: false
If `true` then all consumers within the same group pushes received messages to own dispatching pipeline channel. Each channel has set thread count to `ConsumerThreadCount` value. | {
"content_hash": "4554cb174c8281b5b538292fd9f8953f",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 705,
"avg_line_length": 52.765625,
"alnum_prop": 0.7857565886881848,
"repo_name": "dotnetcore/CAP",
"id": "aeb87db0b017c0fa2bb49441f69f9c874cf22e17",
"size": "6771",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/content/user-guide/en/cap/configuration.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "725630"
},
{
"name": "HTML",
"bytes": "587"
},
{
"name": "JavaScript",
"bytes": "134864"
},
{
"name": "Vue",
"bytes": "32213"
}
],
"symlink_target": ""
} |
<!--
Copyright (C) 2015 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.
-->
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="notification_large_icon_default">48dp</dimen>
<dimen name="forecast_detail_horizontal_padding">32dp</dimen>
<!-- Icon Sizes -->
<dimen name="today_icon">96dp</dimen>
<dimen name="list_icon">40dp</dimen>
<!-- Text Sizes - We are using DP here rather than SP because these are already large
font sizes, and going larger will cause lots of view problems. This is only for
the large forecast numbers in the forecast list -->
<dimen name="forecast_text_size">32dp</dimen>
<!-- This is an odd width, but we're trying to match the font closely to keep things working
on devices that don't yet have Roboto -->
<dimen name="forecast_text_width">58dp</dimen>
<dimen name="forecast_temperature_space">8dp</dimen>
<!-- Extra Padding = abc_list_item_padding_horizontal_material -->
<dimen name="detail_view_extra_padding">16dp</dimen>
<!-- Needed if we aren't including the Material Design Library -->
<dimen name="appbar_elevation">4dp</dimen>
<!-- The amount we want the details view to overlap the app bar -->
<dimen name="details_app_bar_overlap">24dp</dimen>
<dimen name="list_item_extra_padding">0dp</dimen>
<dimen name="detail_view_padding">16dp</dimen>
<dimen name="forecast_detail_padding_wide">16dp</dimen>
<dimen name="detail_container_bottom_margin">@dimen/detail_view_padding</dimen>
<dimen name="detail_card_elevation">6dp</dimen>
<dimen name="landscape_forecast_view_width">360dp</dimen>
<dimen name="forecast_detail_wide_horizontal_padding">6dp</dimen>
<dimen name="detail_card_space_margin">2dp</dimen>
<dimen name="widget_today_default_width">110dp</dimen>
<dimen name="widget_today_default_height">40dp</dimen>
<dimen name="widget_margin">8dp</dimen>
<dimen name="widget_min_wh">40dp</dimen>
<dimen name="widget_today_min_resize_height">40dp</dimen>
<dimen name="widget_today_min_resize_width">40dp</dimen>
<dimen name="widget_today_large_width">220dp</dimen>
<dimen name="forecast_widget_text_width">38dp</dimen>
<dimen name="forecast_widget_text_size">24dp</dimen>
<dimen name="widget_detail_default_width">250dp</dimen>
<dimen name="widget_detail_default_height">180dp</dimen>
<dimen name="widget_detail_min_height">90dp</dimen>
<dimen name="widget_detail_min_resize_width">220dp</dimen>
<dimen name="widget_detail_min_resize_height">@dimen/widget_detail_default_height</dimen>
</resources> | {
"content_hash": "90fae69a0ee5776e4e79221f0029512d",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 96,
"avg_line_length": 46.40277777777778,
"alnum_prop": 0.6982939239748578,
"repo_name": "ribertojunior/Sunshine-Version-2",
"id": "73202ec8eb282d3c141ee716211a67bb2068df7d",
"size": "3341",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/values/dimens.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "232611"
}
],
"symlink_target": ""
} |
class WebsiteSettingsUIBridge;
namespace content {
class WebContents;
}
// This NSWindowController subclass manages the InfoBubbleWindow and view that
// are displayed when the user clicks the favicon or security lock icon.
//
// TODO(palmer, sashab): Normalize all WebsiteSettings*, SiteSettings*,
// PageInfo*, et c. to OriginInfo*.
@interface WebsiteSettingsBubbleController : BaseBubbleController {
@private
content::WebContents* webContents_;
base::scoped_nsobject<NSView> contentView_;
base::scoped_nsobject<NSSegmentedControl> segmentedControl_;
base::scoped_nsobject<NSTabView> tabView_;
// Displays the web site identity.
NSTextField* identityField_;
// Display the identity status (e.g. verified, not verified).
NSTextField* identityStatusField_;
// The main content view for the Permissions tab.
NSView* permissionsTabContentView_;
// The main content view for the Connection tab.
NSView* connectionTabContentView_;
// Container for cookies info on the Permissions tab.
NSView* cookiesView_;
// The link button for showing cookies and site data info.
NSButton* cookiesButton_;
// The link button for showing site settings.
NSButton* siteSettingsButton_;
// The link button for showing certificate information.
NSButton* certificateInfoButton_;
// The link button for revoking certificate decisions.
NSButton* resetDecisionsButton_;
// The ID of the server certificate from the identity info. This should
// always be non-zero on a secure connection, and 0 otherwise.
int certificateId_;
// Container for permission info on the Permissions tab.
NSView* permissionsView_;
NSImageView* identityStatusIcon_;
NSTextField* identityStatusDescriptionField_;
NSView* separatorAfterIdentity_;
NSImageView* connectionStatusIcon_;
NSTextField* connectionStatusDescriptionField_;
NSView* separatorAfterConnection_;
// The link button to launch the Help Center article explaining the
// connection info.
NSButton* helpButton_;
// The UI translates user actions to specific events and forwards them to the
// |presenter_|. The |presenter_| handles these events and updates the UI.
scoped_ptr<WebsiteSettings> presenter_;
// Bridge which implements the WebsiteSettingsUI interface and forwards
// methods on to this class.
scoped_ptr<WebsiteSettingsUIBridge> bridge_;
}
// Designated initializer. The controller will release itself when the bubble
// is closed. |parentWindow| cannot be nil. |webContents| may be nil for
// testing purposes.
- (id)initWithParentWindow:(NSWindow*)parentWindow
websiteSettingsUIBridge:(WebsiteSettingsUIBridge*)bridge
webContents:(content::WebContents*)webContents
isInternalPage:(BOOL)isInternalPage;
// Return the default width of the window. It may be wider to fit the content.
// This may be overriden by a subclass for testing purposes.
- (CGFloat)defaultWindowWidth;
@end
// Provides a bridge between the WebSettingsUI C++ interface and the Cocoa
// implementation in WebsiteSettingsBubbleController.
class WebsiteSettingsUIBridge : public WebsiteSettingsUI {
public:
WebsiteSettingsUIBridge();
~WebsiteSettingsUIBridge() override;
// Creates a |WebsiteSettingsBubbleController| and displays the UI. |parent|
// is the currently active window. |profile| points to the currently active
// profile. |web_contents| points to the WebContents that wraps the currently
// active tab. |url| is the GURL of the currently active tab. |ssl| is the
// |SSLStatus| of the connection to the website in the currently active tab.
static void Show(gfx::NativeWindow parent,
Profile* profile,
content::WebContents* web_contents,
const GURL& url,
const content::SSLStatus& ssl);
void set_bubble_controller(
WebsiteSettingsBubbleController* bubble_controller);
// WebsiteSettingsUI implementations.
void SetCookieInfo(const CookieInfoList& cookie_info_list) override;
void SetPermissionInfo(
const PermissionInfoList& permission_info_list) override;
void SetIdentityInfo(const IdentityInfo& identity_info) override;
void SetSelectedTab(TabId tab_id) override;
private:
// The Cocoa controller for the bubble UI.
WebsiteSettingsBubbleController* bubble_controller_;
DISALLOW_COPY_AND_ASSIGN(WebsiteSettingsUIBridge);
};
| {
"content_hash": "e200786cb81588fd1a29a86e532e9cf2",
"timestamp": "",
"source": "github",
"line_count": 122,
"max_line_length": 79,
"avg_line_length": 36.0655737704918,
"alnum_prop": 0.7545454545454545,
"repo_name": "chuan9/chromium-crosswalk",
"id": "1832187e683f5ce33d44e5558931ba229ffbbf29",
"size": "4793",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "chrome/browser/ui/cocoa/website_settings/website_settings_bubble_controller.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "37073"
},
{
"name": "Batchfile",
"bytes": "8451"
},
{
"name": "C",
"bytes": "9417055"
},
{
"name": "C++",
"bytes": "240920124"
},
{
"name": "CSS",
"bytes": "938860"
},
{
"name": "DM",
"bytes": "60"
},
{
"name": "Groff",
"bytes": "2494"
},
{
"name": "HTML",
"bytes": "27258381"
},
{
"name": "Java",
"bytes": "14580273"
},
{
"name": "JavaScript",
"bytes": "20507007"
},
{
"name": "Makefile",
"bytes": "70992"
},
{
"name": "Objective-C",
"bytes": "1742904"
},
{
"name": "Objective-C++",
"bytes": "9967587"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "PLpgSQL",
"bytes": "178732"
},
{
"name": "Perl",
"bytes": "63937"
},
{
"name": "Protocol Buffer",
"bytes": "480579"
},
{
"name": "Python",
"bytes": "8519074"
},
{
"name": "Shell",
"bytes": "482077"
},
{
"name": "Standard ML",
"bytes": "5034"
},
{
"name": "XSLT",
"bytes": "418"
},
{
"name": "nesC",
"bytes": "18347"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_45) on Fri Jan 10 21:37:06 UTC 2014 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.apache.hadoop.hbase.thrift.generated.Hbase.getTableRegions_args._Fields (HBase 0.94.16 API)
</TITLE>
<META NAME="date" CONTENT="2014-01-10">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.hadoop.hbase.thrift.generated.Hbase.getTableRegions_args._Fields (HBase 0.94.16 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args._Fields.html" title="enum in org.apache.hadoop.hbase.thrift.generated"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?org/apache/hadoop/hbase/thrift/generated//class-useHbase.getTableRegions_args._Fields.html" target="_top"><B>FRAMES</B></A>
<A HREF="Hbase.getTableRegions_args._Fields.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.hadoop.hbase.thrift.generated.Hbase.getTableRegions_args._Fields</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args._Fields.html" title="enum in org.apache.hadoop.hbase.thrift.generated">Hbase.getTableRegions_args._Fields</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.hadoop.hbase.thrift.generated"><B>org.apache.hadoop.hbase.thrift.generated</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.hadoop.hbase.thrift.generated"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args._Fields.html" title="enum in org.apache.hadoop.hbase.thrift.generated">Hbase.getTableRegions_args._Fields</A> in <A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/package-summary.html">org.apache.hadoop.hbase.thrift.generated</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Fields in <A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/package-summary.html">org.apache.hadoop.hbase.thrift.generated</A> with type parameters of type <A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args._Fields.html" title="enum in org.apache.hadoop.hbase.thrift.generated">Hbase.getTableRegions_args._Fields</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="http://java.sun.com/javase/6/docs/api/java/util/Map.html?is-external=true" title="class or interface in java.util">Map</A><<A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args._Fields.html" title="enum in org.apache.hadoop.hbase.thrift.generated">Hbase.getTableRegions_args._Fields</A>,org.apache.thrift.meta_data.FieldMetaData></CODE></FONT></TD>
<TD><CODE><B>Hbase.getTableRegions_args.</B><B><A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args.html#metaDataMap">metaDataMap</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/package-summary.html">org.apache.hadoop.hbase.thrift.generated</A> that return <A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args._Fields.html" title="enum in org.apache.hadoop.hbase.thrift.generated">Hbase.getTableRegions_args._Fields</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args._Fields.html" title="enum in org.apache.hadoop.hbase.thrift.generated">Hbase.getTableRegions_args._Fields</A></CODE></FONT></TD>
<TD><CODE><B>Hbase.getTableRegions_args.</B><B><A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args.html#fieldForId(int)">fieldForId</A></B>(int fieldId)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args._Fields.html" title="enum in org.apache.hadoop.hbase.thrift.generated">Hbase.getTableRegions_args._Fields</A></CODE></FONT></TD>
<TD><CODE><B>Hbase.getTableRegions_args._Fields.</B><B><A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args._Fields.html#findByName(java.lang.String)">findByName</A></B>(<A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> name)</CODE>
<BR>
Find the _Fields constant that matches name, or null if its not found.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args._Fields.html" title="enum in org.apache.hadoop.hbase.thrift.generated">Hbase.getTableRegions_args._Fields</A></CODE></FONT></TD>
<TD><CODE><B>Hbase.getTableRegions_args._Fields.</B><B><A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args._Fields.html#findByThriftId(int)">findByThriftId</A></B>(int fieldId)</CODE>
<BR>
Find the _Fields constant that matches fieldId, or null if its not found.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args._Fields.html" title="enum in org.apache.hadoop.hbase.thrift.generated">Hbase.getTableRegions_args._Fields</A></CODE></FONT></TD>
<TD><CODE><B>Hbase.getTableRegions_args._Fields.</B><B><A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args._Fields.html#findByThriftIdOrThrow(int)">findByThriftIdOrThrow</A></B>(int fieldId)</CODE>
<BR>
Find the _Fields constant that matches fieldId, throwing an exception
if it is not found.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args._Fields.html" title="enum in org.apache.hadoop.hbase.thrift.generated">Hbase.getTableRegions_args._Fields</A></CODE></FONT></TD>
<TD><CODE><B>Hbase.getTableRegions_args._Fields.</B><B><A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args._Fields.html#valueOf(java.lang.String)">valueOf</A></B>(<A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> name)</CODE>
<BR>
Returns the enum constant of this type with the specified name.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args._Fields.html" title="enum in org.apache.hadoop.hbase.thrift.generated">Hbase.getTableRegions_args._Fields</A>[]</CODE></FONT></TD>
<TD><CODE><B>Hbase.getTableRegions_args._Fields.</B><B><A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args._Fields.html#values()">values</A></B>()</CODE>
<BR>
Returns an array containing the constants of this enum type, in
the order they are declared.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/package-summary.html">org.apache.hadoop.hbase.thrift.generated</A> with parameters of type <A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args._Fields.html" title="enum in org.apache.hadoop.hbase.thrift.generated">Hbase.getTableRegions_args._Fields</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A></CODE></FONT></TD>
<TD><CODE><B>Hbase.getTableRegions_args.</B><B><A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args.html#getFieldValue(org.apache.hadoop.hbase.thrift.generated.Hbase.getTableRegions_args._Fields)">getFieldValue</A></B>(<A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args._Fields.html" title="enum in org.apache.hadoop.hbase.thrift.generated">Hbase.getTableRegions_args._Fields</A> field)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> boolean</CODE></FONT></TD>
<TD><CODE><B>Hbase.getTableRegions_args.</B><B><A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args.html#isSet(org.apache.hadoop.hbase.thrift.generated.Hbase.getTableRegions_args._Fields)">isSet</A></B>(<A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args._Fields.html" title="enum in org.apache.hadoop.hbase.thrift.generated">Hbase.getTableRegions_args._Fields</A> field)</CODE>
<BR>
Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>Hbase.getTableRegions_args.</B><B><A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args.html#setFieldValue(org.apache.hadoop.hbase.thrift.generated.Hbase.getTableRegions_args._Fields, java.lang.Object)">setFieldValue</A></B>(<A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args._Fields.html" title="enum in org.apache.hadoop.hbase.thrift.generated">Hbase.getTableRegions_args._Fields</A> field,
<A HREF="http://java.sun.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A> value)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/hbase/thrift/generated/Hbase.getTableRegions_args._Fields.html" title="enum in org.apache.hadoop.hbase.thrift.generated"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?org/apache/hadoop/hbase/thrift/generated//class-useHbase.getTableRegions_args._Fields.html" target="_top"><B>FRAMES</B></A>
<A HREF="Hbase.getTableRegions_args._Fields.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2014 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All Rights Reserved.
</BODY>
</HTML>
| {
"content_hash": "ffd5a2cfc874f1898e7ef6842188fc1d",
"timestamp": "",
"source": "github",
"line_count": 272,
"max_line_length": 501,
"avg_line_length": 63.88970588235294,
"alnum_prop": 0.6675106456439176,
"repo_name": "wanhao/IRIndex",
"id": "30dca8c80a08a8dbd5e00ee624ed1243803dee84",
"size": "17378",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/apidocs/org/apache/hadoop/hbase/thrift/generated/class-use/Hbase.getTableRegions_args._Fields.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "9918"
},
{
"name": "CSS",
"bytes": "29691"
},
{
"name": "Java",
"bytes": "15679586"
},
{
"name": "PHP",
"bytes": "7350"
},
{
"name": "Perl",
"bytes": "8667"
},
{
"name": "Python",
"bytes": "14535"
},
{
"name": "Ruby",
"bytes": "396034"
},
{
"name": "Shell",
"bytes": "69638"
},
{
"name": "XSLT",
"bytes": "4379"
}
],
"symlink_target": ""
} |
Dev
***
Contents
.. toctree::
:maxdepth: 1
activex
bho
debug
dotnet/index
internet-explorer
msbuild
sql-server/index
visual-studio/index
wix/index
| {
"content_hash": "8d3857e551f270de53aca1d7317efee4",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 22,
"avg_line_length": 10.588235294117647,
"alnum_prop": 0.6388888888888888,
"repo_name": "pkimber/my-memory",
"id": "6475aa53da71c25ea6477941cc9dff63e575eb2e",
"size": "180",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/microsoft/dev/index.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5101"
},
{
"name": "HTML",
"bytes": "694"
},
{
"name": "JavaScript",
"bytes": "1694"
},
{
"name": "Makefile",
"bytes": "5565"
},
{
"name": "Python",
"bytes": "12535"
},
{
"name": "Shell",
"bytes": "2820"
},
{
"name": "TeX",
"bytes": "1888"
}
],
"symlink_target": ""
} |
/*
* 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 net.rptools.lib.result;
import java.util.List;
import net.rptools.lib.datavalue.DataValue;
/**
* The Result class represents values that may have additional information attached
* to them such as a detailed explanation of the value and/or a list of individual
* values that make up that the result.
*
*/
public class Result {
/** The actual result this represents. */
private final DataValue value;
/** Any detailed information about the result. */
private final DataValue detailedResult;
/** Any individual values that make up the result, e.g. dice rolls. */
private final List<DataValue> values;
/** The {@link RollExpression} if any that is attached to this result. */
private final RollExpression rollExpression;
/**
* Creates a new Result object.
*
* @param val The value to be represented.
* @param details Any detailed information that helps explain the result.
* @param vals Any individual values that go with the result.
*/
Result(DataValue val, DataValue details, List<DataValue> vals, RollExpression rexpr) {
value = val;
detailedResult = details;
values = vals;
rollExpression = rexpr;
}
/**
* Returns the value represented by this object.
*
* @return the value represented result.
*/
public DataValue getValue() {
return value;
}
/**
* Returns the detailed information associated with the value.
*
* @return the detailed information.
*/
public DataValue getDetailedResult() {
return detailedResult;
}
/**
* Returns the individual values associated with the result.
*
* @return the individual values.
*/
public List<DataValue> getValues() {
return values;
}
/**
* Checks to see if there is a {@link RollExpression} is attached to
* this Result.
*
* @return true if there is a a {@link RollExpression} attached to
* this Result.
*/
public boolean hasRollExpression() {
return rollExpression != null;
}
/**
* Returns the {@link RollExpression} attached to this Result.
*
* @return the {@link RollExpression} attached to this Result.
*/
public RollExpression getRollExpression() {
return rollExpression;
}
@Override
public String toString() {
return "Result: value = " + value.toString() + ", detailedResult = " +
detailedResult.toString() + ", values = " + values.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((detailedResult == null) ? 0 : detailedResult.hashCode());
result = prime * result
+ ((this.value == null) ? 0 : this.value.hashCode());
result = prime * result + ((values == null) ? 0 : values.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Result other = (Result) obj;
if (detailedResult == null) {
if (other.detailedResult != null)
return false;
} else if (!detailedResult.equals(other.detailedResult))
return false;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
if (values == null) {
if (other.values != null)
return false;
} else if (!values.equals(other.values))
return false;
return true;
}
}
| {
"content_hash": "b66a54836fa5ed601184ebc275a8d5e5",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 87,
"avg_line_length": 26.910958904109588,
"alnum_prop": 0.678544158819038,
"repo_name": "RPTools/zz-old-rptools-common",
"id": "b20b2cdf00264c0a830ff9fb571963af16f314ca",
"size": "3929",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "rplib/src/main/java/net/rptools/lib/result/Result.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "430122"
},
{
"name": "JavaScript",
"bytes": "20068"
}
],
"symlink_target": ""
} |
<div class="example" ng-controller="MainController as vm">
<div class="item" ng-repeat="item in vm.itemList">
{{ item }}
</div>
</div> | {
"content_hash": "5a426d257ee764191796aed5bc18f020",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 58,
"avg_line_length": 27.6,
"alnum_prop": 0.6594202898550725,
"repo_name": "baileyisms/Not-Explorer",
"id": "f3724cfb892e1c976b8db36aab9f8e07a1dd33fe",
"size": "138",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ui/src/window.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "150"
},
{
"name": "HTML",
"bytes": "724"
},
{
"name": "JavaScript",
"bytes": "2409"
}
],
"symlink_target": ""
} |
module Dogcatcher
VERSION = '0.3.3'.freeze
end
| {
"content_hash": "99fb4d427d54e94a8df566e611ba2bdb",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 26,
"avg_line_length": 16.333333333333332,
"alnum_prop": 0.7142857142857143,
"repo_name": "zl4bv/dogcatcher",
"id": "40247788ad4b0f6098cbe510f973ed5c93c143bb",
"size": "49",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/dogcatcher/version.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "23294"
},
{
"name": "Shell",
"bytes": "115"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Piauí</logradouro><bairro>São Paulo</bairro><cidade>Barreiras</cidade><uf>BA</uf><cep>47807024</cep></feed>
| {
"content_hash": "f75123b9deb5c9f712a3ccdb9a1a456e",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 141,
"avg_line_length": 99,
"alnum_prop": 0.7171717171717171,
"repo_name": "chesarex/webservice-cep",
"id": "9714b5267ae536aacf9e699ced14c436c0d5228e",
"size": "200",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/ceps/47/807/024/cep.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Builders;
using Ploeh.AutoFixture.Kernel;
namespace Ploeh.AutoFixture.NUnit3
{
/// <summary>
/// This attribute uses AutoFixture to generate values for unit test parameters.
/// This implementation is based on TestCaseAttribute of NUnit3
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes", Justification = "This attribute is the root of a potential attribute hierarchy.")]
public class AutoDataAttribute : Attribute, ITestBuilder
{
private readonly IFixture _fixture;
/// <summary>
/// Construct a <see cref="AutoDataAttribute"/>
/// </summary>
public AutoDataAttribute()
: this(new Fixture())
{
}
/// <summary>
/// Construct a <see cref="AutoDataAttribute"/> with an <see cref="IFixture"/>
/// </summary>
/// <param name="fixture"></param>
protected AutoDataAttribute(IFixture fixture)
{
if (null == fixture)
{
throw new ArgumentNullException(nameof(fixture));
}
_fixture = fixture;
}
/// <summary>
/// Construct one or more TestMethods from a given MethodInfo,
/// using available parameter data.
/// </summary>
/// <param name="method">The MethodInfo for which tests are to be constructed.</param>
/// <param name="suite">The suite to which the tests will be added.</param>
/// <returns>One or more TestMethods</returns>
public IEnumerable<TestMethod> BuildFrom(IMethodInfo method, Test suite)
{
var test = new NUnitTestCaseBuilder().BuildTestMethod(method, suite, this.GetParametersForMethod(method));
yield return test;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "This method is always expected to return an instance of the TestCaseParameters class.")]
private TestCaseParameters GetParametersForMethod(IMethodInfo method)
{
try
{
var parameters = method.GetParameters();
var parameterValues = this.GetParameterValues(parameters);
return new TestCaseParameters(parameterValues.ToArray());
}
catch (Exception ex)
{
return new TestCaseParameters(ex);
}
}
private IEnumerable<object> GetParameterValues(IEnumerable<IParameterInfo> parameters)
{
return parameters.Select(Resolve);
}
private object Resolve(IParameterInfo parameterInfo)
{
CustomizeFixtureByParameter(parameterInfo);
return new SpecimenContext(this._fixture)
.Resolve(parameterInfo.ParameterInfo);
}
private void CustomizeFixtureByParameter(IParameterInfo parameter)
{
var customizeAttributes = parameter.GetCustomAttributes<CustomizeAttribute>(false)
.OrderBy(x => x, new CustomizeAttributeComparer());
foreach (var ca in customizeAttributes)
{
var customization = ca.GetCustomization(parameter.ParameterInfo);
this._fixture.Customize(customization);
}
}
}
} | {
"content_hash": "7e7010c316392137a94b27fd623133c9",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 224,
"avg_line_length": 36.656565656565654,
"alnum_prop": 0.6277211352989804,
"repo_name": "sergeyshushlyapin/AutoFixture",
"id": "3b771721eb95499af2db211237afcdcf5b7a8c75",
"size": "3631",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "Src/AutoFixture.NUnit3/AutoDataAttribute.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "178"
},
{
"name": "C#",
"bytes": "3974558"
},
{
"name": "F#",
"bytes": "59176"
},
{
"name": "Pascal",
"bytes": "170"
},
{
"name": "PowerShell",
"bytes": "281"
},
{
"name": "Shell",
"bytes": "213"
},
{
"name": "Smalltalk",
"bytes": "2018"
},
{
"name": "XSLT",
"bytes": "17270"
}
],
"symlink_target": ""
} |
/*
* Main.java
*
*
*/
package openjava.ojc;
import java.io.PrintStream;
public class Main {
public static void main(String argc[]) {
System.err.println("OpenJava Compiler Version 1.1 " + "build 20031119");
CommandArguments arguments;
try {
arguments = new CommandArguments(argc);
} catch (Exception e) {
showUsage();
return;
}
new Compiler(arguments).run();
}
private static void showUsage() {
PrintStream o = System.err;
o.println("Usage : ojc <options> <source files>");
o.println("where <options> includes:");
o.println(
" -verbose "
+ "Enable verbose output ");
o.println(
" -g=<number> "
+ "Specify debugging info level ");
o.println(
" -d=<directory> "
+ "Specify where to place generated files ");
o.println(
" -compiler=<class> "
+ "Specify regular Java compiler ");
o.println(
" --default-meta=<file> "
+ "Specify separated meta-binding configurations");
o.println(
" -calleroff "
+ "Turn off caller-side translations ");
o.println(
" -C=<argument> "
+ "Pass the argument to Java compiler ");
o.println(
" -J<argument> "
+ "Pass the argument to JVM ");
}
}
| {
"content_hash": "b27b2b4a3b43cb4ba0b121daf6a10249",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 80,
"avg_line_length": 30.37037037037037,
"alnum_prop": 0.4481707317073171,
"repo_name": "jeffoffutt/OJ",
"id": "652c465bcdb39566c5e29bb5818e42f50868f55b",
"size": "1640",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/openjava/ojc/Main.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1391"
},
{
"name": "Groovy",
"bytes": "75"
},
{
"name": "HTML",
"bytes": "9926985"
},
{
"name": "Java",
"bytes": "1862284"
},
{
"name": "Perl",
"bytes": "24319"
},
{
"name": "Scala",
"bytes": "71"
},
{
"name": "Shell",
"bytes": "6991"
}
],
"symlink_target": ""
} |
layout: post
title: "A modern REST API in Laravel 5 Part 1: Structure"
subtitle: "A modern take on a scalable structure for your Laravel API"
date: 2016-04-11 17:04:00 +0200
author: "Esben Petersen"
header-img: "img/post-bg-01.jpg"
---
## tl;dr
<p>
This article will demonstrate how to separate your Laravel project into "folders-by-component"
rather than "folders-by-type". Confused?
<a href="https://github.com/esbenp/larapi">See the example here</a> or
<a href="https://github.com/esbenp/distributed-laravel">the library here</a>.
</p>
## Introduction
<p>
Over time when your API grows in size it also grows in complexity. Many moving parts
work together in order for it to function. If you do not employ a scaleable structure
you will have a hard time maintaining your API. New additions will cause side effects
and breakage in other places etc.
</p>
<p>
It is important to realize in software development no singular structure is the mother
of all structures. It is important to build a toolbox of patterns which you can employ
given different situations. This article will serve as an opinionated piece on how such a structure <i>could</i> look.
It has enabled <a href="http://traede.com/company">my team and I</a> to keep building
features without introducing (too many :-)) breakages. For me, the structure I am about to show you works well right now,
however it might well be that we refactor into a new one tomorrow. With that said, I hope you
will find inspiration in what I am about to show you. :-)
</p>
## Agenda
<p>
We will take a look at structure on three different levels.
</p>
<ol>
<li>Application flow pattern</li>
<li>Project folder structure</li>
<li>Resource folder structure</li>
</ol>
## Level 1: Application flow pattern
<p>
Too make our project more scalable it is always a good idea to separate our code base into smaller chunks.
I have seen plenty of Laravel projects where everything is written inside controller classes:
authentication, input handling, authorization, data manipulation, database operations, response creation etc.
Imagine something like this...
</p>
```php?start_inline=1
class UserController extends Controller
{
public function create(Request $request)
{
if (!Auth::check()) {
return response()->json([
'error' => "You are not authenticated"
], 401);
}
if (Gate::denies('create-user')) {
return response()->json([
'error' => "You are no authorized to create users"
], 403);
}
$data = $request->get('user');
$email = $data['email'];
$exists = User::where('email', $email)->get()->first();
if (!is_null($exists)) {
return response()->json([
'error' => "A user with the email $email already exists!"
]);
}
$user = User::create($data);
$activation = Activation::create($user->id);
$user->activation->save($activation);
Mail::send('user.activation', function($message) use ($user) {
$m->from('[email protected]', 'Your Application');
$m->to($user->email, $user->name)->subject('Welcome to my crappy app');
});
return response()->json($user, 201);
}
}
```
<p class="note">
NOTE: This is very much a contrived example, probably not even valid code, to demonstrate
giving controllers too many responsibilities.
</p>
<p>
Now imagine your user resource has many endpoints.
</p>
```php
GET /users
GET /users/{id}
POST /users
PUT /users/{id}
DELETE /users/{id}
// etc.
```
<p>
The UserController quickly grows into a monstrosity of duct-tape-code barely holding the fort together.
It is time for separation of concerns.
</p>
### Introducing the service-repository pattern
<p>
In 2013 <a href="https://laracasts.com/lessons/repositories-simplified">the repository pattern was all the rage in the Laravel community</a>.
<a href="https://laracasts.com/series/commands-and-domain-events">Then in 2014 it was the command bus</a>. Remember,
there is no single pattern which is the one to always choose. New patterns emerge all the time, and they should
<i>add to your toolbox, not replace it</i>.
</p>
<p>
Now, for me, the service-repository pattern solves a lot of my issues with complexity. The figure below demonstrates
how we use the pattern at <a href="http://traede.com">Traede</a>.
</p>
<p style="text-align: center">
<img src="/img/service-repository-pattern.png" alt="Service repository pattern in Laravel">
</p>
#### 1. The controller
<p>
The controller is the entry point and exit for the application. It should define the endpoints of our resources.
We use it for simple validation using
<a href="https://laravel.com/docs/master/validation#validation-quickstart">Laravel's request validation</a> and for
parsing any resource control options passed with the request (more on this in part 2). The controller will call
the appropriate service class method and format the response in JSON with the correct status code.
</p>
#### 2. The middleware
<p>
<a href="http://esbenp.github.io/2015/07/31/implementing-before-after-middleware/">I love the concept of middleware</a>.
We use it for many things. However, in our simplified example here it will serve as an <i>authentication checkpoint</i>.
More on that in part 4.
</p>
#### 3. Service class
<p>
They way we are seeing the service class is as the glue of the operation. The goal of our example operation
<code>POST /users</code> is to create a user. The service class will function as the operator that pulls different
classes together in order to complete that operation.
</p>
#### 4. Repositories
<p>
The repository pattern is an easy way to abstract away database operations. This way we separate business logic
and SQL logic from our application. More on this in part 2.
</p>
#### 5. Events
<p>
Using the event system is an effective way abstracting away complexity. It will be used for internal events
(like sending the user created notification) and for webhooks.
</p>
### An example
<p>
Alright, let us have a look on how we can use this pattern to implement our endpoint <code>POST /users</code>.
So the goal is to create a user, but what steps does that operation entail exactly?
</p>
<ol>
<li>Simple data validation (is it a valid email?)</li>
<li>Authenticate the user</li>
<li>Authorize that the user has permission to create users</li>
<li>Complex data validation (is the email unique?)</li>
<li>Create the database record</li>
<li>Send email created notification to the new user</li>
<li>Return the created user in JSON format with status code 201</li>
</ol>
<p></p>
#### 1. The controller
```php?start_inline=1
class UserController extends Controller
{
private $userService;
public function __construct(UserService $userService) {
$this->userService = $userService;
}
public function create(CreateUserRequest $request)
{
$user = $this->userService->create($request->get('user'));
return response()->json($user, 201);
}
}
```
```php?start_inline=1
class CreateUserRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'user' => 'required|array',
'user.email' => 'required|email'
];
}
}
```
<p>
As it is evident, not a lot of stuff going on. This is to ensure our controllers can grow.
It might look empty now, but it will have a decent size (without being to big) once we add
4-5 endpoints more. We have also kept its responsibilities to a minimum thus making the
class easy to reason about for other developers than ourself.
</p>
#### 2. The middleware layer
<p>
The authentication of our user will happen behind the scenes using Laravel's middleware system
and other libraries. We will get to the implementation of this in part 4. For now, just assume it
is there.
</p>
#### 3. The service class
```php?start_inline=1
<?php
namespace App\Services;
use App\Exceptions\EmailIsNotUniqueException;
use App\Events\UserWasCreated;
use App\Helpers\UserValidator;
use App\Repositories\UserRepository;
use Infrastructure\Auth\Authentication;
use Illuminate\Events\Dispatcher;
class UserService
{
private $auth;
private $dispatcher;
private $userRepository;
private $userValidator;
public function __construct(
Authentication $auth,
Dispatcher $dispatcher,
UserRepository $userRepository,
UserValidator $userValidator
) {
$this->auth = $auth;
$this->dispatcher = $dispatcher;
$this->userRepository = $userRepository;
$this->userValidator = $userValidator;
}
public function create(array $data)
{
$account = $this->auth->getCurrentUser();
// Check if the user has permission to create other users.
// Will throw an exception if not.
$account->checkPermission('users.create');
// Use our validation helper to check if the given email
// is unique within the account.
if (!$this->userValidator->isEmailUniqueWithinAccount($data['email'], $account->id)) {
throw new EmailIsNotUniqueException($data['email']);
}
// Set the account ID on the user and create the record in the database
$data['account_id'] = $account->id;
$user = $this->userRepository->create($data);
// If we set the relation right away on the user model, then we can
// call $user->account without quering the database. This is useful if
// we need to call $user->account in any of the event listeners
$user->setRelation('account', $account);
// Fire an event so that listeners can react
$this->dispatcher->fire(new UserWasCreated($user));
return $user;
}
}
```
<p>
Okay, so a lot of stuff going on here. Let us break it down step by step.
</p>
```php?start_inline=1
$account = $this->auth->getCurrentUser();
// Check if the user has permission to create other users.
// Will throw an exception if not.
$account->checkPermission('users.create');
```
<p>
We get the current user (i.e. the user that makes the request). We have to check
if this user has the permission to actually create users. How we do this is covered
in part 4. For now, just know that if the user does not have permission to create
users an exception will be thrown.
</p>
```php?start_inline=1
// Use our validation helper to check if the given email
// is unique within the account.
if (!$this->userValidator->isEmailUniqueWithinAccount($data['email'], $account->id)) {
throw new EmailIsNotUniqueException($data['email']);
}
```
<p>
Okay, so I realize this could have been done in the request validation using an
<a href="https://laravel.com/docs/master/validation#rule-unique">unique rule</a>.
However, this is just to illustrate two things: (I) sometimes you will have to do more
complex data manipulation or validation that cannot be done automatically by Laravel.
Using helper classes and having the service class "string it all together" is a
great way of achieving this. (II) By throwing an exception we abort the flow so
we make sure nothing else is executed before the user has fixed the error. More
on this in part 3.
</p>
```php?start_inline=1
// Set the account ID on the user and create the record in the database
$data['account_id'] = $account->id;
$user = $this->userRepository->create($data);
// If we set the relation right away on the user model, then we can
// call $user->account without quering the database. This is useful if
// we need to call $user->account in any of the event listeners
$user->setRelation('account', $account);
```
<p>
So in our fictitious example we have 1 account. And each account can have many users.
</p>
<pre>
Accounts 1 -------> n Users
</pre>
<p>
We therefore add the <code>account_id</code> to the data, which the repository will
persist in the database. I realize it is simpler to achieve this with
<code>$user->account->save($account)</code>, however in this example we spare 1 more
query to the database. And it is also just to demonstrate there are other ways
of achieving the goal.
</p>
```php?start_inline=1
// Fire an event so that listeners can react
$this->dispatcher->fire(new UserWasCreated($user));
return $user;
```
<p>
We fire an event through the event system for listeners to react to. In this example
a listener will send the email notification. But more on this in part 5.
</p>
<p>
If we want to decrease the responsibilities of our service class further, we can easily
refactor the validation of data and the creation of the database entry to a UserBuilder class.
However, for now we will keep the code as is.
</p>
#### 4. The repository
```php?start_inline=1
class UserRepository
{
public function create(array $data)
{
DB::beginTransaction();
try {
$user = new User;
$user->account_id = $data['account_id'];
$user->fill($data);
$user->save();
$activation = new Activation;
$activation->user_id = $user->id;
$activation->save();
} catch(Exception $e) {
DB::rollBack();
throw $e;
}
DB::commit();
return $user;
}
}
```
```php?start_inline=1
class User extends EloquentModel
{
protected $fillable = [
'email'
];
// Activation relation
}
```
<p>
For now our repository is super simple. Later on, we will let it extend a base
class for advanced functionality but for now it will due. Notice, we never let
relation properties be fillable.
</p>
<p>
So in our example each user has an activation record that indicates whether or not
the user has activated (by clicking an activation link we send our by email).
Thus when creating a user we have to create both records and relate them to one another.
This is the reason why we wrap our code in a database transaction. Should the
activation record creation fail, for whatever reason, we want to fail the user record
as well and let the exception bubble up so we can handle it (we will do so in part 3).
</p>
<p>
<img src="/img/service-repository-pattern-2.png">
</p>
<p>
Before we get into how we can structure our project folder, let us recap what we did.
We divided an operation into different parts that each has a more narrower field of
responsibility, thereby effectively allowing our code base to grow.
</p>
### Level 2: Project folder structure
<p>
One of the first things that happened as our API grew was that we introduced a lot of custom infrastructure. Things like analytics integration, base repositories, exception handlers, queue infrastructure, testing helpers, custom validation rules etc. became part of our code base.
</p>
<p>
What we realized was that we were mixing <i>business code</i> with
<i>infrastructure code</i>. Confused? Think about it. How would it look if
all the Laravel framework code was in the same folder as your API code?
That would make no sense, right? This is because the Laravel framework is merely infrastructure
that enables you to rapidly iterate on your <i>business code</i> without having to write a lot of infrastructure code. If you are interested in
such architectural topics I suggest you look into stuff like
<a href="http://fideloper.com/hexagonal-architecture">Hexagonal Architecture</a> and <a href="https://domainlanguage.com/">Domain Driven Design</a>.
</p>
<p>
To make matters even worse for us, in Traede, we have an app store. Basically it is a bunch of apps you can install in your account, i.e. they are <u>not part of the core product</u>. We realized we could divide our API into three parts: (I) the core business, (II) infrastructure and (III) extensions installable via app store.
</p>
<p>
<img src="/img/traede-structure.png">
</p>
<p>
So we decided our project structure should reflect the same.
</p>
<p>
<img src="/img/old-new-api-structure.png">
</p>
<p>
Above you see a comparison of how our project structure changed. On the left is the standard
Laravel structure most of you are probably used to. In the past it contained all of our code:
business code, infrastructure, extensions - everything! Now we have separated those concerns
into separate namespaces. And the best part is that it is ridiculously easy to implement.
In the <code>autoload</code> section of your <code>composer.json</code> set it up like so.
</p>
```json
// ...
"psr-4": {
"Apps\\": "app-store/",
"Traede\\": "traede/",
"Infrastructure\\": "infrastructure/"
}
// ...
```
<p>
If you want tests to be run you will also have to add a testsuite to <code>phpunit.xml</code>.
<a href="https://github.com/esbenp/larapi/blob/master/phpunit.xml#L12">See how here</a>.
</p>
<p>
Now, if you are an attentive reader (as I am sure you are), you may have noticed that the
<code>resources/</code> and <code>tests/</code> folders have disappeared from the project.
There is a good reason for that which I will explain in the next section.
</p>
### Level 3: Resource folder structure
<!-- Do not change the indention of the HTML here! it will break the rendering -->
<div class="row">
<div class="col-md-4">
<img src="/img/bad-project-structure.png">
</div>
<div class="col-md-8">
<p style="margin-top:0">
What you see on the left is an example of how our code base grew at Traede.
Laravel by default is organized such that the code is "grouped-by-type".
So all the controllers are in a folder together, all the
models are in a folder together, all the events are in a folder together etc.
</p>
<p>
What often happened was that I would be working on let us say the "Products component"
of our API. The files of interest can be described as below.
</p>
{% highlight bash %}
/ app
/ Http
/ Controllers
..
/ ProductController.php
..
/ Models
..
Product.php
ProductVariant.php
ProductVariantPrice.php
..
/ Repositories
..
ProductRepository.php
ProductVariantRepository.php
ProductVariantPriceRepository.php
..
/ Services
..
ProductService.php
VariantService.php
..
{% endhighlight %}
<p class="note" style="margin-bottom:0;">
<code>..</code> represents other files and folders.
</p>
</div>
</div>
<p>
As you can imagine your files are spread very far from each other vertically in your
project tree. I was not event able to take a screenshot with my
product-component repositories and services in the same image. As I see it,
this structure only makes sense if you "work on all the repositories right now" or
"work on all the models right now". But you rarely do that, do you?
</p>
<p>
Would it not be better if all the files were organized by component? E.g.
all the product-oriented services, repositories, models, routes etc. in the same
folder?
</p>
<!-- Do not change the indention of the HTML here! it will break the rendering -->
<div class="row">
<div class="col-md-4">
<img src="/img/better-project-structure.png">
</div>
<div class="col-md-8">
<p style="margin-top:0">
As you can see we have divided the core product of Traede into 8 separate components.
A component typically has these folders
</p>
{% highlight bash %}
/ Products
/ Controllers
# We typically have a controller per
# resource, e.g. ProductController,
# TagController, VariantController etc.
/ Events
# All the events that can be raised by
# the component, e.g. ProductWasCreated,
# VariantPriceDeleted etc.
/ Exceptions
# All exceptions. We currently have about 20
# custom exceptions for products like
# DuplicateSkuException and
# BasePriceNotDefinedException
/ Listeners
# Listeners for events
/ Models
# Eloquent models: Product, Variant, Tag etc.
/ Repositories
# We typically have a repository per eloquent model
# ProductRepository, VariantRepository etc.
/ Requests
# HTTP requests for validation
/ Services
# A few larger classes that string together operations
# typically we make one per controller, like
# ProductController -> ProductService
/ Tests
# All tests for the component
# Typically used to connect events and listeners.
ProductServiceProvider.php
# All the routes for the component. Having distributed
# route files, makes them ALOT more clear when you
# have 100+ routes :-)
routes.php
{% endhighlight %}
</div>
</div>
<p>
So this clears up what happened to the <code>tests/</code> folder of the
root folder. We simply gave each component a folder to have its tests
within. But what about the <code>resources/</code>?
</p>
<p>
One of the powers of the
<a href="https://github.com/esbenp/distributed-laravel">distributed laravel</a>
package is that it can search for resource files in the new component structure.
</p>
<p>
In our entities component we have a lot of email views for transactional emails.
The system will simply look for a <code>resources/</code> folder within
<code>traede/Entities/</code> an load it into Laravel as the normal resources folder
is.
</p>
<p>
Another example is that Laravel by default comes with a langugage file for
validation rules saved in <code>resources/lang/en/validation.php</code>.
We have a validation component in our infrastructure that contains custom
validation rules etc. It looks like this.
</p>
```bash
/ infrastructure
.. # Other infrastructure components
/ Validation
/ resources
/ en
# The default validation translations
/ validation.php
# Loads custom validation rules
ValidationServiceProvider.php
```
## Getting started
<p>
Go to GitHub to see the <a href="https://github.com/esbenp/larapi">Larapi</a> example
to see how the code is structured. If you want to implement this in an existing
project you can use the service providers of
<a href="https://github.com/esbenp/distributed-laravel">distributed-laravel</a> to
load the components into Laravel. Browsing the Larapi code is best way to see
how you should restructure.
</p>
## Conclusion
<p>
This structure is still very new for me, so I am still experimenting and I am
sure somethings could be done better. You think so as well? Reach out on
<a href="mailto:[email protected]">e-mail</a>,
<a href="https://twitter.com/esbenp">twitter</a> or
<a href="https://github.com/esbenp/larapi/issues">the Larapi repository</a>
</p>
| {
"content_hash": "593674fd53ce5a160ef8e02e01cc2c90",
"timestamp": "",
"source": "github",
"line_count": 708,
"max_line_length": 330,
"avg_line_length": 32.24152542372882,
"alnum_prop": 0.6960178735707715,
"repo_name": "esbenp/esbenp.github.io",
"id": "5a26c71af4be7f67291d1b61a65a7710727dafb2",
"size": "22831",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2016-04-11-modern-rest-api-laravel-part-1.markdown",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "30179"
},
{
"name": "HTML",
"bytes": "10718"
},
{
"name": "JavaScript",
"bytes": "53211"
},
{
"name": "PHP",
"bytes": "11810"
},
{
"name": "Ruby",
"bytes": "3239"
}
],
"symlink_target": ""
} |
package com.google.gwtexpui.clippy.client;
import com.google.gwt.resources.client.CssResource;
public interface ClippyCss extends CssResource {
String label();
String copier();
String swf();
}
| {
"content_hash": "10e646778999027262048e6495c6bfb9",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 51,
"avg_line_length": 22.333333333333332,
"alnum_prop": 0.7661691542288557,
"repo_name": "MerritCR/merrit",
"id": "05a1861f8c28483c591ecabd4988137004b250a8",
"size": "810",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "gerrit-gwtexpui/src/main/java/com/google/gwtexpui/clippy/client/ClippyCss.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "52838"
},
{
"name": "GAP",
"bytes": "4119"
},
{
"name": "Go",
"bytes": "6200"
},
{
"name": "Groff",
"bytes": "28221"
},
{
"name": "HTML",
"bytes": "380099"
},
{
"name": "Java",
"bytes": "10070223"
},
{
"name": "JavaScript",
"bytes": "197056"
},
{
"name": "Makefile",
"bytes": "1313"
},
{
"name": "PLpgSQL",
"bytes": "4202"
},
{
"name": "Perl",
"bytes": "9943"
},
{
"name": "Prolog",
"bytes": "17904"
},
{
"name": "Python",
"bytes": "18218"
},
{
"name": "Shell",
"bytes": "48919"
},
{
"name": "TypeScript",
"bytes": "1882"
}
],
"symlink_target": ""
} |
#include "../header/game_object.h"
//Main State constants
const u16 SCREENHOLE =48; //How big percieved hole between screens is
const u16 BORDER = 4; //Border in pixels around screen (used for collisions)
//Defines for width and height of screen
const u16 SHEIGHT = 191;
const u16 SWIDTH = 255;
//Defines for width of pitch
const u16 PWIDTH = SWIDTH-(BORDER*2);
const u16 PHEIGHT = SHEIGHT-BORDER;//No border on top
//Define max min x for game objects
const u16 MAXX = SWIDTH - BORDER;
const u16 MINX = 0+BORDER;
//Defines for max min y for an game object to be screen 0 (bottom)
const u16 MAXYS0 = SHEIGHT*2+SCREENHOLE - BORDER;
const u16 MINYS0 = 0+SHEIGHT+SCREENHOLE;
//Defines max min y for game object to be on screen 1 (top)
const u16 MAXYS1 = SHEIGHT;
const u16 MINYS1 = 0+BORDER;
//Defines max min y for game object to be dual screen
const u16 MAXYDUAL = SHEIGHT*2+SCREENHOLE - BORDER;
const u16 MINYDUAL = 0+BORDER;
//Define for square root LUT size
const u16 LUTSIZE = 4624;
//Define for goal
const u16 GOALWIDTH = 80;
const u16 GOALHEIGHT = 10;
class InGame : public State{
public:
InGame(int level);
~InGame();
void run();
void reset();
void initGraphics();
NAME getMyName(); //Not implemented yet
protected:
void init(int level);
private:
int playerScore;
int computerScore;
void resetGameObjects();
void doCollisions(void);
u32 getDistance(s16 x1,s16 y1,s16 x2,s16 y2);
void doDrawing(void);
void print_debug(void);
void processInput(void);
inline u32 square(u32 a);
void goalScored(int computerScored);
void drawScore(int screen);
void doIntel1();
void doIntel2();
void doIntel3();
void doIntel4();
void doIntel5();
void handlePuckCollision(GameObject * puck,GameObject * handle);
void boundaryCheck(GameObject * gameObject,s32 minx,s32 maxx,s32 miny,s32 maxy);
void boundaryCheckPuck();
//Level dependent stuff
int currentLevel;
int computerWidth;
void (InGame::* intelPointer) (); //What AI are we gonna use?
void* computerImage; //What computer image are we going to use
int obj_size;
};
#endif
| {
"content_hash": "a44da967a19cdd5d9a29b41a31d04086",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 82,
"avg_line_length": 27.59493670886076,
"alnum_prop": 0.6944954128440367,
"repo_name": "jrgrafton/pucka-ds",
"id": "c7ff252693b02654362adfc2381377a45a8d0e79",
"size": "2222",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pukka/header/in_game.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "593893"
},
{
"name": "C++",
"bytes": "30385"
},
{
"name": "Objective-C",
"bytes": "5320"
},
{
"name": "Shell",
"bytes": "12"
}
],
"symlink_target": ""
} |
package org.uberfire.client.screens.todo;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;
import org.jboss.errai.common.client.api.Caller;
import org.jboss.errai.common.client.api.RemoteCallback;
import org.uberfire.backend.vfs.Path;
import org.uberfire.backend.vfs.VFSService;
import org.uberfire.client.annotations.DefaultPosition;
import org.uberfire.client.annotations.WorkbenchPartView;
import org.uberfire.workbench.model.CompassPosition;
import org.uberfire.workbench.model.Position;
public abstract class AbstractMarkdownScreen extends Composite {
protected static final String EMPTY = "<p>-- empty --</p>";
protected HTML markdown = new HTML(EMPTY);
@Inject
protected Caller<VFSService> vfsServices;
public static native String parseMarkdown(String content)/*-{
return $wnd.marked(content);
}-*/;
@PostConstruct
public void init() {
vfsServices.call(new RemoteCallback<Path>() {
@Override
public void callback(final Path o) {
vfsServices.call(new RemoteCallback<String>() {
@Override
public void callback(final String response) {
if (response == null) {
setContent(EMPTY);
} else {
try {
setContent(parseMarkdown(response));
} catch (Exception e) {
setContent(EMPTY);
GWT.log("Error parsing markdown content",
e);
}
}
}
}).readAllString(o);
}
}).get(getMarkdownFileURI());
markdown.getElement().getStyle().setPadding(15,
Style.Unit.PX);
initWidget(markdown);
}
@WorkbenchPartView
public Widget getView() {
return this;
}
@DefaultPosition
public Position getDefaultPosition() {
return CompassPosition.EAST;
}
public abstract String getMarkdownFileURI();
protected void setContent(final String content) {
this.markdown.setHTML(content);
}
}
| {
"content_hash": "5e1ef4568ccdf209b63d69d408c20c5e",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 73,
"avg_line_length": 32.46153846153846,
"alnum_prop": 0.5864928909952607,
"repo_name": "porcelli-forks/uberfire",
"id": "bcf02a856ff37ffbfdb4945baedceaf0554028d3",
"size": "3153",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "uberfire-showcase/uberfire-webapp/src/main/java/org/uberfire/client/screens/todo/AbstractMarkdownScreen.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "74063"
},
{
"name": "FreeMarker",
"bytes": "46611"
},
{
"name": "HTML",
"bytes": "91780"
},
{
"name": "Java",
"bytes": "13164946"
},
{
"name": "JavaScript",
"bytes": "85658"
},
{
"name": "Shell",
"bytes": "5830"
}
],
"symlink_target": ""
} |
// Copyright 2015 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 "content/renderer/categorized_worker_pool.h"
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/containers/contains.h"
#include "base/containers/cxx20_erase.h"
#include "base/strings/stringprintf.h"
#include "base/task/sequence_manager/task_time_observer.h"
#include "base/task/single_thread_task_runner.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread_restrictions.h"
#include "base/trace_event/typed_macros.h"
#include "build/build_config.h"
#include "cc/base/math_util.h"
#include "cc/raster/task_category.h"
namespace content {
namespace {
// Task categories running at normal thread priority.
constexpr cc::TaskCategory kNormalThreadPriorityCategories[] = {
cc::TASK_CATEGORY_NONCONCURRENT_FOREGROUND, cc::TASK_CATEGORY_FOREGROUND,
cc::TASK_CATEGORY_BACKGROUND_WITH_NORMAL_THREAD_PRIORITY};
// Task categories running at background thread priority.
constexpr cc::TaskCategory kBackgroundThreadPriorityCategories[] = {
cc::TASK_CATEGORY_BACKGROUND};
// Foreground task categories.
constexpr cc::TaskCategory kForegroundCategories[] = {
cc::TASK_CATEGORY_NONCONCURRENT_FOREGROUND, cc::TASK_CATEGORY_FOREGROUND};
// Background task categories. Tasks in these categories cannot start running
// when a task with a category in |kForegroundCategories| is running or ready to
// run.
constexpr cc::TaskCategory kBackgroundCategories[] = {
cc::TASK_CATEGORY_BACKGROUND,
cc::TASK_CATEGORY_BACKGROUND_WITH_NORMAL_THREAD_PRIORITY};
// A thread which forwards to CategorizedWorkerPool::Run with the runnable
// categories.
class CategorizedWorkerPoolThread : public base::SimpleThread {
public:
CategorizedWorkerPoolThread(
const std::string& name_prefix,
const Options& options,
CategorizedWorkerPool* pool,
std::vector<cc::TaskCategory> categories,
base::ConditionVariable* has_ready_to_run_tasks_cv)
: SimpleThread(name_prefix, options),
pool_(pool),
categories_(categories),
has_ready_to_run_tasks_cv_(has_ready_to_run_tasks_cv) {}
void SetBackgroundingCallback(
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
base::OnceCallback<void(base::PlatformThreadId)> callback) {
DCHECK(!HasStartBeenAttempted());
background_task_runner_ = std::move(task_runner);
backgrounding_callback_ = std::move(callback);
}
// base::SimpleThread:
void BeforeRun() override {
if (backgrounding_callback_) {
DCHECK(background_task_runner_);
background_task_runner_->PostTask(
FROM_HERE, base::BindOnce(std::move(backgrounding_callback_), tid()));
}
}
void Run() override { pool_->Run(categories_, has_ready_to_run_tasks_cv_); }
private:
CategorizedWorkerPool* const pool_;
const std::vector<cc::TaskCategory> categories_;
base::ConditionVariable* const has_ready_to_run_tasks_cv_;
base::OnceCallback<void(base::PlatformThreadId)> backgrounding_callback_;
scoped_refptr<base::SingleThreadTaskRunner> background_task_runner_;
};
} // namespace
// A sequenced task runner which posts tasks to a CategorizedWorkerPool.
class CategorizedWorkerPool::CategorizedWorkerPoolSequencedTaskRunner
: public base::SequencedTaskRunner {
public:
explicit CategorizedWorkerPoolSequencedTaskRunner(
cc::TaskGraphRunner* task_graph_runner)
: task_graph_runner_(task_graph_runner),
namespace_token_(task_graph_runner->GenerateNamespaceToken()) {}
// Overridden from base::TaskRunner:
bool PostDelayedTask(const base::Location& from_here,
base::OnceClosure task,
base::TimeDelta delay) override {
return PostNonNestableDelayedTask(from_here, std::move(task), delay);
}
// Overridden from base::SequencedTaskRunner:
bool PostNonNestableDelayedTask(const base::Location& from_here,
base::OnceClosure task,
base::TimeDelta delay) override {
// Use CHECK instead of DCHECK to crash earlier. See http://crbug.com/711167
// for details.
CHECK(task);
base::AutoLock lock(lock_);
// Remove completed tasks.
DCHECK(completed_tasks_.empty());
task_graph_runner_->CollectCompletedTasks(namespace_token_,
&completed_tasks_);
tasks_.erase(tasks_.begin(), tasks_.begin() + completed_tasks_.size());
tasks_.push_back(base::MakeRefCounted<ClosureTask>(std::move(task)));
graph_.Reset();
for (const auto& graph_task : tasks_) {
int dependencies = 0;
if (!graph_.nodes.empty())
dependencies = 1;
// Treat any tasks that are enqueued through the SequencedTaskRunner as
// FOREGROUND priority. We don't have enough information to know the
// actual priority of such tasks, so we run them as soon as possible.
cc::TaskGraph::Node node(graph_task, cc::TASK_CATEGORY_FOREGROUND,
0u /* priority */, dependencies);
if (dependencies) {
graph_.edges.push_back(cc::TaskGraph::Edge(
graph_.nodes.back().task.get(), node.task.get()));
}
graph_.nodes.push_back(std::move(node));
}
task_graph_runner_->ScheduleTasks(namespace_token_, &graph_);
completed_tasks_.clear();
return true;
}
bool RunsTasksInCurrentSequence() const override { return true; }
private:
~CategorizedWorkerPoolSequencedTaskRunner() override {
{
base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope allow_wait;
task_graph_runner_->WaitForTasksToFinishRunning(namespace_token_);
}
task_graph_runner_->CollectCompletedTasks(namespace_token_,
&completed_tasks_);
}
// Lock to exclusively access all the following members that are used to
// implement the SequencedTaskRunner interfaces.
base::Lock lock_;
cc::TaskGraphRunner* task_graph_runner_;
// Namespace used to schedule tasks in the task graph runner.
cc::NamespaceToken namespace_token_;
// List of tasks currently queued up for execution.
cc::Task::Vector tasks_;
// Graph object used for scheduling tasks.
cc::TaskGraph graph_;
// Cached vector to avoid allocation when getting the list of complete
// tasks.
cc::Task::Vector completed_tasks_;
};
CategorizedWorkerPool::CategorizedWorkerPool()
: namespace_token_(GenerateNamespaceToken()),
has_task_for_normal_priority_thread_cv_(&lock_),
has_task_for_background_priority_thread_cv_(&lock_),
has_namespaces_with_finished_running_tasks_cv_(&lock_),
shutdown_(false) {
// Declare the two ConditionVariables which are used by worker threads to
// sleep-while-idle as such to avoid throwing off //base heuristics.
has_task_for_normal_priority_thread_cv_.declare_only_used_while_idle();
has_task_for_background_priority_thread_cv_.declare_only_used_while_idle();
}
void CategorizedWorkerPool::Start(int num_normal_threads) {
DCHECK(threads_.empty());
// |num_normal_threads| normal threads and 1 background threads are created.
const size_t num_threads = num_normal_threads + 1;
threads_.reserve(num_threads);
// Start |num_normal_threads| normal priority threads, which run foreground
// work and background work that cannot run at background thread priority.
std::vector<cc::TaskCategory> normal_thread_prio_categories(
std::begin(kNormalThreadPriorityCategories),
std::end(kNormalThreadPriorityCategories));
for (int i = 0; i < num_normal_threads; i++) {
auto thread = std::make_unique<CategorizedWorkerPoolThread>(
base::StringPrintf("CompositorTileWorker%d", i + 1),
base::SimpleThread::Options(), this, normal_thread_prio_categories,
&has_task_for_normal_priority_thread_cv_);
thread->StartAsync();
threads_.push_back(std::move(thread));
}
// Start a single thread running at background thread priority.
std::vector<cc::TaskCategory> background_thread_prio_categories{
std::begin(kBackgroundThreadPriorityCategories),
std::end(kBackgroundThreadPriorityCategories)};
base::SimpleThread::Options thread_options;
#if !defined(OS_MAC)
thread_options.priority = base::ThreadPriority::BACKGROUND;
#endif
auto thread = std::make_unique<CategorizedWorkerPoolThread>(
"CompositorTileWorkerBackground", thread_options, this,
background_thread_prio_categories,
&has_task_for_background_priority_thread_cv_);
if (backgrounding_callback_) {
thread->SetBackgroundingCallback(std::move(background_task_runner_),
std::move(backgrounding_callback_));
}
thread->StartAsync();
threads_.push_back(std::move(thread));
DCHECK_EQ(num_threads, threads_.size());
}
void CategorizedWorkerPool::Shutdown() {
{
base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope allow_wait;
WaitForTasksToFinishRunning(namespace_token_);
}
CollectCompletedTasks(namespace_token_, &completed_tasks_);
// Shutdown raster threads.
{
base::AutoLock lock(lock_);
DCHECK(!work_queue_.HasReadyToRunTasks());
DCHECK(!work_queue_.HasAnyNamespaces());
DCHECK(!shutdown_);
shutdown_ = true;
// Wake up all workers so they exit.
has_task_for_normal_priority_thread_cv_.Broadcast();
has_task_for_background_priority_thread_cv_.Broadcast();
}
while (!threads_.empty()) {
threads_.back()->Join();
threads_.pop_back();
}
}
// Overridden from base::TaskRunner:
bool CategorizedWorkerPool::PostDelayedTask(const base::Location& from_here,
base::OnceClosure task,
base::TimeDelta delay) {
base::AutoLock lock(lock_);
// Remove completed tasks.
DCHECK(completed_tasks_.empty());
CollectCompletedTasksWithLockAcquired(namespace_token_, &completed_tasks_);
base::EraseIf(tasks_, [this](const scoped_refptr<cc::Task>& e)
EXCLUSIVE_LOCKS_REQUIRED(lock_) {
return base::Contains(this->completed_tasks_, e);
});
tasks_.push_back(base::MakeRefCounted<ClosureTask>(std::move(task)));
graph_.Reset();
for (const auto& graph_task : tasks_) {
// Delayed tasks are assigned FOREGROUND category, ensuring that they run as
// soon as possible once their delay has expired.
graph_.nodes.push_back(
cc::TaskGraph::Node(graph_task.get(), cc::TASK_CATEGORY_FOREGROUND,
0u /* priority */, 0u /* dependencies */));
}
ScheduleTasksWithLockAcquired(namespace_token_, &graph_);
completed_tasks_.clear();
return true;
}
void CategorizedWorkerPool::Run(
const std::vector<cc::TaskCategory>& categories,
base::ConditionVariable* has_ready_to_run_tasks_cv) {
base::AutoLock lock(lock_);
while (true) {
if (!RunTaskWithLockAcquired(categories)) {
// We are no longer running tasks, which may allow another category to
// start running. Signal other worker threads.
SignalHasReadyToRunTasksWithLockAcquired();
// Make sure the END of the last trace event emitted before going idle
// is flushed to perfetto.
// TODO(crbug.com/1021571): Remove this once fixed.
PERFETTO_INTERNAL_ADD_EMPTY_EVENT();
// Exit when shutdown is set and no more tasks are pending.
if (shutdown_)
break;
// Wait for more tasks.
has_ready_to_run_tasks_cv->Wait();
continue;
}
}
}
void CategorizedWorkerPool::FlushForTesting() {
base::AutoLock lock(lock_);
while (!work_queue_.HasFinishedRunningTasksInAllNamespaces()) {
has_namespaces_with_finished_running_tasks_cv_.Wait();
}
}
scoped_refptr<base::SequencedTaskRunner>
CategorizedWorkerPool::CreateSequencedTaskRunner() {
return new CategorizedWorkerPoolSequencedTaskRunner(this);
}
void CategorizedWorkerPool::SetBackgroundingCallback(
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
base::OnceCallback<void(base::PlatformThreadId)> callback) {
// The callback must be set before the threads have been created.
DCHECK(threads_.empty());
backgrounding_callback_ = std::move(callback);
background_task_runner_ = std::move(task_runner);
}
CategorizedWorkerPool::~CategorizedWorkerPool() = default;
cc::NamespaceToken CategorizedWorkerPool::GenerateNamespaceToken() {
base::AutoLock lock(lock_);
return work_queue_.GenerateNamespaceToken();
}
void CategorizedWorkerPool::ScheduleTasks(cc::NamespaceToken token,
cc::TaskGraph* graph) {
TRACE_EVENT2("disabled-by-default-cc.debug",
"CategorizedWorkerPool::ScheduleTasks", "num_nodes",
graph->nodes.size(), "num_edges", graph->edges.size());
{
base::AutoLock lock(lock_);
ScheduleTasksWithLockAcquired(token, graph);
}
}
void CategorizedWorkerPool::ScheduleTasksWithLockAcquired(
cc::NamespaceToken token,
cc::TaskGraph* graph) {
DCHECK(token.IsValid());
DCHECK(!cc::TaskGraphWorkQueue::DependencyMismatch(graph));
DCHECK(!shutdown_);
work_queue_.ScheduleTasks(token, graph);
// There may be more work available, so wake up another worker thread.
SignalHasReadyToRunTasksWithLockAcquired();
}
void CategorizedWorkerPool::WaitForTasksToFinishRunning(
cc::NamespaceToken token) {
TRACE_EVENT0("disabled-by-default-cc.debug",
"CategorizedWorkerPool::WaitForTasksToFinishRunning");
DCHECK(token.IsValid());
{
base::AutoLock lock(lock_);
auto* task_namespace = work_queue_.GetNamespaceForToken(token);
if (!task_namespace)
return;
while (!work_queue_.HasFinishedRunningTasksInNamespace(task_namespace))
has_namespaces_with_finished_running_tasks_cv_.Wait();
// There may be other namespaces that have finished running tasks, so wake
// up another origin thread.
has_namespaces_with_finished_running_tasks_cv_.Signal();
}
}
void CategorizedWorkerPool::CollectCompletedTasks(
cc::NamespaceToken token,
cc::Task::Vector* completed_tasks) {
TRACE_EVENT0("disabled-by-default-cc.debug",
"CategorizedWorkerPool::CollectCompletedTasks");
{
base::AutoLock lock(lock_);
CollectCompletedTasksWithLockAcquired(token, completed_tasks);
}
}
void CategorizedWorkerPool::CollectCompletedTasksWithLockAcquired(
cc::NamespaceToken token,
cc::Task::Vector* completed_tasks) {
DCHECK(token.IsValid());
work_queue_.CollectCompletedTasks(token, completed_tasks);
}
bool CategorizedWorkerPool::RunTaskWithLockAcquired(
const std::vector<cc::TaskCategory>& categories) {
for (const auto& category : categories) {
if (ShouldRunTaskForCategoryWithLockAcquired(category)) {
RunTaskInCategoryWithLockAcquired(category);
return true;
}
}
return false;
}
void CategorizedWorkerPool::RunTaskInCategoryWithLockAcquired(
cc::TaskCategory category) {
lock_.AssertAcquired();
auto prioritized_task = work_queue_.GetNextTaskToRun(category);
TRACE_EVENT(
"toplevel", "TaskGraphRunner::RunTask", [&](perfetto::EventContext ctx) {
ctx.event<perfetto::protos::pbzero::ChromeTrackEvent>()
->set_chrome_raster_task()
->set_source_frame_number(prioritized_task.task->frame_number());
});
// There may be more work available, so wake up another worker thread.
SignalHasReadyToRunTasksWithLockAcquired();
{
base::AutoUnlock unlock(lock_);
prioritized_task.task->RunOnWorkerThread();
}
auto* task_namespace = prioritized_task.task_namespace.get();
work_queue_.CompleteTask(std::move(prioritized_task));
// If namespace has finished running all tasks, wake up origin threads.
if (work_queue_.HasFinishedRunningTasksInNamespace(task_namespace))
has_namespaces_with_finished_running_tasks_cv_.Signal();
}
bool CategorizedWorkerPool::ShouldRunTaskForCategoryWithLockAcquired(
cc::TaskCategory category) {
lock_.AssertAcquired();
if (!work_queue_.HasReadyToRunTasksForCategory(category))
return false;
if (base::Contains(kBackgroundCategories, category)) {
// Only run background tasks if there are no foreground tasks running or
// ready to run.
for (cc::TaskCategory foreground_category : kForegroundCategories) {
if (work_queue_.NumRunningTasksForCategory(foreground_category) > 0 ||
work_queue_.HasReadyToRunTasksForCategory(foreground_category)) {
return false;
}
}
// Enforce that only one background task runs at a time.
for (cc::TaskCategory background_category : kBackgroundCategories) {
if (work_queue_.NumRunningTasksForCategory(background_category) > 0)
return false;
}
}
// Enforce that only one nonconcurrent task runs at a time.
if (category == cc::TASK_CATEGORY_NONCONCURRENT_FOREGROUND &&
work_queue_.NumRunningTasksForCategory(
cc::TASK_CATEGORY_NONCONCURRENT_FOREGROUND) > 0) {
return false;
}
return true;
}
void CategorizedWorkerPool::SignalHasReadyToRunTasksWithLockAcquired() {
lock_.AssertAcquired();
for (cc::TaskCategory category : kNormalThreadPriorityCategories) {
if (ShouldRunTaskForCategoryWithLockAcquired(category)) {
has_task_for_normal_priority_thread_cv_.Signal();
return;
}
}
// Due to the early return in the previous loop, this only runs when there are
// no tasks to run on normal priority threads.
for (cc::TaskCategory category : kBackgroundThreadPriorityCategories) {
if (ShouldRunTaskForCategoryWithLockAcquired(category)) {
has_task_for_background_priority_thread_cv_.Signal();
return;
}
}
}
CategorizedWorkerPool::ClosureTask::ClosureTask(base::OnceClosure closure)
: closure_(std::move(closure)) {}
// Overridden from cc::Task:
void CategorizedWorkerPool::ClosureTask::RunOnWorkerThread() {
std::move(closure_).Run();
}
CategorizedWorkerPool::ClosureTask::~ClosureTask() {}
} // namespace content
| {
"content_hash": "bf4eeacba47e8b5b34e69f1bbbb206a1",
"timestamp": "",
"source": "github",
"line_count": 516,
"max_line_length": 80,
"avg_line_length": 35.30813953488372,
"alnum_prop": 0.6995444316373017,
"repo_name": "ric2b/Vivaldi-browser",
"id": "bc3b469f52ad1146942e42516875cbeb82571bf4",
"size": "18219",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chromium/content/renderer/categorized_worker_pool.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
/**
* Select2 Bootstrap CSS 1.0
* Compatible with select2 3.3.2 and bootstrap 2.3.1
* MIT License
*/
.select2-container {
margin-top: 5px;
font-style: italic;
vertical-align: middle;
}
.select2-container.input-mini {
width: 60px;
}
.select2-container.input-small {
width: 90px;
}
.select2-container.input-medium {
width: 150px;
}
.select2-container.input-large {
width: 210px;
}
.select2-container.input-xlarge {
width: 270px;
}
.select2-container.input-xxlarge {
width: 530px;
}
.select2-container.input-default {
width: 220px;
}
.select2-container[class*="span"] {
float: none;
margin-left: 0;
}
.select2-container .select2-choice,
.select2-container-multi .select2-choices {
height: 28px;
line-height: 29px;
border: 1px solid #cccccc;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
background: none;
background-color: white;
filter: none;
/*
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
*/
}
.select2-container .select2-choice div, .select2-container .select2-choice .select2-arrow,
.select2-container.select2-container-disabled .select2-choice div,
.select2-container.select2-container-disabled .select2-choice .select2-arrow {
border-left: none;
background: none;
filter: none;
}
.control-group.error [class^="select2-choice"] {
/* border-color: #b94a48; */
border-color: #cccccc;
}
.select2-container-multi .select2-choices .select2-search-field {
height: 28px;
line-height: 27px;
}
.select2-container-active .select2-choice,
.select2-container-multi.select2-container-active .select2-choices {
/* border-color: rgba(82, 168, 236, 0.8); */
border-color: #cccccc;
outline: none;
/*
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
-moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
*/
}
[class^="input-"] .select2-container {
font-size: 14px;
}
.input-prepend [class^="select2-choice"] {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.input-append [class^="select2-choice"] {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.select2-dropdown-open [class^="select2-choice"] {
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
.select2-dropdown-open.select2-drop-above [class^="select2-choice"] {
border-top-left-radius: 0;
border-top-right-radius: 0;
}
[class^="input-"] .select2-offscreen {
position: absolute;
}
/**
* This stops the quick flash when a native selectbox is shown and
* then replaced by a select2 input when javascript kicks in. This can be
* removed if javascript is not present
*/
select.select2 {
height: 28px;
visibility: hidden;
}
| {
"content_hash": "40e6f0d8a37322fd5c131ef581082401",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 92,
"avg_line_length": 24.214876033057852,
"alnum_prop": 0.6866894197952218,
"repo_name": "cheftestn/redis-stat",
"id": "d86f692dd88e30b5205736d5f44301fdcdc4fd91",
"size": "2930",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "lib/redis-stat/server/public/select2/select2-bootstrap.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "24076"
},
{
"name": "HTML",
"bytes": "6425"
},
{
"name": "JavaScript",
"bytes": "5806"
},
{
"name": "Ruby",
"bytes": "37714"
}
],
"symlink_target": ""
} |
module TmGrammar
module RSpec
module Util
module TempFiles
module_function
def files
@files ||= []
end
def clear
files.each(&:unlink)
end
end
end
end
end
| {
"content_hash": "21744c8b81099fb6c2d73d40e5514e99",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 30,
"avg_line_length": 14.117647058823529,
"alnum_prop": 0.49583333333333335,
"repo_name": "jacob-carlborg/tm_grammar",
"id": "654effa02f9c6d980e9d64367ad3ceeb4dea5d7e",
"size": "240",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/tm_grammar/rspec/util/temp_files.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "20984"
},
{
"name": "Shell",
"bytes": "58"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>friction_velocity — MetPy 0.6</title>
<link rel="shortcut icon" href="../../_static/metpy_32x32.ico"/>
<link rel="canonical" href="https://unidata.github.io/MetPy/latest/api/generated/metpy.calc.friction_velocity.html"/>
<link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />
<link rel="stylesheet" href="../../_static/gallery.css" type="text/css" />
<link rel="stylesheet" href="../../_static/theme_override.css" type="text/css" />
<link rel="index" title="Index"
href="../../genindex.html"/>
<link rel="search" title="Search" href="../../search.html"/>
<link rel="top" title="MetPy 0.6" href="../../index.html"/>
<link rel="up" title="calc" href="metpy.calc.html"/>
<link rel="next" title="frontogenesis" href="metpy.calc.frontogenesis.html"/>
<link rel="prev" title="find_intersections" href="metpy.calc.find_intersections.html"/>
<script src="../../_static/js/modernizr.min.js"></script>
</head>
<body class="wy-body-for-nav" role="document">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-scroll">
<div class="wy-side-nav-search">
<a href="../../index.html" class="icon icon-home"> MetPy
<img src="../../_static/metpy_150x150.png" class="logo" />
</a>
<div class="version">
<div class="version-dropdown">
<select class="version-list" id="version-list">
<option value=''>0.6</option>
<option value="../latest">latest</option>
<option value="../dev">dev</option>
</select>
</div>
</div>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="../../search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="../../installguide.html">Installation Guide</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../units.html">Unit Support</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../examples/index.html">MetPy Examples</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../tutorials/index.html">MetPy Tutorials</a></li>
<li class="toctree-l1 current"><a class="reference internal" href="../index.html">The MetPy API</a><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="metpy.constants.html">constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="metpy.units.html">units</a></li>
<li class="toctree-l2"><a class="reference internal" href="metpy.io.html">io</a></li>
<li class="toctree-l2"><a class="reference internal" href="metpy.io.cdm.html">cdm</a></li>
<li class="toctree-l2 current"><a class="reference internal" href="metpy.calc.html">calc</a><ul class="current">
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.add_height_to_pressure.html">add_height_to_pressure</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.add_pressure_to_height.html">add_pressure_to_height</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.advection.html">advection</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.bulk_shear.html">bulk_shear</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.bunkers_storm_motion.html">bunkers_storm_motion</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.cape_cin.html">cape_cin</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.convergence_vorticity.html">convergence_vorticity</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.coriolis_parameter.html">coriolis_parameter</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.density.html">density</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.dewpoint.html">dewpoint</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.dewpoint_rh.html">dewpoint_rh</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.dry_lapse.html">dry_lapse</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.el.html">el</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.equivalent_potential_temperature.html">equivalent_potential_temperature</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.find_intersections.html">find_intersections</a></li>
<li class="toctree-l3 current"><a class="current reference internal" href="#">friction_velocity</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.frontogenesis.html">frontogenesis</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.geostrophic_wind.html">geostrophic_wind</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.get_layer.html">get_layer</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.get_layer_heights.html">get_layer_heights</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.get_perturbation.html">get_perturbation</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.get_wind_components.html">get_wind_components</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.get_wind_dir.html">get_wind_dir</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.get_wind_speed.html">get_wind_speed</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.h_convergence.html">h_convergence</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.heat_index.html">heat_index</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.height_to_pressure_std.html">height_to_pressure_std</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.interp.html">interp</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.interpolate_nans.html">interpolate_nans</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.isentropic_interpolation.html">isentropic_interpolation</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.kinematic_flux.html">kinematic_flux</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.lcl.html">lcl</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.lfc.html">lfc</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.log_interp.html">log_interp</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.mean_pressure_weighted.html">mean_pressure_weighted</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.mixed_layer.html">mixed_layer</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.mixed_parcel.html">mixed_parcel</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.mixing_ratio.html">mixing_ratio</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.mixing_ratio_from_specific_humidity.html">mixing_ratio_from_specific_humidity</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.moist_lapse.html">moist_lapse</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.montgomery_streamfunction.html">montgomery_streamfunction</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.most_unstable_cape_cin.html">most_unstable_cape_cin</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.most_unstable_parcel.html">most_unstable_parcel</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.nearest_intersection_idx.html">nearest_intersection_idx</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.parcel_profile.html">parcel_profile</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.potential_temperature.html">potential_temperature</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.precipitable_water.html">precipitable_water</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.pressure_to_height_std.html">pressure_to_height_std</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.psychrometric_vapor_pressure_wet.html">psychrometric_vapor_pressure_wet</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.reduce_point_density.html">reduce_point_density</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.relative_humidity_from_mixing_ratio.html">relative_humidity_from_mixing_ratio</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.relative_humidity_from_specific_humidity.html">relative_humidity_from_specific_humidity</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.relative_humidity_wet_psychrometric.html">relative_humidity_wet_psychrometric</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.resample_nn_1d.html">resample_nn_1d</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.saturation_mixing_ratio.html">saturation_mixing_ratio</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.saturation_vapor_pressure.html">saturation_vapor_pressure</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.shearing_deformation.html">shearing_deformation</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.shearing_stretching_deformation.html">shearing_stretching_deformation</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.sigma_to_pressure.html">sigma_to_pressure</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.significant_tornado.html">significant_tornado</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.storm_relative_helicity.html">storm_relative_helicity</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.stretching_deformation.html">stretching_deformation</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.supercell_composite.html">supercell_composite</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.surface_based_cape_cin.html">surface_based_cape_cin</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.tke.html">tke</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.total_deformation.html">total_deformation</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.v_vorticity.html">v_vorticity</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.vapor_pressure.html">vapor_pressure</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.virtual_potential_temperature.html">virtual_potential_temperature</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.virtual_temperature.html">virtual_temperature</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.windchill.html">windchill</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="metpy.plots.html">plots</a></li>
<li class="toctree-l2"><a class="reference internal" href="metpy.plots.ctables.html">ctables</a></li>
<li class="toctree-l2"><a class="reference internal" href="metpy.gridding.html">gridding</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../developerguide.html">Developer’s Guide</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../CONTRIBUTING.html">Contributing</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../citing.html">Citing MetPy</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../references.html">References</a></li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
<nav class="wy-nav-top" role="navigation" aria-label="top navigation">
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="../../index.html">MetPy</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="breadcrumbs navigation">
<ul class="wy-breadcrumbs">
<li><a href="../../index.html">Docs</a> »</li>
<li><a href="../index.html">The MetPy API</a> »</li>
<li><a href="metpy.calc.html">calc</a> »</li>
<li>friction_velocity</li>
<li class="wy-breadcrumbs-aside">
<a href="../../_sources/api/generated/metpy.calc.friction_velocity.rst.txt" rel="nofollow"> View page source</a>
</li>
</ul>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="articleBody">
<div class="section" id="friction-velocity">
<h1>friction_velocity<a class="headerlink" href="#friction-velocity" title="Permalink to this headline">¶</a></h1>
<dl class="function">
<dt id="metpy.calc.friction_velocity">
<code class="descclassname">metpy.calc.</code><code class="descname">friction_velocity</code><span class="sig-paren">(</span><em>u</em>, <em>w</em>, <em>v=None</em>, <em>perturbation=False</em>, <em>axis=-1</em><span class="sig-paren">)</span><a class="reference internal" href="../../_modules/metpy/calc/turbulence.html#friction_velocity"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#metpy.calc.friction_velocity" title="Permalink to this definition">¶</a></dt>
<dd><p>Compute the friction velocity from the time series of velocity components.</p>
<p>Compute the friction velocity from the time series of the x, z,
and optionally y, velocity components.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first simple">
<li><strong>u</strong> (<em>array_like</em>) – The wind component along the x-axis</li>
<li><strong>w</strong> (<em>array_like</em>) – The wind component along the z-axis</li>
<li><strong>v</strong> (<em>array_like</em><em>, </em><em>optional</em>) – The wind component along the y-axis.</li>
<li><strong>perturbation</strong> (<em>{False</em><em>, </em><em>True}</em><em>, </em><em>optional</em>) – True if the <em class="xref py py-obj">u</em>, <em class="xref py py-obj">w</em>, and <em class="xref py py-obj">v</em> components of wind speed
supplied to the function are perturbation velocities.
If False, perturbation velocities will be calculated by
removing the mean value from each component.</li>
</ul>
</td>
</tr>
<tr class="field-even field"><th class="field-name">Returns:</th><td class="field-body"><p class="first"><em>array_like</em> – The corresponding friction velocity</p>
</td>
</tr>
<tr class="field-odd field"><th class="field-name" colspan="2">Other Parameters:</th></tr>
<tr class="field-odd field"><td> </td><td class="field-body"><p class="first last"><strong>axis</strong> (<em>int</em>) – The index of the time axis. Default is -1</p>
</td>
</tr>
</tbody>
</table>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference internal" href="metpy.calc.kinematic_flux.html#metpy.calc.kinematic_flux" title="metpy.calc.kinematic_flux"><code class="xref py py-func docutils literal"><span class="pre">kinematic_flux()</span></code></a></dt>
<dd>Used to compute the x-component and y-component vertical kinematic momentum flux(es) used in the computation of the friction velocity.</dd>
</dl>
</div>
<p class="rubric">Notes</p>
<p>The Friction Velocity is computed as:</p>
<div class="math">
\[u_{*} = \sqrt[4]{\left(\overline{u^{\prime}w^{\prime}}\right)^2 +
\left(\overline{v^{\prime}w^{\prime}}\right)^2},\]</div>
<p>where :math: overline{u^{prime}w^{prime}} and
:math: overline{v^{prime}w^{prime}}
are the x-component and y-components of the vertical kinematic momentum
flux, respectively. If the optional v component of velocity is not
supplied to the function, the computation of the friction velocity is
reduced to</p>
<div class="math">
\[u_{*} = \sqrt[4]{\left(\overline{u^{\prime}w^{\prime}}\right)^2}\]</div>
<p>For more information on the subject, please see <a class="reference internal" href="../../references.html#garratt1994" id="id1">[Garratt1994]</a>.</p>
</dd></dl>
<div style='clear:both'></div></div>
</div>
<div class="articleComments">
</div>
</div>
<footer>
<div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
<a href="metpy.calc.frontogenesis.html" class="btn btn-neutral float-right" title="frontogenesis" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right"></span></a>
<a href="metpy.calc.find_intersections.html" class="btn btn-neutral" title="find_intersections" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> Previous</a>
</div>
<hr/>
<div role="contentinfo">
<p>
© Copyright 2016, MetPy Developers.
Last updated on Nov 05, 2017 at 06:18:53.
</p>
</div>
Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-92978945-1', 'auto');
ga('send', 'pageview');
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/pop_ver.js"></script>
<p>Do you enjoy using MetPy?
<a href="https://saythanks.io/to/unidata" class="btn btn-neutral" title="Installation Guide" accesskey="n">Say Thanks!</a>
</p>
</footer>
</div>
</div>
</section>
</div>
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT:'../../',
VERSION:'0.6.1',
LANGUAGE:'None',
COLLAPSE_INDEX:false,
FILE_SUFFIX:'.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="../../_static/jquery.js"></script>
<script type="text/javascript" src="../../_static/underscore.js"></script>
<script type="text/javascript" src="../../_static/doctools.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/javascript" src="../../_static/js/theme.js"></script>
<script type="text/javascript">
jQuery(function () {
SphinxRtdTheme.StickyNav.enable();
});
</script>
</body>
</html> | {
"content_hash": "3ac6a5094289dc089b7f3261eb6c3996",
"timestamp": "",
"source": "github",
"line_count": 426,
"max_line_length": 493,
"avg_line_length": 49.532863849765256,
"alnum_prop": 0.6579782948675418,
"repo_name": "metpy/MetPy",
"id": "baead9dcd9129b22efd599f8e234edd666a381ff",
"size": "21119",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "v0.6/api/generated/metpy.calc.friction_velocity.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "989941"
},
{
"name": "Python",
"bytes": "551868"
}
],
"symlink_target": ""
} |
// MIT License:
//
// Copyright (c) 2010-2012, Joe Walnes
//
// 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.
/**
* This behaves like a WebSocket in every way, except if it fails to connect,
* or it gets disconnected, it will repeatedly poll until it succesfully connects
* again.
*
* It is API compatible, so when you have:
* ws = new WebSocket('ws://....');
* you can replace with:
* ws = new ReconnectingWebSocket('ws://....');
*
* The event stream will typically look like:
* onconnecting
* onopen
* onmessage
* onmessage
* onclose // lost connection
* onconnecting
* onopen // sometime later...
* onmessage
* onmessage
* etc...
*
* It is API compatible with the standard WebSocket API.
*
* Latest version: https://github.com/joewalnes/reconnecting-websocket/
* - Joe Walnes
*/
function ReconnectingWebSocket(url, protocols) {
protocols = protocols || [];
// These can be altered by calling code.
this.debug = false;
this.reconnectInterval = 1000;
this.timeoutInterval = 2000;
var self = this;
var ws;
var forcedClose = false;
var timedOut = false;
this.url = url;
this.protocols = protocols;
this.readyState = WebSocket.CONNECTING;
this.URL = url; // Public API
this.onopen = function(event) {
};
this.onclose = function(event) {
};
this.onconnecting = function(event) {
};
this.onmessage = function(event) {
};
this.onerror = function(event) {
};
function connect(reconnectAttempt) {
ws = new WebSocket(url, protocols);
self.onconnecting();
if (self.debug || ReconnectingWebSocket.debugAll) {
console.debug('ReconnectingWebSocket', 'attempt-connect', url);
}
var localWs = ws;
var timeout = setTimeout(function() {
if (self.debug || ReconnectingWebSocket.debugAll) {
console.debug('ReconnectingWebSocket', 'connection-timeout', url);
}
timedOut = true;
localWs.close();
timedOut = false;
}, self.timeoutInterval);
ws.onopen = function(event) {
clearTimeout(timeout);
if (self.debug || ReconnectingWebSocket.debugAll) {
console.debug('ReconnectingWebSocket', 'onopen', url);
}
self.readyState = WebSocket.OPEN;
reconnectAttempt = false;
self.onopen(event);
};
ws.onclose = function(event) {
clearTimeout(timeout);
ws = null;
if (forcedClose) {
self.readyState = WebSocket.CLOSED;
self.onclose(event);
} else {
self.readyState = WebSocket.CONNECTING;
self.onconnecting();
if (!reconnectAttempt && !timedOut) {
if (self.debug || ReconnectingWebSocket.debugAll) {
console.debug('ReconnectingWebSocket', 'onclose', url);
}
self.onclose(event);
}
setTimeout(function() {
connect(true);
}, self.reconnectInterval);
}
};
ws.onmessage = function(event) {
if (self.debug || ReconnectingWebSocket.debugAll) {
console.debug('ReconnectingWebSocket', 'onmessage', url, event.data);
}
self.onmessage(event);
};
ws.onerror = function(event) {
if (self.debug || ReconnectingWebSocket.debugAll) {
console.debug('ReconnectingWebSocket', 'onerror', url, event);
}
self.onerror(event);
};
}
connect(url);
this.send = function(data) {
if (ws) {
if (self.debug || ReconnectingWebSocket.debugAll) {
console.debug('ReconnectingWebSocket', 'send', url, data);
}
return ws.send(data);
} else {
throw 'INVALID_STATE_ERR : Pausing to reconnect websocket';
}
};
this.close = function() {
if (ws) {
forcedClose = true;
ws.close();
}
};
/**
* Additional public API method to refresh the connection if still open (close, re-open).
* For example, if the app suspects bad data / missed heart beats, it can try to refresh.
*/
this.refresh = function() {
if (ws) {
ws.close();
}
};
}
/**
* Setting this to true is the equivalent of setting all instances of ReconnectingWebSocket.debug to true.
*/
ReconnectingWebSocket.debugAll = false;
| {
"content_hash": "62b9f7bc832941cd25243b4626dc8bae",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 106,
"avg_line_length": 32.95530726256983,
"alnum_prop": 0.5756907950500085,
"repo_name": "wangzhibinjunhua/watch_tcp_server",
"id": "f4a2116162a214f3f93baa4257e840767a3839d5",
"size": "5899",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Applications/VMStat/Web/js/reconnecting-websocket.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "166879"
},
{
"name": "HTML",
"bytes": "2208"
},
{
"name": "JavaScript",
"bytes": "36671"
},
{
"name": "PHP",
"bytes": "622807"
},
{
"name": "Shell",
"bytes": "2910"
}
],
"symlink_target": ""
} |
if (typeof define !== 'function') {
var define = require('amdefine')(module);
}
// Functions which will be available to external callers
define([ "myclass","log4js", "./native_lib", "./utils", "./bridjs_exception", "./abstract_struct"], function(my, log4js, bridjs, Utils, BridjsException, AbstractStruct){
var UnionStruct = my.Class(AbstractStruct,{
constructor:function(pointer){
UnionStruct.Super.call(this, pointer);
},
getImplClass:function(){
return bridjs.dc.UnionStruct;
}
});
return UnionStruct;
}); | {
"content_hash": "5b72a67e35367ad2c1d1e043e913a5c6",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 170,
"avg_line_length": 31.473684210526315,
"alnum_prop": 0.6187290969899666,
"repo_name": "gautmaire/See-To-Learn",
"id": "b497443449992ca241988863252bd2d423362c18",
"size": "2385",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "node_modules/bridjs/lib/union_struct.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "39693"
},
{
"name": "CSS",
"bytes": "139944"
},
{
"name": "HTML",
"bytes": "57145"
},
{
"name": "JavaScript",
"bytes": "549249"
},
{
"name": "PHP",
"bytes": "2411"
}
],
"symlink_target": ""
} |
<?php
require_once __DIR__.'/../src/autoload.php';
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\DependencyInjection\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
//use Application\DevoriginBundle\DevoriginBundle;
//use Bundle\NewsBundle\NewsBundle;
class DevoriginKernel extends Kernel
{
public function registerRootDir()
{
return __DIR__;
}
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
// enable third-party bundles
new Symfony\Bundle\ZendBundle\ZendBundle(),
new Symfony\Bundle\DoctrineBundle\DoctrineBundle(),
new Symfony\Bundle\DoctrineMigrationsBundle\DoctrineMigrationsBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
//new Symfony\Bundle\DoctrineMigrationsBundle\DoctrineMigrationsBundle(),
//new Symfony\Bundle\DoctrineMongoDBBundle\DoctrineMongoDBBundle(),
//new Symfony\Bundle\PropelBundle\PropelBundle(),
//new Symfony\Bundle\TwigBundle\TwigBundle(),
new Application\DevoriginBundle\DevoriginBundle(),
new Bundle\NewsBundle\NewsBundle(),
new Bundle\TagHelperBundle\TagHelperBundle(),
new Bundle\MenuBundle\MenuBundle(),
);
if ($this->isDebug()) {
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
}
return $bundles;
}
public function registerBundleDirs()
{
return array(
'Application' => __DIR__.'/../src/Application',
'Bundle' => __DIR__.'/../src/Bundle',
'Symfony\\Bundle' => __DIR__.'/../src/vendor/symfony/src/Symfony/Bundle',
);
}
/**
* Returns the config_{environment}_local.yml file or
* the default config_{environment}.yml if it does not exist.
* Useful to override development password.
*
* @param string Environment
* @return The configuration file path
*/
protected function getLocalConfigurationFile($environment)
{
$basePath = __DIR__.'/config/config_';
$file = $basePath.$environment.'_local.yml';
if(\file_exists($file)) {
return $file;
}
return $basePath.$environment.'.yml';
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$container = new ContainerBuilder();
$loader->load($this->getLocalConfigurationFile($this->getEnvironment()));
return $container;
}
}
| {
"content_hash": "cfa77585777c453065b18c74369e9eb9",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 85,
"avg_line_length": 31.535714285714285,
"alnum_prop": 0.6311815779539449,
"repo_name": "vjousse/devorigin-symfony2",
"id": "b68242fa94060ae9dc836337ec891604f4335d16",
"size": "2649",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "devorigin/DevoriginKernel.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "42152"
},
{
"name": "Shell",
"bytes": "111"
}
],
"symlink_target": ""
} |
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
//
// This file implements the "bridge" between Java and C++ for
// ROCKSDB_NAMESPACE::CompactionFilter.
#include <jni.h>
#include "include/org_rocksdb_AbstractCompactionFilter.h"
#include "rocksdb/compaction_filter.h"
// <editor-fold desc="org.rocksdb.AbstractCompactionFilter">
/*
* Class: org_rocksdb_AbstractCompactionFilter
* Method: disposeInternal
* Signature: (J)V
*/
void Java_org_rocksdb_AbstractCompactionFilter_disposeInternal(JNIEnv* /*env*/,
jobject /*jobj*/,
jlong handle) {
auto* cf = reinterpret_cast<ROCKSDB_NAMESPACE::CompactionFilter*>(handle);
assert(cf != nullptr);
delete cf;
}
// </editor-fold>
| {
"content_hash": "e893d43ffef2a93702843d8d22ddfe85",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 80,
"avg_line_length": 36.67857142857143,
"alnum_prop": 0.6416747809152873,
"repo_name": "TeamSPoon/logicmoo_workspace",
"id": "c3a68cdf284d5a81f57823852f8ae4bb9b0af5cb",
"size": "1027",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "packs_lib/rocksdb/rocksdb/java/rocksjni/compaction_filter.cc",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "342"
},
{
"name": "C",
"bytes": "1"
},
{
"name": "C++",
"bytes": "1"
},
{
"name": "CSS",
"bytes": "126627"
},
{
"name": "HTML",
"bytes": "839172"
},
{
"name": "Java",
"bytes": "11116"
},
{
"name": "JavaScript",
"bytes": "238700"
},
{
"name": "PHP",
"bytes": "42253"
},
{
"name": "Perl 6",
"bytes": "23"
},
{
"name": "Prolog",
"bytes": "440882"
},
{
"name": "PureBasic",
"bytes": "1334"
},
{
"name": "Rich Text Format",
"bytes": "3436542"
},
{
"name": "Roff",
"bytes": "42"
},
{
"name": "Shell",
"bytes": "61603"
},
{
"name": "TeX",
"bytes": "99504"
}
],
"symlink_target": ""
} |
/*
* 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 io.prestosql.type;
import org.testng.annotations.Test;
import java.lang.invoke.MethodType;
import java.util.function.LongFunction;
import java.util.function.LongUnaryOperator;
import static io.prestosql.type.SingleAccessMethodCompiler.compileSingleAccessMethod;
import static java.lang.invoke.MethodHandles.lookup;
import static org.testng.Assert.assertEquals;
public class TestSingleAccessMethodCompiler
{
@Test
public void testBasic()
throws ReflectiveOperationException
{
LongUnaryOperator addOne = compileSingleAccessMethod(
"AddOne",
LongUnaryOperator.class,
lookup().findStatic(TestSingleAccessMethodCompiler.class, "increment", MethodType.methodType(long.class, long.class)));
assertEquals(addOne.applyAsLong(1), 2L);
}
private static long increment(long x)
{
return x + 1;
}
@Test
public void testGeneric()
throws ReflectiveOperationException
{
@SuppressWarnings("unchecked")
LongFunction<String> print = (LongFunction<String>) compileSingleAccessMethod(
"Print",
LongFunction.class,
lookup().findStatic(TestSingleAccessMethodCompiler.class, "incrementAndPrint", MethodType.methodType(String.class, long.class)));
assertEquals(print.apply(1), "2");
}
private static String incrementAndPrint(long x)
{
return String.valueOf(x + 1);
}
}
| {
"content_hash": "b9ea9c5583129ea99738bf0b57b43d24",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 145,
"avg_line_length": 34.2,
"alnum_prop": 0.702729044834308,
"repo_name": "erichwang/presto",
"id": "40b90f42c1c67fdd700b6a5c70fd278feb0ddf0f",
"size": "2052",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "presto-main/src/test/java/io/prestosql/type/TestSingleAccessMethodCompiler.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "19017"
},
{
"name": "HTML",
"bytes": "56868"
},
{
"name": "Java",
"bytes": "14031411"
},
{
"name": "JavaScript",
"bytes": "4863"
},
{
"name": "Makefile",
"bytes": "6819"
},
{
"name": "PLSQL",
"bytes": "6538"
},
{
"name": "Python",
"bytes": "4479"
},
{
"name": "SQLPL",
"bytes": "6363"
},
{
"name": "Shell",
"bytes": "9313"
}
],
"symlink_target": ""
} |
package com.bushstar.htmlcoinj.core;
import com.bushstar.htmlcoinj.params.MainNetParams;
import org.junit.Test;
import org.spongycastle.util.encoders.Hex;
import java.util.Arrays;
import static org.junit.Assert.*;
public class BloomFilterTest {
@Test
public void insertSerializeTest() {
BloomFilter filter = new BloomFilter(3, 0.01, 0, BloomFilter.BloomUpdate.UPDATE_ALL);
filter.insert(Hex.decode("99108ad8ed9bb6274d3980bab5a85c048f0950c8"));
assertTrue (filter.contains(Hex.decode("99108ad8ed9bb6274d3980bab5a85c048f0950c8")));
// One bit different in first byte
assertFalse(filter.contains(Hex.decode("19108ad8ed9bb6274d3980bab5a85c048f0950c8")));
filter.insert(Hex.decode("b5a2c786d9ef4658287ced5914b37a1b4aa32eee"));
assertTrue(filter.contains(Hex.decode("b5a2c786d9ef4658287ced5914b37a1b4aa32eee")));
filter.insert(Hex.decode("b9300670b4c5366e95b2699e8b18bc75e5f729c5"));
assertTrue(filter.contains(Hex.decode("b9300670b4c5366e95b2699e8b18bc75e5f729c5")));
// Value generated by the reference client
assertTrue(Arrays.equals(Hex.decode("03614e9b050000000000000001"), filter.htmlcoinSerialize()));
}
@Test
public void insertSerializeTestWithTweak() {
BloomFilter filter = new BloomFilter(3, 0.01, 2147483649L);
filter.insert(Hex.decode("99108ad8ed9bb6274d3980bab5a85c048f0950c8"));
assertTrue (filter.contains(Hex.decode("99108ad8ed9bb6274d3980bab5a85c048f0950c8")));
// One bit different in first byte
assertFalse(filter.contains(Hex.decode("19108ad8ed9bb6274d3980bab5a85c048f0950c8")));
filter.insert(Hex.decode("b5a2c786d9ef4658287ced5914b37a1b4aa32eee"));
assertTrue(filter.contains(Hex.decode("b5a2c786d9ef4658287ced5914b37a1b4aa32eee")));
filter.insert(Hex.decode("b9300670b4c5366e95b2699e8b18bc75e5f729c5"));
assertTrue(filter.contains(Hex.decode("b9300670b4c5366e95b2699e8b18bc75e5f729c5")));
// Value generated by the reference client
assertTrue(Arrays.equals(Hex.decode("03ce4299050000000100008002"), filter.htmlcoinSerialize()));
}
@Test
public void walletTest() throws Exception {
NetworkParameters params = MainNetParams.get();
DumpedPrivateKey privKey = new DumpedPrivateKey(params, "5Kg1gnAjaLfKiwhhPpGS3QfRg2m6awQvaj98JCZBZQ5SuS2F15C");
Address addr = privKey.getKey().toAddress(params);
assertTrue(addr.toString().equals("17Wx1GQfyPTNWpQMHrTwRSMTCAonSiZx9e"));
Wallet wallet = new Wallet(params);
// Check that the wallet was created with no keys
// If wallets ever get created with keys, this test needs redone.
for (ECKey key : wallet.getKeys())
fail();
wallet.addKey(privKey.getKey());
// Add a random key which happens to have been used in a recent generation
wallet.addKey(new ECKey(null, Hex.decode("03cb219f69f1b49468bd563239a86667e74a06fcba69ac50a08a5cbc42a5808e99")));
wallet.commitTx(new Transaction(params, Hex.decode("01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0d038754030114062f503253482fffffffff01c05e559500000000232103cb219f69f1b49468bd563239a86667e74a06fcba69ac50a08a5cbc42a5808e99ac00000000")));
// We should have 2 per pubkey, and one for the pay-2-pubkey output we have
assertTrue(wallet.getBloomFilterElementCount() == 5);
BloomFilter filter = wallet.getBloomFilter(wallet.getBloomFilterElementCount(), 0.001, 0);
// Value generated by the reference client
assertTrue(Arrays.equals(Hex.decode("082ae5edc8e51d4a03080000000000000002"), filter.htmlcoinSerialize()));
}
}
| {
"content_hash": "7c0c094bf32bd2d14d1c9a3315607dbe",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 281,
"avg_line_length": 49.62337662337662,
"alnum_prop": 0.7278199424234494,
"repo_name": "machado-rev/htmlcoinj",
"id": "fdf8c697817e778545fd18a518cc6cc22e290433",
"size": "3821",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/test/java/com/htmlcoin/htmlcoin/core/BloomFilterTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "3208122"
},
{
"name": "C++",
"bytes": "39683"
},
{
"name": "CSS",
"bytes": "346"
},
{
"name": "Java",
"bytes": "6848328"
},
{
"name": "Makefile",
"bytes": "1147"
},
{
"name": "Protocol Buffer",
"bytes": "31926"
}
],
"symlink_target": ""
} |
// ToolsAdd.cpp : implementation file
//
#include "stdafx.h"
#include "p4win.h"
#include "ToolsAdd.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CToolsAdd dialog
CToolsAdd::CToolsAdd(CWnd* pParent /*=NULL*/)
: CDialog(CToolsAdd::IDD, pParent)
{
//{{AFX_DATA_INIT(CToolsAdd)
m_MenuType = 0;
//}}AFX_DATA_INIT
m_LabelText=_T("");
m_IsOK2Cr8SubMenu = FALSE;
m_RadioShow = 0;
}
void CToolsAdd::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CToolsAdd)
DDX_Text(pDX, IDC_EDIT, m_Name);
DDX_Radio(pDX, IDC_COMMAND, m_MenuType);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CToolsAdd, CDialog)
//{{AFX_MSG_MAP(CToolsAdd)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CToolsAdd message handlers
BOOL CToolsAdd::OnInitDialog()
{
CDialog::OnInitDialog();
SetWindowText(m_Title);
if (m_LabelText.GetLength())
GetDlgItem(IDC_LABEL_TEXT)->SetWindowText(m_LabelText);
UpdateData( FALSE );
if (!m_IsOK2Cr8SubMenu)
GetDlgItem(IDC_SUBMENU)->EnableWindow(FALSE);
if (m_RadioShow)
{
switch (m_RadioShow)
{
case 1:
GetDlgItem(IDC_COMMAND)->EnableWindow(FALSE);
break;
case 2:
GetDlgItem(IDC_SUBMENU)->EnableWindow(FALSE);
break;
case 3:
GetDlgItem(IDC_STATIC_TITLE)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_COMMAND)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_SUBMENU)->ShowWindow(SW_HIDE);
break;
}
}
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CToolsAdd::OnOK()
{
UpdateData( );
m_Name.TrimLeft();
m_Name.TrimRight(_T("» "));
UpdateData(FALSE);
EndDialog(IDOK);
CDialog::OnOK();
}
| {
"content_hash": "717bb535439a2ca011605fec6103f457",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 77,
"avg_line_length": 22.227272727272727,
"alnum_prop": 0.5976482617586912,
"repo_name": "danieljennings/p4win",
"id": "a44ecbb6e6bdb6a021b62c29f839963b348f07b6",
"size": "1956",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gui/ToolsAdd.cpp",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "360990"
},
{
"name": "C++",
"bytes": "3168182"
},
{
"name": "Objective-C",
"bytes": "93416"
},
{
"name": "Shell",
"bytes": "1235"
}
],
"symlink_target": ""
} |
package com.thoughtworks.go.plugin.access.authorization;
import com.thoughtworks.go.plugin.domain.authorization.AuthorizationPluginInfo;
import com.thoughtworks.go.plugin.infra.PluginManager;
import com.thoughtworks.go.plugin.infra.plugininfo.GoPluginDescriptor;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.*;
public class AuthorizationMetadataLoaderTest {
private AuthorizationExtension extension;
private AuthorizationPluginInfoBuilder infoBuilder;
private AuthorizationMetadataStore metadataStore;
private PluginManager pluginManager;
@Before
public void setUp() throws Exception {
extension = mock(AuthorizationExtension.class);
infoBuilder = mock(AuthorizationPluginInfoBuilder.class);
metadataStore = mock(AuthorizationMetadataStore.class);
pluginManager = mock(PluginManager.class);
}
@Test
public void shouldBeAPluginChangeListener() throws Exception {
AuthorizationMetadataLoader authorizationMetadataLoader = new AuthorizationMetadataLoader(pluginManager, metadataStore, infoBuilder, extension);
verify(pluginManager).addPluginChangeListener(eq(authorizationMetadataLoader));
}
@Test
public void onPluginLoaded_shouldAddPluginInfoToMetadataStore() throws Exception {
GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build();
AuthorizationMetadataLoader metadataLoader = new AuthorizationMetadataLoader(pluginManager, metadataStore, infoBuilder, extension);
AuthorizationPluginInfo pluginInfo = new AuthorizationPluginInfo(descriptor, null, null, null, null);
when(extension.canHandlePlugin(descriptor.id())).thenReturn(true);
when(infoBuilder.pluginInfoFor(descriptor)).thenReturn(pluginInfo);
metadataLoader.pluginLoaded(descriptor);
verify(metadataStore).setPluginInfo(pluginInfo);
}
@Test
public void onPluginLoaded_shouldIgnoreNonAuthorizationPlugins() throws Exception {
GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build();
AuthorizationMetadataLoader metadataLoader = new AuthorizationMetadataLoader(pluginManager, metadataStore, infoBuilder, extension);
when(extension.canHandlePlugin(descriptor.id())).thenReturn(false);
metadataLoader.pluginLoaded(descriptor);
verifyZeroInteractions(infoBuilder);
verifyZeroInteractions(metadataStore);
}
@Test
public void onPluginUnloded_shouldRemoveTheCorrespondingPluginInfoFromStore() throws Exception {
GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build();
AuthorizationMetadataLoader metadataLoader = new AuthorizationMetadataLoader(pluginManager, metadataStore, infoBuilder, extension);
AuthorizationPluginInfo pluginInfo = new AuthorizationPluginInfo(descriptor, null, null, null, null);
metadataStore.setPluginInfo(pluginInfo);
metadataLoader.pluginUnLoaded(descriptor);
verify(metadataStore).remove(descriptor.id());
}
}
| {
"content_hash": "c21c4b36a351c7b89a7b46c3cb55e936",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 152,
"avg_line_length": 42.57534246575342,
"alnum_prop": 0.7718790218790219,
"repo_name": "marques-work/gocd",
"id": "26ac4801c7819c6b2f47ca9fe959d1784200c2d1",
"size": "3709",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "plugin-infra/go-plugin-access/src/test/java/com/thoughtworks/go/plugin/access/authorization/AuthorizationMetadataLoaderTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "466"
},
{
"name": "CSS",
"bytes": "807605"
},
{
"name": "FreeMarker",
"bytes": "9759"
},
{
"name": "Groovy",
"bytes": "2317159"
},
{
"name": "HTML",
"bytes": "641338"
},
{
"name": "Java",
"bytes": "21014983"
},
{
"name": "JavaScript",
"bytes": "2539248"
},
{
"name": "NSIS",
"bytes": "23525"
},
{
"name": "PowerShell",
"bytes": "691"
},
{
"name": "Ruby",
"bytes": "1907011"
},
{
"name": "Shell",
"bytes": "169586"
},
{
"name": "TSQL",
"bytes": "200114"
},
{
"name": "TypeScript",
"bytes": "3423163"
},
{
"name": "XSLT",
"bytes": "203240"
}
],
"symlink_target": ""
} |
'use strict';
/**
* @ngdoc directive
* @name ubiApp.directive:taskList
* @description
* # taskList
*/
angular.module('ubiApp')
.directive('taskList', function () {
return {
templateUrl: 'views/tasklist.html',
controller: 'TasklistCtrl',
restrict: 'E',
scope:{
data:'=',
title:'='
},
link: function postLink(scope, element, attrs) {
}
};
});
| {
"content_hash": "b9b404b080788c5ab1de62ea9e86ae87",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 54,
"avg_line_length": 19.136363636363637,
"alnum_prop": 0.5439429928741093,
"repo_name": "healyma/ubidobi",
"id": "7dd49bb9c9e0bf61bb16dc831a1a11968d094618",
"size": "421",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ubi2/app/scripts/directives/tasklist.js",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.wildfly.swarm.internal;
import java.nio.file.Path;
/**
* Dummy implementation of {@link FileSystemLayout} which is to be used only in the appropriate test case.
*/
public class CustomFileSystemLayout extends FileSystemLayout {
public CustomFileSystemLayout(String path) {
super(path);
}
@Override
public String determinePackagingType() {
throw new UnsupportedOperationException("Operation not implemented");
}
@Override
public Path resolveBuildClassesDir() {
throw new UnsupportedOperationException("Operation not implemented");
}
@Override
public Path resolveBuildResourcesDir() {
throw new UnsupportedOperationException("Operation not implemented");
}
@Override
public Path resolveSrcWebAppDir() {
throw new UnsupportedOperationException("Operation not implemented");
}
@Override
public Path getRootPath() {
throw new UnsupportedOperationException("Operation not implemented");
}
/**
* Simulate instantiation exception.
*/
public static class CustomInvalidFileSystemLayout extends CustomFileSystemLayout {
public CustomInvalidFileSystemLayout(String path) {
super(path);
throw new IllegalArgumentException("Test case needs an exception to be raised.");
}
}
}
| {
"content_hash": "fc5845a61ef8595f82d79f6045773d7b",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 106,
"avg_line_length": 26.764705882352942,
"alnum_prop": 0.6981684981684981,
"repo_name": "wildfly-swarm/wildfly-swarm",
"id": "51d58772d88cb7c8c5d637a7d763a618bd6d96d3",
"size": "1995",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "core/container/src/test/java/org/wildfly/swarm/internal/CustomFileSystemLayout.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5821"
},
{
"name": "HTML",
"bytes": "7818"
},
{
"name": "Java",
"bytes": "4405312"
},
{
"name": "JavaScript",
"bytes": "13301"
},
{
"name": "Ruby",
"bytes": "5349"
},
{
"name": "Shell",
"bytes": "7843"
},
{
"name": "XSLT",
"bytes": "20396"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_13) on Wed Aug 05 08:53:10 ICT 2009 -->
<META http-equiv="Content-Type" content="text/html; charset=utf8">
<TITLE>
Method
</TITLE>
<META NAME="date" CONTENT="2009-08-05">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Method";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/Method.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../org/aopalliance/reflect/Metadata.html" title="interface in org.aopalliance.reflect"><B>PREV CLASS</B></A>
<A HREF="../../../org/aopalliance/reflect/ProgramUnit.html" title="interface in org.aopalliance.reflect"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?org/aopalliance/reflect/Method.html" target="_top"><B>FRAMES</B></A>
<A HREF="Method.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | CONSTR | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | CONSTR | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
org.aopalliance.reflect</FONT>
<BR>
Interface Method</H2>
<DL>
<DT><B>All Superinterfaces:</B> <DD><A HREF="../../../org/aopalliance/reflect/Member.html" title="interface in org.aopalliance.reflect">Member</A>, <A HREF="../../../org/aopalliance/reflect/ProgramUnit.html" title="interface in org.aopalliance.reflect">ProgramUnit</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>public interface <B>Method</B><DT>extends <A HREF="../../../org/aopalliance/reflect/Member.html" title="interface in org.aopalliance.reflect">Member</A></DL>
</PRE>
<P>
This represents a method of a class.
<P>
<P>
<HR>
<P>
<!-- =========== FIELD SUMMARY =========== -->
<A NAME="field_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Field Summary</B></FONT></TH>
</TR>
</TABLE>
<A NAME="fields_inherited_from_class_org.aopalliance.reflect.Member"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Fields inherited from interface org.aopalliance.reflect.<A HREF="../../../org/aopalliance/reflect/Member.html" title="interface in org.aopalliance.reflect">Member</A></B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><A HREF="../../../org/aopalliance/reflect/Member.html#PROVIDER_SIDE">PROVIDER_SIDE</A>, <A HREF="../../../org/aopalliance/reflect/Member.html#USER_SIDE">USER_SIDE</A></CODE></TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../org/aopalliance/reflect/Code.html" title="interface in org.aopalliance.reflect">Code</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/aopalliance/reflect/Method.html#getBody()">getBody</A></B>()</CODE>
<BR>
Returns the body of the current method.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../org/aopalliance/reflect/CodeLocator.html" title="interface in org.aopalliance.reflect">CodeLocator</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/aopalliance/reflect/Method.html#getCallLocator()">getCallLocator</A></B>()</CODE>
<BR>
This locator contains all the points in the program that call this
method.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../org/aopalliance/reflect/CodeLocator.html" title="interface in org.aopalliance.reflect">CodeLocator</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/aopalliance/reflect/Method.html#getCallLocator(int)">getCallLocator</A></B>(int side)</CODE>
<BR>
A full version of <A HREF="../../../org/aopalliance/reflect/Method.html#getCallLocator()"><CODE>getCallLocator()</CODE></A>.</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_org.aopalliance.reflect.Member"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from interface org.aopalliance.reflect.<A HREF="../../../org/aopalliance/reflect/Member.html" title="interface in org.aopalliance.reflect">Member</A></B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><A HREF="../../../org/aopalliance/reflect/Member.html#getDeclaringClass()">getDeclaringClass</A>, <A HREF="../../../org/aopalliance/reflect/Member.html#getModifiers()">getModifiers</A>, <A HREF="../../../org/aopalliance/reflect/Member.html#getName()">getName</A></CODE></TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_org.aopalliance.reflect.ProgramUnit"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from interface org.aopalliance.reflect.<A HREF="../../../org/aopalliance/reflect/ProgramUnit.html" title="interface in org.aopalliance.reflect">ProgramUnit</A></B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><A HREF="../../../org/aopalliance/reflect/ProgramUnit.html#addMetadata(org.aopalliance.reflect.Metadata)">addMetadata</A>, <A HREF="../../../org/aopalliance/reflect/ProgramUnit.html#getLocator()">getLocator</A>, <A HREF="../../../org/aopalliance/reflect/ProgramUnit.html#getMetadata(java.lang.Object)">getMetadata</A>, <A HREF="../../../org/aopalliance/reflect/ProgramUnit.html#getMetadatas()">getMetadatas</A>, <A HREF="../../../org/aopalliance/reflect/ProgramUnit.html#removeMetadata(java.lang.Object)">removeMetadata</A></CODE></TD>
</TR>
</TABLE>
<P>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="getCallLocator()"><!-- --></A><H3>
getCallLocator</H3>
<PRE>
<A HREF="../../../org/aopalliance/reflect/CodeLocator.html" title="interface in org.aopalliance.reflect">CodeLocator</A> <B>getCallLocator</B>()</PRE>
<DL>
<DD>This locator contains all the points in the program that call this
method.
<p>
Note that this code locator corresponds to the client-side call event
(equiv. to <code>this.getLocator(USER_SIDE)</code>. To get the
server-side equivalent locator, one must write
<code>this.getBody().getLocator()</code> or
<code>this.getLocator(PROVIDER_SIDE)</code>.
<p>
It is a very invasive feature since it designates all the calling points
in all the classes of the application. To only designate the calling
points in a given client method, one should write
<code>aClientMethod.getBody().getCallLocator(this)</code>.
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>See Also:</B><DD><A HREF="../../../org/aopalliance/reflect/Code.html#getLocator()"><CODE>Code.getLocator()</CODE></A>,
<A HREF="../../../org/aopalliance/reflect/Code.html#getCallLocator(org.aopalliance.reflect.Method)"><CODE>Code.getCallLocator(Method)</CODE></A></DL>
</DD>
</DL>
<HR>
<A NAME="getCallLocator(int)"><!-- --></A><H3>
getCallLocator</H3>
<PRE>
<A HREF="../../../org/aopalliance/reflect/CodeLocator.html" title="interface in org.aopalliance.reflect">CodeLocator</A> <B>getCallLocator</B>(int side)</PRE>
<DL>
<DD>A full version of <A HREF="../../../org/aopalliance/reflect/Method.html#getCallLocator()"><CODE>getCallLocator()</CODE></A>.
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>side</CODE> - USER_SIDE || PROVIDER_SIDE<DT><B>See Also:</B><DD><A HREF="../../../org/aopalliance/reflect/Method.html#getCallLocator()"><CODE>getCallLocator()</CODE></A></DL>
</DD>
</DL>
<HR>
<A NAME="getBody()"><!-- --></A><H3>
getBody</H3>
<PRE>
<A HREF="../../../org/aopalliance/reflect/Code.html" title="interface in org.aopalliance.reflect">Code</A> <B>getBody</B>()</PRE>
<DL>
<DD>Returns the body of the current method.
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/Method.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../org/aopalliance/reflect/Metadata.html" title="interface in org.aopalliance.reflect"><B>PREV CLASS</B></A>
<A HREF="../../../org/aopalliance/reflect/ProgramUnit.html" title="interface in org.aopalliance.reflect"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?org/aopalliance/reflect/Method.html" target="_top"><B>FRAMES</B></A>
<A HREF="Method.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | CONSTR | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | CONSTR | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| {
"content_hash": "abbd8a44fbe8a5cdb22b9ca97717d42a",
"timestamp": "",
"source": "github",
"line_count": 317,
"max_line_length": 545,
"avg_line_length": 46.26813880126183,
"alnum_prop": 0.6372809708870253,
"repo_name": "desiderantes/jgentle",
"id": "ae412c03bb1725e59d4f053021ede0347231807e",
"size": "14667",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "JGentleProject/doc/org/aopalliance/reflect/Method.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1420"
},
{
"name": "HTML",
"bytes": "20499195"
},
{
"name": "Java",
"bytes": "4562180"
},
{
"name": "JavaScript",
"bytes": "108"
}
],
"symlink_target": ""
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Indentation;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Indentation;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting.Indentation
{
[UseExportProvider]
public class SmartTokenFormatterFormatRangeTests
{
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task BeginningOfFile()
{
var code = @" using System;$$";
var expected = @" using System;";
Assert.NotNull(await Record.ExceptionAsync(() => AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.None)));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Namespace1()
{
var code = @"using System;
namespace NS
{
}$$";
var expected = @"using System;
namespace NS
{
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Namespace2()
{
var code = @"using System;
namespace NS
{
class Class
{
}
}$$";
var expected = @"using System;
namespace NS
{
class Class
{
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Namespace3()
{
var code = @"using System;
namespace NS { }$$";
var expected = @"using System;
namespace NS { }";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Namespace4()
{
var code = @"using System;
namespace NS {
}$$";
var expected = @"using System;
namespace NS
{
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Namespace5()
{
var code = @"using System;
namespace NS
{
class Class { }
}$$";
var expected = @"using System;
namespace NS
{
class Class { }
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Namespace6()
{
var code = @"using System;
namespace NS
{
class Class {
}
}$$";
var expected = @"using System;
namespace NS
{
class Class
{
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Namespace7()
{
var code = @"using System;
namespace NS
{
class Class {
}
namespace NS2
{}
}$$";
var expected = @"using System;
namespace NS
{
class Class
{
}
namespace NS2
{ }
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Namespace8()
{
var code = @"using System;
namespace NS { class Class { } namespace NS2 { } }$$";
var expected = @"using System;
namespace NS { class Class { } namespace NS2 { } }";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Class1()
{
var code = @"using System;
class Class {
}$$";
var expected = @"using System;
class Class
{
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Class2()
{
var code = @"using System;
class Class
{
void Method(int i) {
}
}$$";
var expected = @"using System;
class Class
{
void Method(int i)
{
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Class3()
{
var code = @"using System;
class Class
{
void Method(int i) { }
}$$";
var expected = @"using System;
class Class
{
void Method(int i) { }
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Class4()
{
var code = @"using System;
class Class
{
delegate void Test(int i);
}$$";
var expected = @"using System;
class Class
{
delegate void Test(int i);
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Class5()
{
var code = @"using System;
class Class
{
delegate void Test(int i);
void Method()
{
}
}$$";
var expected = @"using System;
class Class
{
delegate void Test(int i);
void Method()
{
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Interface1()
{
var code = @"using System;
interface II
{
delegate void Test(int i);
int Prop { get; set; }
}$$";
var expected = @"using System;
interface II
{
delegate void Test(int i);
int Prop { get; set; }
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Struct1()
{
var code = @"using System;
struct Struct
{
Struct(int i)
{
}
}$$";
var expected = @"using System;
struct Struct
{
Struct(int i)
{
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Enum1()
{
var code = @"using System;
enum Enum
{
A = 1, B = 2,
C = 3
}$$";
var expected = @"using System;
enum Enum
{
A = 1, B = 2,
C = 3
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task AccessorList1()
{
var code = @"using System;
class Class
{
int Prop { get { return 1; }$$";
var expected = @"using System;
class Class
{
int Prop { get { return 1; }";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task AccessorList2()
{
var code = @"using System;
class Class
{
int Prop { get { return 1; } }$$";
var expected = @"using System;
class Class
{
int Prop { get { return 1; } }";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.IntKeyword);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task AccessorList3()
{
var code = @"using System;
class Class
{
int Prop { get { return 1; }
}$$";
var expected = @"using System;
class Class
{
int Prop
{
get { return 1; }
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.IntKeyword);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task AccessorList4()
{
var code = @"using System;
class Class
{
int Prop { get { return 1;
}$$";
var expected = @"using System;
class Class
{
int Prop { get
{
return 1;
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.GetKeyword);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task AccessorList5()
{
var code = @"using System;
class Class
{
int Prop {
get { return 1;
}$$";
var expected = @"using System;
class Class
{
int Prop {
get { return 1;
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[WorkItem(16984, "https://github.com/dotnet/roslyn/issues/16984")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task AccessorList5b()
{
var code = @"using System;
class Class
{
int Prop {
get { return 1;
}$$
}
}";
var expected = @"using System;
class Class
{
int Prop {
get
{
return 1;
}
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task AccessorList6()
{
var code = @"using System;
class Class
{
int Prop
{
get { return 1;
} }$$";
var expected = @"using System;
class Class
{
int Prop
{
get
{
return 1;
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.IntKeyword);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task AccessorList7()
{
var code = @"using System;
class Class
{
int Prop
{
get
{
return 1;$$
}
}";
var expected = @"using System;
class Class
{
int Prop
{
get
{
return 1;
}
}";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[WorkItem(16984, "https://github.com/dotnet/roslyn/issues/16984")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task AccessorList8()
{
var code = @"class C
{
int Prop
{
get
{
return 0;
}$$
}
}";
var expected = @"class C
{
int Prop
{
get
{
return 0;
}
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfTheory]
[WorkItem(16984, "https://github.com/dotnet/roslyn/issues/16984")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
[InlineData("get")]
[InlineData("set")]
[InlineData("init")]
public async Task AccessorList9(string accessor)
{
var code = $@"class C
{{
int Prop
{{
{accessor}
{{
;
}}$$
}}
}}";
var expected = $@"class C
{{
int Prop
{{
{accessor}
{{
;
}}
}}
}}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[WorkItem(16984, "https://github.com/dotnet/roslyn/issues/16984")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task AccessorList10()
{
var code = @"class C
{
event EventHandler E
{
add
{
}$$
remove
{
}
}
}";
var expected = @"class C
{
event EventHandler E
{
add
{
}
remove
{
}
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[WorkItem(16984, "https://github.com/dotnet/roslyn/issues/16984")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task AccessorList11()
{
var code = @"class C
{
event EventHandler E
{
add
{
}
remove
{
}$$
}
}";
var expected = @"class C
{
event EventHandler E
{
add
{
}
remove
{
}
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.CloseBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block1()
{
var code = @"using System;
class Class
{
public int Method()
{ }$$";
var expected = @"using System;
class Class
{
public int Method()
{ }";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block2()
{
var code = @"using System;
class Class
{
public int Method() { }$$";
var expected = @"using System;
class Class
{
public int Method() { }";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block3()
{
var code = @"using System;
class Class
{
public int Method() {
}$$
}";
var expected = @"using System;
class Class
{
public int Method()
{
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block4()
{
var code = @"using System;
class Class
{
public static Class operator +(Class c1, Class c2) {
}$$
}";
var expected = @"using System;
class Class
{
public static Class operator +(Class c1, Class c2)
{
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block5()
{
var code = @"using System;
class Class
{
void Method()
{
{ }$$";
var expected = @"using System;
class Class
{
void Method()
{
{ }";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block6()
{
var code = @"using System;
class Class
{
void Method()
{
{
}$$";
var expected = @"using System;
class Class
{
void Method()
{
{
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block7()
{
var code = @"using System;
class Class
{
void Method()
{
{ { }$$";
var expected = @"using System;
class Class
{
void Method()
{
{ { }";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block8()
{
var code = @"using System;
class Class
{
void Method()
{
{ {
}$$
}";
var expected = @"using System;
class Class
{
void Method()
{
{
{
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task SwitchStatement1()
{
var code = @"using System;
class Class
{
void Method()
{
switch (a) {
case 1:
break;
}$$
}
}";
var expected = @"using System;
class Class
{
void Method()
{
switch (a)
{
case 1:
break;
}
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task SwitchStatement2()
{
var code = @"using System;
class Class
{
void Method()
{
switch (true) { }$$";
var expected = @"using System;
class Class
{
void Method()
{
switch (true) { }";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task SwitchStatement3()
{
var code = @"using System;
class Class
{
void Method()
{
switch (true)
{
case 1: { }$$";
var expected = @"using System;
class Class
{
void Method()
{
switch (true)
{
case 1: { }";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.ColonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task SwitchStatement4()
{
var code = @"using System;
class Class
{
void Method()
{
switch (true)
{
case 1: {
}$$";
var expected = @"using System;
class Class
{
void Method()
{
switch (true)
{
case 1:
{
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.ColonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Initializer1()
{
var code = @"using System;
class Class
{
void Method()
{
var arr = new int[] { }$$";
var expected = @"using System;
class Class
{
void Method()
{
var arr = new int[] { }";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Initializer2()
{
var code = @"using System;
class Class
{
void Method()
{
var arr = new int[] {
}$$";
var expected = @"using System;
class Class
{
void Method()
{
var arr = new int[] {
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Initializer3()
{
var code = @"using System;
class Class
{
void Method()
{
var arr = new { A = 1, B = 2
}$$";
var expected = @"using System;
class Class
{
void Method()
{
var arr = new
{
A = 1,
B = 2
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Initializer4()
{
var code = @"using System;
class Class
{
void Method()
{
var arr = new { A = 1, B = 2 }$$";
var expected = @"using System;
class Class
{
void Method()
{
var arr = new { A = 1, B = 2 }";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Initializer5()
{
var code = @"using System;
class Class
{
void Method()
{
var arr = new[] {
1, 2, 3, 4,
5 }$$";
var expected = @"using System;
class Class
{
void Method()
{
var arr = new[] {
1, 2, 3, 4,
5 }";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Initializer6()
{
var code = @"using System;
class Class
{
void Method()
{
var arr = new int[] {
1, 2, 3, 4,
5 }$$";
var expected = @"using System;
class Class
{
void Method()
{
var arr = new int[] {
1, 2, 3, 4,
5 }";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmbeddedStatement1()
{
var code = @"using System;
class Class
{
void Method()
{
if (true) { }$$";
var expected = @"using System;
class Class
{
void Method()
{
if (true) { }";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmbeddedStatement2()
{
var code = @"using System;
class Class
{
void Method()
{
if (true) {
}$$
}";
var expected = @"using System;
class Class
{
void Method()
{
if (true)
{
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmbeddedStatement3()
{
var code = @"using System;
class Class
{
void Method()
{
if (true)
{ }$$";
var expected = @"using System;
class Class
{
void Method()
{
if (true)
{ }";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmbeddedStatement4()
{
var code = @"using System;
class Class
{
void Method()
{
while (true) {
}$$
}";
var expected = @"using System;
class Class
{
void Method()
{
while (true)
{
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[WorkItem(8413, "https://github.com/dotnet/roslyn/issues/8413")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmbeddedStatementDoBlockAlone()
{
var code = @"using System;
class Class
{
void Method()
{
do {
}$$
}
}";
var expected = @"using System;
class Class
{
void Method()
{
do
{
}
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmbeddedStatement5()
{
var code = @"using System;
class Class
{
void Method()
{
do {
} while(true);$$
}
}";
var expected = @"using System;
class Class
{
void Method()
{
do
{
} while (true);
}
}";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmbeddedStatement6()
{
var code = @"using System;
class Class
{
void Method()
{
for (int i = 0; i < 10; i++) {
}$$
}";
var expected = @"using System;
class Class
{
void Method()
{
for (int i = 0; i < 10; i++)
{
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmbeddedStatement7()
{
var code = @"using System;
class Class
{
void Method()
{
foreach (var i in collection) {
}$$
}";
var expected = @"using System;
class Class
{
void Method()
{
foreach (var i in collection)
{
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmbeddedStatement8()
{
var code = @"using System;
class Class
{
void Method()
{
using (var resource = GetResource()) {
}$$
}";
var expected = @"using System;
class Class
{
void Method()
{
using (var resource = GetResource())
{
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmbeddedStatement9()
{
var code = @"using System;
class Class
{
void Method()
{
if (true)
int i = 10;$$";
var expected = @"using System;
class Class
{
void Method()
{
if (true)
int i = 10;";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task FieldlInitializer()
{
var code = @"using System;
class Class
{
string str = Console.Title;$$
";
var expected = @"using System;
class Class
{
string str = Console.Title;
";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task ArrayFieldlInitializer()
{
var code = @"using System;
namespace NS
{
class Class
{
string[] strArr = { ""1"", ""2"" };$$
";
var expected = @"using System;
namespace NS
{
class Class
{
string[] strArr = { ""1"", ""2"" };
";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task ExpressionValuedPropertyInitializer()
{
var code = @"using System;
class Class
{
public int Three => 1+2;$$
";
var expected = @"using System;
class Class
{
public int Three => 1 + 2;
";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmbeddedStatement10()
{
var code = @"using System;
class Class
{
void Method()
{
if (true)
int i = 10;$$
}";
var expected = @"using System;
class Class
{
void Method()
{
if (true)
int i = 10;
}";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmbeddedStatement11()
{
var code = @"using System;
class Class
{
void Method()
{
using (var resource = GetResource()) resource.Do();$$";
var expected = @"using System;
class Class
{
void Method()
{
using (var resource = GetResource()) resource.Do();";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmbeddedStatement12()
{
var code = @"using System;
class Class
{
void Method()
{
using (var resource = GetResource())
resource.Do();$$";
var expected = @"using System;
class Class
{
void Method()
{
using (var resource = GetResource())
resource.Do();";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmbeddedStatement13()
{
var code = @"using System;
class Class
{
void Method()
{
using (var resource = GetResource())
resource.Do();$$
}";
var expected = @"using System;
class Class
{
void Method()
{
using (var resource = GetResource())
resource.Do();
}";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmbeddedStatement14()
{
var code = @"using System;
class Class
{
void Method()
{
do i = 10;$$";
var expected = @"using System;
class Class
{
void Method()
{
do i = 10;";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmbeddedStatement15()
{
var code = @"using System;
class Class
{
void Method()
{
do
i = 10;$$";
var expected = @"using System;
class Class
{
void Method()
{
do
i = 10;";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmbeddedStatement16()
{
var code = @"using System;
class Class
{
void Method()
{
do
i = 10;$$
}";
var expected = @"using System;
class Class
{
void Method()
{
do
i = 10;
}";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmbeddedStatement17()
{
var code = @"using System;
class Class
{
void Method()
{
do
i = 10;
while (true);$$
}";
var expected = @"using System;
class Class
{
void Method()
{
do
i = 10;
while (true);
}";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task FollowPreviousElement1()
{
var code = @"using System;
class Class
{
int i = 10;
int i2 = 10;$$";
var expected = @"using System;
class Class
{
int i = 10;
int i2 = 10;";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task FollowPreviousElement2()
{
var code = @"using System;
class Class
{
void Method(int i)
{
}
void Method2()
{
}$$
}";
var expected = @"using System;
class Class
{
void Method(int i)
{
}
void Method2()
{
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.CloseBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task FollowPreviousElement3()
{
var code = @"using System;
class Class
{
void Method(int i)
{
}
A a = new A
{
Prop = 1,
Prop2 = 2
};$$
}";
var expected = @"using System;
class Class
{
void Method(int i)
{
}
A a = new A
{
Prop = 1,
Prop2 = 2
};
}";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.CloseBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task FollowPreviousElement4()
{
var code = @"using System;
class Class
{
void Method(int i)
{
int i = 10;
int i2 = 10;$$";
var expected = @"using System;
class Class
{
void Method(int i)
{
int i = 10;
int i2 = 10;";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task FollowPreviousElement5()
{
var code = @"using System;
class Class
{
void Method(int i)
{
int i = 10;
if (true)
i = 50;$$";
var expected = @"using System;
class Class
{
void Method(int i)
{
int i = 10;
if (true)
i = 50;";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task FollowPreviousElement6()
{
var code = @" using System;
using System.Linq;$$";
var expected = @" using System;
using System.Linq;";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task FollowPreviousElement7()
{
var code = @" using System;
namespace NS
{
}
namespace NS2
{
}$$";
var expected = @" using System;
namespace NS
{
}
namespace NS2
{
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.CloseBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task FollowPreviousElement8()
{
var code = @"using System;
namespace NS
{
class Class
{
}
class Class1
{
}$$
}";
var expected = @"using System;
namespace NS
{
class Class
{
}
class Class1
{
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.CloseBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task IfStatement1()
{
var code = @"using System;
class Class
{
void Method()
{
if (true)
{
}$$";
var expected = @"using System;
class Class
{
void Method()
{
if (true)
{
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task IfStatement2()
{
var code = @"using System;
class Class
{
void Method()
{
if (true)
{
}
else
{
}$$";
var expected = @"using System;
class Class
{
void Method()
{
if (true)
{
}
else
{
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task IfStatement3()
{
var code = @"using System;
class Class
{
void Method()
{
if (true)
{
}
else if (false)
{
}$$";
var expected = @"using System;
class Class
{
void Method()
{
if (true)
{
}
else if (false)
{
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task IfStatement4()
{
var code = @"using System;
class Class
{
void Method()
{
if (true)
return ;
else if (false)
return ;$$";
var expected = @"using System;
class Class
{
void Method()
{
if (true)
return;
else if (false)
return;";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TryStatement1()
{
var code = @"using System;
class Class
{
void Method()
{
try
{
}$$";
var expected = @"using System;
class Class
{
void Method()
{
try
{
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TryStatement2()
{
var code = @"using System;
class Class
{
void Method()
{
try
{
}
catch ( Exception ex)
{
}$$";
var expected = @"using System;
class Class
{
void Method()
{
try
{
}
catch (Exception ex)
{
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TryStatement3()
{
var code = @"using System;
class Class
{
void Method()
{
try
{
}
catch ( Exception ex)
{
}
catch (Exception ex2)
{
}$$";
var expected = @"using System;
class Class
{
void Method()
{
try
{
}
catch (Exception ex)
{
}
catch (Exception ex2)
{
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TryStatement4()
{
var code = @"using System;
class Class
{
void Method()
{
try
{
}
finally
{
}$$";
var expected = @"using System;
class Class
{
void Method()
{
try
{
}
finally
{
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[WorkItem(6645, "https://github.com/dotnet/roslyn/issues/6645")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TryStatement5()
{
var code = @"using System;
class Class
{
void Method()
{
try {
}$$
}
}";
var expected = @"using System;
class Class
{
void Method()
{
try
{
}
}
}";
await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
[WorkItem(537555, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537555")]
public async Task SingleLine()
{
var code = @"class C { void M() { C.M( );$$ } }";
var expected = @"class C { void M() { C.M(); } }";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task StringLiterals()
{
var code = @"class C { void M() { C.M(""Test {0}$$";
var expected = string.Empty;
await AutoFormatOnMarkerAsync(code, expected, SyntaxKind.StringLiteralToken, SyntaxKind.None);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task CharLiterals()
{
var code = @"class C { void M() { C.M('}$$";
var expected = string.Empty;
await AutoFormatOnMarkerAsync(code, expected, SyntaxKind.CharacterLiteralToken, SyntaxKind.None);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
[WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")]
public async Task CharLiterals1()
{
var code = @"';$$";
var expected = string.Empty;
await AutoFormatOnMarkerAsync(code, expected, SyntaxKind.CharacterLiteralToken, SyntaxKind.None);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Comments()
{
var code = @"class C { void M() { // { }$$";
var expected = string.Empty;
await AutoFormatOnMarkerAsync(code, expected, SyntaxKind.OpenBraceToken, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task FirstLineInFile()
{
var code = @"using System;$$";
await AutoFormatOnSemicolonAsync(code, "using System;", SyntaxKind.UsingKeyword);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Label1()
{
var code = @"class C
{
void Method()
{
L : int i = 20;$$
}
}";
var expected = @"class C
{
void Method()
{
L: int i = 20;
}
}";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Label2()
{
var code = @"class C
{
void Method()
{
L :
int i = 20;$$
}
}";
var expected = @"class C
{
void Method()
{
L:
int i = 20;
}
}";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Label3()
{
var code = @"class C
{
void Method()
{
int base = 10;
L :
int i = 20;$$
}
}";
var expected = @"class C
{
void Method()
{
int base = 10;
L:
int i = 20;
}
}";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Label4()
{
var code = @"class C
{
void Method()
{
int base = 10;
L:
int i = 20;
int nextLine = 30 ;$$
}
}";
var expected = @"class C
{
void Method()
{
int base = 10;
L:
int i = 20;
int nextLine = 30;
}
}";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Label6()
{
var code = @"class C
{
void Method()
{
L:
int i = 20;
int nextLine = 30 ;$$
}
}";
var expected = @"class C
{
void Method()
{
L:
int i = 20;
int nextLine = 30;
}
}";
await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken);
}
[WorkItem(537776, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537776")]
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task DisappearedTokens()
{
var code = @"class Class1
{
int goo()
return 0;
}$$
}";
var expected = @"class Class1
{
int goo()
return 0;
}
}";
await AutoFormatOnCloseBraceAsync(
code,
expected,
SyntaxKind.ClassKeyword);
}
[WorkItem(537779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537779")]
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task DisappearedTokens2()
{
var code = @"class Class1
{
void Goo()
{
Object o=new Object);$$
}
}";
var expected = @"class Class1
{
void Goo()
{
Object o=new Object);
}
}";
await AutoFormatOnSemicolonAsync(
code,
expected,
SyntaxKind.SemicolonToken);
}
[WorkItem(537793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537793")]
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Delegate1()
{
var code = @"delegate void MyDelegate(int a,int b);$$";
var expected = @"delegate void MyDelegate(int a, int b);";
await AutoFormatOnSemicolonAsync(
code,
expected,
SyntaxKind.DelegateKeyword);
}
[WorkItem(537827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537827")]
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task DoubleInitializer()
{
var code = @"class C
{
void Method()
{
int[,] a ={{ 1 , 1 }$$
}
}";
var expected = @"class C
{
void Method()
{
int[,] a ={{ 1 , 1 }
}
}";
await AutoFormatOnCloseBraceAsync(
code,
expected,
SyntaxKind.OpenBraceToken);
}
[WorkItem(537825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537825")]
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task MissingToken1()
{
var code = @"public class Class1
{
int a = 1}$$;
}";
var expected = @"public class Class1
{
int a = 1};
}";
await AutoFormatOnCloseBraceAsync(
code,
expected,
SyntaxKind.PublicKeyword);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task ArrayInitializer1()
{
var code = @"public class Class1
{
var a = new []
{
1, 2, 3, 4
}$$
}";
var expected = @"public class Class1
{
var a = new[]
{
1, 2, 3, 4
}
}";
await AutoFormatOnCloseBraceAsync(
code,
expected,
SyntaxKind.NewKeyword);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task ArrayInitializer2()
{
var code = @"public class Class1
{
var a = new []
{
1, 2, 3, 4
} ;$$
}";
var expected = @"public class Class1
{
var a = new[]
{
1, 2, 3, 4
};
}";
await AutoFormatOnSemicolonAsync(
code,
expected,
SyntaxKind.OpenBraceToken);
}
[WpfFact]
[WorkItem(537825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537825")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task MalformedCode()
{
var code = @"namespace ClassLibrary1
{
public class Class1
{
int a}$$;
}
}";
var expected = @"namespace ClassLibrary1
{
public class Class1
{
int a};
}
}";
await AutoFormatOnCloseBraceAsync(
code,
expected,
SyntaxKind.OpenBraceToken);
}
[WpfFact]
[WorkItem(537804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537804")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Colon_SwitchLabel()
{
var code = @"namespace ClassLibrary1
{
public class Class1
{
void Test()
{
switch(E.Type)
{
case 1 :$$
}
}
}
}";
var expected = @"namespace ClassLibrary1
{
public class Class1
{
void Test()
{
switch(E.Type)
{
case 1:
}
}
}
}";
await AutoFormatOnColonAsync(
code,
expected,
SyntaxKind.OpenBraceToken);
}
[WpfFact]
[WorkItem(584599, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/584599")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Colon_SwitchLabel_Comment()
{
var code = @"namespace ClassLibrary1
{
public class Class1
{
void Test()
{
switch(E.Type)
{
// test
case 1 :$$
}
}
}
}";
var expected = @"namespace ClassLibrary1
{
public class Class1
{
void Test()
{
switch(E.Type)
{
// test
case 1:
}
}
}
}";
await AutoFormatOnColonAsync(
code,
expected,
SyntaxKind.OpenBraceToken);
}
[WpfFact]
[WorkItem(584599, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/584599")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Colon_SwitchLabel_Comment2()
{
var code = @"namespace ClassLibrary1
{
public class Class1
{
void Test()
{
switch(E.Type)
{
case 2:
// test
case 1 :$$
}
}
}
}";
var expected = @"namespace ClassLibrary1
{
public class Class1
{
void Test()
{
switch(E.Type)
{
case 2:
// test
case 1:
}
}
}
}";
await AutoFormatOnColonAsync(
code,
expected,
SyntaxKind.ColonToken);
}
[Fact]
[WorkItem(537804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537804")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Colon_Label()
{
var code = @"namespace ClassLibrary1
{
public class Class1
{
void Test()
{
label :$$
}
}
}";
var expected = @"namespace ClassLibrary1
{
public class Class1
{
void Test()
{
label :
}
}
}";
await AutoFormatOnColonAsync(
code,
expected,
SyntaxKind.None);
}
[WpfFact]
[WorkItem(538793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538793")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Colon_Label2()
{
var code = @"namespace ClassLibrary1
{
public class Class1
{
void Test()
{
label : Console.WriteLine(10) ;$$
}
}
}";
var expected = @"namespace ClassLibrary1
{
public class Class1
{
void Test()
{
label: Console.WriteLine(10);
}
}
}";
await AutoFormatOnSemicolonAsync(
code,
expected,
SyntaxKind.OpenBraceToken);
}
[WpfFact]
[WorkItem(3186, "DevDiv_Projects/Roslyn")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task SemicolonInElseIfStatement()
{
var code = @"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int a = 0;
if (a == 0)
a = 1;
else if (a == 1)
a=2;$$
else
a = 3;
}
}";
var expected = @"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int a = 0;
if (a == 0)
a = 1;
else if (a == 1)
a = 2;
else
a = 3;
}
}";
await AutoFormatOnSemicolonAsync(
code,
expected,
SyntaxKind.SemicolonToken);
}
[WpfFact]
[WorkItem(538391, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538391")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task SemicolonInElseIfStatement2()
{
var code = @"public class Class1
{
void Method()
{
int a = 1;
if (a == 0)
a = 8;$$
else
a = 10;
}
}";
var expected = @"public class Class1
{
void Method()
{
int a = 1;
if (a == 0)
a = 8;
else
a = 10;
}
}";
await AutoFormatOnSemicolonAsync(
code,
expected,
SyntaxKind.SemicolonToken);
}
[WpfFact]
[WorkItem(8385, "DevDiv_Projects/Roslyn")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task NullCoalescingOperator()
{
var code = @"class C
{
void M()
{
object o2 = null??null;$$
}
}";
var expected = @"class C
{
void M()
{
object o2 = null ?? null;
}
}";
await AutoFormatOnSemicolonAsync(
code,
expected,
SyntaxKind.OpenBraceToken);
}
[WpfFact]
[WorkItem(541517, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541517")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task SwitchDefault()
{
var code = @"using System;
class Program
{
static void Main()
{
switch (DayOfWeek.Monday)
{
case DayOfWeek.Monday:
case DayOfWeek.Tuesday:
break;
case DayOfWeek.Wednesday:
break;
default:$$
}
}
}";
var expected = @"using System;
class Program
{
static void Main()
{
switch (DayOfWeek.Monday)
{
case DayOfWeek.Monday:
case DayOfWeek.Tuesday:
break;
case DayOfWeek.Wednesday:
break;
default:
}
}
}";
await AutoFormatOnColonAsync(
code,
expected,
SyntaxKind.SemicolonToken);
}
[WpfFact]
[WorkItem(542538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542538")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task MissingTokens1()
{
var code = @"class Program
{
static void Main(string[] args)
{
gl::$$
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
gl::
}
}";
await AutoFormatOnMarkerAsync(
code,
expected,
SyntaxKind.ColonColonToken,
SyntaxKind.OpenBraceToken);
}
[WpfFact]
[WorkItem(542538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542538")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task MissingTokens2()
{
var code = @"class C { void M() { M(() => { }$$ } }";
var expected = @"class C { void M() { M(() => { } } }";
await AutoFormatOnCloseBraceAsync(
code,
expected,
SyntaxKind.EqualsGreaterThanToken);
}
[WpfFact]
[WorkItem(542953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542953")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task UsingAlias()
{
var code = @"using Alias=System;$$";
var expected = @"using Alias = System;";
await AutoFormatOnSemicolonAsync(
code,
expected,
SyntaxKind.UsingKeyword);
}
[WpfFact]
[WorkItem(542953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542953")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task NoLineChangeWithSyntaxError()
{
var code = @"struct Goo { public int member; }
class Program{
void Main()
{
var f = new Goo { member;$$ }
}
}";
var expected = @"struct Goo { public int member; }
class Program{
void Main()
{
var f = new Goo { member; }
}
}";
await AutoFormatOnSemicolonAsync(
code,
expected,
SyntaxKind.OpenBraceToken);
}
[WpfTheory]
[CombinatorialData]
[WorkItem(620568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/620568")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void SkippedTokens1(bool useTabs)
{
var code = @";$$*";
var expected = @";*";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[WorkItem(530830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530830")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void AutoPropertyAccessor(bool useTabs)
{
var code = @"class C
{
int Prop { get ;$$
}";
var expected = @"class C
{
int Prop { get;
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[WorkItem(530830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530830")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void AutoPropertyAccessor2(bool useTabs)
{
var code = @"class C
{
int Prop { get; set ;$$
}";
var expected = @"class C
{
int Prop { get; set;
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[WorkItem(530830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530830")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void AutoPropertyAccessor3(bool useTabs)
{
var code = @"class C
{
int Prop { get; set ; }$$
}";
var expected = @"class C
{
int Prop { get; set; }
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[WorkItem(784674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/784674")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void AutoPropertyAccessor4(bool useTabs)
{
var code = @"class C
{
int Prop { get;$$ }
}";
var expected = @"class C
{
int Prop { get; }
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[WorkItem(924469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924469")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void AutoPropertyAccessor5(bool useTabs)
{
var code = @"class C
{
int Prop { get; set ;$$ }
}";
var expected = @"class C
{
int Prop { get; set; }
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[WorkItem(924469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924469")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void AutoPropertyAccessor6(bool useTabs)
{
var code = @"class C
{
int Prop { get;set;$$}
}";
var expected = @"class C
{
int Prop { get; set; }
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[WorkItem(924469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924469")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void AutoPropertyAccessor7(bool useTabs)
{
var code = @"class C
{
int Prop { get;set;$$}
}";
var expected = @"class C
{
int Prop { get; set; }
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void NestedUsingStatement(bool useTabs)
{
var code = @"class C
{
public void M()
{
using (null)
using(null)$$
}
}";
var expected = @"class C
{
public void M()
{
using (null)
using (null)
}
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void NestedNotUsingStatement(bool useTabs)
{
var code = @"class C
{
public void M()
{
using (null)
for(;;)$$
}
}";
var expected = @"class C
{
public void M()
{
using (null)
for(;;)
}
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void UsingStatementWithNestedFixedStatement(bool useTabs)
{
var code = @"class C
{
public void M()
{
using (null)
fixed (void* ptr = &i)
{
}$$
}
}";
var expected = @"class C
{
public void M()
{
using (null)
fixed (void* ptr = &i)
{
}
}
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void UsingStatementWithNestedCheckedStatement(bool useTabs)
{
var code = @"class C
{
public void M()
{
using (null)
checked
{
}$$
}
}";
var expected = @"class C
{
public void M()
{
using (null)
checked
{
}
}
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void UsingStatementWithNestedUncheckedStatement(bool useTabs)
{
var code = @"class C
{
public void M()
{
using (null)
unchecked
{
}$$
}
}";
var expected = @"class C
{
public void M()
{
using (null)
unchecked
{
}
}
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void FixedStatementWithNestedUsingStatement(bool useTabs)
{
var code = @"class C
{
public void M()
{
fixed (void* ptr = &i)
using (null)$$
}
}";
var expected = @"class C
{
public void M()
{
fixed (void* ptr = &i)
using (null)
}
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void FixedStatementWithNestedFixedStatement(bool useTabs)
{
var code = @"class C
{
public void M()
{
fixed (void* ptr1 = &i)
fixed (void* ptr2 = &i)
{
}$$
}
}";
var expected = @"class C
{
public void M()
{
fixed (void* ptr1 = &i)
fixed (void* ptr2 = &i)
{
}
}
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void FixedStatementWithNestedNotFixedStatement(bool useTabs)
{
var code = @"class C
{
public void M()
{
fixed (void* ptr = &i)
if (false)
{
}$$
}
}";
var expected = @"class C
{
public void M()
{
fixed (void* ptr = &i)
if (false)
{
}
}
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void NotFixedStatementWithNestedFixedStatement(bool useTabs)
{
var code = @"class C
{
public void M()
{
if (false)
fixed (void* ptr = &i)
{
}$$
}
}";
var expected = @"class C
{
public void M()
{
if (false)
fixed (void* ptr = &i)
{
}
}
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[WorkItem(954386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954386")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void FormattingRangeForFirstStatementOfBlock(bool useTabs)
{
var code = @"class C
{
public void M()
{int s;$$
}
}";
var expected = @"class C
{
public void M()
{
int s;
}
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[WorkItem(954386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954386")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void FormattingRangeForFirstMemberofType(bool useTabs)
{
var code = @"class C
{int s;$$
public void M()
{
}
}";
var expected = @"class C
{
int s;
public void M()
{
}
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[WorkItem(954386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954386")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void FormattingRangeForFirstMethodMemberofType(bool useTabs)
{
var code = @"interface C
{void s();$$
}";
var expected = @"interface C
{
void s();
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[WorkItem(17257, "https://github.com/dotnet/roslyn/issues/17257")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void FormattingRangeForConstructor(bool useTabs)
{
var code = @"class C
{public C()=>f=1;$$
}";
var expected = @"class C
{
public C() => f = 1;
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[WorkItem(17257, "https://github.com/dotnet/roslyn/issues/17257")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void FormattingRangeForDestructor(bool useTabs)
{
var code = @"class C
{~C()=>f=1;$$
}";
var expected = @"class C
{
~C() => f = 1;
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[WorkItem(17257, "https://github.com/dotnet/roslyn/issues/17257")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void FormattingRangeForOperator(bool useTabs)
{
var code = @"class C
{public static C operator +(C left, C right)=>field=1;$$
static int field;
}";
var expected = @"class C
{
public static C operator +(C left, C right) => field = 1;
static int field;
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[WorkItem(954386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954386")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void FormattingRangeForFirstMemberOfNamespace(bool useTabs)
{
var code = @"namespace C
{delegate void s();$$
}";
var expected = @"namespace C
{
delegate void s();
}";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[WorkItem(981821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981821")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatDirectiveTriviaAlwaysToColumnZero(bool useTabs)
{
var code = @"class Program
{
static void Main(string[] args)
{
#if
#$$
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
#if
#
}
}
";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[WorkItem(981821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981821")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatDirectiveTriviaAlwaysToColumnZeroWithCode(bool useTabs)
{
var code = @"class Program
{
static void Main(string[] args)
{
#if
int s = 10;
#$$
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
#if
int s = 10;
#
}
}
";
AutoFormatToken(code, expected, useTabs);
}
[WpfTheory]
[CombinatorialData]
[WorkItem(981821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981821")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatDirectiveTriviaAlwaysToColumnZeroWithBrokenElseDirective(bool useTabs)
{
var code = @"class Program
{
static void Main(string[] args)
{
#else
#$$
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
#else
#
}
}
";
AutoFormatToken(code, expected, useTabs);
}
internal static void AutoFormatToken(string markup, string expected, bool useTabs)
{
if (useTabs)
{
markup = markup.Replace(" ", "\t");
expected = expected.Replace(" ", "\t");
}
using var workspace = TestWorkspace.CreateCSharp(markup);
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
.WithChangedOption(FormattingOptions2.UseTabs, LanguageNames.CSharp, useTabs)));
var subjectDocument = workspace.Documents.Single();
var commandHandler = workspace.GetService<FormatCommandHandler>();
var typedChar = subjectDocument.GetTextBuffer().CurrentSnapshot.GetText(subjectDocument.CursorPosition.Value - 1, 1);
commandHandler.ExecuteCommand(new TypeCharCommandArgs(subjectDocument.GetTextView(), subjectDocument.GetTextBuffer(), typedChar[0]), () => { }, TestCommandExecutionContext.Create());
var newSnapshot = subjectDocument.GetTextBuffer().CurrentSnapshot;
Assert.Equal(expected, newSnapshot.GetText());
}
private static Task AutoFormatOnColonAsync(string codeWithMarker, string expected, SyntaxKind startTokenKind)
=> AutoFormatOnMarkerAsync(codeWithMarker, expected, SyntaxKind.ColonToken, startTokenKind);
private static Task AutoFormatOnSemicolonAsync(string codeWithMarker, string expected, SyntaxKind startTokenKind)
=> AutoFormatOnMarkerAsync(codeWithMarker, expected, SyntaxKind.SemicolonToken, startTokenKind);
private static Task AutoFormatOnCloseBraceAsync(string codeWithMarker, string expected, SyntaxKind startTokenKind)
=> AutoFormatOnMarkerAsync(codeWithMarker, expected, SyntaxKind.CloseBraceToken, startTokenKind);
private static async Task AutoFormatOnMarkerAsync(string initialMarkup, string expected, SyntaxKind tokenKind, SyntaxKind startTokenKind)
{
await AutoFormatOnMarkerAsync(initialMarkup, expected, useTabs: false, tokenKind, startTokenKind).ConfigureAwait(false);
await AutoFormatOnMarkerAsync(initialMarkup.Replace(" ", "\t"), expected.Replace(" ", "\t"), useTabs: true, tokenKind, startTokenKind).ConfigureAwait(false);
}
private static async Task AutoFormatOnMarkerAsync(string initialMarkup, string expected, bool useTabs, SyntaxKind tokenKind, SyntaxKind startTokenKind)
{
using var workspace = TestWorkspace.CreateCSharp(initialMarkup);
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
.WithChangedOption(FormattingOptions2.UseTabs, LanguageNames.CSharp, useTabs)));
var testDocument = workspace.Documents.Single();
var buffer = testDocument.GetTextBuffer();
var position = testDocument.CursorPosition.Value;
var document = workspace.CurrentSolution.GetDocument(testDocument.Id);
var rules = Formatter.GetDefaultFormattingRules(document);
var root = (CompilationUnitSyntax)await document.GetSyntaxRootAsync();
var endToken = root.FindToken(position);
if (position == endToken.SpanStart && !endToken.GetPreviousToken().IsKind(SyntaxKind.None))
{
endToken = endToken.GetPreviousToken();
}
Assert.Equal(tokenKind, endToken.Kind());
var options = await IndentationOptions.FromDocumentAsync(document, CancellationToken.None);
var formatter = new CSharpSmartTokenFormatter(options, rules, root);
var tokenRange = FormattingRangeHelper.FindAppropriateRange(endToken);
if (tokenRange == null)
{
Assert.Equal(SyntaxKind.None, startTokenKind);
return;
}
Assert.Equal(startTokenKind, tokenRange.Value.Item1.Kind());
if (tokenRange.Value.Item1.Equals(tokenRange.Value.Item2))
{
return;
}
var changes = formatter.FormatRange(workspace.Services, tokenRange.Value.Item1, tokenRange.Value.Item2, CancellationToken.None);
var actual = GetFormattedText(buffer, changes);
Assert.Equal(expected, actual);
}
private static string GetFormattedText(ITextBuffer buffer, IList<TextChange> changes)
{
using (var edit = buffer.CreateEdit())
{
foreach (var change in changes)
{
edit.Replace(change.Span.ToSpan(), change.NewText);
}
edit.Apply();
}
return buffer.CurrentSnapshot.GetText();
}
}
}
| {
"content_hash": "ae1c7cd3d5bd3452778f80848e1f0c8f",
"timestamp": "",
"source": "github",
"line_count": 3627,
"max_line_length": 194,
"avg_line_length": 22.42624758753791,
"alnum_prop": 0.5299483648881239,
"repo_name": "KevinRansom/roslyn",
"id": "3f5ef74ec4eaf72fe80f4a1fb28fd2bb64bd933d",
"size": "81342",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatRangeTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "1C Enterprise",
"bytes": "257760"
},
{
"name": "Batchfile",
"bytes": "8186"
},
{
"name": "C#",
"bytes": "165251418"
},
{
"name": "C++",
"bytes": "5602"
},
{
"name": "CMake",
"bytes": "11076"
},
{
"name": "Dockerfile",
"bytes": "441"
},
{
"name": "F#",
"bytes": "549"
},
{
"name": "PowerShell",
"bytes": "279605"
},
{
"name": "Shell",
"bytes": "123448"
},
{
"name": "Vim Snippet",
"bytes": "6353"
},
{
"name": "Visual Basic .NET",
"bytes": "73602862"
}
],
"symlink_target": ""
} |
title: Get started with Calico network policy for OpenStack
description: Extend OpenStack security groups by applying Calico network policy and using labels to identify VMs within network policy rules.
---
### Big picture
Use {{site.prodname}} network policy to extend security beyond OpenStack security groups.
### Value
For **deployment users**, OpenStack security groups provides enough features and flexibility. But for **deployment administrators**, limited labeling in VM security groups makes it difficult to address all security use cases that arise. {{site.prodname}} network policy provides special VM labels so you can identify VMs and impose additional restrictions that cannot be bypassed by users’ security group configuration.
### Features
This how-to guide uses the following {{site.prodname}} features:
- {{site.prodname}} predefined **OpenStack VM endpoint labels**
- **GlobalNetworkPolicy** or **NetworkPolicy**
### Concepts
#### Multi-region deployments
Using the OpenStack API, it is difficult to apply policy to cross-region network traffic because security groups are local to a single region. In {{site.prodname}}, each region in your OpenStack deployment becomes a separate {{site.prodname}} namespace in a single etcd datastore. With regions mapped to namespaces, you can easily define {{site.prodname}} network policy for communications between VMs in different regions.
#### Labels: more flexibility, greater security
{{site.prodname}} provides predefined [VM endpoint labels]({{ site.baseurl }}/networking/openstack/labels) (projects, security groups, and namespaces) for OpenStack deployments. You can use these labels in selector fields in {{site.prodname}} network policy to identify the VMs for allow/deny policy.
#### Policy ordering and enforcement
{{site.prodname}} network policy is always enforced before OpenStack security groups, and cannot be overridden by user-level security group configuration.
### Before you begin...
- [Set up {{site.prodname}} for OpenStack]({{ site.baseurl }}/networking/openstack/dev-machine-setup)
- If you are using a multi-region VM deployment, [follow these extra steps]({{ site.baseurl }}/networking/openstack/multiple-regions)
### How to
- [Restrict all ingress traffic between specific security groups](#restrict-all-ingress-traffic-between-specific-security-groups)
- [Allow specific traffic between VMs in different regions](#allow-specific-traffic-between-vms-in-different-regions)
#### Restrict all ingress traffic between specific security groups
In the following example, we create a **GlobalNetworkPolicy** that is applied before any OpenStack security group policy. It prevents all ingress communication between the OpenStack **superman** and **lexluthor** projects. We use the predefined {{site.prodname}} VM endpoint label, **openstack-project-name**, to identify projects.
```yaml
apiVersion: projectcalico.org/v3
kind: GlobalNetworkPolicy
metadata:
name: deny-lexluthor-to-superman
spec:
order: 10
selector: "projectcalico.org/openstack-project-name == 'superman'"
types:
- Ingress
ingress:
- action: Deny
source:
selector: "projectcalico.org/openstack-project-name == 'lexluthor'"
---
apiVersion: projectcalico.org/v3
kind: GlobalNetworkPolicy
metadata:
name: deny-superman-to-lexluthor
spec:
order: 10
selector: "projectcalico.org/openstack-project-name == 'lexluthor'"
types:
- Ingress
ingress:
- action: Deny
source:
selector: "projectcalico.org/openstack-project-name == 'superman'"
```
#### Allow specific traffic between VMs in different regions
In the following example, we use the predefined VM endpoint label, **openstack-security_group_ID**. Traffic is allowed to VMs with the label, **openstack-a773…** on port 80, from VMs in any region with the label, **openstack-85cc…**.
```yaml
apiVersion: projectcalico.org/v3
kind: GlobalNetworkPolicy
metadata:
name: allow-tcp-80
spec:
selector: "has(sg.projectcalico.org/openstack-a7734e61-b545-452d-a3cd-0189cbd9747a)"
types:
- Ingress
ingress:
- action: Allow
protocol: TCP
source:
selector: "has(sg.projectcalico.org/openstack-85cc3048-abc3-43cc-89b3-377341426ac5)"
destination:
ports:
- 80
```
### Above and beyond
- For additional {{site.prodname}} network policy features, see [{{site.prodname}} network policy]({{ site.baseurl }}/reference/resources/networkpolicy) and [Calico global network policy]({{ site.baseurl }}/reference/resources/globalnetworkpolicy)
- For details on the OpenStack integration with {{site.prodname}}, see [{{site.prodname}} for OpenStack]({{ site.baseurl }}/networking/openstack/dev-machine-setup)
| {
"content_hash": "ad24cd243a364f87c3b0343e2c303e3f",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 424,
"avg_line_length": 45.08653846153846,
"alnum_prop": 0.7622094263169119,
"repo_name": "bcreane/calico",
"id": "cbcc21a16901b8e266146bb474217a509cc14bca",
"size": "4699",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "security/network-policy-openstack.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "10694"
},
{
"name": "Dockerfile",
"bytes": "4393"
},
{
"name": "Go",
"bytes": "7861"
},
{
"name": "HTML",
"bytes": "28363"
},
{
"name": "JavaScript",
"bytes": "6641"
},
{
"name": "Makefile",
"bytes": "23224"
},
{
"name": "Python",
"bytes": "9167"
},
{
"name": "Ruby",
"bytes": "206260"
},
{
"name": "Shell",
"bytes": "35202"
},
{
"name": "Smarty",
"bytes": "3471"
}
],
"symlink_target": ""
} |
package org.ovirt.engine.core.bll;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.queries.TimeZoneQueryParams;
public class GetDefaultTimeZoneQuery<P extends TimeZoneQueryParams> extends QueriesCommandBase<P> {
public GetDefaultTimeZoneQuery(P parameters) {
super(parameters);
}
@Override
protected void executeQueryCommand() {
ConfigValues defaultTimeZoneConfigKey;
switch (getParameters().getTimeZoneType()) {
default:
case GENERAL_TIMEZONE:
defaultTimeZoneConfigKey = ConfigValues.DefaultGeneralTimeZone;
break;
case WINDOWS_TIMEZONE:
defaultTimeZoneConfigKey = ConfigValues.DefaultWindowsTimeZone;
break;
}
String timeZone = Config.<String> getValue(defaultTimeZoneConfigKey);
getQueryReturnValue().setReturnValue(timeZone);
}
}
| {
"content_hash": "873a9d7d3d9f4c96881578789a0d8f5f",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 99,
"avg_line_length": 33.62068965517241,
"alnum_prop": 0.7138461538461538,
"repo_name": "zerodengxinchao/ovirt-engine",
"id": "592a1bd45a80c2498c99ce46e328d142e8fb877b",
"size": "975",
"binary": false,
"copies": "10",
"ref": "refs/heads/eayunos-4.2",
"path": "backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/GetDefaultTimeZoneQuery.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "68312"
},
{
"name": "HTML",
"bytes": "16218"
},
{
"name": "Java",
"bytes": "35067557"
},
{
"name": "JavaScript",
"bytes": "69948"
},
{
"name": "Makefile",
"bytes": "24723"
},
{
"name": "PLSQL",
"bytes": "533"
},
{
"name": "PLpgSQL",
"bytes": "796728"
},
{
"name": "Python",
"bytes": "970860"
},
{
"name": "Roff",
"bytes": "10764"
},
{
"name": "Shell",
"bytes": "163853"
},
{
"name": "XSLT",
"bytes": "54683"
}
],
"symlink_target": ""
} |
#ifndef EFI_TIMER_DELAY_H
#define EFI_TIMER_DELAY_H
/**
* <!-- description -->
* @brief Defines the layout of the EFI_TIMER_DELAY struct:
* https://uefi.org/sites/default/files/resources/UEFI_Spec_2_8_final.pdf
*/
typedef enum
{
/**
* @brief The event’s timer setting is to be cancelled and no timer
* trigger is to be set. TriggerTime is ignored when canceling a timer.
*/
TimerCancel,
/**
* @brief The event is to be signaled periodically at TriggerTime
* intervals from the current time. This is the only timer trigger Type
* for which the event timer does not need to be reset for each
* notification. All other timer trigger types are “one shot.”
*/
TimerPeriodic,
/**
* @brief The event is to be signaled in TriggerTime 100ns units.
*/
TimerRelative
} EFI_TIMER_DELAY;
#endif
| {
"content_hash": "f0451ccf335240a7c379f18759772f29",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 77,
"avg_line_length": 25.91176470588235,
"alnum_prop": 0.6549375709421112,
"repo_name": "Bareflank/hypervisor",
"id": "97af6a05b5582d830fa3a5bf273cc7bd62c872fa",
"size": "2082",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "loader/efi/include/efi/efi_timer_delay.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "65359"
},
{
"name": "C",
"bytes": "128272"
},
{
"name": "C++",
"bytes": "4106171"
},
{
"name": "CMake",
"bytes": "214959"
},
{
"name": "Makefile",
"bytes": "1885"
},
{
"name": "Shell",
"bytes": "19153"
}
],
"symlink_target": ""
} |
var extractZipFile,
resultObjs = {},
threadCallback = null,
_utils = require("../../lib/utils");
module.exports = {
extract: function (success, fail, args, env) {
var result = new PluginResult(args, env);
resultObjs[result.callbackId] = result;
extractZipFile.getInstance().extractFile(result.callbackId, args);
result.noResult(true);
},
compress: function (success, fail, args, env) {
var result = new PluginResult(args, env);
resultObjs[result.callbackId] = result;
extractZipFile.getInstance().compressFile(result.callbackId, args);
result.noResult(true);
}
};
///////////////////////////////////////////////////////////////////
// JavaScript wrapper for JNEXT plugin for connection
///////////////////////////////////////////////////////////////////
JNEXT.ExtractZipFile = function () {
var self = this,
hasInstance = false;
self.getId = function () {
return self.m_id;
};
self.init = function () {
if (!JNEXT.require("libExtractZipFile")) {
return false;
}
self.m_id = JNEXT.createObject("libExtractZipFile.ExtractZipFileJS");
if (self.m_id === "") {
return false;
}
JNEXT.registerEvents(self);
};
// ************************
// Enter your methods here
// ************************
// calls into InvokeMethod(string command) in template_js.cpp
self.extractFile = function (callbackId, input) {
var args = decodeURIComponent(input[0]);
return JNEXT.invoke(self.m_id, "extractFile " + callbackId + ' ' + args);
};
self.compressFile = function (callbackId, input) {
var args = decodeURIComponent(input[0]);
return JNEXT.invoke(self.m_id, "compressFile " + callbackId + ' ' + args);
};
self.onEvent = function (strData) {
var arData = strData.split(" "),
callbackId = arData[0],
result = resultObjs[callbackId],
data = arData.slice(1, arData.length).join(" ");
if (result) {
if (callbackId != threadCallback) {
// We do not use the default
// sucess vs fail callbacks
// instead the RAW api merges it
result.callbackOk(data, false);
delete resultObjs[callbackId];
} else {
result.callbackOk(data, true);
}
}
};
// ************************
// End of methods to edit
// ************************
self.m_id = "";
self.getInstance = function () {
if (!hasInstance) {
hasInstance = true;
self.init();
}
return self;
};
};
extractZipFile = new JNEXT.ExtractZipFile();
| {
"content_hash": "29155f7afe7cd3a929bb3874c58aa8fe",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 76,
"avg_line_length": 24.683673469387756,
"alnum_prop": 0.5965274906986358,
"repo_name": "Makoz/WebWorks-Community-APIs",
"id": "ed24f6351a69dd1d078158efe2ff1f88e7012f88",
"size": "3006",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "BB10-Cordova/ExtractZipFile/plugin/src/blackberry10/index.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ActionScript",
"bytes": "970616"
},
{
"name": "C",
"bytes": "1140961"
},
{
"name": "C++",
"bytes": "8571455"
},
{
"name": "CSS",
"bytes": "300036"
},
{
"name": "DIGITAL Command Language",
"bytes": "1802"
},
{
"name": "HTML",
"bytes": "196658"
},
{
"name": "Java",
"bytes": "457472"
},
{
"name": "JavaScript",
"bytes": "2464959"
},
{
"name": "Makefile",
"bytes": "5118"
},
{
"name": "Objective-C",
"bytes": "27968"
},
{
"name": "QMake",
"bytes": "20562"
},
{
"name": "Shell",
"bytes": "655"
}
],
"symlink_target": ""
} |
package com.eebbk.joy;
import com.eebbk.joy.utils.L;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class TabIndicator extends LinearLayout {
private Context context;
private OnIndicatorItemClickListener mListener;
private String[] mTitle = {"ÐÂÎÅ","Ц»°","Ȥͼ","ÖÇÄÜСÆß"};
private boolean isFirstIn = true;
public TabIndicator(Context context) {
this(context,null);
}
public TabIndicator(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
initView();
}
/**
* µã»÷ʼþµÄ¼àÌý
* @author jyqqhw
*
*/
public interface OnIndicatorItemClickListener{
void onClick(View view,int position);
}
public void setOnIndicatorItemClickListener(OnIndicatorItemClickListener listener){
mListener = listener;
}
private void initView(){
for(int i = 0;i<4;i++){
initSingleIndicator(i);
}
}
private void initSingleIndicator(final int index){
Button tv = new Button(context);
// TextView tv = new TextView(context);
tv.setId(0xdffeeee+index*0x4fdc);
tv.setText(mTitle[index]);
tv.setTextColor(Color.WHITE);
tv.setTextSize(22.0f);
if(0 == index && isFirstIn){
tv.setBackgroundResource(R.drawable.main_indicator_btn_title_pressed);
isFirstIn = false;
}else{
tv.setBackgroundResource(R.drawable.main_indicator_btn_title_nornal);
}
tv.setGravity(Gravity.CENTER);
LayoutParams params = new LayoutParams(80, 60,1);
tv.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(null != mListener){
mListener.onClick(v,index);
}
setItemSelected(index);
return false;
}
});
addView(tv, params);
}
/**
* ָʾËùѡλÖÃ
*
* @param position
*/
public void setItemSelected(int position){
for(int i = 0;i<4;i++){
if(i == position){
findViewById(0xdffeeee+position*0x4fdc).setBackgroundResource(R.drawable.main_indicator_btn_title_pressed);
continue;
}
findViewById(0xdffeeee+i*0x4fdc).setBackgroundResource(R.drawable.main_indicator_btn_title_nornal);
}
}
}
| {
"content_hash": "b33ea1c798f572e7e6f4a0dc89201266",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 111,
"avg_line_length": 20.5,
"alnum_prop": 0.69932716568545,
"repo_name": "jyqqhw/Joy",
"id": "0ad640c932719fc65ecbc83e846f2ccd44da106c",
"size": "2378",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/eebbk/joy/TabIndicator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "63536"
}
],
"symlink_target": ""
} |
import { isStringNotEmpty } from "@runningdinner/shared";
/**
*
* @param queryParams URLSearchParams
* @param queryParamName name of URL query param
* @returns Returns the decoded url query param or an empty string
*/
export function getDecodedQueryParam(queryParams: URLSearchParams, queryParamName: string) {
const queryParamValue = queryParams.get(queryParamName);
if (isStringNotEmpty(queryParamValue)) {
return decodeURI(queryParamValue);
}
return "";
}
| {
"content_hash": "f0541de9a6a5a1561a9f4a5966617bef",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 92,
"avg_line_length": 31.866666666666667,
"alnum_prop": 0.7594142259414226,
"repo_name": "Clemens85/runningdinner",
"id": "eb7dc3e3f9fa00f4804203ca610a12abc05d8313",
"size": "478",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "runningdinner-client/packages/webapp/src/common/QueryParamDecoder.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9964"
},
{
"name": "HTML",
"bytes": "220884"
},
{
"name": "Java",
"bytes": "1059912"
},
{
"name": "JavaScript",
"bytes": "915942"
},
{
"name": "Less",
"bytes": "18959"
},
{
"name": "Shell",
"bytes": "3096"
},
{
"name": "TypeScript",
"bytes": "656882"
}
],
"symlink_target": ""
} |
package com.linkedin.thirdeye.dashboard.resources;
import com.wordnik.swagger.annotations.ApiOperation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.validation.constraints.NotNull;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.node.ObjectNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkedin.thirdeye.api.MetricType;
import com.linkedin.thirdeye.dashboard.Utils;
import com.linkedin.thirdeye.datalayer.bao.MetricConfigManager;
import com.linkedin.thirdeye.datalayer.dto.MetricConfigDTO;
import com.linkedin.thirdeye.datasource.DAORegistry;
import com.linkedin.thirdeye.util.JsonResponseUtil;
import com.linkedin.thirdeye.util.ThirdEyeUtils;
@Path(value = "/thirdeye-admin/metric-config")
@Produces(MediaType.APPLICATION_JSON)
public class MetricConfigResource {
private static final Logger LOG = LoggerFactory.getLogger(MetricConfigResource.class);
private static final DAORegistry DAO_REGISTRY = DAORegistry.getInstance();
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private MetricConfigManager metricConfigDao;
public MetricConfigResource() {
this.metricConfigDao = DAO_REGISTRY.getMetricConfigDAO();
}
@GET
@Path("/create")
public String createMetricConfig(@QueryParam("dataset") String dataset, @QueryParam("name") String name, @QueryParam("datatype") String metricType,
@QueryParam("active") boolean active, @QueryParam("derived") boolean derived, @QueryParam("derivedFunctionType") String derivedFunctionType,
@QueryParam("numerator") String numerator, @QueryParam("denominator") String denominator,
@QueryParam("derivedMetricExpression") String derivedMetricExpression, @QueryParam("inverseMetric") boolean inverseMetric,
@QueryParam("cellSizeExpression") String cellSizeExpression, @QueryParam("rollupThreshold") Double rollupThreshold) {
try {
MetricConfigDTO metricConfigDTO = new MetricConfigDTO();
populateMetricConfig(metricConfigDTO, dataset, name, metricType, active, derived, derivedFunctionType, numerator, denominator, derivedMetricExpression,
inverseMetric, cellSizeExpression, rollupThreshold);
Long id = metricConfigDao.save(metricConfigDTO);
metricConfigDTO.setId(id);
return JsonResponseUtil.buildResponseJSON(metricConfigDTO).toString();
} catch (Exception e) {
LOG.warn("Failed to create metric:{}", name, e);
return JsonResponseUtil.buildErrorResponseJSON("Failed to create metric:" + name + " Message:" + e.getMessage()).toString();
}
}
private void populateMetricConfig(MetricConfigDTO metricConfigDTO, String dataset, String name, String metricType, boolean active, boolean derived,
String derivedFunctionType, String numerator, String denominator, String derivedMetricExpression, boolean inverseMetric, String cellSizeExpression,
Double rollupThreshold) {
metricConfigDTO.setDataset(dataset);
metricConfigDTO.setName(name);
metricConfigDTO.setAlias(ThirdEyeUtils.constructMetricAlias(dataset, name));
metricConfigDTO.setDatatype(MetricType.valueOf(metricType));
metricConfigDTO.setActive(active);
// optional ones
metricConfigDTO.setCellSizeExpression(cellSizeExpression);
metricConfigDTO.setInverseMetric(inverseMetric);
if (rollupThreshold != null) {
metricConfigDTO.setRollupThreshold(rollupThreshold);
}
// handle derived
if (derived) {
if (StringUtils.isEmpty(derivedMetricExpression) && numerator != null && denominator != null) {
MetricConfigDTO numMetricConfigDTO = metricConfigDao.findByAliasAndDataset(numerator, dataset);
MetricConfigDTO denMetricConfigDTO = metricConfigDao.findByAliasAndDataset(denominator, dataset);
if ("RATIO".equals(derivedFunctionType)) {
derivedMetricExpression = String.format("id%s/id%s", numMetricConfigDTO.getId(), denMetricConfigDTO.getId());
} else if ("PERCENT".equals(derivedFunctionType)) {
derivedMetricExpression = String.format("id%s*100/id%s", numMetricConfigDTO.getId(), denMetricConfigDTO.getId());
}
}
metricConfigDTO.setDerived(derived);
metricConfigDTO.setDerivedMetricExpression(derivedMetricExpression);
}
}
@GET
@Path("/metrics")
public String getMetricsForDataset(@NotNull @QueryParam("dataset") String dataset) {
Map<String, Object> filters = new HashMap<>();
filters.put("dataset", dataset);
List<MetricConfigDTO> metricConfigDTOs = metricConfigDao.findByParams(filters);
List<String> metrics = new ArrayList<>();
for (MetricConfigDTO metricConfigDTO : metricConfigDTOs) {
metrics.add(metricConfigDTO.getAlias());
}
return JsonResponseUtil.buildResponseJSON(metrics).toString();
}
@GET
@Path("/update")
public String updateMetricConfig(@NotNull @QueryParam("id") long metricConfigId, @QueryParam("dataset") String dataset, @QueryParam("name") String name,
@QueryParam("datatype") String metricType, @QueryParam("active") boolean active, @QueryParam("derived") boolean derived,
@QueryParam("derivedFunctionType") String derivedFunctionType, @QueryParam("numerator") String numerator, @QueryParam("denominator") String denominator,
@QueryParam("derivedMetricExpression") String derivedMetricExpression, @QueryParam("inverseMetric") boolean inverseMetric,
@QueryParam("cellSizeExpression") String cellSizeExpression, @QueryParam("rollupThreshold") Double rollupThreshold) {
try {
MetricConfigDTO metricConfigDTO = metricConfigDao.findById(metricConfigId);
populateMetricConfig(metricConfigDTO, dataset, name, metricType, active, derived, derivedFunctionType, numerator, denominator, derivedMetricExpression,
inverseMetric, cellSizeExpression, rollupThreshold);
int numRowsUpdated = metricConfigDao.update(metricConfigDTO);
if (numRowsUpdated == 1) {
return JsonResponseUtil.buildResponseJSON(metricConfigDTO).toString();
} else {
return JsonResponseUtil.buildErrorResponseJSON("Failed to update metric id:" + metricConfigId).toString();
}
} catch (Exception e) {
return JsonResponseUtil.buildErrorResponseJSON("Failed to update metric id:" + metricConfigId + ". Exception:" + e.getMessage()).toString();
}
}
@GET
@Path("/delete")
public String deleteMetricConfig(@NotNull @QueryParam("dataset") String dataset, @NotNull @QueryParam("id") Long metricConfigId) {
metricConfigDao.deleteById(metricConfigId);
return JsonResponseUtil.buildSuccessResponseJSON("Successully deleted " + metricConfigId).toString();
}
@GET
@Path("/list")
@Produces(MediaType.APPLICATION_JSON)
public String viewMetricConfig(@NotNull @QueryParam("dataset") String dataset, @DefaultValue("0") @QueryParam("jtStartIndex") int jtStartIndex,
@DefaultValue("100") @QueryParam("jtPageSize") int jtPageSize) {
Map<String, Object> filters = new HashMap<>();
filters.put("dataset", dataset);
List<MetricConfigDTO> metricConfigDTOs = metricConfigDao.findByParams(filters);
Collections.sort(metricConfigDTOs, new Comparator<MetricConfigDTO>() {
@Override
public int compare(MetricConfigDTO m1, MetricConfigDTO m2) {
return m1.getName().compareTo(m2.getName());
}
});
List<MetricConfigDTO> subList = Utils.sublist(metricConfigDTOs, jtStartIndex, jtPageSize);
ObjectNode rootNode = JsonResponseUtil.buildResponseJSON(subList);
return rootNode.toString();
}
@GET
@Path("/view")
@Produces(MediaType.APPLICATION_JSON)
public MetricConfigDTO viewMetricConfigByIdOrName(@QueryParam("id") String id,
@QueryParam("dataset") String dataset,
@QueryParam("metric") String metric) {
MetricConfigDTO metricConfigDTO = null;
if (StringUtils.isBlank(id) && (StringUtils.isBlank(dataset) || StringUtils.isBlank(metric))) {
LOG.error("Must provide either id or metric+dataset {} {} {}", id, metric, dataset);
}
if (StringUtils.isNotBlank(id)) {
metricConfigDTO = metricConfigDao.findById(Long.valueOf(id));
} else {
metricConfigDTO = metricConfigDao.findByMetricAndDataset(metric, dataset);
}
return metricConfigDTO;
}
@GET
@Path("/view/dataset/{dataset}")
@Produces(MediaType.APPLICATION_JSON)
public List<MetricConfigDTO> findByDataset(@PathParam("dataset") String dataset) {
List<MetricConfigDTO> metricConfigs = metricConfigDao.findByDataset(dataset);
return metricConfigs;
}
@POST
@Path("/create/payload")
public Long createMetricConfig(String payload) {
Long id = null;
try {
MetricConfigDTO metricConfig = OBJECT_MAPPER.readValue(payload, MetricConfigDTO.class);
id = metricConfigDao.save(metricConfig);
} catch (IOException e) {
LOG.error("Exception in creating dataset config with payload {}", payload);
}
return id;
}
@PUT
@Path("{id}/create-tag")
@ApiOperation("Endpoint for tagging a metric")
public Response createMetricTag(
@PathParam("id") Long id,
@NotNull @QueryParam("tag") String tag) throws Exception {
if (StringUtils.isBlank(tag)) {
throw new IllegalArgumentException(String.format("Received a null/empty tag: ", tag));
}
Map<String, String> responseMessage = new HashMap<>();
MetricConfigDTO metricConfigDTO = metricConfigDao.findById(id);
if (metricConfigDTO == null) {
responseMessage.put("message", "cannot find the metric " + id + ".");
return Response.status(Response.Status.BAD_REQUEST).entity(responseMessage).build();
}
Set<String> tags = new HashSet<String>(Arrays.asList(tag));
if (metricConfigDTO.getTags() == null) {
metricConfigDTO.setTags(tags);
} else {
metricConfigDTO.getTags().addAll(tags);
}
metricConfigDao.update(metricConfigDTO);
responseMessage.put("message", "successfully tagged metric" + id + " with tag " + tag);
return Response.ok(responseMessage).build();
}
@PUT
@Path("{id}/remove-tag")
@ApiOperation("Endpoint for removing a metric tag")
public Response removeMetricTag(
@PathParam("id") Long id,
@NotNull @QueryParam("tag") String tag) throws Exception {
if (StringUtils.isBlank(tag)) {
throw new IllegalArgumentException(String.format("Received a null/empty tag: ", tag));
}
Map<String, String> responseMessage = new HashMap<>();
MetricConfigDTO metricConfigDTO = metricConfigDao.findById(id);
if (metricConfigDTO == null) {
responseMessage.put("message", "cannot find the metric " + id + ".");
return Response.status(Response.Status.BAD_REQUEST).entity(responseMessage).build();
}
if (metricConfigDTO.getTags() != null) {
metricConfigDTO.getTags().removeAll(Collections.singleton(tag));
}
metricConfigDao.update(metricConfigDTO);
responseMessage.put("message", "successfully removed tag " + tag + " from metric" + id);
return Response.ok(responseMessage).build();
}
public Long createMetricConfig(MetricConfigDTO metricConfig) {
Long id = metricConfigDao.save(metricConfig);
return id;
}
public void updateMetricConfig(MetricConfigDTO metricConfig) {
metricConfigDao.update(metricConfig);
}
}
| {
"content_hash": "9de0eb15d06f605b4da60c0afbbb3f03",
"timestamp": "",
"source": "github",
"line_count": 280,
"max_line_length": 158,
"avg_line_length": 42.25,
"alnum_prop": 0.7377852916314455,
"repo_name": "apucher/pinot",
"id": "3a2d43cc7a7f16e70ee264cdb301b980a7bf79e8",
"size": "12467",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "thirdeye/thirdeye-pinot/src/main/java/com/linkedin/thirdeye/dashboard/resources/MetricConfigResource.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "4620"
},
{
"name": "Batchfile",
"bytes": "7738"
},
{
"name": "CSS",
"bytes": "925082"
},
{
"name": "FreeMarker",
"bytes": "243834"
},
{
"name": "HTML",
"bytes": "274305"
},
{
"name": "Java",
"bytes": "14420303"
},
{
"name": "JavaScript",
"bytes": "5189610"
},
{
"name": "Makefile",
"bytes": "8076"
},
{
"name": "Python",
"bytes": "36574"
},
{
"name": "Shell",
"bytes": "51677"
},
{
"name": "Thrift",
"bytes": "5028"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>The source code</title>
<link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="../resources/prettify/prettify.js"></script>
<style type="text/css">
.highlight { display: block; background-color: #ddd; }
</style>
<script type="text/javascript">
function highlight() {
document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
}
</script>
</head>
<body onload="prettyPrint(); highlight();">
<pre class="prettyprint lang-js"><span id='global-property-'>/**
</span> * @ignore
* droppable for kissy
* @author [email protected]
*/
KISSY.add('dd/droppable/base', function (S, Node, RichBase, DD) {
var DDM = DD.DDM,
PREFIX_CLS = DDM.PREFIX_CLS;
function validDrop(dropGroups, dragGroups) {
if (dragGroups === true) {
return 1;
}
for (var d in dropGroups) {
if (dragGroups[d]) {
return 1;
}
}
return 0;
}
<span id='KISSY-DD-Droppable'> /**
</span> * @class KISSY.DD.Droppable
* @extends KISSY.RichBase
* Make a node droppable.
*/
return RichBase.extend({
initializer: function () {
var self = this;
self.addTarget(DDM);
<span id='KISSY-DD-DDM-event-dropexit'> /**
</span> * fired after a draggable leaves a droppable
* @event dropexit
* @member KISSY.DD.DDM
* @param e
* @param e.drag current draggable object
* @param e.drop current droppable object
*/
<span id='KISSY-DD-Droppable-event-dropexit'> /**
</span> *
* fired after a draggable leaves a droppable
* @event dropexit
* @member KISSY.DD.Droppable
* @param e
* @param e.drag current draggable object
* @param e.drop current droppable object
*/
<span id='KISSY-DD-DDM-event-dropenter'> /**
</span> * fired after a draggable object mouseenter a droppable object
* @event dropenter
* @member KISSY.DD.DDM
* @param e
* @param e.drag current draggable object
* @param e.drop current droppable object
*/
<span id='KISSY-DD-Droppable-event-dropenter'> /**
</span> * fired after a draggable object mouseenter a droppable object
* @event dropenter
* @member KISSY.DD.Droppable
* @param e
* @param e.drag current draggable object
* @param e.drop current droppable object
*/
<span id='KISSY-DD-DDM-event-dropover'> /**
</span> *
* fired after a draggable object mouseover a droppable object
* @event dropover
* @member KISSY.DD.DDM
* @param e
* @param e.drag current draggable object
* @param e.drop current droppable object
*/
<span id='KISSY-DD-Droppable-event-dropover'> /**
</span> *
* fired after a draggable object mouseover a droppable object
* @event dropover
* @member KISSY.DD.Droppable
* @param e
* @param e.drag current draggable object
* @param e.drop current droppable object
*/
<span id='KISSY-DD-DDM-event-drophit'> /**
</span> *
* fired after drop a draggable onto a droppable object
* @event drophit
* @member KISSY.DD.DDM
* @param e
* @param e.drag current draggable object
* @param e.drop current droppable object
*/
<span id='KISSY-DD-Droppable-event-drophit'> /**
</span> *
* fired after drop a draggable onto a droppable object
* @event drophit
* @member KISSY.DD.Droppable
* @param e
* @param e.drag current draggable object
* @param e.drop current droppable object
*/
DDM._regDrop(this);
},
<span id='KISSY-DD-Droppable-method-getNodeFromTarget'> /**
</span> * Get drop node from target
* @protected
*/
getNodeFromTarget: function (ev, dragNode, proxyNode) {
var node = this.get('node'),
domNode = node[0];
// 排除当前拖放和代理节点
return domNode == dragNode ||
domNode == proxyNode
? null : node;
},
_active: function () {
var self = this,
drag = DDM.get('activeDrag'),
node = self.get('node'),
dropGroups = self.get('groups'),
dragGroups = drag.get('groups');
if (validDrop(dropGroups, dragGroups)) {
DDM._addValidDrop(self);
// 委托时取不到节点
if (node) {
node.addClass(PREFIX_CLS + 'drop-active-valid');
DDM.cacheWH(node);
}
} else if (node) {
node.addClass(PREFIX_CLS + 'drop-active-invalid');
}
},
_deActive: function () {
var node = this.get('node');
if (node) {
node.removeClass(PREFIX_CLS + 'drop-active-valid')
.removeClass(PREFIX_CLS + 'drop-active-invalid');
}
},
__getCustomEvt: function (ev) {
return S.mix({
drag: DDM.get('activeDrag'),
drop: this
}, ev);
},
_handleOut: function () {
var self = this,
ret = self.__getCustomEvt();
self.get('node').removeClass(PREFIX_CLS + 'drop-over');
// html5 => dragleave
self.fire('dropexit', ret);
},
_handleEnter: function (ev) {
var self = this,
e = self.__getCustomEvt(ev);
e.drag._handleEnter(e);
self.get('node').addClass(PREFIX_CLS + 'drop-over');
self.fire('dropenter', e);
},
_handleOver: function (ev) {
var self = this,
e = self.__getCustomEvt(ev);
e.drag._handleOver(e);
self.fire('dropover', e);
},
_end: function () {
var self = this,
ret = self.__getCustomEvt();
self.get('node').removeClass(PREFIX_CLS + 'drop-over');
self.fire('drophit', ret);
},
<span id='KISSY-DD-Droppable-method-destructor'> /**
</span> * make this droppable' element undroppable
* @private
*/
destructor: function () {
DDM._unRegDrop(this);
}
}, {
ATTRS: {
<span id='KISSY-DD-Droppable-cfg-node'> /**
</span> * droppable element
* @cfg {String|HTMLElement|KISSY.NodeList} node
* @member KISSY.DD.Droppable
*/
<span id='KISSY-DD-Droppable-property-node'> /**
</span> * droppable element
* @type {KISSY.NodeList}
* @property node
* @member KISSY.DD.Droppable
*/
<span id='global-property-node'> /**
</span> * @ignore
*/
node: {
setter: function (v) {
if (v) {
return Node.one(v);
}
}
},
<span id='KISSY-DD-Droppable-cfg-groups'> /**
</span> * groups this droppable object belongs to.
* @cfg {Object|Boolean} groups
* @member KISSY.DD.Droppable
*/
<span id='global-property-groups'> /**
</span> * @ignore
*/
groups: {
value: {
}
}
}
});
},
{ requires: ['node', 'rich-base', 'dd/base'] });</pre>
</body>
</html>
| {
"content_hash": "c1c92ede1fb409c65651b24b0d3b959b",
"timestamp": "",
"source": "github",
"line_count": 262,
"max_line_length": 86,
"avg_line_length": 34.82824427480916,
"alnum_prop": 0.4391232876712329,
"repo_name": "007slm/kissy",
"id": "7ffe0d27acd3b9848541b56fc1f45d3cf940983a",
"size": "9163",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/api/source/base6.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
/* $Id: lwdnoop.c,v 1.13 2008/01/22 23:28:04 tbox Exp $ */
/*! \file */
#include <config.h>
#include <isc/socket.h>
#include <isc/util.h>
#include <named/types.h>
#include <named/lwdclient.h>
void
ns_lwdclient_processnoop(ns_lwdclient_t *client, lwres_buffer_t *b) {
lwres_nooprequest_t *req;
lwres_noopresponse_t resp;
isc_result_t result;
lwres_result_t lwres;
isc_region_t r;
lwres_buffer_t lwb;
REQUIRE(NS_LWDCLIENT_ISRECVDONE(client));
INSIST(client->byaddr == NULL);
req = NULL;
result = lwres_nooprequest_parse(client->clientmgr->lwctx,
b, &client->pkt, &req);
if (result != LWRES_R_SUCCESS)
goto send_error;
client->pkt.recvlength = LWRES_RECVLENGTH;
client->pkt.authtype = 0; /* XXXMLG */
client->pkt.authlength = 0;
client->pkt.result = LWRES_R_SUCCESS;
resp.datalength = req->datalength;
resp.data = req->data;
lwres = lwres_noopresponse_render(client->clientmgr->lwctx, &resp,
&client->pkt, &lwb);
if (lwres != LWRES_R_SUCCESS)
goto cleanup_req;
r.base = lwb.base;
r.length = lwb.used;
client->sendbuf = r.base;
client->sendlength = r.length;
result = ns_lwdclient_sendreply(client, &r);
if (result != ISC_R_SUCCESS)
goto cleanup_lwb;
/*
* We can now destroy request.
*/
lwres_nooprequest_free(client->clientmgr->lwctx, &req);
NS_LWDCLIENT_SETSEND(client);
return;
cleanup_lwb:
lwres_context_freemem(client->clientmgr->lwctx, lwb.base, lwb.length);
cleanup_req:
lwres_nooprequest_free(client->clientmgr->lwctx, &req);
send_error:
ns_lwdclient_errorpktsend(client, LWRES_R_FAILURE);
}
| {
"content_hash": "8f7d41e32d93a60ce162ccb1e4bd0e22",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 71,
"avg_line_length": 21.86111111111111,
"alnum_prop": 0.6880559085133418,
"repo_name": "dplbsd/soc2013",
"id": "14d8e0c4cfbbc15f3f453f91a3cbcc5bd6f16e87",
"size": "2441",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "head/contrib/bind9/bin/named/lwdnoop.c",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "AGS Script",
"bytes": "62471"
},
{
"name": "Assembly",
"bytes": "4478661"
},
{
"name": "Awk",
"bytes": "278525"
},
{
"name": "Batchfile",
"bytes": "20417"
},
{
"name": "C",
"bytes": "383420305"
},
{
"name": "C++",
"bytes": "72796771"
},
{
"name": "CSS",
"bytes": "109748"
},
{
"name": "ChucK",
"bytes": "39"
},
{
"name": "D",
"bytes": "3784"
},
{
"name": "DIGITAL Command Language",
"bytes": "10640"
},
{
"name": "DTrace",
"bytes": "2311027"
},
{
"name": "Emacs Lisp",
"bytes": "65902"
},
{
"name": "EmberScript",
"bytes": "286"
},
{
"name": "Forth",
"bytes": "184405"
},
{
"name": "GAP",
"bytes": "72156"
},
{
"name": "Groff",
"bytes": "32248806"
},
{
"name": "HTML",
"bytes": "6749816"
},
{
"name": "IGOR Pro",
"bytes": "6301"
},
{
"name": "Java",
"bytes": "112547"
},
{
"name": "KRL",
"bytes": "4950"
},
{
"name": "Lex",
"bytes": "398817"
},
{
"name": "Limbo",
"bytes": "3583"
},
{
"name": "Logos",
"bytes": "187900"
},
{
"name": "Makefile",
"bytes": "3551839"
},
{
"name": "Mathematica",
"bytes": "9556"
},
{
"name": "Max",
"bytes": "4178"
},
{
"name": "Module Management System",
"bytes": "817"
},
{
"name": "NSIS",
"bytes": "3383"
},
{
"name": "Objective-C",
"bytes": "836351"
},
{
"name": "PHP",
"bytes": "6649"
},
{
"name": "Perl",
"bytes": "5530761"
},
{
"name": "Perl6",
"bytes": "41802"
},
{
"name": "PostScript",
"bytes": "140088"
},
{
"name": "Prolog",
"bytes": "29514"
},
{
"name": "Protocol Buffer",
"bytes": "61933"
},
{
"name": "Python",
"bytes": "299247"
},
{
"name": "R",
"bytes": "764"
},
{
"name": "Rebol",
"bytes": "738"
},
{
"name": "Ruby",
"bytes": "45958"
},
{
"name": "Scilab",
"bytes": "197"
},
{
"name": "Shell",
"bytes": "10501540"
},
{
"name": "SourcePawn",
"bytes": "463194"
},
{
"name": "SuperCollider",
"bytes": "80208"
},
{
"name": "Tcl",
"bytes": "80913"
},
{
"name": "TeX",
"bytes": "719821"
},
{
"name": "VimL",
"bytes": "22201"
},
{
"name": "XS",
"bytes": "25451"
},
{
"name": "XSLT",
"bytes": "31488"
},
{
"name": "Yacc",
"bytes": "1857830"
}
],
"symlink_target": ""
} |
// going to break the game into periods:1, 2, 3, 4, 5 etc. and that way all posts and all data will be the same for all players no matter when they start to play. This also solves Alessandra Casella's problem. There has to be a global clock that is gotten by an ajax call. The global clock gives periods: 1, 2, 3, plus how many seconds are left before the next period starts. Each bet and each datapoint is tagged with a period number (the current one). Each players interface pulls out the current bets and datapoints out of the mongodb database.
var putWindowDebug = false;
var callWindowDebug = false;
var betWindowDebug = false;
function getTime()
{
var d = new Date();
return d.getTime();
}
var previousUpdateTime = getTime();
function makeBetButton2(betView)
{
var betButton = makeButton("Offer Buy!", 70, 15);
var callback = {
'betView':betView,
'truth':truth,
"call": function()
{
//var theBet = this.bet.activeChoice;
//var points = this.points.activeChoice;
var betView = this.betView;
//var theBet = this.betView.pointsInp.getNumVal();
var theBet = "A";
var points = "" + this.betView.pointsInp.getNumVal();
var bayesVar = betView.bayesVar;
//alert(truth[truth.length-1].period);
if (bayesVar.possibilities.indexOf(theBet) >= 0 && points in range(101))
{
$.ajax({
type: "post",
url: '/ajax/newpost',
async: true,
data:JSON.stringify({"variable":bayesVar.varName.replace(/\s+/g, ''),
"username":user.name, "userid":user.id, "subject":theBet, 'price':points, 'open': 1, 'comments':[], 'period': truth[truth.length-1].period}),
dataType: "json",
contentType: "application/json",
success: function(user){alert(user.name)}
});
//betView.refresh(truth);
}
else {alert("you must first choose a value for your bet and you must decide how many points you want to bet!")}
}
};
makeClickable(betButton, callback);
return betButton;
}
function makePutButton(betView)
{
var putButton = makeButton("Offer Sale!", 70, 15);
var callback = {
'betView': betView,
'truth': truth,
"call": function() {
var betView = this.betView;
//var thePut = this.betView.pointsInp.getNumVal();
var thePut = "A";
var points = "" + this.betView.pointsInp.getNumVal();
//alert("this is the point:" + points)
var bayesVar = betView.bayesVar;
//alert(truth[truth.length-1].period);
if (bayesVar.possibilities.indexOf(thePut) >= 0 && points in range(101))
{
$.ajax({
type: "post",
url: '/ajax/newput',
async: true,
data:JSON.stringify({ "variable": bayesVar.varName.replace(/\s+/g, ''),
"username": user.name,
"userid": user.id,
"subject": thePut,
'price': points,
'open': 1,
'comments':[],
'period': getCurrTimePeriod()}),
dataType: "json",
contentType: "application/json",
success: function(user) {
alert(user.name);
}
});
//betView.refresh(truth);
}
else {
alert("you must first choose a value for your bet and you must decide how many points you want to bet!")
}
}
};
makeClickable(putButton, callback);
return putButton;
}
function makeContractedButton(inpWindow)
{
var height=25;
var width = inpWindow.width/2;
var contractedButton = Object.create(Widget);
contractedButton.height = height;
contractedButton.setShape(new createjs.Container());
contractedButton.background = makeRect(width, height, "#ffffff", 1, "#666", 3);
contractedButton.background.render(contractedButton.shape, {x:0, y:0});
contractedButton.text = makeTextWidget(inpWindow.text, 15, "Verdana", "#666");
contractedButton.text.render(contractedButton.shape, {x:(width-contractedButton.text.width)/2, y:(height-contractedButton.text.height)/2});
contractedButton.frameWindow = inpWindow;
var callback = {
"button": contractedButton,
"window": inpWindow,
"call": function() {
var frameWindow = this.button.frameWindow;
frameWindow.render(topLayer.shape, {x:frameWindow.xPos, y:frameWindow.yPos});
this.button.erase();
}
};
makeClickable(contractedButton, callback)
return contractedButton;
}
function makeBarButton(inpWindow)
{
var height = 25;
var width = inpWindow.width + inpWindow.borderWidth*2;
var barButton = Object.create(Button);
barButton.setShape(new createjs.Container());
barButton.background = makeRect(width, height, /*"#3B4DD0"*/ "#3b5998", 0, 1, 3);
barButton.background.render(barButton.shape, {x:0, y:0});
barButton.text=makeTextWidget(inpWindow.text, 15,"Verdana", "#ffffff");
barButton.text.render(barButton.shape, {x:(width-barButton.text.width)/2, y:(height-barButton.text.height)/2});
barButton.shape.on("click", function (evt)
{
var button = makeContractedButton(inpWindow)
//dataWindow=makeDataWindow(truth, ['A', 'B', 'C'], variables);
button.render(stage, {x:inpWindow.xPos, y:stageHeight-25});
inpWindow.erase()
});
return barButton;
}
function makeDataWindow(data, domain, variables, xPos)
{
variables.map(function(variable){variable.enabled=true});
var borderWidth = 0.3;
var names=[];
var enabled={};
variables.map(function(variable){names.push(variable.varName.toLowerCase().replace(" ", "_"))});
names.map(function(name){enabled[name]=true});
var colors={}
variables.map(function(variable){
colors[variable.varName.toLowerCase().replace(" ", "_")] = variable.color;
});
var view = Object.create(View);
view.enabled=enabled;
view.height = stageHeight-80;
view.width=(domain.length + 1)*50;
view.frameHeight = (data.length + 1)*40;
view.borderWidth=borderWidth;
view.xPos = xPos;
view.yPos = stageHeight - view.height;
view.text="DATA";
view.setShape(new createjs.Container());
view.barButton=makeBarButton(view);
view.background = makeRect(view.width, view.height, '#EBEEF4'/*"#f0f0f0"*/, borderWidth, 1, 3);
view.background.render(view.shape, {x:0, y:0});
view.barButton.render(view.shape, {x:-borderWidth, y:-22});
xCoord = 20;
coords = {};
domain.map(function(element)
{
makeTextWidget(element, 30, 'Arial', '#666').renderW(view, {x:xCoord, y:10});
coords[element] = xCoord;
xCoord += view.width/(domain.length);
})
view.data = data;
view.drawInnerFrame = function()
{
view.innerFrame = WidgetHL();
yCoord = 40;
view.data.map(function(dat)
{
names.map(function(key)
{
value = dat[key];
col = colors[key];
//alert(JSON.stringify({'col':col, 'x':xCoord, 'y':yCoord}));
if (value!==undefined)
{
makeCircle(8, col).renderW(view.innerFrame, {x: coords[value], y: yCoord})
}
})
dat.yCoord = yCoord;
yCoord += 40;
})
for (var i = 1; i < view.data.length; i++)
{
var dataLine = new createjs.Shape();
var graphics = dataLine.graphics.setStrokeStyle(2);
names.map(function(key) {
value0 = view.data[i-1][key];
value1 = view.data[i][key]
col = colors[key];
graphics.beginStroke(col).moveTo(coords[value0] + 8,
view.data[i-1].yCoord + 8).lineTo(coords[value1] + 8,
view.data[i].yCoord + 8);
graphics.endStroke();
view.innerFrame.shape.addChild(dataLine);
//alert(JSON.stringify({'col':col, 'x':xCoord, 'y':yCoord}));
//makeCircle(8, col).renderW(view,{x:coords[value], y:yCoord})
});
}
}
view.drawInnerFrame();
var num;
var count;
var countDown = WidgetHL();
$.ajax(
{
type: "GET",
url: '/ajax/clock',
async: true,
dataType: "json",
success: function(data)
{
//do your stuff with the JSON data;
num = data[0] + 1;
//count = data[1]
countDown.text = makeTextWidget("New data in "+ num + " minutes", 12, "Arial", "#666");
countDown.background = makeRect(countDown.text.width+10, 20, '#EBEEF4');
countDown.background.renderW(countDown, Point(0, 0));
countDown.text.renderW(countDown, Point(5, 5));
countDown.renderW(view, Point((view.width - countDown.text.width)/2, /*view.height-40*/stageHeight-110));
}
});
updateCount = function()
{
$.ajax({
type: "GET",
url: '/ajax/clock',
dataType: "json",
async: false, //options.sync,
success: function(data) {
count = data[1]// todo
if (count===0) {
num-=1;
}
if (num===1) {
if (count!==0) {
countDown.text.changeText("New data in "+count+" seconds")
}
} else if (num==0) {
renewData()
num=2;
} else {
countDown.text.changeText("New data in "+num+" minutes")
}
}
});
}
renewData = function()
{
//we don't need to produce any new data directed from the client side; the server takes care of that. We just need to request the newest data.
$.ajax({
type: "GET",
url: '/ajax/newData',
async: true,
dataType: "json",
success: function(data)
{
var newTruth1 = data[0];
var newTruth2 = data[1];
newTruth1.yCoord = truth[truth.length-1].yCoord;
newTruth2.yCoord = truth[truth.length-1].yCoord + 40;
truth = truth.slice(0, truth.length-1).concat([newTruth1, newTruth2]);
//alert(JSON.stringify(truth[truth.length-2]['prize_door']));
view.data = view.data.slice(0, view.data.length-1).concat(data);
//alert(JSON.stringify(view.data.slice(view.data.length-2,view.data.length)));
view.frame.erase();
view.frameHeight += 40;
view.drawInnerFrame();
view.frame = makeFrameWidget(
view.width, view.height-80,
view.innerFrame, view.frameHeight);
view.frame.render(view.shape, {x:0, y:45});
countDown.renderW(view, Point((view.width-countDown.text.width)/2-20, stageHeight-110));
var totalWinnings=0;
if (truth[truth.length-2]['prize_door']===share_door)
{
user.points += user.shares*100;
//pointWindow.points.changeText(user.points +" points");
totalWinnings = user.shares*100;
}
else
{
//pointWindow.points.changeText(user.points +" points");
totalWinnings = 0;
}
if (truth[truth.length-1]['monty_door']==='A')
{
share_door='B';
}
else
{
share_door='A';
}
var winningsWindow = WidgetHL();
winningsWindow.background = makeRect(400, 200, '#EBEEF4'/*"#f0f0f0"*/, 0.5, 1, 3);
winningsWindow.background.render(winningsWindow.shape, Point(0, 0));
winningsWindow.bar = makeRect(401, 25, "#3b5998", 0, 1, 3);
winningsWindow.bar.render(winningsWindow.shape, Point(0, -25.5));
winningsWindow.killButton=makeDeleteCross(10, 10, "#8b9dc3", 2);
winningsWindow.killButton.render(winningsWindow.shape, Point(385, -18));
winningsWindow.killButton.shape.on('click', function(){winningsWindow.erase()});
winningsWindow.killButton.shape.on("mouseover", function(evt)
{
winningsWindow.killButton.changeColor("#ffffff");
})
winningsWindow.killButton.shape.on("mouseout", function(evt)
{
winningsWindow.killButton.changeColor('#8b9dc3'/*"#f0f0f0"*/);
});
var message=user.first_name + ", ";
var message2="";
if (totalWinnings > 0) {
message2 += "won " + totalWinnings + " points."
}
else{
message2 += "lost " + Math.abs(totalWinnings) + " points."
}
winningsWindow.message1 = makeTextWidget(message, 16, "Arial", "#666");
winningsWindow.message2 = makeTextWidget(message2, 16, "Arial", "#666");
winningsWindow.message1.renderW(winningsWindow, Point(10, 10));
winningsWindow.message2.renderW(winningsWindow, Point(10, 40));
//winningsWindow.render(topLayer.shape, Point(stageWidth/2-200, stageHeight/2-100));
}
});
}
var resInterval = window.setInterval('updateCount()', 1000); // 1 second
//count=updateCount(count);
view.drawInnerFrame();
view.frame = makeFrameWidget(
view.width, view.height-80,
view.innerFrame, view.frameHeight);
view.frame.render(view.shape, {x:0, y:45});
return view;
}
alertStatus = 0
function getCurrTimePeriod()
{
// the variable "truth" is just the data that the server returns
return truth[truth.length-1].period;
}
function removeSpaces(inpStr)
{
return inpStr.replace(/\s+/g, '');
}
function makePutWindow(bets, domain, betVariable, xPos)
{
return makeBetWindow2(bets, domain, betVariable, xPos, true);
}
function makeCallWindow(bets, domain, betVariable, xPos, isPut)
{
return makeBetWindow2(bets, domain, betVariable, xPos, false);
}
function makeBetWindow2(bets, domain, betVariable, xPos, isPut)
{
//the variable "betVariable" is the variable on which bets are placed.
var betWidth = 100;
var betHeight = 40
var betSpacing = 10;
var distBetweenYs = betHeight + betSpacing;
var borderWidth = 0.3;
//var view = Object.create(Widget);
var view = WidgetHL();
view.width = 240;
//alert(bets.length);
//view.height = Math.max(distBetweenYs*bets.length + 20, 170);//it would be great to make this adoptable!
view.height = 170;
view.frameHeight=190;
//view.background.render(view.shape, {x:0, y:0});
view.borderWidth = borderWidth;
view.xPos = xPos; //this is the x position of the entire view, along the stage.
if (isPut) {
view.text = "FOR SALE";
} else {
view.text = "SEEKING TO BUY";
}
view.barButton = makeBarButton(view);
view.bayesVar = betVariable;
view.background = makeRect(view.width, view.height, '#EBEEF4'/*"#f0f0f0"*/, borderWidth, 1, 3);
view.background.renderW(view, {x:0, y:0});
view.yPos = stageHeight - view.height - 25;
//var frame=makeBettingFrame(betVariable, view);
view.bets = bets;
view.data = {"myputs": [], "myposts": []};
view.drawFrame = function()
{
var view = this;
var frame = WidgetHL();
frame.postItems = [];
view.bets.map(function(bet)
{
var postItem = WidgetHL();
postItem.bet = bet;
bet.postItem = postItem;
postItem.value = makeTextWidget(bet.title, 16, "Arial", "#666");
postItem.betEdge = makeRect(40, betHeight-20, "#A9D0F5", 1, "#A9D0F5", 50);
postItem.betEdge.renderW(postItem, {x: 40, y: 20});
postItem.betBackground = makeRect(view.width,betHeight-20,"#A9D0F5", 1, "#A9D0F5");
postItem.betBackground.renderW(postItem, {x:50, y:20});
postItem.value.renderW(postItem, {x:45, y:22});
if (bet.userid)
{
bet.pic = new createjs.Bitmap(THIS_DOMAIN + "/ajax/picture/" + bet.userid + "/12/12");
bet.pic.x = 0;
bet.pic.y = 20;
bet.pic.scaleX *= 0.18;
bet.pic.scaleY *= 0.18;
postItem.shape.addChild(bet.pic);
}
postItem.points = makeTextWidget(bet.price, 16, "Arial", "#666");
postItem.pointsBackground=makeRect(30,betHeight-20,"#ffffff", 1, "#A9D0F5", 50);
postItem.pointsBackground.renderW(postItem, {x:view.width-45, y:20});
postItem.points.renderW(postItem, {x:view.width-40, y:22});
postItem.author = makeTextWidget(postItem.bet.author, 12, "Arial", "#666");
postItem.author.renderW(postItem, {x:65, y:23});
postItem.view = view;
postItem.hasAccept = false;
if (postItem.bet.userid !== user.id)
{
postItem.hasAccept = true;
postItem.acceptButton = WidgetHL();
var acceptButton = postItem.acceptButton;
acceptButton.background = makeRect(60, 20, "#3B5998");
acceptButton.background.renderW(acceptButton, {x: 0, y: 0});
if (postItem.view.isPut) {
var acceptText = "BUY";
} else {
var acceptText = "SELL";
}
acceptButton.text = makeTextWidget(acceptText, 10, "Arial", "white");
acceptButton.text.renderW(acceptButton, {x: 10, y:5});
acceptButton.renderW(postItem, {x:150, y: 45})
var acceptButtonCallBack = {
"acceptButton": acceptButton,
"postItem": postItem,
"call": function() {
var acceptOperation;
if (this.postItem.view.isPut) {
acceptOperation = 'accept_put';
} else {
acceptOperation = 'accept_call';
}
$.ajax({
type: "post",
url: '/ajax/' + acceptOperation + '/' + this.postItem.bet.id+"/"+ user.id+'/'+ this.postItem.bet.userid,
async: true,
data: JSON.stringify({"points": this.postItem.bet.price}),
dataType: "json",
contentType: "application/json",
success: function(){}
});
}
};
makeClickable3(acceptButton, acceptButtonCallBack, "orange", "red");
}
frame.postItems.push(postItem);
////postItem.yCoord=yCoord;
////postItem.renderW(frame, {x:10, y:view.height-postItem.yCoord});
////yCoord += distBetweenYs;
});
if (betWindowDebug) {
alert("frame.postItems.length: " + frame.postItems.length);
}
////frame.postItems[i]
////for (var i=0;i<
yCoord = 70;
view.frameHeight = Math.max(distBetweenYs*frame.postItems.length+20, 190);//it would be great to make this adoptable!
for (var i=0;i<frame.postItems.length;i++)
{
frame.postItems[i].yCoord = yCoord;
frame.postItems[i].renderW(frame, {x:10, y: view.frameHeight-frame.postItems[i].yCoord});
yCoord += distBetweenYs;
}
view.frame = makeFrameWidget(
view.width, 160,
frame, view.frameHeight);
view.frame.render(view.shape, {x:0, y:3});
}
view.drawFrame();
view.isPut = isPut;
view.previousUpdateTime = getTime();
function refreshBets(event, data)
{
var view = data.view;
var currentTime = getTime();
if (currentTime-view.previousUpdateTime > 400)
{
view.previousUpdateTime = currentTime;
var getBetsUrl;
if (view.isPut) {
getBetsUrl = '/ajax/puts/'+ removeSpaces(view.bayesVar.varName) + '/' + getCurrTimePeriod();
view.dataReturnKey = "myputs";
} else {
getBetsUrl = '/ajax/' + removeSpaces(view.bayesVar.varName) + '/' + getCurrTimePeriod();
view.dataReturnKey = "myposts";
}
//alert("sending update request to " + getBetsUrl);
$.ajax(
{
type: "GET",
url: getBetsUrl,
async: true,
dataType: "json",
success: function(data)
{
//console.log(data);
//do your stuff with the JSON data;
if (view.data[view.dataReturnKey].length !== data[view.dataReturnKey].length)
{
if ((putWindowDebug && view.isPut) || (callWindowDebug && !view.isPut))
{
var typeOfBet;
if (view.isPut) {
typeOfBet = "PUTS";
} else {
typeOfBet = "CALLS";
}
alert("NUMBER OF " + typeOfBet + " HAS CHANGED");
alert("view.data." + view.dataReturnKey + ".length: " + view.data[view.dataReturnKey].length);
alert("data." + view.dataReturnKey + ".length: " + data[view.dataReturnKey].length);
}
view.frame.erase();
view.bets = data[view.dataReturnKey];
view.drawFrame();
view.data = data;
}
}
});
}
}
var count=0;
previousTimeT2 = getTime();
createjs.Ticker.on("tick", refreshBets, null, false, {view: view});
view.betBack = makeRect(view.width, 27, "#ffffff", borderWidth, 1, 0);
view.betBack.render(view.shape, {x:0, y:162});
view.inputLabel = makeTextWidget("Points:", 12, "Arial", "#666");
view.inputLabel.render(view.shape, {x:70, y:170});
//view.pointMenu = makeScrollMenu(["10", "20", "30", "40", "50", "60", "70", "80", "90"], 40, 15, "white","0", 12);
//view.bettingMenu = makeScrollMenu(["A", "B", "C"], 40, 15, "white","Value", 12);
//view.pointMenu.render(view.shape, {x:120, y:170})
//view.bettingMenu.render(view.shape, {x:35, y:170});
view.pointsInp = makeTextBox(20);
view.pointsInp.renderW(view, Point(110, 165));
view.barButton.render(view.shape, {x:-borderWidth, y:-22});
if (view.isPut) {
view.betButton = makePutButton(view);
} else {
view.betButton = makeBetButton2(view);
}
view.betButton.render(view.shape, {x:view.width-75, y:170});
return view;
}
function showTestDataWindow()
{
dataWindow = makeDataWindow(truth, ['A', 'B', 'C'], variables[2]);
dataWindow.render(stage, {x:600, y:stageHeight-290});
}
| {
"content_hash": "921cb41f2a07c1cad5bb25898fd9f40b",
"timestamp": "",
"source": "github",
"line_count": 646,
"max_line_length": 548,
"avg_line_length": 37.9953560371517,
"alnum_prop": 0.519942961906702,
"repo_name": "jac2130/BayesGame",
"id": "4e9fd388f1f57e51d128a5b0ac3d8f30f277f661",
"size": "24545",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "clientScriptsNew/data.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "95"
},
{
"name": "C#",
"bytes": "1110"
},
{
"name": "CSS",
"bytes": "2118"
},
{
"name": "HTML",
"bytes": "166635"
},
{
"name": "JavaScript",
"bytes": "751618"
},
{
"name": "PHP",
"bytes": "339"
},
{
"name": "Perl",
"bytes": "3136"
},
{
"name": "Python",
"bytes": "1821680"
},
{
"name": "Shell",
"bytes": "1630"
},
{
"name": "Smarty",
"bytes": "7840"
}
],
"symlink_target": ""
} |
package net.drewke.tdme.gui.elements;
import net.drewke.tdme.gui.events.GUIKeyboardEvent;
import net.drewke.tdme.gui.events.GUIMouseEvent;
import net.drewke.tdme.gui.events.GUIMouseEvent.Type;
import net.drewke.tdme.gui.nodes.GUIColor;
import net.drewke.tdme.gui.nodes.GUIElementNode;
import net.drewke.tdme.gui.nodes.GUINode;
import net.drewke.tdme.gui.nodes.GUINodeConditions;
import net.drewke.tdme.gui.nodes.GUINodeController;
import net.drewke.tdme.gui.nodes.GUIParentNode;
import net.drewke.tdme.utils.MutableString;
/**
* GUI tab controller
* @author Andreas Drewke
* @version $Id$
*/
public final class GUITabController extends GUINodeController {
private static final String CONDITION_DISABLED = "disabled";
private static final String CONDITION_ENABLED = "enabled";
private static final String CONDITION_SELECTED = "selected";
private static final String CONDITION_UNSELECTED = "unselected";
private GUINode tabsNode;
private GUINode tabsHeaderNode;
private boolean selected;
private GUIColor unfocussedNodeBorderLeftColor;
private GUIColor unfocussedNodeBorderRightColor;
private GUIColor unfocussedNodeBorderTopColor;
private GUIColor unfocussedNodeBorderBottomColor;
private boolean disabled;
/**
* GUI Checkbox controller
* @param node
*/
protected GUITabController(GUINode node) {
super(node);
this.tabsNode = null;
this.tabsHeaderNode = null;
this.selected = false;
this.unfocussedNodeBorderLeftColor = null;
this.unfocussedNodeBorderRightColor = null;
this.unfocussedNodeBorderTopColor = null;
this.unfocussedNodeBorderBottomColor = null;
this.disabled = ((GUIElementNode)node).isDisabled();
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.nodes.GUINodeController#isDisabled()
*/
public boolean isDisabled() {
return disabled;
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.nodes.GUINodeController#setDisabled(boolean)
*/
public void setDisabled(boolean disabled) {
GUINodeConditions nodeConditions = ((GUIElementNode)node).getActiveConditions();
nodeConditions.remove(this.disabled == true?CONDITION_DISABLED:CONDITION_ENABLED);
this.disabled = disabled;
nodeConditions.add(this.disabled == true?CONDITION_DISABLED:CONDITION_ENABLED);
}
/**
* @return is checked
*/
protected boolean isSelected() {
return selected;
}
/**
* Set checked
* @param selected
*/
protected void setSelected(boolean selected) {
// remove old selection condition, add new selection condition
GUINodeConditions nodeConditions = ((GUIElementNode)this.node).getActiveConditions();
nodeConditions.remove(this.selected == true?CONDITION_SELECTED:CONDITION_UNSELECTED);
this.selected = selected;
nodeConditions.add(this.selected == true?CONDITION_SELECTED:CONDITION_UNSELECTED);
// handle focus, alter border depending on tabs header node focus and selection state
if (((GUITabsHeaderController)tabsHeaderNode.getController()).hasFocus() == true) {
if (selected == true) {
GUIColor focussedBorderColor = node.getScreenNode().getGUI().getFoccussedBorderColor();
GUINode.Border border = node.getBorder();
border.topColor = focussedBorderColor;
border.leftColor = focussedBorderColor;
border.bottomColor = focussedBorderColor;
border.rightColor = focussedBorderColor;
} else {
GUINode.Border border = node.getBorder();
border.topColor = unfocussedNodeBorderTopColor;
border.leftColor = unfocussedNodeBorderLeftColor;
border.bottomColor = unfocussedNodeBorderBottomColor;
border.rightColor = unfocussedNodeBorderRightColor;
}
} else {
GUINode.Border border = node.getBorder();
border.topColor = unfocussedNodeBorderTopColor;
border.leftColor = unfocussedNodeBorderLeftColor;
border.bottomColor = unfocussedNodeBorderBottomColor;
border.rightColor = unfocussedNodeBorderRightColor;
}
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.GUINodeController#initialize()
*/
public void initialize() {
// get "tabs" node
tabsNode = ((GUIParentNode)node).getParentControllerNode().getParentControllerNode();
// get "tabs header" node
tabsHeaderNode = ((GUIParentNode)node).getParentControllerNode();
// store original border
GUINode.Border border = node.getBorder();
unfocussedNodeBorderTopColor = border.topColor;
unfocussedNodeBorderLeftColor = border.leftColor;
unfocussedNodeBorderBottomColor = border.bottomColor;
unfocussedNodeBorderRightColor = border.rightColor;
// set initial state
setSelected(selected);
setDisabled(disabled);
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.GUINodeController#dispose()
*/
public void dispose() {
// no op
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.nodes.GUINodeController#postLayout()
*/
public void postLayout() {
// no op
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.nodes.GUINodeController#handleMouseEvent(net.drewke.tdme.gui.nodes.GUINode, net.drewke.tdme.gui.events.GUIMouseEvent)
*/
public void handleMouseEvent(GUINode node, GUIMouseEvent event) {
// check if our node was clicked
if (disabled == false &&
node == this.node &&
node.isEventBelongingToNode(event) &&
event.getButton() == 1) {
// set event processed
event.setProcessed(true);
// check if mouse released
if (event.getType() == Type.MOUSE_RELEASED) {
GUITabsController guiTabsController = (GUITabsController)tabsNode.getController();
// unselect all tabs
guiTabsController.unselect();
// select current
setSelected(selected == true?false:true);
// select tab content
guiTabsController.setTabContentSelected(node.getId());
}
}
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.nodes.GUINodeController#handleKeyboardEvent(net.drewke.tdme.gui.nodes.GUINode, net.drewke.tdme.gui.events.GUIKeyboardEvent)
*/
public void handleKeyboardEvent(GUINode node, GUIKeyboardEvent event) {
// no op for now
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.nodes.GUINodeController#tick()
*/
public void tick() {
// no op
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.nodes.GUINodeController#onFocusGained()
*/
public void onFocusGained() {
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.nodes.GUINodeController#onFocusLost()
*/
public void onFocusLost() {
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.nodes.GUINodeController#hasValue()
*/
public boolean hasValue() {
return false;
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.nodes.GUINodeController#getValue()
*/
public MutableString getValue() {
return null;
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.nodes.GUINodeController#setValue(net.drewke.tdme.utils.MutableString)
*/
public void setValue(MutableString value) {
// no op
}
/**
* Select this tab
*/
public void selectTab() {
GUITabsController guiTabsController = (GUITabsController)tabsNode.getController();
// unselect all tabs
guiTabsController.unselect();
// select current
setSelected(true);
// select tab content
guiTabsController.setTabContentSelected(node.getId());
//
node.getScreenNode().getGUI().invalidateFocussedNode();
}
}
| {
"content_hash": "3469e766d990094436db8ca08cdf9c50",
"timestamp": "",
"source": "github",
"line_count": 257,
"max_line_length": 152,
"avg_line_length": 27.92217898832685,
"alnum_prop": 0.7364827201783724,
"repo_name": "andreasdr/tdme",
"id": "3b452cc598bb0ba1b35cf2022bc547db06f5f994",
"size": "7176",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/net/drewke/tdme/gui/elements/GUITabController.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "41107"
},
{
"name": "HTML",
"bytes": "9159"
},
{
"name": "Java",
"bytes": "2029963"
}
],
"symlink_target": ""
} |
<!doctype html>
<html class="default no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>DestinyItemStateRequest | The Traveler</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../assets/css/main.css">
</head>
<body>
<header>
<div class="tsd-page-toolbar">
<div class="container">
<div class="table-wrap">
<div class="table-cell" id="tsd-search" data-index="../assets/js/search.js" data-base="..">
<div class="field">
<label for="tsd-search-field" class="tsd-widget search no-caption">Search</label>
<input id="tsd-search-field" type="text" />
</div>
<ul class="results">
<li class="state loading">Preparing search index...</li>
<li class="state failure">The search index is not available</li>
</ul>
<a href="../index.html" class="title">The Traveler</a>
</div>
<div class="table-cell" id="tsd-widgets">
<div id="tsd-filter">
<a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a>
<div class="tsd-filter-group">
<div class="tsd-select" id="tsd-filter-visibility">
<span class="tsd-select-label">All</span>
<ul class="tsd-select-list">
<li data-value="public">Public</li>
<li data-value="protected">Public/Protected</li>
<li data-value="private" class="selected">All</li>
</ul>
</div>
<input type="checkbox" id="tsd-filter-inherited" checked />
<label class="tsd-widget" for="tsd-filter-inherited">Inherited</label>
<input type="checkbox" id="tsd-filter-externals" checked />
<label class="tsd-widget" for="tsd-filter-externals">Externals</label>
<input type="checkbox" id="tsd-filter-only-exported" />
<label class="tsd-widget" for="tsd-filter-only-exported">Only exported</label>
</div>
</div>
<a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a>
</div>
</div>
</div>
</div>
<div class="tsd-page-title">
<div class="container">
<ul class="tsd-breadcrumb">
<li>
<a href="../globals.html">Globals</a>
</li>
<li>
<a href="destinyitemstaterequest.html">DestinyItemStateRequest</a>
</li>
</ul>
<h1>Interface DestinyItemStateRequest</h1>
</div>
</div>
</header>
<div class="container container-main">
<div class="row">
<div class="col-8 col-content">
<section class="tsd-panel tsd-hierarchy">
<h3>Hierarchy</h3>
<ul class="tsd-hierarchy">
<li>
<span class="target">DestinyItemStateRequest</span>
</li>
</ul>
</section>
<section class="tsd-panel-group tsd-index-group">
<h2>Index</h2>
<section class="tsd-panel tsd-index-panel">
<div class="tsd-index-content">
<section class="tsd-index-section tsd-is-external">
<h3>Properties</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-property tsd-parent-kind-interface tsd-is-external"><a href="destinyitemstaterequest.html#characterid" class="tsd-kind-icon">character<wbr>Id</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface tsd-is-external"><a href="destinyitemstaterequest.html#itemid" class="tsd-kind-icon">item<wbr>Id</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface tsd-is-external"><a href="destinyitemstaterequest.html#membershiptype" class="tsd-kind-icon">membership<wbr>Type</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface tsd-is-external"><a href="destinyitemstaterequest.html#state" class="tsd-kind-icon">state</a></li>
</ul>
</section>
</div>
</section>
</section>
<section class="tsd-panel-group tsd-member-group tsd-is-external">
<h2>Properties</h2>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a name="characterid" class="tsd-anchor"></a>
<h3>character<wbr>Id</h3>
<div class="tsd-signature tsd-kind-icon">character<wbr>Id<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">string</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/alexanderwe/the-traveler/blob/bfd7db0/src/type-definitions/destiny2/interfaces.ts#L7065">type-definitions/destiny2/interfaces.ts:7065</a></li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a name="itemid" class="tsd-anchor"></a>
<h3>item<wbr>Id</h3>
<div class="tsd-signature tsd-kind-icon">item<wbr>Id<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">string</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/alexanderwe/the-traveler/blob/bfd7db0/src/type-definitions/destiny2/interfaces.ts#L7064">type-definitions/destiny2/interfaces.ts:7064</a></li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a name="membershiptype" class="tsd-anchor"></a>
<h3>membership<wbr>Type</h3>
<div class="tsd-signature tsd-kind-icon">membership<wbr>Type<span class="tsd-signature-symbol">:</span> <a href="../enums/bungiemembershiptype.html" class="tsd-signature-type">BungieMembershipType</a></div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/alexanderwe/the-traveler/blob/bfd7db0/src/type-definitions/destiny2/interfaces.ts#L7066">type-definitions/destiny2/interfaces.ts:7066</a></li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a name="state" class="tsd-anchor"></a>
<h3>state</h3>
<div class="tsd-signature tsd-kind-icon">state<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">boolean</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/alexanderwe/the-traveler/blob/bfd7db0/src/type-definitions/destiny2/interfaces.ts#L7063">type-definitions/destiny2/interfaces.ts:7063</a></li>
</ul>
</aside>
</section>
</section>
</div>
<div class="col-4 col-menu menu-sticky-wrap menu-highlight">
<nav class="tsd-navigation primary">
<ul>
<li class="globals ">
<a href="../globals.html"><em>Globals</em></a>
</li>
</ul>
</nav>
<nav class="tsd-navigation secondary menu-sticky">
<ul class="before-current">
</ul>
<ul class="current">
<li class="current tsd-kind-interface tsd-is-external">
<a href="destinyitemstaterequest.html" class="tsd-kind-icon">Destiny<wbr>Item<wbr>State<wbr>Request</a>
<ul>
<li class=" tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a href="destinyitemstaterequest.html#characterid" class="tsd-kind-icon">character<wbr>Id</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a href="destinyitemstaterequest.html#itemid" class="tsd-kind-icon">item<wbr>Id</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a href="destinyitemstaterequest.html#membershiptype" class="tsd-kind-icon">membership<wbr>Type</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a href="destinyitemstaterequest.html#state" class="tsd-kind-icon">state</a>
</li>
</ul>
</li>
</ul>
<ul class="after-current">
</ul>
</nav>
</div>
</div>
</div>
<footer>
<div class="container">
<h2>Legend</h2>
<div class="tsd-legend-group">
<ul class="tsd-legend">
<li class="tsd-kind-module"><span class="tsd-kind-icon">Module</span></li>
<li class="tsd-kind-object-literal"><span class="tsd-kind-icon">Object literal</span></li>
<li class="tsd-kind-variable"><span class="tsd-kind-icon">Variable</span></li>
<li class="tsd-kind-function"><span class="tsd-kind-icon">Function</span></li>
<li class="tsd-kind-function tsd-has-type-parameter"><span class="tsd-kind-icon">Function with type parameter</span></li>
<li class="tsd-kind-index-signature"><span class="tsd-kind-icon">Index signature</span></li>
<li class="tsd-kind-type-alias"><span class="tsd-kind-icon">Type alias</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-enum"><span class="tsd-kind-icon">Enumeration</span></li>
<li class="tsd-kind-enum-member"><span class="tsd-kind-icon">Enumeration member</span></li>
<li class="tsd-kind-property tsd-parent-kind-enum"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-enum"><span class="tsd-kind-icon">Method</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li>
<li class="tsd-kind-interface tsd-has-type-parameter"><span class="tsd-kind-icon">Interface with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-interface"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-interface"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-class"><span class="tsd-kind-icon">Class</span></li>
<li class="tsd-kind-class tsd-has-type-parameter"><span class="tsd-kind-icon">Class with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-class"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class"><span class="tsd-kind-icon">Accessor</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-constructor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static property</span></li>
<li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static method</span></li>
</ul>
</div>
</div>
</footer>
<div class="overlay"></div>
<script src="../assets/js/main.js"></script>
<script>if (location.protocol == 'file:') document.write('<script src="../assets/js/search.js"><' + '/script>');</script>
</body>
</html> | {
"content_hash": "887850a50c1d6d890af7d0f229bc3763",
"timestamp": "",
"source": "github",
"line_count": 236,
"max_line_length": 211,
"avg_line_length": 52.42796610169491,
"alnum_prop": 0.66806756647539,
"repo_name": "alexanderwe/the-traveler",
"id": "7ae944fab6094d6693aea1bad5a888e8dcc0fbf7",
"size": "12373",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/interfaces/destinyitemstaterequest.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "298"
},
{
"name": "TypeScript",
"bytes": "690965"
}
],
"symlink_target": ""
} |
//
// GPKGFeatureOverlayQueryUtils.h
// geopackage-iosTests
//
// Created by Brian Osborn on 5/3/22.
// Copyright © 2022 NGA. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "GPKGGeoPackage.h"
/**
* Feature overlay query utils
*/
@interface GPKGFeatureOverlayQueryUtils : NSObject
/**
* Test Build Map Click Table Data
*
* @param geoPackage
*/
+(void) testBuildMapClickTableData: (GPKGGeoPackage *) geoPackage;
@end
| {
"content_hash": "27b487a0448547a56d3b73e0bfda4e90",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 66,
"avg_line_length": 18.666666666666668,
"alnum_prop": 0.7165178571428571,
"repo_name": "ngageoint/geopackage-ios",
"id": "4a3490ef988c5fc5e7d6361025faf17dfd4b02c6",
"size": "449",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "geopackage-iosTests/tiles/overlay/GPKGFeatureOverlayQueryUtils.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "6395019"
},
{
"name": "Ruby",
"bytes": "1469"
},
{
"name": "Swift",
"bytes": "8139"
}
],
"symlink_target": ""
} |
import json
import nltk.sentiment.util
import os
import random
from _operator import itemgetter
from datetime import timedelta
from nltk.sentiment import SentimentIntensityAnalyzer
from Clustering.clustering import find_tweets_with_keywords_idf
from config.config import PROJECT_DIR, PCLOUD_DIR
from inputoutput.cli import query_yes_no
from inputoutput.getters import get_articles, update_tweets_cache, get_articles_by_date
# output
article_clusters = {} # article_id -> tweet_id
article_clusters_filepath = os.path.join(PROJECT_DIR, 'article_clusters_PD_after_2016_11_07.json')
# the idf baseline to use
idf_file = os.path.join(PCLOUD_DIR, 'idf', 'idf_tweet_PD_ALL.json')
# treshold to make sure only words that are unique are searched for
TRESHOLD = 15
def exe(article_clusters, article_clusters_filepath, TRESHOLD):
tweets_cache = {}
# if os.path.exists(article_clusters_filepath):
# if not query_yes_no("Are you sure you want to overwrite %s" % article_clusters_filepath, default='no'):
# exit()
# get idf values
with open(idf_file) as fp:
idf = json.load(fp)
# For all articles after 2016_11_06
articles = []
for m in [11, 12]:
if m == 11:
for d in range(7, 32):
articles += get_articles_by_date(filename_prefix='articles_2016_%d_%02d' % (m, d))
else:
for d in range(1, 32):
articles += get_articles_by_date(filename_prefix='articles_2016_%d_%02d' % (m, d))
articles += get_articles_by_date(filename_prefix='articles_2017')
i = 1
last_start_date = None
for a in articles:
try:
if a.id[0] != 'r':
raise Exception("Non article is get_articles! %s" % a)
kwds = a.get_preproc_title()
if a.get_date() != last_start_date:
last_start_date = a.get_date()
update_tweets_cache(last_start_date - timedelta(days=0), last_start_date + timedelta(days=10), tweets_cache)
all_tweets = []
for tweets in tweets_cache.values():
all_tweets += tweets
ts = find_tweets_with_keywords_idf(all_tweets, kwds, idf, TRESHOLD)
if len(ts) > 0:
ts.sort(reverse=True, key=itemgetter(0))
article_clusters[a.id] = process_cluster(a, ts)
i += 1
else:
# Do not add to output
pass
except Exception as err:
try:
print("Writing to %s" % article_clusters_filepath)
json.dump(article_clusters, open(article_clusters_filepath, 'w+', encoding='utf-8'), indent=1)
except Exception as e:
print(article_clusters)
raise e
print("Error: Could not cluster with article %s\n%s" % (a, err))
if i % 200 == 0:
print("Writing to %s" % article_clusters_filepath)
json.dump(article_clusters, open(article_clusters_filepath, 'w+', encoding='utf-8'), indent=1)
print("Writing to %s" % article_clusters_filepath)
json.dump(article_clusters, open(article_clusters_filepath, 'w+', encoding='utf-8'), indent=1)
vader_analyzer = SentimentIntensityAnalyzer()
####
#### DO THIS
####
def process_cluster(article, idf_and_tweets):
article_max_hit = idf_and_tweets[0][0]
rumor_value = 0
tweets_output = []
for idf, tweet in idf_and_tweets:
quotation_marks = int(tweet['n_quationmarks']) / len(tweet['keywords']) * 0.5
abbreviations = - int( tweet['n_abbriviations']) / len(tweet['keywords']) * 1
question_marks = - (0.5 if tweet['questionmark'] else 0)
media = -len(tweet['media']) * 0.3
source = 0.2 if tweet['source_type'] == 'web_client' else -0.1
polarity_scores = vader_analyzer.polarity_scores(tweet['full_text'])
sentiment = polarity_scores['neu'] - 0.5
tweet_rumor_value = quotation_marks + abbreviations + question_marks + media + source + sentiment
tweet_output = {
'id': tweet.id_str(),
'idf_sum': idf,
'quotation_marks': quotation_marks,
'abbreviations': abbreviations,
'question_marks': question_marks,
'media': media,
'source': source,
'sentiment': sentiment,
'tweet_rumor_value': tweet_rumor_value,
}
# print("tweets_output:\n%s\n%s\n" % (tweet, tweet_output))
rumor_value += tweet_rumor_value
tweets_output.append(tweet_output)
rumor_value /= len(idf_and_tweets)
return {
'article_max_hit': article_max_hit,
'rumor_value': rumor_value,
'tweets': tweets_output,
}
if __name__ == '__main__':
exe(article_clusters, article_clusters_filepath, TRESHOLD)
| {
"content_hash": "bf9bb759ff55fea2ff466c0735a13089",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 124,
"avg_line_length": 36.621212121212125,
"alnum_prop": 0.5982623086470832,
"repo_name": "den1den/web-inf-ret-ml",
"id": "8cba69d28c7bf632b287a1970dce0c27dfdc4480",
"size": "4834",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Clustering/exe_articles_to_tweets.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "72580"
},
{
"name": "HTML",
"bytes": "19702"
},
{
"name": "JavaScript",
"bytes": "33368"
},
{
"name": "Python",
"bytes": "171576"
},
{
"name": "Shell",
"bytes": "804"
}
],
"symlink_target": ""
} |
/**************************************************************************************************
*** This file was autogenerated from GrCircleEffect.fp; do not modify.
**************************************************************************************************/
#ifndef GrCircleEffect_DEFINED
#define GrCircleEffect_DEFINED
#include "include/core/SkTypes.h"
#include "src/gpu/GrCoordTransform.h"
#include "src/gpu/GrFragmentProcessor.h"
class GrCircleEffect : public GrFragmentProcessor {
public:
static std::unique_ptr<GrFragmentProcessor> Make(GrClipEdgeType edgeType, SkPoint center,
float radius) {
// A radius below half causes the implicit insetting done by this processor to become
// inverted. We could handle this case by making the processor code more complicated.
if (radius < .5f && GrProcessorEdgeTypeIsInverseFill(edgeType)) {
return nullptr;
}
return std::unique_ptr<GrFragmentProcessor>(new GrCircleEffect(edgeType, center, radius));
}
GrCircleEffect(const GrCircleEffect& src);
std::unique_ptr<GrFragmentProcessor> clone() const override;
const char* name() const override { return "CircleEffect"; }
GrClipEdgeType edgeType;
SkPoint center;
float radius;
private:
GrCircleEffect(GrClipEdgeType edgeType, SkPoint center, float radius)
: INHERITED(kGrCircleEffect_ClassID,
(OptimizationFlags)kCompatibleWithCoverageAsAlpha_OptimizationFlag)
, edgeType(edgeType)
, center(center)
, radius(radius) {}
GrGLSLFragmentProcessor* onCreateGLSLInstance() const override;
void onGetGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder*) const override;
bool onIsEqual(const GrFragmentProcessor&) const override;
GR_DECLARE_FRAGMENT_PROCESSOR_TEST
typedef GrFragmentProcessor INHERITED;
};
#endif
| {
"content_hash": "8c5bd8a87f844e33e234c8cc1d0b5143",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 100,
"avg_line_length": 45.51162790697674,
"alnum_prop": 0.6320899335717935,
"repo_name": "HalCanary/skia-hc",
"id": "c43ab987ea38fd043ce3433ff6c1f2de2a9800e9",
"size": "2100",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "src/gpu/effects/generated/GrCircleEffect.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "1277297"
},
{
"name": "Batchfile",
"bytes": "865"
},
{
"name": "C",
"bytes": "505166"
},
{
"name": "C#",
"bytes": "4683"
},
{
"name": "C++",
"bytes": "32234337"
},
{
"name": "CMake",
"bytes": "2850"
},
{
"name": "CSS",
"bytes": "3078"
},
{
"name": "Dockerfile",
"bytes": "14764"
},
{
"name": "GLSL",
"bytes": "109164"
},
{
"name": "Go",
"bytes": "135327"
},
{
"name": "HTML",
"bytes": "1321397"
},
{
"name": "Java",
"bytes": "167849"
},
{
"name": "JavaScript",
"bytes": "463920"
},
{
"name": "Lex",
"bytes": "2521"
},
{
"name": "Lua",
"bytes": "70982"
},
{
"name": "Makefile",
"bytes": "13502"
},
{
"name": "Objective-C",
"bytes": "83351"
},
{
"name": "Objective-C++",
"bytes": "366996"
},
{
"name": "PHP",
"bytes": "139510"
},
{
"name": "PowerShell",
"bytes": "1432"
},
{
"name": "Python",
"bytes": "1055437"
},
{
"name": "Shell",
"bytes": "95010"
}
],
"symlink_target": ""
} |
package cmd
import (
"fmt"
"io/ioutil"
"reflect"
"sort"
"testing"
kerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
clientgotesting "k8s.io/client-go/testing"
kapi "k8s.io/kubernetes/pkg/apis/core"
"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake"
appsapi "github.com/openshift/origin/pkg/apps/apis/apps"
appstest "github.com/openshift/origin/pkg/apps/apis/apps/test"
appsfake "github.com/openshift/origin/pkg/apps/generated/internalclientset/fake"
appsutil "github.com/openshift/origin/pkg/apps/util"
// install all APIs
_ "github.com/openshift/origin/pkg/api/install"
_ "k8s.io/kubernetes/pkg/apis/core/install"
)
func deploymentFor(config *appsapi.DeploymentConfig, status appsapi.DeploymentStatus) *kapi.ReplicationController {
d, err := appsutil.MakeTestOnlyInternalDeployment(config)
if err != nil {
panic(err)
}
d.Annotations[appsapi.DeploymentStatusAnnotation] = string(status)
return d
}
// TestCmdDeploy_latestOk ensures that attempts to start a new deployment
// succeeds given an existing deployment in a terminal state.
func TestCmdDeploy_latestOk(t *testing.T) {
validStatusList := []appsapi.DeploymentStatus{
appsapi.DeploymentStatusComplete,
appsapi.DeploymentStatusFailed,
}
for _, status := range validStatusList {
config := appstest.OkDeploymentConfig(1)
updatedConfig := config
osClient := &appsfake.Clientset{}
osClient.PrependReactor("get", "deploymentconfigs", func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) {
return true, config, nil
})
osClient.PrependReactor("create", "deploymentconfigs", func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) {
if action.GetSubresource() != "instantiate" {
return false, nil, nil
}
updatedConfig.Status.LatestVersion++
return true, updatedConfig, nil
})
kubeClient := fake.NewSimpleClientset()
kubeClient.PrependReactor("get", "replicationcontrollers", func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) {
return true, deploymentFor(config, status), nil
})
o := &DeployOptions{appsClient: osClient.Apps(), kubeClient: kubeClient, out: ioutil.Discard}
err := o.deploy(config)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if exp, got := int64(2), updatedConfig.Status.LatestVersion; exp != got {
t.Fatalf("expected deployment config version: %d, got: %d", exp, got)
}
}
}
// TestCmdDeploy_latestConcurrentRejection ensures that attempts to start a
// deployment concurrent with a running deployment are rejected.
func TestCmdDeploy_latestConcurrentRejection(t *testing.T) {
invalidStatusList := []appsapi.DeploymentStatus{
appsapi.DeploymentStatusNew,
appsapi.DeploymentStatusPending,
appsapi.DeploymentStatusRunning,
}
for _, status := range invalidStatusList {
config := appstest.OkDeploymentConfig(1)
existingDeployment := deploymentFor(config, status)
kubeClient := fake.NewSimpleClientset(existingDeployment)
o := &DeployOptions{kubeClient: kubeClient, out: ioutil.Discard}
err := o.deploy(config)
if err == nil {
t.Errorf("expected an error starting deployment with existing status %s", status)
}
}
}
// TestCmdDeploy_latestLookupError ensures that an error is thrown when
// existing deployments can't be looked up due to some fatal server error.
func TestCmdDeploy_latestLookupError(t *testing.T) {
kubeClient := fake.NewSimpleClientset()
kubeClient.PrependReactor("get", "replicationcontrollers", func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) {
return true, nil, kerrors.NewInternalError(fmt.Errorf("internal error"))
})
config := appstest.OkDeploymentConfig(1)
o := &DeployOptions{kubeClient: kubeClient, out: ioutil.Discard}
err := o.deploy(config)
if err == nil {
t.Fatal("expected an error")
}
}
// TestCmdDeploy_retryOk ensures that a failed deployment can be retried.
func TestCmdDeploy_retryOk(t *testing.T) {
deletedPods := []string{}
config := appstest.OkDeploymentConfig(1)
var updatedDeployment *kapi.ReplicationController
existingDeployment := deploymentFor(config, appsapi.DeploymentStatusFailed)
existingDeployment.Annotations[appsapi.DeploymentCancelledAnnotation] = appsapi.DeploymentCancelledAnnotationValue
existingDeployment.Annotations[appsapi.DeploymentStatusReasonAnnotation] = appsapi.DeploymentCancelledByUser
mkpod := func(name string) kapi.Pod {
return kapi.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Labels: map[string]string{
appsapi.DeployerPodForDeploymentLabel: existingDeployment.Name,
},
},
}
}
existingDeployerPods := []kapi.Pod{
mkpod("hook-pre"), mkpod("hook-post"), mkpod("deployerpod"),
}
kubeClient := fake.NewSimpleClientset()
kubeClient.PrependReactor("get", "replicationcontrollers", func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) {
return true, existingDeployment, nil
})
kubeClient.PrependReactor("update", "replicationcontrollers", func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) {
updatedDeployment = action.(clientgotesting.UpdateAction).GetObject().(*kapi.ReplicationController)
return true, updatedDeployment, nil
})
kubeClient.PrependReactor("list", "pods", func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) {
return true, &kapi.PodList{Items: existingDeployerPods}, nil
})
kubeClient.PrependReactor("delete", "pods", func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) {
deletedPods = append(deletedPods, action.(clientgotesting.DeleteAction).GetName())
return true, nil, nil
})
o := &DeployOptions{kubeClient: kubeClient, out: ioutil.Discard}
err := o.retry(config)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if updatedDeployment == nil {
t.Fatalf("expected updated config")
}
if appsutil.IsDeploymentCancelled(updatedDeployment) {
t.Fatalf("deployment should not have the cancelled flag set anymore")
}
if appsutil.DeploymentStatusReasonFor(updatedDeployment) != "" {
t.Fatalf("deployment status reason should be empty")
}
sort.Strings(deletedPods)
expectedDeletions := []string{"deployerpod", "hook-post", "hook-pre"}
if e, a := expectedDeletions, deletedPods; !reflect.DeepEqual(e, a) {
t.Fatalf("Not all deployer pods for the failed deployment were deleted.\nEXPECTED: %v\nACTUAL: %v", e, a)
}
if e, a := appsapi.DeploymentStatusNew, appsutil.DeploymentStatusFor(updatedDeployment); e != a {
t.Fatalf("expected deployment status %s, got %s", e, a)
}
}
// TestCmdDeploy_retryRejectNonFailed ensures that attempts to retry a non-
// failed deployment are rejected.
func TestCmdDeploy_retryRejectNonFailed(t *testing.T) {
invalidStatusList := []appsapi.DeploymentStatus{
appsapi.DeploymentStatusNew,
appsapi.DeploymentStatusPending,
appsapi.DeploymentStatusRunning,
appsapi.DeploymentStatusComplete,
}
for _, status := range invalidStatusList {
config := appstest.OkDeploymentConfig(1)
existingDeployment := deploymentFor(config, status)
kubeClient := fake.NewSimpleClientset(existingDeployment)
o := &DeployOptions{kubeClient: kubeClient, out: ioutil.Discard}
err := o.retry(config)
if err == nil {
t.Errorf("expected an error retrying deployment with status %s", status)
}
}
}
// TestCmdDeploy_cancelOk ensures that attempts to cancel deployments
// for a config result in cancelling all in-progress deployments
// and none of the completed/faild ones.
func TestCmdDeploy_cancelOk(t *testing.T) {
type existing struct {
version int64
status appsapi.DeploymentStatus
shouldCancel bool
}
type scenario struct {
version int64
existing []existing
}
scenarios := []scenario{
// No existing deployments
{1, []existing{{1, appsapi.DeploymentStatusComplete, false}}},
// A single existing failed deployment
{1, []existing{{1, appsapi.DeploymentStatusFailed, false}}},
// Multiple existing completed/failed deployments
{2, []existing{{2, appsapi.DeploymentStatusFailed, false}, {1, appsapi.DeploymentStatusComplete, false}}},
// A single existing new deployment
{1, []existing{{1, appsapi.DeploymentStatusNew, true}}},
// A single existing pending deployment
{1, []existing{{1, appsapi.DeploymentStatusPending, true}}},
// A single existing running deployment
{1, []existing{{1, appsapi.DeploymentStatusRunning, true}}},
// Multiple existing deployments with one in new/pending/running
{3, []existing{{3, appsapi.DeploymentStatusRunning, true}, {2, appsapi.DeploymentStatusComplete, false}, {1, appsapi.DeploymentStatusFailed, false}}},
// Multiple existing deployments with more than one in new/pending/running
{3, []existing{{3, appsapi.DeploymentStatusNew, true}, {2, appsapi.DeploymentStatusRunning, true}, {1, appsapi.DeploymentStatusFailed, false}}},
}
for _, scenario := range scenarios {
updatedDeployments := []kapi.ReplicationController{}
config := appstest.OkDeploymentConfig(scenario.version)
existingDeployments := &kapi.ReplicationControllerList{}
for _, e := range scenario.existing {
d, _ := appsutil.MakeTestOnlyInternalDeployment(appstest.OkDeploymentConfig(e.version))
d.Annotations[appsapi.DeploymentStatusAnnotation] = string(e.status)
existingDeployments.Items = append(existingDeployments.Items, *d)
}
kubeClient := fake.NewSimpleClientset()
kubeClient.PrependReactor("update", "replicationcontrollers", func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) {
updated := action.(clientgotesting.UpdateAction).GetObject().(*kapi.ReplicationController)
updatedDeployments = append(updatedDeployments, *updated)
return true, updated, nil
})
kubeClient.PrependReactor("list", "replicationcontrollers", func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) {
return true, existingDeployments, nil
})
o := &DeployOptions{kubeClient: kubeClient, out: ioutil.Discard}
err := o.cancel(config)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
expectedCancellations := []int64{}
actualCancellations := []int64{}
for _, e := range scenario.existing {
if e.shouldCancel {
expectedCancellations = append(expectedCancellations, e.version)
}
}
for _, d := range updatedDeployments {
actualCancellations = append(actualCancellations, appsutil.DeploymentVersionFor(&d))
}
sort.Sort(Int64Slice(actualCancellations))
sort.Sort(Int64Slice(expectedCancellations))
if !reflect.DeepEqual(actualCancellations, expectedCancellations) {
t.Fatalf("expected cancellations: %v, actual: %v", expectedCancellations, actualCancellations)
}
}
}
type Int64Slice []int64
func (p Int64Slice) Len() int { return len(p) }
func (p Int64Slice) Less(i, j int) bool { return p[i] < p[j] }
func (p Int64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func TestDeploy_reenableTriggers(t *testing.T) {
mktrigger := func() appsapi.DeploymentTriggerPolicy {
t := appstest.OkImageChangeTrigger()
t.ImageChangeParams.Automatic = false
return t
}
var updated *appsapi.DeploymentConfig
osClient := &appsfake.Clientset{}
osClient.AddReactor("update", "deploymentconfigs", func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) {
updated = action.(clientgotesting.UpdateAction).GetObject().(*appsapi.DeploymentConfig)
return true, updated, nil
})
config := appstest.OkDeploymentConfig(1)
config.Spec.Triggers = []appsapi.DeploymentTriggerPolicy{}
count := 3
for i := 0; i < count; i++ {
config.Spec.Triggers = append(config.Spec.Triggers, mktrigger())
}
o := &DeployOptions{appsClient: osClient.Apps(), out: ioutil.Discard}
err := o.reenableTriggers(config)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if updated == nil {
t.Fatalf("expected an updated config")
}
if e, a := count, len(config.Spec.Triggers); e != a {
t.Fatalf("expected %d triggers, got %d", e, a)
}
for _, trigger := range config.Spec.Triggers {
if !trigger.ImageChangeParams.Automatic {
t.Errorf("expected trigger to be enabled: %#v", trigger.ImageChangeParams)
}
}
}
| {
"content_hash": "8ca662e096d977f0ddbea4b48e5a0f37",
"timestamp": "",
"source": "github",
"line_count": 332,
"max_line_length": 152,
"avg_line_length": 37.102409638554214,
"alnum_prop": 0.7443578503003735,
"repo_name": "legionus/origin",
"id": "530ea8e21299a248a85780d5802564674940c7f5",
"size": "12318",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pkg/oc/cli/cmd/deploy_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "1842"
},
{
"name": "DIGITAL Command Language",
"bytes": "117"
},
{
"name": "Go",
"bytes": "18908374"
},
{
"name": "Groovy",
"bytes": "5288"
},
{
"name": "HTML",
"bytes": "74732"
},
{
"name": "Makefile",
"bytes": "21890"
},
{
"name": "Protocol Buffer",
"bytes": "635763"
},
{
"name": "Python",
"bytes": "33408"
},
{
"name": "Roff",
"bytes": "2049"
},
{
"name": "Ruby",
"bytes": "484"
},
{
"name": "Shell",
"bytes": "2159344"
},
{
"name": "Smarty",
"bytes": "626"
}
],
"symlink_target": ""
} |
#ifndef __TimedAction_H_
#define __TimedAction_H_
#include "Action.h"
#include "Node.h"
namespace cocosdl
{
namespace action
{
/**
* This subclass of action provides the means of measuring time and calculating how much time has elapsed from one
* game engine call to other. Cannot be used directly, it is a pure virtual class that must be subclassed.
*
* @author [email protected]
* @version 1.0
*/
class TimedAction : public Action
{
public:
virtual void run( Node *node );
virtual void reset( const Node *node );
long long int getDurationMs() const
{
return _durationMs;
}
protected:
TimedAction( long long durationMs );
TimedAction( const TimedAction &other );
virtual ~TimedAction();
TimedAction &operator = ( const TimedAction &other );
long long _durationMs;
long long _lastExecution;
/**
* Run the action.<br/>
* This method must be implemented by subclasses to provide their function.
*
* @param node the node to run the action on
* @param percent percentage of time elapsed since starting the action (percentage of the action to apply).
*/
virtual void runStep( Node *node, float percent ) = 0;
};
}
}
#endif //__TimedAction_H_
| {
"content_hash": "c54fdbd5aa8646655ac411a3a44d8abd",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 118,
"avg_line_length": 22.483333333333334,
"alnum_prop": 0.6293550778354337,
"repo_name": "ncerezo/cocosdl",
"id": "31da18adb5dff1c42baf69659d9ce91295a37d11",
"size": "1965",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/action/TimedAction.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "204864"
},
{
"name": "Objective-C",
"bytes": "1092"
}
],
"symlink_target": ""
} |
package org.apache.camel.component.websocket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.AvailablePortFinder;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.ws.WebSocket;
import org.asynchttpclient.ws.WebSocketListener;
import org.asynchttpclient.ws.WebSocketUpgradeHandler;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class WebsocketProducerRouteExampleTest extends CamelTestSupport {
private static List<Object> received = new ArrayList<>();
private static CountDownLatch latch;
private int port;
private Logger log = LoggerFactory.getLogger(getClass());
@Produce("direct:shop")
private ProducerTemplate producer;
@Override
@BeforeEach
public void setUp() throws Exception {
port = AvailablePortFinder.getNextAvailable();
super.setUp();
received.clear();
latch = new CountDownLatch(1);
}
@Test
public void testWSHttpCall() throws Exception {
AsyncHttpClient c = new DefaultAsyncHttpClient();
WebSocket websocket = c.prepareGet("ws://localhost:" + port + "/shop").execute(
new WebSocketUpgradeHandler.Builder()
.addWebSocketListener(new WebSocketListener() {
@Override
public void onOpen(WebSocket websocket) {
}
@Override
public void onClose(WebSocket websocket, int code, String reason) {
}
@Override
public void onError(Throwable t) {
log.warn("Unhandled exception: {}", t.getMessage(), t);
}
@Override
public void onBinaryFrame(byte[] payload, boolean finalFragment, int rsv) {
}
@Override
public void onTextFrame(String payload, boolean finalFragment, int rsv) {
received.add(payload);
log.info("received --> " + payload);
latch.countDown();
}
@Override
public void onPingFrame(byte[] payload) {
}
@Override
public void onPongFrame(byte[] payload) {
}
}).build())
.get();
// Send message to the direct endpoint
producer.sendBodyAndHeader("Beer on stock at Apache Mall", WebsocketConstants.SEND_TO_ALL, "true");
assertTrue(latch.await(10, TimeUnit.SECONDS));
assertEquals(1, received.size());
Object r = received.get(0);
assertTrue(r instanceof String);
assertEquals("Beer on stock at Apache Mall", r);
websocket.sendCloseFrame();
c.close();
}
@Test
public void testWSBytesHttpCall() throws Exception {
AsyncHttpClient c = new DefaultAsyncHttpClient();
WebSocket websocket = c.prepareGet("ws://localhost:" + port + "/shop").execute(
new WebSocketUpgradeHandler.Builder()
.addWebSocketListener(new WebSocketListener() {
@Override
public void onOpen(WebSocket websocket) {
}
@Override
public void onClose(WebSocket websocket, int code, String reason) {
}
@Override
public void onError(Throwable t) {
}
@Override
public void onBinaryFrame(byte[] payload, boolean finalFragment, int rsv) {
received.add(payload);
log.info("received --> " + Arrays.toString(payload));
latch.countDown();
}
@Override
public void onTextFrame(String payload, boolean finalFragment, int rsv) {
}
@Override
public void onPingFrame(byte[] payload) {
}
@Override
public void onPongFrame(byte[] payload) {
}
}).build())
.get();
// Send message to the direct endpoint
byte[] testmessage = "Beer on stock at Apache Mall".getBytes("utf-8");
producer.sendBodyAndHeader(testmessage, WebsocketConstants.SEND_TO_ALL, "true");
assertTrue(latch.await(10, TimeUnit.SECONDS));
assertEquals(1, received.size());
Object r = received.get(0);
assertTrue(r instanceof byte[]);
assertArrayEquals(testmessage, (byte[]) r);
websocket.sendCloseFrame();
c.close();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
public void configure() {
WebsocketComponent websocketComponent = (WebsocketComponent) context.getComponent("websocket");
websocketComponent.setMaxThreads(25);
websocketComponent.setMinThreads(1);
from("direct:shop")
.log(">>> Message received from Shopping center : ${body}")
.to("websocket://localhost:" + port + "/shop");
}
};
}
}
| {
"content_hash": "86d9e3e76d250fead7a3a44e83efb56b",
"timestamp": "",
"source": "github",
"line_count": 182,
"max_line_length": 111,
"avg_line_length": 35.604395604395606,
"alnum_prop": 0.5348765432098765,
"repo_name": "mcollovati/camel",
"id": "71d5a887242f492fa413e2f70bc7e31694070e67",
"size": "7282",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "components/camel-websocket/src/test/java/org/apache/camel/component/websocket/WebsocketProducerRouteExampleTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6521"
},
{
"name": "Batchfile",
"bytes": "2353"
},
{
"name": "CSS",
"bytes": "5472"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "8015"
},
{
"name": "Groovy",
"bytes": "14479"
},
{
"name": "HTML",
"bytes": "915679"
},
{
"name": "Java",
"bytes": "84048197"
},
{
"name": "JavaScript",
"bytes": "100326"
},
{
"name": "Makefile",
"bytes": "513"
},
{
"name": "RobotFramework",
"bytes": "8461"
},
{
"name": "Shell",
"bytes": "17240"
},
{
"name": "TSQL",
"bytes": "28835"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "546"
},
{
"name": "XSLT",
"bytes": "275257"
}
],
"symlink_target": ""
} |
package com.google.gerrit.server.query.change;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.flogger.LazyArgs.lazy;
import static com.google.gerrit.server.project.ProjectCache.noSuchProject;
import static java.util.concurrent.TimeUnit.MINUTES;
import com.google.common.flogger.FluentLogger;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.google.gerrit.entities.BooleanProjectConfig;
import com.google.gerrit.entities.BranchNameKey;
import com.google.gerrit.entities.Change;
import com.google.gerrit.entities.Project;
import com.google.gerrit.entities.SubmitTypeRecord;
import com.google.gerrit.exceptions.StorageException;
import com.google.gerrit.index.query.PostFilterPredicate;
import com.google.gerrit.index.query.Predicate;
import com.google.gerrit.index.query.QueryParseException;
import com.google.gerrit.server.git.CodeReviewCommit;
import com.google.gerrit.server.project.NoSuchProjectException;
import com.google.gerrit.server.project.ProjectCache;
import com.google.gerrit.server.project.ProjectState;
import com.google.gerrit.server.query.change.ChangeQueryBuilder.Arguments;
import com.google.gerrit.server.submit.SubmitDryRun;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
public class ConflictsPredicate {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
// UI code may depend on this string, so use caution when changing.
protected static final String TOO_MANY_FILES = "too many files to find conflicts";
private ConflictsPredicate() {}
public static Predicate<ChangeData> create(Arguments args, String value, Change c)
throws QueryParseException {
ChangeData cd;
List<String> files;
try {
cd = args.changeDataFactory.create(c);
files = cd.currentFilePaths();
} catch (StorageException e) {
warnWithOccasionalStackTrace(
e,
"Error constructing conflicts predicates for change %s in %s",
c.getId(),
c.getProject());
return ChangeIndexPredicate.none();
}
if (3 + files.size() > args.indexConfig.maxTerms()) {
// Short-circuit with a nice error message if we exceed the index
// backend's term limit. This assumes that "conflicts:foo" is the entire
// query; if there are more terms in the input, we might not
// short-circuit here, which will result in a more generic error message
// later on in the query parsing.
throw new QueryParseException(TOO_MANY_FILES);
}
List<Predicate<ChangeData>> filePredicates = new ArrayList<>(files.size());
for (String file : files) {
filePredicates.add(ChangePredicates.path(file));
}
List<Predicate<ChangeData>> and = new ArrayList<>(5);
and.add(ChangePredicates.project(c.getProject()));
and.add(ChangePredicates.ref(c.getDest().branch()));
and.add(Predicate.not(ChangePredicates.idStr(c.getId())));
and.add(Predicate.or(filePredicates));
ChangeDataCache changeDataCache = new ChangeDataCache(cd, args.projectCache);
and.add(new CheckConflict(value, args, c, changeDataCache));
return Predicate.and(and);
}
private static final class CheckConflict extends PostFilterPredicate<ChangeData> {
private final Arguments args;
private final BranchNameKey dest;
private final ChangeDataCache changeDataCache;
CheckConflict(String value, Arguments args, Change c, ChangeDataCache changeDataCache) {
super(ChangeQueryBuilder.FIELD_CONFLICTS, value);
this.args = args;
this.dest = c.getDest();
this.changeDataCache = changeDataCache;
}
@Override
public boolean match(ChangeData object) {
Change.Id id = object.getId();
Project.NameKey otherProject = null;
ObjectId other = null;
try {
Change otherChange = object.change();
if (otherChange == null || !otherChange.getDest().equals(dest)) {
return false;
}
otherProject = otherChange.getProject();
SubmitTypeRecord str = object.submitTypeRecord();
if (!str.isOk()) {
return false;
}
ProjectState projectState;
try {
projectState = changeDataCache.getProjectState();
} catch (NoSuchProjectException e) {
return false;
}
other = object.currentPatchSet().commitId();
ConflictKey conflictsKey =
ConflictKey.create(
changeDataCache.getTestAgainst(),
other,
str.type,
projectState.is(BooleanProjectConfig.USE_CONTENT_MERGE));
return args.conflictsCache.get(conflictsKey, new Loader(object, changeDataCache, args));
} catch (StorageException | ExecutionException | UncheckedExecutionException e) {
ObjectId finalOther = other;
warnWithOccasionalStackTrace(
e,
"Merge failure checking conflicts of change %s in %s (%s): %s",
id,
firstNonNull(otherProject, "unknown project"),
lazy(() -> finalOther != null ? finalOther.name() : "unknown commit"),
e.getMessage());
return false;
}
}
@Override
public int getCost() {
return 5;
}
}
static class ChangeDataCache {
private final ChangeData cd;
private final ProjectCache projectCache;
private ObjectId testAgainst;
private ProjectState projectState;
private Set<ObjectId> alreadyAccepted;
ChangeDataCache(ChangeData cd, ProjectCache projectCache) {
this.cd = cd;
this.projectCache = projectCache;
}
ObjectId getTestAgainst() {
if (testAgainst == null) {
testAgainst = cd.currentPatchSet().commitId();
}
return testAgainst;
}
ProjectState getProjectState() throws NoSuchProjectException {
if (projectState == null) {
projectState = projectCache.get(cd.project()).orElseThrow(noSuchProject(cd.project()));
}
return projectState;
}
Set<ObjectId> getAlreadyAccepted(Repository repo) throws IOException {
if (alreadyAccepted == null) {
alreadyAccepted = SubmitDryRun.getAlreadyAccepted(repo);
}
return alreadyAccepted;
}
}
private static void warnWithOccasionalStackTrace(Throwable cause, String format, Object... args) {
logger.atWarning().logVarargs(format, args);
logger
.atWarning()
.withCause(cause)
.atMostEvery(1, MINUTES)
.logVarargs("(Re-logging with stack trace) " + format, args);
}
private static class Loader implements Callable<Boolean> {
private final ChangeData changeData;
private final ConflictsPredicate.ChangeDataCache changeDataCache;
private final ChangeQueryBuilder.Arguments args;
private Loader(
ChangeData changeData,
ConflictsPredicate.ChangeDataCache changeDataCache,
ChangeQueryBuilder.Arguments args) {
this.changeData = changeData;
this.changeDataCache = changeDataCache;
this.args = args;
}
@Override
public Boolean call() throws Exception {
Change otherChange = changeData.change();
ObjectId other = changeData.currentPatchSet().commitId();
try (Repository repo = args.repoManager.openRepository(otherChange.getProject());
CodeReviewCommit.CodeReviewRevWalk rw = CodeReviewCommit.newRevWalk(repo)) {
return !args.submitDryRun.run(
null,
changeData.submitTypeRecord().type,
repo,
rw,
otherChange.getDest(),
changeDataCache.getTestAgainst(),
other,
getAlreadyAccepted(repo, rw));
} catch (NoSuchProjectException | IOException e) {
warnWithOccasionalStackTrace(
e,
"Failure when loading conflicts of change %s in %s (%s): %s",
lazy(changeData::getId),
lazy(() -> firstNonNull(otherChange.getProject(), "unknown project")),
lazy(() -> other != null ? other.name() : "unknown commit"),
e.getMessage());
return false;
}
}
private Set<RevCommit> getAlreadyAccepted(Repository repo, RevWalk rw) {
try {
Set<RevCommit> accepted = new HashSet<>();
SubmitDryRun.addCommits(changeDataCache.getAlreadyAccepted(repo), rw, accepted);
ObjectId tip = changeDataCache.getTestAgainst();
if (tip != null) {
accepted.add(rw.parseCommit(tip));
}
return accepted;
} catch (StorageException | IOException e) {
throw new StorageException("Failed to determine already accepted commits.", e);
}
}
}
}
| {
"content_hash": "7b49dc9d63b79b77e6cc826faf34076c",
"timestamp": "",
"source": "github",
"line_count": 248,
"max_line_length": 100,
"avg_line_length": 36.375,
"alnum_prop": 0.6835162398847134,
"repo_name": "GerritCodeReview/gerrit",
"id": "fc4c1d084daf272a0baa83785edef085c4c09768",
"size": "9630",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java/com/google/gerrit/server/query/change/ConflictsPredicate.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "10735"
},
{
"name": "Closure Templates",
"bytes": "87947"
},
{
"name": "Dockerfile",
"bytes": "2833"
},
{
"name": "GAP",
"bytes": "5268"
},
{
"name": "Go",
"bytes": "2731"
},
{
"name": "HTML",
"bytes": "65080"
},
{
"name": "Java",
"bytes": "19516048"
},
{
"name": "JavaScript",
"bytes": "73591"
},
{
"name": "Makefile",
"bytes": "367"
},
{
"name": "Perl",
"bytes": "9943"
},
{
"name": "Prolog",
"bytes": "27464"
},
{
"name": "Python",
"bytes": "86775"
},
{
"name": "Roff",
"bytes": "25754"
},
{
"name": "Scala",
"bytes": "49306"
},
{
"name": "Shell",
"bytes": "91452"
},
{
"name": "Starlark",
"bytes": "280825"
},
{
"name": "TypeScript",
"bytes": "6249575"
}
],
"symlink_target": ""
} |
package com.nike.cerberus.validation;
import static org.mockito.Mockito.mock;
import com.nike.cerberus.domain.UserGroupPermission;
import java.util.HashSet;
import javax.validation.ConstraintValidatorContext;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.internal.util.collections.Sets;
/** Tests the UserGroupPermissionsValidator class */
public class UserGroupPermissionsValidatorTest {
private ConstraintValidatorContext mockConstraintValidatorContext;
private UserGroupPermissionsValidator subject;
@Before
public void setup() {
mockConstraintValidatorContext = mock(ConstraintValidatorContext.class);
subject = new UserGroupPermissionsValidator();
}
@Test
public void null_set_is_valid() {
Assert.assertTrue(subject.isValid(null, mockConstraintValidatorContext));
}
@Test
public void empty_set_is_valid() {
Assert.assertTrue(subject.isValid(new HashSet<>(), mockConstraintValidatorContext));
}
@Test
public void unique_set_is_valid() {
UserGroupPermission a = new UserGroupPermission();
a.setName("abc");
UserGroupPermission b = new UserGroupPermission();
b.setName("def");
Assert.assertTrue(subject.isValid(Sets.newSet(a, b), mockConstraintValidatorContext));
}
}
| {
"content_hash": "2eeb0453ce1db470bb3c67020b733c48",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 90,
"avg_line_length": 27.48936170212766,
"alnum_prop": 0.7708978328173375,
"repo_name": "Nike-Inc/cerberus",
"id": "549edd2299f97858288b6871071fcbe8454d471d",
"size": "1886",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "cerberus-domain/src/test/java/com/nike/cerberus/validation/UserGroupPermissionsValidatorTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1126"
},
{
"name": "Groovy",
"bytes": "123084"
},
{
"name": "HTML",
"bytes": "2160"
},
{
"name": "Java",
"bytes": "1337217"
},
{
"name": "JavaScript",
"bytes": "276262"
},
{
"name": "SCSS",
"bytes": "73750"
},
{
"name": "Shell",
"bytes": "3122"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "4d8e09e9f1d6892814abb4d32e1e37d1",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "2263557f0388a3aa40b113e3b4c35497bd23747b",
"size": "177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Cactaceae/Mammillaria/Mammillaria leucacantha/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<#
.NOTES
Copyright (c) Microsoft Corporation. All rights reserved.
.SYNOPSIS
Create a VM as a new container host
.DESCRIPTION
Collects collateral required to create a container host
Creates a VM
Configures the VM as a new container host
.PARAMETER DockerPath
Path to a private Docker.exe. Defaults to https://aka.ms/tp5/docker
.PARAMETER DockerDPath
Path to a private DockerD.exe. Defaults to https://aka.ms/tp5/dockerd
.PARAMETER Password
Password for the built-in Administrator account.
.PARAMETER HyperV
If passed, prepare the machine for Hyper-V containers
.PARAMETER ScriptPath
Path to a private Install-ContainerHost.ps1. Defaults to https://aka.ms/tp5/Install-ContainerHost
.PARAMETER SwitchName
Specify a switch to give the container host network connectivity
.PARAMETER UnattendPath
Path to custom unattend.xml for use in the container host VM. If not passed, a default
unattend.xml will be used that contains a built-in Administrator account
.PARAMETER VhdPath
Path to a private Windows Server image.
.PARAMETER VmName
Friendly name for container host VM to be created. Required.
.PARAMETER WimPath
Path to a private .wim file that contains the base package image. Only required if -VhdPath is also passed
.PARAMETER WindowsImage
Image to use for the VM. One of NanoServer, ServerDatacenter, or ServerDatacenterCore [default]
.EXAMPLE
.\Install-ContainerHost.ps1
#>
#Requires -Version 4.0
[CmdletBinding(DefaultParameterSetName="Deploy")]
param(
[string]
[ValidateNotNullOrEmpty()]
$DockerPath = "https://aka.ms/tp5/b/docker",
[string]
[ValidateNotNullOrEmpty()]
$DockerDPath = "https://aka.ms/tp5/b/dockerd",
[switch]
$HyperV,
[Parameter(ParameterSetName="Deploy")]
[string]
[ValidateNotNullOrEmpty()]
$IsoPath = "https://aka.ms/tp5/serveriso",
[Parameter(ParameterSetName="Deploy", Mandatory, Position=1)]
[Security.SecureString]
$Password = ("P@ssw0rd" | ConvertTo-SecureString -AsPlainText -Force),
[Parameter(ParameterSetName="Prompt", Mandatory)]
[switch]
$Prompt,
[string]
[ValidateNotNullOrEmpty()]
$ScriptPath = "https://aka.ms/tp5/Install-ContainerHost",
[Parameter(ParameterSetName="Staging", Mandatory)]
[switch]
$Staging,
[string]
$SwitchName,
[string]
[ValidateNotNullOrEmpty()]
$UnattendPath,
[string]
[ValidateNotNullOrEmpty()]
$VhdPath,
[Parameter(ParameterSetName="Deploy", Mandatory, Position=0)]
[Parameter(ParameterSetName="Staging", Mandatory, Position=0)]
[string]
[ValidateNotNullOrEmpty()]
$VmName,
[string]
[ValidateNotNullOrEmpty()]
$WimPath,
[string]
[ValidateSet("NanoServer", "ServerDatacenter", "ServerDatacenterCore")]
$WindowsImage = "ServerDatacenterCore"
)
if ($Prompt)
{
if ((Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V).State -ne "Enabled")
{
throw "Hyper-V must be enabled to continue"
}
$VmName = Read-Host 'Please specify a name for your VM'
#
# Do we require nesting?
#
$nestedChoiceList = New-Object System.Collections.ObjectModel.Collection[System.Management.Automation.Host.ChoiceDescription]
$nestedChoiceList.Add((New-Object "System.Management.Automation.Host.ChoiceDescription" -ArgumentList "&No"))
$nestedChoiceList.Add((New-Object "System.Management.Automation.Host.ChoiceDescription" -ArgumentList "&Yes"))
$HyperV = [boolean]$Host.ui.PromptForChoice($null, "Would you like to enable Hyper-V containers?", $nestedChoiceList, 0)
#
# Which image?
#
$imageChoiceList = New-Object System.Collections.ObjectModel.Collection[System.Management.Automation.Host.ChoiceDescription]
$imageChoiceList.Add((New-Object "System.Management.Automation.Host.ChoiceDescription" -ArgumentList "&NanoServer"))
$imageChoiceList.Add((New-Object "System.Management.Automation.Host.ChoiceDescription" -ArgumentList "&ServerDatacenter"))
$imageChoiceList.Add((New-Object "System.Management.Automation.Host.ChoiceDescription" -ArgumentList "ServerDatacenter&Core"))
$imageIndex = $Host.ui.PromptForChoice($null, "Select your container host image", $imageChoiceList, 2)
switch ($imageIndex)
{
0 {$WindowsImage = "NanoServer"}
1 {$WindowsImage = "ServerDatacenter"}
2 {$WindowsImage = "ServerDatacenterCore"}
}
#
# Administrator password?
#
$Password = Read-Host 'Please specify Administrator password' -AsSecureString
$global:ParameterSet = "Deploy"
}
else
{
$global:ParameterSet = $PSCmdlet.ParameterSetName
}
$global:WimSaveMode = $true
$global:PowerShellDirectMode = $true
$global:VmGeneration = 2
#
# Image information
#
if ($HyperV -or ($WindowsImage -eq "NanoServer"))
{
$global:imageName = "NanoServer"
}
else
{
$global:imageName = "WindowsServerCore"
}
$global:imageVersion = "14300.1000"
#
# Branding strings
#
$global:brand = $WindowsImage
$global:imageBrand = "$($global:brand)_en-us_TP5_Container"
$global:isoBrandName = "$global:brand ISO"
$global:vhdBrandName = "$global:brand VHD"
#
# Get the management service settings
#
$global:localVhdRoot = "$((Get-VMHost).VirtualHardDiskPath)".TrimEnd("\")
$global:freeSpaceGB = 0
#
# Define a default VHD name if not specified
#
if ($VhdPath -and ($(Split-Path -Leaf $VhdPath) -match ".*\.vhdx?"))
{
$global:localVhdName = $(Split-Path -Leaf $VhdPath)
#
# Assume this is an official Windows build VHD/X. We parse the build number and QFE from the filename
#
if ($global:localVhdName -match "(\d{5})\.(\d{1,5}).(.*\.\d{6}-\d{4})_.*\.vhdx?")
{
$global:imageVersion = "$($Matches[1]).$($Matches[2])"
if (-not $WimPath)
{
#
# Register the private
#
.\Register-TestContainerHost.ps1 -BuildName "$($Matches[1]).$($Matches[2]).$($Matches[3])"
}
}
}
else
{
$global:localVhdName = "$($global:imageBrand).vhdx"
}
$global:localIsoName = "WindowsServerTP5.iso"
$global:localIsoPath = "$global:localVhdRoot\$global:localIsoName"
$global:localIsoVersion = "$global:localVhdRoot\ContainerISOVersion.$($global:imageVersion).txt"
$global:localVhdPath = "$global:localVhdRoot\$global:localVhdName"
$global:localVhdVersion = "$global:localVhdRoot\ContainerVHDVersion.$($global:imageVersion).txt"
$global:localWimName = "$global:imageName.wim"
$global:localWimVhdPath = "$global:localVhdRoot\$($global:imageName)-WIM-$($global:imageVersion).vhdx"
$global:localWimVhdVersion = "$global:localVhdRoot\$($global:imageName)Version.$($global:imageVersion).txt"
function
Cache-HostFiles
{
if ($(Test-Path $global:localVhdPath) -and
$(Test-Path $global:localVhdVersion))
{
Write-Output "The latest $global:vhdBrandName is already present on this system."
}
else
{
if ($global:freeSpaceGB -le 20)
{
Write-Warning "You currently have only $global:freeSpaceGB GB of free space available; 20GB is required"
}
if ($(Test-Path $global:localVhdPath) -and
-not (Test-Path $global:localVhdVersion))
{
Write-Warning "There is a newer $global:vhdBrandName available."
}
if ($VhdPath)
{
Write-Output "Copying $global:vhdBrandName from $VhdPath to $global:localVhdPath..."
Copy-File -SourcePath $VhdPath -DestinationPath $global:localVhdPath
}
else
{
if (Test-Path $global:localIsoPath)
{
Write-Output "The latest $global:isoBrandName is already present on this system."
}
else
{
Write-Output "Copying $global:isoBrandName from $IsoPath to $global:localIsoPath (this may take several minutes)..."
Copy-File -SourcePath $IsoPath -DestinationPath $global:localIsoPath
}
try
{
$convertScript = $(Join-Path $global:localVhdRoot "Convert-WindowsImage.ps1")
Write-Verbose "Copying Convert-WindowsImage..."
Copy-File -SourcePath 'https://aka.ms/tp5/Convert-WindowsImage' -DestinationPath $convertScript
#
# Dot-source until this is a module
#
. $convertScript
Write-Output "Mounting ISO..."
$openIso = Mount-DiskImage $global:localIsoPath
# Refresh the DiskImage object so we can get the real information about it. I assume this is a bug.
$openIso = Get-DiskImage -ImagePath $global:localIsoPath
$driveLetter = ($openIso | Get-Volume).DriveLetter
Write-Output "Converting WIM to VHD..."
if ($WindowsImage -eq "NanoServer")
{
Import-Module "$($driveLetter):\NanoServer\NanoServerImageGenerator\NanoServerImageGenerator.psm1"
if ($Staging)
{
New-NanoServerImage -DeploymentType Guest -Edition Standard -MediaPath "$($driveLetter):\" -TargetPath $global:localVhdPath -Containers -AdministratorPassword $Password
}
else
{
New-NanoServerImage -DeploymentType Guest -Edition Standard -MediaPath "$($driveLetter):\" -TargetPath $global:localVhdPath -Compute -Containers -AdministratorPassword $Password
}
}
else
{
Convert-WindowsImage -DiskLayout UEFI -SourcePath "$($driveLetter):\sources\install.wim" -Edition $WindowsImage -VhdPath $global:localVhdPath
}
}
catch
{
throw $_
}
finally
{
Write-Output "Dismounting ISO..."
Dismount-DiskImage $global:localIsoPath
}
}
"This file indicates the web version of the base VHD" | Out-File -FilePath $global:localVhdVersion
}
if ($global:WimSaveMode -or $WimPath)
{
$global:WimSaveMode = $true
#
# The combo VHD already contains the WIM. Only cache if we are NOT using the combo VHD.
#
if ($(Test-Path $global:localWimVhdPath) -and
$(Test-Path $global:localWimVhdVersion))
{
Write-Output "$global:brand Container OS Image (WIM) is already present on this system."
}
else
{
if ($(Test-Path $global:localWimVhdPath) -and
-not (Test-Path $global:localWimVhdVersion))
{
Write-Warning "Wrong version of Container OS Image (WIM) inside $global:localWimVhdPath..."
Remove-Item $global:localWimVhdPath
}
Write-Output "Creating temporary VHDX for the Containers OS Image WIM..."
$dataVhdx = New-VHD -Path $global:localWimVhdPath -Dynamic -SizeBytes 8GB -BlockSizeBytes 1MB
$disk = $dataVhdx | Mount-VHD -PassThru
try
{
Write-Output "Initializing disk..."
Initialize-Disk -Number $disk.Number -PartitionStyle MBR
#
# Create single partition
#
Write-Verbose "Creating single partition..."
$partition = New-Partition -DiskNumber $disk.Number -Size $disk.LargestFreeExtent -MbrType IFS -IsActive
Write-Verbose "Formatting volume..."
$volume = Format-Volume -Partition $partition -FileSystem NTFS -Force -Confirm:$false
$partition | Add-PartitionAccessPath -AssignDriveLetter
$driveLetter = (Get-Volume |? UniqueId -eq $volume.UniqueId).DriveLetter
if ($WimPath)
{
Write-Output "Saving private Container OS image ($global:imageName) (this may take a few minutes)..."
Copy-File -SourcePath $WimPath -DestinationPath "$($driveLetter):\$global:localWimName"
}
else
{
Test-ContainerImageProvider
$imageVersion = "10.0.$global:imageVersion"
Write-Output "Saving Container OS image ($global:imageName -MinimumVersion $imageVersion) from OneGet to $($driveLetter): (this may take a few minutes)..."
#
# TODO: should be error action stop by default
#
Save-ContainerImage -Name $global:imageName -MinimumVersion $imageVersion -Path $env:TEMP -ErrorAction Stop | Out-Null
#
# TODO: don't use env:temp once OneGet supports mounted drives
#
Move-Item -Path (Resolve-Path "$env:TEMP\*-*.wim") -Destination "$($driveLetter):\$global:localWimName"
}
if (-not (Test-Path "$($driveLetter):\$global:localWimName"))
{
throw "Container image not saved successfully"
}
"This file indicates the web version of the image WIM VHD" | Out-File -FilePath $global:localWimVhdVersion
}
catch
{
throw $_
}
finally
{
Write-Output "Dismounting VHD..."
Dismount-VHD -Path $dataVhdx.Path
}
}
}
}
function
Add-Unattend
{
[CmdletBinding()]
param(
[string]
$DriveLetter
)
$unattendFilePath = "$($DriveLetter):\unattend.xml"
if ($UnattendPath -ne "")
{
Copy-File -SourcePath $UnattendPath -DestinationPath $unattendFilePath
$unattendFile = New-Object XML
$unattendFile.Load($unattendFilePath)
Write-Output "Writing custom unattend.xml..."
}
else
{
$credential = New-Object System.Management.Automation.PsCredential("Administrator", $Password)
$unattendFile = (Get-Unattend -Password $credential.GetNetworkCredential().Password).Clone()
Write-Output "Writing default unattend.xml..."
}
if (-not $global:PowerShellDirectMode)
{
Write-Output "Configuring Install-ContainerHost.ps1 to run at first launch..."
$installCommand = "%SystemDrive%\Install-ContainerHost.ps1 "
if ($Staging)
{
$installCommand += '-Staging '
}
else
{
$installCommand += '-DockerPath %SystemRoot%\System32\docker.exe -DockerDPath %SystemRoot%\System32\dockerd.exe'
}
if ($global:WimSaveMode)
{
$installCommand += "-WimPath 'D:\$global:localWimName' "
}
try
{
[System.Xml.XmlNamespaceManager]$nsmgr = $unattendFile.NameTable
$nsmgr.AddNamespace('urn', "urn:schemas-microsoft-com:unattend")
$nsmgr.AddNamespace('wcm', "http://schemas.microsoft.com/WMIConfig/2002/State")
$firstLogonElement = $unattendFile.CreateElement("FirstLogonCommands", $nsmgr.LookupNamespace("urn"))
$synchronousCommandElement = $unattendFile.CreateElement("SynchronousCommand", $nsmgr.LookupNamespace("urn"))
$synchronousCommandElement.SetAttribute("action", $nsmgr.LookupNamespace("wcm"), "add") | Out-Null
$commandLineElement = $unattendFile.CreateElement("CommandLine", $nsmgr.LookupNamespace("urn"))
$commandLineElement.InnerText = "%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell -NoLogo -NonInteractive -ExecutionPolicy Unrestricted -Command ""& { $installCommand } "" "
$descriptionElement = $unattendFile.CreateElement("Description", $nsmgr.LookupNamespace("urn"))
$descriptionElement.InnerText = "Running Containers Host setup script"
$orderElement = $unattendFile.CreateElement("Order", $nsmgr.LookupNamespace("urn"))
$orderElement.InnerText = "1"
$synchronousCommandElement.AppendChild($commandLineElement) | Out-Null
$synchronousCommandElement.AppendChild($descriptionElement) | Out-Null
$synchronousCommandElement.AppendChild($orderElement) | Out-Null
$firstLogonElement.AppendChild($synchronousCommandElement) | Out-Null
$oobeSystemNode = $unattendFile.unattend.settings |? pass -eq "oobeSystem"
$shellSetupNode = $oobeSystemNode.component |? name -eq "Microsoft-Windows-Shell-Setup"
$shellSetupNode.AppendChild($firstLogonElement) | Out-Null
}
catch
{
Write-Warning "Failed to modify unattend.xml. Please manually run 'powershell $installCommand' in the VM"
}
}
$unattendFile.Save($unattendFilePath)
}
function
Edit-BootVhd
{
[CmdletBinding()]
param(
[string]
$BootVhdPath
)
#
# Protect this with a mutex
#
$mutex = New-Object System.Threading.Mutex($False, $global:imageName);
$bootVhd = Get-Vhd $BootVhdPath
try
{
Write-Output "VHD mount must be synchronized with other running instances of this script. Waiting for exclusive access..."
$mutex.WaitOne() | Out-Null;
Write-Verbose "Mutex acquired."
Write-Output "Mounting $global:vhdBrandName for offline processing..."
$disk = $bootVhd | Mount-VHD -PassThru | Get-Disk
if ($disk.PartitionStyle -eq "GPT")
{
#
# Generation 2: we assume the only partition with a drive letter is the Windows partition
#
$driveLetter = ($disk | Get-Partition | Where-Object DriveLetter).DriveLetter
}
else
{
#
# Generation 1: we will assume there is one partition/volume
#
$global:VmGeneration = 1
$driveLetter = ($disk | Get-Partition | Get-Volume).DriveLetter
}
if ($WindowsImage -eq "NanoServer")
{
if ((Test-Path $global:localIsoPath) -and $Staging)
{
#
# Add packages
#
try
{
Write-Output "Mounting ISO..."
$openIso = Mount-DiskImage $global:localIsoPath
# Refresh the DiskImage object so we can get the real information about it. I assume this is a bug.
$openIso = Get-DiskImage -ImagePath $global:localIsoPath
$isoDriveLetter = ($openIso | Get-Volume).DriveLetter
#
# Copy all packages into the image to make it easier to add them later (at the cost of disk space)
#
Write-Output "Copying Nano packages into image..."
Copy-Item "$($isoDriveLetter):\NanoServer\Packages" "$($driveLetter):\Packages" -Recurse
}
catch
{
throw $_
}
finally
{
Write-Output "Dismounting ISO..."
Dismount-DiskImage $global:localIsoPath
}
}
}
else
{
if ($global:PowerShellDirectMode)
{
#
# Enable containers feature. This saves a reboot
#
Write-Output "Enabling Containers feature on drive $driveLetter..."
Enable-WindowsOptionalFeature -FeatureName Containers -Path "$($driveLetter):" | Out-Null
if ($HyperV)
{
Write-Output "Enabling Hyper-V feature on drive $driveLetter..."
Enable-WindowsOptionalFeature -FeatureName Microsoft-Hyper-V -Path "$($driveLetter):" | Out-Null
}
}
else
{
# Windows 8.1 DISM cannot operate on Windows 10 guests.
}
}
#
# Copy docker
#
Write-Output "Copying Docker into $global:vhdBrandName..."
Copy-File -SourcePath $DockerPath -DestinationPath "$($driveLetter):\Windows\System32\docker.exe"
try
{
Write-Output "Copying Docker daemon into $global:vhdBrandName..."
Copy-File -SourcePath $DockerDPath -DestinationPath "$($driveLetter):\Windows\System32\dockerd.exe"
}
catch
{
Write-Warning "DockerD not yet present."
}
#
# Add unattend
#
Add-Unattend $driveLetter
#
# Add Install-ContainerHost.ps1
#
Write-Output "Copying Install-ContainerHost.ps1 into $global:vhdBrandName..."
Copy-File -SourcePath $ScriptPath -DestinationPath "$($driveLetter):\Install-ContainerHost.ps1"
#
# Copy test tools
#
if (Test-Path ".\Register-TestContainerHost.ps1")
{
Copy-Item ".\Register-TestContainerHost.ps1" "$($driveLetter):\"
}
}
catch
{
throw $_
}
finally
{
Write-Output "Dismounting VHD..."
Dismount-VHD -Path $bootVhd.Path
$mutex.ReleaseMutex()
}
}
function
New-ContainerHost()
{
Write-Output "Using VHD path $global:localVhdRoot"
try
{
$global:freeSpaceGB = [float]((Get-Volume -DriveLetter $global:localVhdRoot[0]).SizeRemaining / 1GB)
}
catch
{
Write-Warning "Cannot detect volume free space at $global:localVhdRoot"
}
#
# Validate network configuration
#
if ($SwitchName -eq "")
{
$switches = (Get-VMSwitch |? SwitchType -eq "External")
if ($switches.Count -gt 0)
{
$SwitchName = $switches[0].Name
}
}
if ($SwitchName -ne "")
{
Write-Output "Using external switch $SwitchName"
}
elseif ($Staging)
{
Write-Output "No external virtual switch connectivity; OK for staging mode"
}
else
{
throw "This script requires an external virtual switch. Please configure a virtual switch (New-VMSwitch) and re-run."
}
#
# Get prerequisites
#
Cache-HostFiles
if ($(Get-VM $VmName -ea SilentlyContinue) -ne $null)
{
throw "VM name $VmName already exists on this host"
}
#
# Prepare VHDs
#
Write-Output "Creating VHD files for VM $VmName..."
if ($global:WimSaveMode)
{
$wimVhdPath = "$global:localVhdRoot\$VmName-WIM.vhdx"
if (Test-Path $wimVhdPath)
{
Remove-Item $wimVhdPath
}
$wimVhd = New-VHD -Path "$wimVhdPath" -ParentPath $global:localWimVhdPath -Differencing -BlockSizeBytes 1MB
}
if ($global:freeSpaceGB -le 10)
{
Write-Warning "You currently have only $global:freeSpaceGB GB of free space available at $global:localVhdRoot)"
}
$global:localVhdPath -match "\.vhdx?" | Out-Null
$bootVhdPath = "$global:localVhdRoot\$($VmName)$($matches[0])"
if (Test-Path $bootVhdPath)
{
Remove-Item $bootVhdPath
}
$bootVhd = New-VHD -Path "$bootVhdPath" -ParentPath $global:localVhdPath -Differencing
Edit-BootVhd -BootVhdPath $bootVhdPath
#
# Create VM
#
Write-Output "Creating VM $VmName..."
$vm = New-VM -Name $VmName -VHDPath $bootVhd.Path -Generation $global:VmGeneration
Write-Output "Configuring VM $($vm.Name)..."
$vm | Set-VMProcessor -Count ([Math]::min((Get-VMHost).LogicalProcessorCount, 64))
$vm | Get-VMDvdDrive | Remove-VMDvdDrive
$vm | Set-VM -DynamicMemory | Out-Null
if ($SwitchName -eq "")
{
$switches = (Get-VMSwitch |? SwitchType -eq "External")
if ($switches.Count -gt 0)
{
$SwitchName = $switches[0].Name
}
}
if ($SwitchName -ne "")
{
Write-Output "Connecting VM to switch $SwitchName"
$vm | Get-VMNetworkAdapter | Connect-VMNetworkAdapter -SwitchName "$SwitchName"
}
if ($HyperV)
{
#
# Enable nested to support Hyper-V containers
#
$vm | Set-VMProcessor -ExposeVirtualizationExtensions $true
#
# Disable dynamic memory
#
$vm | Set-VMMemory -DynamicMemoryEnabled $false
}
if ($global:WimSaveMode)
{
#
# Add WIM VHD
#
$wimHardDiskDrive = $vm | Add-VMHardDiskDrive -Path $wimVhd.Path -ControllerType SCSI
}
if ($Staging -and ($WindowsImage -eq "NanoServer"))
{
Write-Output "NanoServer VM is staged..."
}
else
{
Write-Output "Starting VM $($vm.Name)..."
$vm | Start-VM | Out-Null
Write-Output "Waiting for VM $($vm.Name) to boot..."
do
{
Start-Sleep -sec 1
}
until (($vm | Get-VMIntegrationService |? Id -match "84EAAE65-2F2E-45F5-9BB5-0E857DC8EB47").PrimaryStatusDescription -eq "OK")
Write-Output "Connected to VM $($vm.Name) Heartbeat IC."
if ($global:PowerShellDirectMode)
{
$credential = New-Object System.Management.Automation.PsCredential("Administrator", $Password)
$psReady = $false
Write-Output "Waiting for specialization to complete (this may take a few minutes)..."
$startTime = Get-Date
do
{
$timeElapsed = $(Get-Date) - $startTime
if ($($timeElapsed).TotalMinutes -ge 30)
{
throw "Could not connect to PS Direct after 30 minutes"
}
Start-Sleep -sec 1
$psReady = Invoke-Command -VMName $($vm.Name) -Credential $credential -ScriptBlock { $True } -ErrorAction SilentlyContinue
}
until ($psReady)
Write-Verbose "PowerShell Direct connected."
$guestScriptBlock =
{
[CmdletBinding()]
param(
[Parameter(Position=0)]
[string]
$WimName,
[Parameter(Position=1)]
[string]
$ParameterSetName,
[Parameter(Position=2)]
[bool]
$HyperV
)
Write-Verbose "Onlining disks..."
Get-Disk | ? IsOffline | Set-Disk -IsOffline:$false
Write-Output "Completing container install..."
$installCommand = "$($env:SystemDrive)\Install-ContainerHost.ps1 -PSDirect "
if ($ParameterSetName -eq "Staging")
{
$installCommand += "-Staging "
}
else
{
$installCommand += "-DockerPath ""$($env:SystemRoot)\System32\docker.exe"" -DockerDPath ""$($env:SystemRoot)\System32\dockerd.exe"""
}
if ($WimName -ne "")
{
$installCommand += "-WimPath ""D:\$WimName"" "
}
if ($HyperV)
{
$installCommand += "-HyperV "
}
#
# This is required so that Install-ContainerHost.err goes in the right place
#
$pwd = "$($env:SystemDrive)\"
$installCommand += "*>&1 | Tee-Object -FilePath ""$($env:SystemDrive)\Install-ContainerHost.log"" -Append"
Invoke-Expression $installCommand
}
Write-Output "Executing Install-ContainerHost.ps1 inside the VM..."
$wimName = ""
if ($global:WimSaveMode)
{
$wimName = $global:localWimName
}
Invoke-Command -VMName $($vm.Name) -Credential $credential -ScriptBlock $guestScriptBlock -ArgumentList $wimName,$global:ParameterSet,$HyperV
$scriptFailed = Invoke-Command -VMName $($vm.Name) -Credential $credential -ScriptBlock { Test-Path "$($env:SystemDrive)\Install-ContainerHost.err" }
if ($scriptFailed)
{
throw "Install-ContainerHost.ps1 failed in the VM"
}
#
# Cleanup
#
if ($global:WimSaveMode)
{
Write-Output "Cleaning up temporary WIM VHD"
$vm | Get-VMHardDiskDrive |? Path -eq $wimVhd.Path | Remove-VMHardDiskDrive
Remove-Item $wimVhd.Path
}
Write-Output "VM $($vm.Name) is ready for use as a container host."
}
else
{
Write-Output "VM $($vm.Name) will be ready to use as a container host when Install-ContainerHost.ps1 completes execution inside the VM."
}
}
Write-Output "See https://msdn.microsoft.com/virtualization/windowscontainers/containers_welcome for more information about using Containers."
Write-Output "The source code for these installation scripts is available here: https://github.com/Microsoft/Virtualization-Documentation/tree/live/windows-server-container-tools"
}
$global:AdminPriviledges = $false
$global:DockerData = "$($env:ProgramData)\docker"
$global:DockerServiceName = "docker"
function
Copy-File
{
[CmdletBinding()]
param(
[string]
$SourcePath,
[string]
$DestinationPath
)
if ($SourcePath -eq $DestinationPath)
{
return
}
if (Test-Path $SourcePath)
{
Copy-Item -Path $SourcePath -Destination $DestinationPath
}
elseif (($SourcePath -as [System.URI]).AbsoluteURI -ne $null)
{
if (Test-Nano)
{
$handler = New-Object System.Net.Http.HttpClientHandler
$client = New-Object System.Net.Http.HttpClient($handler)
$client.Timeout = New-Object System.TimeSpan(0, 30, 0)
$cancelTokenSource = [System.Threading.CancellationTokenSource]::new()
$responseMsg = $client.GetAsync([System.Uri]::new($SourcePath), $cancelTokenSource.Token)
$responseMsg.Wait()
if (!$responseMsg.IsCanceled)
{
$response = $responseMsg.Result
if ($response.IsSuccessStatusCode)
{
$downloadedFileStream = [System.IO.FileStream]::new($DestinationPath, [System.IO.FileMode]::Create, [System.IO.FileAccess]::Write)
$copyStreamOp = $response.Content.CopyToAsync($downloadedFileStream)
$copyStreamOp.Wait()
$downloadedFileStream.Close()
if ($copyStreamOp.Exception -ne $null)
{
throw $copyStreamOp.Exception
}
}
}
}
elseif ($PSVersionTable.PSVersion.Major -ge 5)
{
#
# We disable progress display because it kills performance for large downloads (at least on 64-bit PowerShell)
#
$ProgressPreference = 'SilentlyContinue'
wget -Uri $SourcePath -OutFile $DestinationPath -UseBasicParsing
$ProgressPreference = 'Continue'
}
else
{
$webClient = New-Object System.Net.WebClient
$webClient.DownloadFile($SourcePath, $DestinationPath)
}
}
else
{
throw "Cannot copy from $SourcePath"
}
}
function
Expand-ArchiveNano
{
[CmdletBinding()]
param
(
[string] $Path,
[string] $DestinationPath
)
[System.IO.Compression.ZipFile]::ExtractToDirectory($Path, $DestinationPath)
}
function
Expand-ArchivePrivate
{
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true)]
[string]
$Path,
[Parameter(Mandatory=$true)]
[string]
$DestinationPath
)
$shell = New-Object -com Shell.Application
$zipFile = $shell.NameSpace($Path)
$shell.NameSpace($DestinationPath).CopyHere($zipFile.items())
}
function
Test-InstalledContainerImage
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]
[ValidateNotNullOrEmpty()]
$BaseImageName
)
$path = Join-Path (Join-Path $env:ProgramData "Microsoft\Windows\Images") "*$BaseImageName*"
return Test-Path $path
}
function
Test-Admin()
{
# Get the ID and security principal of the current user account
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
# Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
# Check to see if we are currently running "as Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole))
{
$global:AdminPriviledges = $true
return
}
else
{
#
# We are not running "as Administrator"
# Exit from the current, unelevated, process
#
throw "You must run this script as administrator"
}
}
function
Test-ContainerImageProvider()
{
if (-not (Get-Command Install-ContainerImage -ea SilentlyContinue))
{
Wait-Network
Write-Output "Installing ContainerImage provider..."
Install-PackageProvider ContainerImage -Force | Out-Null
}
if (-not (Get-Command Install-ContainerImage -ea SilentlyContinue))
{
throw "Could not install ContainerImage provider"
}
}
function
Test-Client()
{
return (-not ((Get-Command Get-WindowsFeature -ErrorAction SilentlyContinue) -or (Test-Nano)))
}
function
Test-Nano()
{
$EditionId = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name 'EditionID').EditionId
return (($EditionId -eq "ServerStandardNano") -or
($EditionId -eq "ServerDataCenterNano") -or
($EditionId -eq "NanoServer") -or
($EditionId -eq "ServerTuva"))
}
function
Wait-Network()
{
$connectedAdapter = Get-NetAdapter |? ConnectorPresent
if ($connectedAdapter -eq $null)
{
throw "No connected network"
}
$startTime = Get-Date
$timeElapsed = $(Get-Date) - $startTime
while ($($timeElapsed).TotalMinutes -lt 5)
{
$readyNetAdapter = $connectedAdapter |? Status -eq 'Up'
if ($readyNetAdapter -ne $null)
{
return;
}
Write-Output "Waiting for network connectivity..."
Start-Sleep -sec 5
$timeElapsed = $(Get-Date) - $startTime
}
throw "Network not connected after 5 minutes"
}
function
Get-DockerImages
{
return docker images
}
function
Find-DockerImages
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]
[ValidateNotNullOrEmpty()]
$BaseImageName
)
return docker images | Where { $_ -match $BaseImageName.tolower() }
}
function
Install-Docker()
{
[CmdletBinding()]
param(
[string]
[ValidateNotNullOrEmpty()]
$DockerPath = "https://aka.ms/tp5/docker",
[string]
[ValidateNotNullOrEmpty()]
$DockerDPath = "https://aka.ms/tp5/dockerd"
)
Test-Admin
Write-Output "Installing Docker..."
Copy-File -SourcePath $DockerPath -DestinationPath $env:windir\System32\docker.exe
Write-Output "Installing Docker daemon..."
Copy-File -SourcePath $DockerDPath -DestinationPath $env:windir\System32\dockerd.exe
#
# Register the docker service.
# Configuration options should be placed at %programdata%\docker\config\daemon.json
#
$daemonSettings = New-Object PSObject
$certsPath = Join-Path $global:DockerData "certs.d"
if (Test-Path $certsPath)
{
$daemonSettings | Add-Member NoteProperty hosts @("npipe://", "0.0.0.0:2376")
$daemonSettings | Add-Member NoteProperty tlsverify true
$daemonSettings | Add-Member NoteProperty tlscacert (Join-Path $certsPath "ca.pem")
$daemonSettings | Add-Member NoteProperty tlscert (Join-Path $certsPath "server-cert.pem")
$daemonSettings | Add-Member NoteProperty tlskey (Join-Path $certsPath "server-key.pem")
}
else
{
# Default local host
$daemonSettings | Add-Member NoteProperty hosts @("npipe://")
}
& dockerd --register-service --service-name $global:DockerServiceName
$daemonSettingsFile = "$global:DockerData\config\daemon.json"
$daemonSettings | ConvertTo-Json | Out-File -FilePath $daemonSettingsFile -Encoding ASCII
Start-Docker
#
# Waiting for docker to come to steady state
#
Wait-Docker
Write-Output "The following images are present on this machine:"
foreach ($image in (Get-DockerImages))
{
Write-Output " $image"
}
Write-Output ""
}
function
Start-Docker()
{
Start-Service -Name $global:DockerServiceName
}
function
Stop-Docker()
{
Stop-Service -Name $global:DockerServiceName
}
function
Test-Docker()
{
$service = Get-Service -Name $global:DockerServiceName -ErrorAction SilentlyContinue
return ($service -ne $null)
}
function
Wait-Docker()
{
Write-Output "Waiting for Docker daemon..."
$dockerReady = $false
$startTime = Get-Date
while (-not $dockerReady)
{
try
{
docker version | Out-Null
if (-not $?)
{
throw "Docker daemon is not running yet"
}
$dockerReady = $true
}
catch
{
$timeElapsed = $(Get-Date) - $startTime
if ($($timeElapsed).TotalMinutes -ge 1)
{
throw "Docker Daemon did not start successfully within 1 minute."
}
# Swallow error and try again
Start-Sleep -sec 1
}
}
Write-Output "Successfully connected to Docker Daemon."
}
function
Write-DockerImageTag()
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]
$BaseImageName
)
$dockerOutput = Find-DockerImages $BaseImageName
if ($dockerOutput.Count -gt 1)
{
Write-Output "Base image is already tagged:"
}
else
{
if ($dockerOutput.Count -lt 1)
{
#
# Docker restart required if the image was installed after Docker was
# last started
#
Stop-Docker
Start-Docker
$dockerOutput = Find-DockerImages $BaseImageName
if ($dockerOutput.Count -lt 1)
{
throw "Could not find Docker image to match '$BaseImageName'"
}
}
if ($dockerOutput.Count -gt 1)
{
Write-Output "Base image is already tagged:"
}
else
{
#
# Register the base image with Docker
#
$imageId = ($dockerOutput -split "\s+")[2]
Write-Output "Tagging new base image ($imageId)..."
docker tag $imageId "$($BaseImageName.tolower()):latest"
Write-Output "Base image is now tagged:"
$dockerOutput = Find-DockerImages $BaseImageName
}
}
Write-Output $dockerOutput
}
function
Get-Unattend
{
[CmdletBinding()]
param(
[string]
$Password
)
$unattendSource = [xml]@"
<?xml version="1.0" encoding="utf-8"?>
<unattend xmlns="urn:schemas-microsoft-com:unattend">
<servicing></servicing>
<settings pass="generalize">
<component name="Microsoft-Windows-PnpSysprep" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<PersistAllDeviceInstalls>true</PersistAllDeviceInstalls>
<DoNotCleanUpNonPresentDevices>true</DoNotCleanUpNonPresentDevices>
</component>
<component name="Microsoft-Windows-Security-SPP" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SkipRearm>1</SkipRearm>
</component>
</settings>"
<settings pass="specialize">
<component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<AutoLogon>
<Password>
<Value>$Password</Value>
<PlainText>true</PlainText>
</Password>
<Enabled>true</Enabled>
<LogonCount>999</LogonCount>
<Username>Administrator</Username>
</AutoLogon>
<ComputerName>*</ComputerName>
<ProductKey>2KNJJ-33Y9H-2GXGX-KMQWH-G6H67</ProductKey>
</component>
<component name="Microsoft-Windows-TerminalServices-LocalSessionManager" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<fDenyTSConnections>false</fDenyTSConnections>
</component>
<component name="Microsoft-Windows-TerminalServices-RDP-WinStationExtensions" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<UserAuthentication>0</UserAuthentication>
</component>
<component name="Networking-MPSSVC-Svc" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<FirewallGroups>
<FirewallGroup wcm:action="add" wcm:keyValue="RemoteDesktop">
<Active>true</Active>
<Profile>all</Profile>
<Group>@FirewallAPI.dll,-28752</Group>
</FirewallGroup>
</FirewallGroups>
</component>
</settings>
<settings pass="oobeSystem">
<component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<OOBE>
<HideEULAPage>true</HideEULAPage>
<HideLocalAccountScreen>true</HideLocalAccountScreen>
<HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE>
<NetworkLocation>Work</NetworkLocation>
<ProtectYourPC>1</ProtectYourPC>
</OOBE>
<UserAccounts>
<AdministratorPassword>
<Value>$Password</Value>
<PlainText>True</PlainText>
</AdministratorPassword>
</UserAccounts>
</component>
<component name="Microsoft-Windows-International-Core" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<InputLocale>en-us</InputLocale>
<SystemLocale>en-us</SystemLocale>
<UILanguage>en-us</UILanguage>
<UILanguageFallback>en-us</UILanguageFallback>
<UserLocale>en-us</UserLocale>
</component>
</settings>
</unattend>
"@
return $unattendSource
}
$global:MinimumWimSaveBuild = 10586
$global:MinimumPowerShellBuild = 10240
$global:MinimumSupportedBuild = 9600
function
Approve-Eula
{
$choiceList = New-Object System.Collections.ObjectModel.Collection[System.Management.Automation.Host.ChoiceDescription]
$choiceList.Add((New-Object "System.Management.Automation.Host.ChoiceDescription" -ArgumentList "&No"))
$choiceList.Add((New-Object "System.Management.Automation.Host.ChoiceDescription" -ArgumentList "&Yes"))
$eulaText = @"
Before installing and using the Windows Server Technical Preview 5 with Containers virtual machine you must:
1. Review the license terms by navigating to this link: https://aka.ms/tp5/containerseula
2. Print and retain a copy of the license terms for your records.
By downloading and using the Windows Technical Preview 5 with Containers virtual machine you agree to such license terms. Please confirm you have accepted and agree to the license terms.
"@
return [boolean]$Host.ui.PromptForChoice($null, $eulaText, $choiceList, 0)
}
function
Test-Version()
{
$os = Get-WmiObject -Class Win32_OperatingSystem
if ([int]($os.BuildNumber) -lt $global:MinimumSupportedBuild)
{
throw "This script is not supported. Upgrade to build $global:MinimumSupportedBuild or higher."
}
if ([int]($os.BuildNumber) -lt $global:MinimumPowerShellBuild)
{
Write-Warning "PowerShell Direct is not supported on this version of Windows."
$global:PowerShellDirectMode = $false
}
if ([int]($os.BuildNumber) -lt $global:MinimumWimSaveBuild)
{
Write-Warning "Save-ContainerImage is not supported on this version of Windows."
$global:WimSaveMode = $false
}
if (-not (Get-Module Hyper-V))
{
throw "Hyper-V must be enabled on this machine."
}
}
try
{
Test-Version
Test-Admin
if (-not $(Approve-Eula))
{
throw "Read and accept the EULA to continue."
}
New-ContainerHost
}
catch
{
Write-Error $_
}
| {
"content_hash": "13bc4c966e50bbc2a95b4d165f2f5591",
"timestamp": "",
"source": "github",
"line_count": 1491,
"max_line_length": 309,
"avg_line_length": 31.632461435278337,
"alnum_prop": 0.5936943431430752,
"repo_name": "larsiwer/Virtualization-Documentation",
"id": "57170797294a9b69eb1b904db8ab71ef0f2ce3a2",
"size": "47447",
"binary": false,
"copies": "4",
"ref": "refs/heads/live",
"path": "windows-server-container-tools/New-ContainerHost/New-ContainerHost.ps1",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PowerShell",
"bytes": "674585"
}
],
"symlink_target": ""
} |
package org.apache.hadoop.hive.ql.exec.vector.expressions.aggregates;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.vector.expressions.aggregates.VectorAggregateExpression;
import org.apache.hadoop.hive.ql.exec.vector.ColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.VectorAggregationBufferRow;
import org.apache.hadoop.hive.ql.exec.vector.VectorAggregationDesc;
import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch;
import org.apache.hadoop.hive.ql.exec.vector.Decimal64ColumnVector;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator.Mode;
import org.apache.hadoop.hive.ql.util.JavaDataModel;
import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable;
import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo;
/**
* VectorUDAFSumLong. Vectorized implementation for SUM aggregates.
*/
@Description(name = "sum",
value = "_FUNC_(expr) - Returns the sum value of expr (vectorized, type: decimal64 -> decimal64)")
public class VectorUDAFSumDecimal64 extends VectorAggregateExpression {
private static final long serialVersionUID = 1L;
/**
* class for storing the current aggregate value.
*/
private static final class Aggregation implements AggregationBuffer {
private static final long serialVersionUID = 1L;
transient private long sum;
/**
* Value is explicitly (re)initialized in reset()
*/
transient private boolean isNull = true;
transient private long outputDecimal64AbsMax;
transient private boolean isOverflowed = false;
public Aggregation(long outputDecimal64AbsMax) {
this.outputDecimal64AbsMax = outputDecimal64AbsMax;
}
public void sumValue(long value) {
if (isOverflowed) {
return;
}
if (isNull) {
sum = value;
isNull = false;
} else {
sum += value;
if (Math.abs(sum) > outputDecimal64AbsMax) {
isOverflowed = true;
}
}
}
// The isNull check and work has already been performed.
public void sumValueNoNullCheck(long value) {
sum += value;
if (Math.abs(sum) > outputDecimal64AbsMax) {
isOverflowed = true;
}
}
@Override
public int getVariableSize() {
throw new UnsupportedOperationException();
}
@Override
public void reset () {
isNull = true;
isOverflowed = false;
sum = 0;;
}
}
private DecimalTypeInfo outputDecimalTypeInfo;
private long outputDecimal64AbsMax;
// This constructor is used to momentarily create the object so match can be called.
public VectorUDAFSumDecimal64() {
super();
}
public VectorUDAFSumDecimal64(VectorAggregationDesc vecAggrDesc) {
super(vecAggrDesc);
init();
}
private void init() {
outputDecimalTypeInfo = (DecimalTypeInfo) outputTypeInfo;
outputDecimal64AbsMax =
HiveDecimalWritable.getDecimal64AbsMax(
outputDecimalTypeInfo.getPrecision());
}
private Aggregation getCurrentAggregationBuffer(
VectorAggregationBufferRow[] aggregationBufferSets,
int aggregateIndex,
int row) {
VectorAggregationBufferRow mySet = aggregationBufferSets[row];
Aggregation myagg = (Aggregation) mySet.getAggregationBuffer(aggregateIndex);
return myagg;
}
@Override
public void aggregateInputSelection(
VectorAggregationBufferRow[] aggregationBufferSets,
int aggregateIndex,
VectorizedRowBatch batch) throws HiveException {
int batchSize = batch.size;
if (batchSize == 0) {
return;
}
inputExpression.evaluate(batch);
Decimal64ColumnVector inputVector =
(Decimal64ColumnVector) batch.cols[
this.inputExpression.getOutputColumnNum()];
long[] vector = inputVector.vector;
if (inputVector.noNulls) {
if (inputVector.isRepeating) {
iterateNoNullsRepeatingWithAggregationSelection(
aggregationBufferSets, aggregateIndex,
vector[0], batchSize);
} else {
if (batch.selectedInUse) {
iterateNoNullsSelectionWithAggregationSelection(
aggregationBufferSets, aggregateIndex,
vector, batch.selected, batchSize);
} else {
iterateNoNullsWithAggregationSelection(
aggregationBufferSets, aggregateIndex,
vector, batchSize);
}
}
} else {
if (inputVector.isRepeating) {
iterateHasNullsRepeatingWithAggregationSelection(
aggregationBufferSets, aggregateIndex,
vector[0], batchSize, inputVector.isNull);
} else {
if (batch.selectedInUse) {
iterateHasNullsSelectionWithAggregationSelection(
aggregationBufferSets, aggregateIndex,
vector, batchSize, batch.selected, inputVector.isNull);
} else {
iterateHasNullsWithAggregationSelection(
aggregationBufferSets, aggregateIndex,
vector, batchSize, inputVector.isNull);
}
}
}
}
private void iterateNoNullsRepeatingWithAggregationSelection(
VectorAggregationBufferRow[] aggregationBufferSets,
int aggregateIndex,
long value,
int batchSize) {
for (int i=0; i < batchSize; ++i) {
Aggregation myagg = getCurrentAggregationBuffer(
aggregationBufferSets,
aggregateIndex,
i);
myagg.sumValue(value);
}
}
private void iterateNoNullsSelectionWithAggregationSelection(
VectorAggregationBufferRow[] aggregationBufferSets,
int aggregateIndex,
long[] values,
int[] selection,
int batchSize) {
for (int i=0; i < batchSize; ++i) {
Aggregation myagg = getCurrentAggregationBuffer(
aggregationBufferSets,
aggregateIndex,
i);
myagg.sumValue(values[selection[i]]);
}
}
private void iterateNoNullsWithAggregationSelection(
VectorAggregationBufferRow[] aggregationBufferSets,
int aggregateIndex,
long[] values,
int batchSize) {
for (int i=0; i < batchSize; ++i) {
Aggregation myagg = getCurrentAggregationBuffer(
aggregationBufferSets,
aggregateIndex,
i);
myagg.sumValue(values[i]);
}
}
private void iterateHasNullsRepeatingWithAggregationSelection(
VectorAggregationBufferRow[] aggregationBufferSets,
int aggregateIndex,
long value,
int batchSize,
boolean[] isNull) {
if (isNull[0]) {
return;
}
for (int i=0; i < batchSize; ++i) {
Aggregation myagg = getCurrentAggregationBuffer(
aggregationBufferSets,
aggregateIndex,
i);
myagg.sumValue(value);
}
}
private void iterateHasNullsSelectionWithAggregationSelection(
VectorAggregationBufferRow[] aggregationBufferSets,
int aggregateIndex,
long[] values,
int batchSize,
int[] selection,
boolean[] isNull) {
for (int j=0; j < batchSize; ++j) {
int i = selection[j];
if (!isNull[i]) {
Aggregation myagg = getCurrentAggregationBuffer(
aggregationBufferSets,
aggregateIndex,
j);
myagg.sumValue(values[i]);
}
}
}
private void iterateHasNullsWithAggregationSelection(
VectorAggregationBufferRow[] aggregationBufferSets,
int aggregateIndex,
long[] values,
int batchSize,
boolean[] isNull) {
for (int i=0; i < batchSize; ++i) {
if (!isNull[i]) {
Aggregation myagg = getCurrentAggregationBuffer(
aggregationBufferSets,
aggregateIndex,
i);
myagg.sumValue(values[i]);
}
}
}
@Override
public void aggregateInput(AggregationBuffer agg, VectorizedRowBatch batch)
throws HiveException {
inputExpression.evaluate(batch);
Decimal64ColumnVector inputVector =
(Decimal64ColumnVector) batch.cols[
this.inputExpression.getOutputColumnNum()];
int batchSize = batch.size;
if (batchSize == 0) {
return;
}
Aggregation myagg = (Aggregation)agg;
long[] vector = inputVector.vector;
if (inputVector.isRepeating) {
if (inputVector.noNulls || !inputVector.isNull[0]) {
if (myagg.isNull) {
myagg.isNull = false;
myagg.sum = 0;
}
myagg.sumValueNoNullCheck(vector[0]*batchSize);
}
return;
}
if (!batch.selectedInUse && inputVector.noNulls) {
iterateNoSelectionNoNulls(myagg, vector, batchSize);
}
else if (!batch.selectedInUse) {
iterateNoSelectionHasNulls(myagg, vector, batchSize, inputVector.isNull);
}
else if (inputVector.noNulls){
iterateSelectionNoNulls(myagg, vector, batchSize, batch.selected);
}
else {
iterateSelectionHasNulls(myagg, vector, batchSize, inputVector.isNull, batch.selected);
}
}
private void iterateSelectionHasNulls(
Aggregation myagg,
long[] vector,
int batchSize,
boolean[] isNull,
int[] selected) {
for (int j=0; j< batchSize; ++j) {
int i = selected[j];
if (!isNull[i]) {
long value = vector[i];
if (myagg.isNull) {
myagg.isNull = false;
myagg.sum = 0;
}
myagg.sumValueNoNullCheck(value);
}
}
}
private void iterateSelectionNoNulls(
Aggregation myagg,
long[] vector,
int batchSize,
int[] selected) {
if (myagg.isNull) {
myagg.sum = 0;
myagg.isNull = false;
}
for (int i=0; i< batchSize; ++i) {
long value = vector[selected[i]];
myagg.sumValueNoNullCheck(value);
}
}
private void iterateNoSelectionHasNulls(
Aggregation myagg,
long[] vector,
int batchSize,
boolean[] isNull) {
for(int i=0;i<batchSize;++i) {
if (!isNull[i]) {
long value = vector[i];
if (myagg.isNull) {
myagg.sum = 0;
myagg.isNull = false;
}
myagg.sumValueNoNullCheck(value);
}
}
}
private void iterateNoSelectionNoNulls(
Aggregation myagg,
long[] vector,
int batchSize) {
if (myagg.isNull) {
myagg.sum = 0;
myagg.isNull = false;
}
for (int i=0;i<batchSize;++i) {
long value = vector[i];
myagg.sumValueNoNullCheck(value);
}
}
@Override
public AggregationBuffer getNewAggregationBuffer() throws HiveException {
return new Aggregation(outputDecimal64AbsMax);
}
@Override
public void reset(AggregationBuffer agg) throws HiveException {
Aggregation myAgg = (Aggregation) agg;
myAgg.reset();
}
@Override
public long getAggregationBufferFixedSize() {
JavaDataModel model = JavaDataModel.get();
return JavaDataModel.alignUp(
model.object(),
model.memoryAlign());
}
@Override
public boolean matches(String name, ColumnVector.Type inputColVectorType,
ColumnVector.Type outputColVectorType, Mode mode) {
/*
* Sum input and output are DECIMAL_64.
*
* Any mode (PARTIAL1, PARTIAL2, FINAL, COMPLETE).
*/
return
name.equals("sum") &&
inputColVectorType == ColumnVector.Type.DECIMAL_64 &&
outputColVectorType == ColumnVector.Type.DECIMAL_64;
}
@Override
public void assignRowColumn(VectorizedRowBatch batch, int batchIndex, int columnNum,
AggregationBuffer agg) throws HiveException {
Decimal64ColumnVector outputColVector = (Decimal64ColumnVector) batch.cols[columnNum];
Aggregation myagg = (Aggregation) agg;
if (myagg.isNull || myagg.isOverflowed) {
outputColVector.noNulls = false;
outputColVector.isNull[batchIndex] = true;
return;
}
outputColVector.isNull[batchIndex] = false;
outputColVector.vector[batchIndex] = myagg.sum;
}
} | {
"content_hash": "ab4aa531472c2c681cf7cdf334b99c36",
"timestamp": "",
"source": "github",
"line_count": 436,
"max_line_length": 102,
"avg_line_length": 27.09633027522936,
"alnum_prop": 0.6627729812087354,
"repo_name": "alanfgates/hive",
"id": "7f2a18ab8eddec25241d49602cebaeaaa1475c76",
"size": "12619",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "ql/src/java/org/apache/hadoop/hive/ql/exec/vector/expressions/aggregates/VectorUDAFSumDecimal64.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "54376"
},
{
"name": "Batchfile",
"bytes": "845"
},
{
"name": "C",
"bytes": "28218"
},
{
"name": "C++",
"bytes": "45308"
},
{
"name": "CSS",
"bytes": "5157"
},
{
"name": "GAP",
"bytes": "172907"
},
{
"name": "HTML",
"bytes": "58711"
},
{
"name": "HiveQL",
"bytes": "7025058"
},
{
"name": "Java",
"bytes": "50295783"
},
{
"name": "JavaScript",
"bytes": "43855"
},
{
"name": "M4",
"bytes": "2276"
},
{
"name": "PHP",
"bytes": "148097"
},
{
"name": "PLSQL",
"bytes": "8724"
},
{
"name": "PLpgSQL",
"bytes": "311787"
},
{
"name": "Perl",
"bytes": "319842"
},
{
"name": "PigLatin",
"bytes": "12333"
},
{
"name": "Python",
"bytes": "406889"
},
{
"name": "Roff",
"bytes": "5379"
},
{
"name": "SQLPL",
"bytes": "4773"
},
{
"name": "Shell",
"bytes": "299376"
},
{
"name": "Thrift",
"bytes": "141153"
},
{
"name": "XSLT",
"bytes": "20199"
},
{
"name": "q",
"bytes": "608417"
}
],
"symlink_target": ""
} |
require 'minitest/autorun'
require 'semverb'
class TestSemveRB < MiniTest::Test
def setup
@starting_pwd = Dir.pwd
end
def teardown
Dir.chdir(@starting_pwd)
end
def test_find_version_rb
Dir.chdir('test/fixtures/version_rb')
r = SemveRB.find_rb_version_const
assert_equal(['lib/foo/version.rb', 2, '1.2.3', :version_rb], r)
end
def test_find_rb_version_const
Dir.chdir('test/fixtures/version_const')
r = SemveRB.find_rb_version_const
assert_equal(['lib/some_dir/some_file.rb', 3, '1.2.3', :version_const], r)
end
def test_find_gemspec_version_const
Dir.chdir('test/fixtures/gemspec_version_const')
r = SemveRB.find_gemspec_version_const
assert_equal(['lib/foo.rb', 2, '1.2.3', :gemspec_version_const], r)
end
def test_find_gemspec_version
Dir.chdir('test/fixtures/gemspec_version')
r = SemveRB.find_gemspec_version
assert_equal(['foo.gemspec', 3, '1.2.3', :gemspec_version], r)
end
end
| {
"content_hash": "25957fbaf9a17d1da363f93bb6275952",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 78,
"avg_line_length": 26.944444444444443,
"alnum_prop": 0.6742268041237114,
"repo_name": "lloeki/semverb",
"id": "12fb6a7223b52fde81be277b9ee9263acda9f812",
"size": "970",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/test_semverb.rb",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Ruby",
"bytes": "4559"
}
],
"symlink_target": ""
} |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin Developers
// Copyright (c) 2011-2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
// Why base-58 instead of standard base-64 encoding?
// - Don't want 0OIl characters that look the same in some fonts and
// could be used to create visually identical looking account numbers.
// - A string with non-alphanumeric characters is not as easily accepted as an account number.
// - E-mail usually won't line-break if there's no punctuation to break at.
// - Doubleclicking selects the whole number as one word if it's all alphanumeric.
//
#ifndef BITCOIN_BASE58_H
#define BITCOIN_BASE58_H
#include <string>
#include <vector>
#include "bignum.h"
#include "key.h"
#include "script.h"
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
// Encode a byte sequence as a base58-encoded string
inline std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
{
CAutoBN_CTX pctx;
CBigNum bn58 = 58;
CBigNum bn0 = 0;
// Convert big endian data to little endian
// Extra zero at the end make sure bignum will interpret as a positive number
std::vector<unsigned char> vchTmp(pend-pbegin+1, 0);
reverse_copy(pbegin, pend, vchTmp.begin());
// Convert little endian data to bignum
CBigNum bn;
bn.setvch(vchTmp);
// Convert bignum to std::string
std::string str;
// Expected size increase from base58 conversion is approximately 137%
// use 138% to be safe
str.reserve((pend - pbegin) * 138 / 100 + 1);
CBigNum dv;
CBigNum rem;
while (bn > bn0)
{
if (!BN_div(&dv, &rem, &bn, &bn58, pctx))
throw bignum_error("EncodeBase58 : BN_div failed");
bn = dv;
unsigned int c = rem.getulong();
str += pszBase58[c];
}
// Leading zeroes encoded as base58 zeros
for (const unsigned char* p = pbegin; p < pend && *p == 0; p++)
str += pszBase58[0];
// Convert little endian std::string to big endian
reverse(str.begin(), str.end());
return str;
}
// Encode a byte vector as a base58-encoded string
inline std::string EncodeBase58(const std::vector<unsigned char>& vch)
{
return EncodeBase58(&vch[0], &vch[0] + vch.size());
}
// Decode a base58-encoded string psz into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet)
{
CAutoBN_CTX pctx;
vchRet.clear();
CBigNum bn58 = 58;
CBigNum bn = 0;
CBigNum bnChar;
while (isspace(*psz))
psz++;
// Convert big endian string to bignum
for (const char* p = psz; *p; p++)
{
const char* p1 = strchr(pszBase58, *p);
if (p1 == NULL)
{
while (isspace(*p))
p++;
if (*p != '\0')
return false;
break;
}
bnChar.setulong(p1 - pszBase58);
if (!BN_mul(&bn, &bn, &bn58, pctx))
throw bignum_error("DecodeBase58 : BN_mul failed");
bn += bnChar;
}
// Get bignum as little endian data
std::vector<unsigned char> vchTmp = bn.getvch();
// Trim off sign byte if present
if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80)
vchTmp.erase(vchTmp.end()-1);
// Restore leading zeros
int nLeadingZeros = 0;
for (const char* p = psz; *p == pszBase58[0]; p++)
nLeadingZeros++;
vchRet.assign(nLeadingZeros + vchTmp.size(), 0);
// Convert little endian data to big endian
reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size());
return true;
}
// Decode a base58-encoded string str into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58(str.c_str(), vchRet);
}
// Encode a byte vector to a base58-encoded string, including checksum
inline std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
{
// add 4-byte hash check to the end
std::vector<unsigned char> vch(vchIn);
uint256 hash = Hash(vch.begin(), vch.end());
vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
return EncodeBase58(vch);
}
// Decode a base58-encoded string psz that includes a checksum, into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
{
if (!DecodeBase58(psz, vchRet))
return false;
if (vchRet.size() < 4)
{
vchRet.clear();
return false;
}
uint256 hash = Hash(vchRet.begin(), vchRet.end()-4);
if (memcmp(&hash, &vchRet.end()[-4], 4) != 0)
{
vchRet.clear();
return false;
}
vchRet.resize(vchRet.size()-4);
return true;
}
// Decode a base58-encoded string str that includes a checksum, into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58Check(str.c_str(), vchRet);
}
/** Base class for all base58-encoded data */
class CBase58Data
{
protected:
// the version byte
unsigned char nVersion;
// the actually encoded data
std::vector<unsigned char> vchData;
CBase58Data()
{
nVersion = 0;
vchData.clear();
}
~CBase58Data()
{
// zero the memory, as it may contain sensitive data
if (!vchData.empty())
memset(&vchData[0], 0, vchData.size());
}
void SetData(int nVersionIn, const void* pdata, size_t nSize)
{
nVersion = nVersionIn;
vchData.resize(nSize);
if (!vchData.empty())
memcpy(&vchData[0], pdata, nSize);
}
void SetData(int nVersionIn, const unsigned char *pbegin, const unsigned char *pend)
{
SetData(nVersionIn, (void*)pbegin, pend - pbegin);
}
public:
bool SetString(const char* psz)
{
std::vector<unsigned char> vchTemp;
DecodeBase58Check(psz, vchTemp);
if (vchTemp.empty())
{
vchData.clear();
nVersion = 0;
return false;
}
nVersion = vchTemp[0];
vchData.resize(vchTemp.size() - 1);
if (!vchData.empty())
memcpy(&vchData[0], &vchTemp[1], vchData.size());
memset(&vchTemp[0], 0, vchTemp.size());
return true;
}
bool SetString(const std::string& str)
{
return SetString(str.c_str());
}
std::string ToString() const
{
std::vector<unsigned char> vch(1, nVersion);
vch.insert(vch.end(), vchData.begin(), vchData.end());
return EncodeBase58Check(vch);
}
int CompareTo(const CBase58Data& b58) const
{
if (nVersion < b58.nVersion) return -1;
if (nVersion > b58.nVersion) return 1;
if (vchData < b58.vchData) return -1;
if (vchData > b58.vchData) return 1;
return 0;
}
bool operator==(const CBase58Data& b58) const { return CompareTo(b58) == 0; }
bool operator<=(const CBase58Data& b58) const { return CompareTo(b58) <= 0; }
bool operator>=(const CBase58Data& b58) const { return CompareTo(b58) >= 0; }
bool operator< (const CBase58Data& b58) const { return CompareTo(b58) < 0; }
bool operator> (const CBase58Data& b58) const { return CompareTo(b58) > 0; }
};
/** base58-encoded Bitcoin addresses.
* Public-key-hash-addresses have version 0 (or 111 testnet).
* The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
* Script-hash-addresses have version 5 (or 196 testnet).
* The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.
*/
class CBitcoinAddress;
class CBitcoinAddressVisitor : public boost::static_visitor<bool>
{
private:
CBitcoinAddress *addr;
public:
CBitcoinAddressVisitor(CBitcoinAddress *addrIn) : addr(addrIn) { }
bool operator()(const CKeyID &id) const;
bool operator()(const CScriptID &id) const;
bool operator()(const CNoDestination &no) const;
};
class CBitcoinAddress : public CBase58Data
{
public:
enum
{
PUBKEY_ADDRESS = 35, //Set the address first bit here
SCRIPT_ADDRESS = 5,
PUBKEY_ADDRESS_TEST = 111,
SCRIPT_ADDRESS_TEST = 196,
};
bool Set(const CKeyID &id) {
SetData(fTestNet ? PUBKEY_ADDRESS_TEST : PUBKEY_ADDRESS, &id, 20);
return true;
}
bool Set(const CScriptID &id) {
SetData(fTestNet ? SCRIPT_ADDRESS_TEST : SCRIPT_ADDRESS, &id, 20);
return true;
}
bool Set(const CTxDestination &dest)
{
return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);
}
bool IsValid() const
{
unsigned int nExpectedSize = 20;
bool fExpectTestNet = false;
switch(nVersion)
{
case PUBKEY_ADDRESS:
nExpectedSize = 20; // Hash of public key
fExpectTestNet = false;
break;
case SCRIPT_ADDRESS:
nExpectedSize = 20; // Hash of CScript
fExpectTestNet = false;
break;
case PUBKEY_ADDRESS_TEST:
nExpectedSize = 20;
fExpectTestNet = true;
break;
case SCRIPT_ADDRESS_TEST:
nExpectedSize = 20;
fExpectTestNet = true;
break;
default:
return false;
}
return fExpectTestNet == fTestNet && vchData.size() == nExpectedSize;
}
CBitcoinAddress()
{
}
CBitcoinAddress(const CTxDestination &dest)
{
Set(dest);
}
CBitcoinAddress(const std::string& strAddress)
{
SetString(strAddress);
}
CBitcoinAddress(const char* pszAddress)
{
SetString(pszAddress);
}
CTxDestination Get() const {
if (!IsValid())
return CNoDestination();
switch (nVersion) {
case PUBKEY_ADDRESS:
case PUBKEY_ADDRESS_TEST: {
uint160 id;
memcpy(&id, &vchData[0], 20);
return CKeyID(id);
}
case SCRIPT_ADDRESS:
case SCRIPT_ADDRESS_TEST: {
uint160 id;
memcpy(&id, &vchData[0], 20);
return CScriptID(id);
}
}
return CNoDestination();
}
bool GetKeyID(CKeyID &keyID) const {
if (!IsValid())
return false;
switch (nVersion) {
case PUBKEY_ADDRESS:
case PUBKEY_ADDRESS_TEST: {
uint160 id;
memcpy(&id, &vchData[0], 20);
keyID = CKeyID(id);
return true;
}
default: return false;
}
}
bool IsScript() const {
if (!IsValid())
return false;
switch (nVersion) {
case SCRIPT_ADDRESS:
case SCRIPT_ADDRESS_TEST: {
return true;
}
default: return false;
}
}
};
bool inline CBitcoinAddressVisitor::operator()(const CKeyID &id) const { return addr->Set(id); }
bool inline CBitcoinAddressVisitor::operator()(const CScriptID &id) const { return addr->Set(id); }
bool inline CBitcoinAddressVisitor::operator()(const CNoDestination &id) const { return false; }
/** A base58-encoded secret key */
class CBitcoinSecret : public CBase58Data
{
public:
enum
{
PRIVKEY_ADDRESS = CBitcoinAddress::PUBKEY_ADDRESS + 128,
PRIVKEY_ADDRESS_TEST = CBitcoinAddress::PUBKEY_ADDRESS_TEST + 128,
};
void SetSecret(const CSecret& vchSecret, bool fCompressed)
{
assert(vchSecret.size() == 32);
SetData(fTestNet ? PRIVKEY_ADDRESS_TEST : PRIVKEY_ADDRESS, &vchSecret[0], vchSecret.size());
if (fCompressed)
vchData.push_back(1);
}
CSecret GetSecret(bool &fCompressedOut)
{
CSecret vchSecret;
vchSecret.resize(32);
memcpy(&vchSecret[0], &vchData[0], 32);
fCompressedOut = vchData.size() == 33;
return vchSecret;
}
bool IsValid() const
{
bool fExpectTestNet = false;
switch(nVersion)
{
case PRIVKEY_ADDRESS:
break;
case PRIVKEY_ADDRESS_TEST:
fExpectTestNet = true;
break;
default:
return false;
}
return fExpectTestNet == fTestNet && (vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1));
}
bool SetString(const char* pszSecret)
{
return CBase58Data::SetString(pszSecret) && IsValid();
}
bool SetString(const std::string& strSecret)
{
return SetString(strSecret.c_str());
}
CBitcoinSecret(const CSecret& vchSecret, bool fCompressed)
{
SetSecret(vchSecret, fCompressed);
}
CBitcoinSecret()
{
}
};
#endif
| {
"content_hash": "6c9e7ed2498939d3b2e8d01c2aa22ba8",
"timestamp": "",
"source": "github",
"line_count": 467,
"max_line_length": 114,
"avg_line_length": 28.325481798715202,
"alnum_prop": 0.6024342304203205,
"repo_name": "cagecoin-project/cagecoin",
"id": "6e8fcc6b786ca11180c8f8ebae10066584437435",
"size": "13228",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/base58.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "78622"
},
{
"name": "C++",
"bytes": "1371273"
},
{
"name": "IDL",
"bytes": "10956"
},
{
"name": "Objective-C",
"bytes": "2463"
},
{
"name": "Python",
"bytes": "47538"
},
{
"name": "Shell",
"bytes": "1402"
},
{
"name": "TypeScript",
"bytes": "3810608"
}
],
"symlink_target": ""
} |
/* Alloc.c -- Memory allocation functions
2008-09-24
Igor Pavlov
Public domain */
#ifdef _WIN32
#include <windows.h>
#endif
#include <stdlib.h>
#include "7zMyAlloc.h"
/* #define _SZ_ALLOC_DEBUG */
/* use _SZ_ALLOC_DEBUG to debug alloc/free operations */
#ifdef _SZ_ALLOC_DEBUG
#include <stdio.h>
int g_allocCount = 0;
int g_allocCountMid = 0;
int g_allocCountBig = 0;
#endif
void *MyAlloc(size_t size)
{
if (size == 0)
return 0;
#ifdef _SZ_ALLOC_DEBUG
{
void *p = malloc(size);
OutputDebugString("\nAlloc %10d bytes, count = %10d, addr = %8X", size, g_allocCount++, (unsigned)p);
return p;
}
#else
return malloc(size);
#endif
}
void MyFree(void *address)
{
#ifdef _SZ_ALLOC_DEBUG
if (address != 0)
OutputDebugString("\nFree; count = %10d, addr = %8X", --g_allocCount, (unsigned)address);
#endif
free(address);
}
#ifdef _WIN32
void *MidAlloc(size_t size)
{
if (size == 0)
return 0;
#ifdef _SZ_ALLOC_DEBUG
OutputDebugString("\nAlloc_Mid %10d bytes; count = %10d", size, g_allocCountMid++);
#endif
return VirtualAlloc(0, size, MEM_COMMIT, PAGE_READWRITE);
}
void MidFree(void *address)
{
#ifdef _SZ_ALLOC_DEBUG
if (address != 0)
OutputDebugString("\nFree_Mid; count = %10d", --g_allocCountMid);
#endif
if (address == 0)
return;
VirtualFree(address, 0, MEM_RELEASE);
}
#ifndef MEM_LARGE_PAGES
#undef _7ZIP_LARGE_PAGES
#endif
#ifdef _7ZIP_LARGE_PAGES
SIZE_T g_LargePageSize = 0;
typedef SIZE_T (WINAPI *GetLargePageMinimumP)();
#endif
void SetLargePageSize()
{
#ifdef _7ZIP_LARGE_PAGES
SIZE_T size = 0;
GetLargePageMinimumP largePageMinimum = (GetLargePageMinimumP)
GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetLargePageMinimum");
if (largePageMinimum == 0)
return;
size = largePageMinimum();
if (size == 0 || (size & (size - 1)) != 0)
return;
g_LargePageSize = size;
#endif
}
void *BigAlloc(size_t size)
{
if (size == 0)
return 0;
#ifdef _SZ_ALLOC_DEBUG
OutputDebugString("\nAlloc_Big %10d bytes; count = %10d", size, g_allocCountBig++);
#endif
#ifdef _7ZIP_LARGE_PAGES
if (g_LargePageSize != 0 && g_LargePageSize <= (1 << 30) && size >= (1 << 18))
{
void *res = VirtualAlloc(0, (size + g_LargePageSize - 1) & (~(g_LargePageSize - 1)),
MEM_COMMIT | MEM_LARGE_PAGES, PAGE_READWRITE);
if (res != 0)
return res;
}
#endif
return VirtualAlloc(0, size, MEM_COMMIT, PAGE_READWRITE);
}
void BigFree(void *address)
{
#ifdef _SZ_ALLOC_DEBUG
if (address != 0)
OutputDebugString("\nFree_Big; count = %10d", --g_allocCountBig);
#endif
if (address == 0)
return;
VirtualFree(address, 0, MEM_RELEASE);
}
#endif
| {
"content_hash": "93812b4302b57370dbbf34b7e39b4e28",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 106,
"avg_line_length": 21.20472440944882,
"alnum_prop": 0.6476049015967322,
"repo_name": "AllegianceZone/Allegiance",
"id": "2df95c735b1fcf8580bf85fa6313a29b08405b3f",
"size": "2693",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/zlib/7zMyAlloc.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "26927"
},
{
"name": "Batchfile",
"bytes": "20387"
},
{
"name": "C",
"bytes": "3213698"
},
{
"name": "C++",
"bytes": "11383849"
},
{
"name": "CSS",
"bytes": "1905"
},
{
"name": "HTML",
"bytes": "369500"
},
{
"name": "JavaScript",
"bytes": "125561"
},
{
"name": "Makefile",
"bytes": "9519"
},
{
"name": "Objective-C",
"bytes": "41562"
},
{
"name": "Perl",
"bytes": "3074"
},
{
"name": "PigLatin",
"bytes": "250645"
},
{
"name": "Roff",
"bytes": "5275"
},
{
"name": "Visual Basic",
"bytes": "7253"
},
{
"name": "XSLT",
"bytes": "19495"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.