text stringlengths 2 1.04M | meta dict |
|---|---|
title: Staart Site
repo: staart/site
homepage: https://staart.js.org/site
language:
- JavaScript
- TypeScript
license:
- MIT
templates:
- Handlebars
description: SSG for docs that creates ultra-lightweight, 100/100 Lighthouse websites
---
## About Staart Site
Staart Site is a static site generator for helpdesk or documentation websites written in TypeScript. It creates beautiful, accessible, and ultra-lightweight websites that score 100/100 on Lightbox.
It has no configuration required (deploys Markdown files from your `content` folder), including "last modified in commit" links to GitHub. Also generates schema data for SEO, sitemaps, and Shields badges schema. It's incredibly lightweight, at just 1.2kb minzipped CSS for both light and dark themes.
Staart Site is part of [Staart](https://staart.js.org), a set of starter templates written in TypeScript to build SaaS startups, including backend, PWA, and app starters.
| {
"content_hash": "77a27c50e1376bc8ea93e1d5b2c0c2de",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 300,
"avg_line_length": 47.1,
"alnum_prop": 0.7855626326963907,
"repo_name": "netlify/staticgen",
"id": "5f530064a1da1666ee43ac1986fdc6d59fe9a720",
"size": "946",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "content/projects/staart-site.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "49213"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_102) on Tue Nov 29 08:49:19 EST 2016 -->
<title>Deprecated List</title>
<meta name="date" content="2016-11-29">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Deprecated List";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="overview-tree.html">Tree</a></li>
<li class="navBarCell1Rev">Deprecated</li>
<li><a href="index-files/index-1.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?deprecated-list.html" target="_top">Frames</a></li>
<li><a href="deprecated-list.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Deprecated API" class="title">Deprecated API</h1>
<h2 title="Contents">Contents</h2>
<ul>
<li><a href="#field">Deprecated Fields</a></li>
<li><a href="#method">Deprecated Methods</a></li>
</ul>
</div>
<div class="contentContainer"><a name="field">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<table class="deprecatedSummary" border="0" cellpadding="3" cellspacing="0" summary="Deprecated Fields table, listing deprecated fields, and an explanation">
<caption><span>Deprecated Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Field and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="dml/team5/antlr/PLSQLParser.html#tokenNames">dml.team5.antlr.PLSQLParser.tokenNames</a>
<div class="block"><span class="deprecationComment">Use <a href="dml/team5/antlr/PLSQLParser.html#VOCABULARY"><code>PLSQLParser.VOCABULARY</code></a> instead.</span></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="dml/team5/antlr/PLSQLLexer.html#tokenNames">dml.team5.antlr.PLSQLLexer.tokenNames</a>
<div class="block"><span class="deprecationComment">Use <a href="dml/team5/antlr/PLSQLLexer.html#VOCABULARY"><code>PLSQLLexer.VOCABULARY</code></a> instead.</span></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="dml/team5/antlr/ModifiedPLSQLParser.html#tokenNames">dml.team5.antlr.ModifiedPLSQLParser.tokenNames</a>
<div class="block"><span class="deprecationComment">Use <a href="dml/team5/antlr/ModifiedPLSQLParser.html#VOCABULARY"><code>ModifiedPLSQLParser.VOCABULARY</code></a> instead.</span></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="dml/team5/antlr/ModifiedPLSQLLexer.html#tokenNames">dml.team5.antlr.ModifiedPLSQLLexer.tokenNames</a>
<div class="block"><span class="deprecationComment">Use <a href="dml/team5/antlr/ModifiedPLSQLLexer.html#VOCABULARY"><code>ModifiedPLSQLLexer.VOCABULARY</code></a> instead.</span></div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
<a name="method">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<table class="deprecatedSummary" border="0" cellpadding="3" cellspacing="0" summary="Deprecated Methods table, listing deprecated methods, and an explanation">
<caption><span>Deprecated Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="dml/team5/antlr/PLSQLParser.html#getTokenNames--">dml.team5.antlr.PLSQLParser.getTokenNames()</a></td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="dml/team5/antlr/PLSQLLexer.html#getTokenNames--">dml.team5.antlr.PLSQLLexer.getTokenNames()</a></td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="dml/team5/antlr/ModifiedPLSQLParser.html#getTokenNames--">dml.team5.antlr.ModifiedPLSQLParser.getTokenNames()</a></td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="dml/team5/antlr/ModifiedPLSQLLexer.html#getTokenNames--">dml.team5.antlr.ModifiedPLSQLLexer.getTokenNames()</a></td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="overview-tree.html">Tree</a></li>
<li class="navBarCell1Rev">Deprecated</li>
<li><a href="index-files/index-1.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?deprecated-list.html" target="_top">Frames</a></li>
<li><a href="deprecated-list.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "858f5720b2d912677d93c3da829293a2",
"timestamp": "",
"source": "github",
"line_count": 191,
"max_line_length": 187,
"avg_line_length": 34.324607329842934,
"alnum_prop": 0.6728187919463087,
"repo_name": "Dyndrilliac/cop-4710-assignments",
"id": "b8c01b876d5a96a683767fa4b76284069d2332f0",
"size": "6556",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Documentation/Javadoc API Reference/deprecated-list.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ANTLR",
"bytes": "179823"
},
{
"name": "Java",
"bytes": "6193677"
}
],
"symlink_target": ""
} |
module HTTP
class Response
# A Body class that wraps an IO, rather than a the client
# object.
class IoBody
include Enumerable
extend Forwardable
# @return [String,nil] the next `size` octets part of the
# body, or nil if whole body has already been read.
def readpartial(size = HTTP::Connection::BUFFER_SIZE)
stream!
return nil if stream.eof?
stream.readpartial(size)
end
# Iterate over the body, allowing it to be enumerable
def each
while (part = readpartial)
yield part
end
end
# @return [String] eagerly consume the entire body as a string
def to_s
@contents ||= readall
end
alias_method :to_str, :to_s
def_delegator :to_s, :empty?
# Assert that the body is actively being streamed
def stream!
fail StateError, "body has already been consumed" if @streaming == false
@streaming = true
end
# Easier to interpret string inspect
def inspect
"#<#{self.class}:#{object_id.to_s(16)} @streaming=#{!!@streaming}>"
end
protected
def initialize(an_io)
@streaming = nil
@stream = an_io
end
attr_reader :contents, :stream
def readall
fail StateError, "body is being streamed" unless @streaming.nil?
@streaming = false
"".tap do |buf|
buf << stream.read until stream.eof?
end
end
end
end
end
| {
"content_hash": "ef2552bf9350b208d73faef8f0304e3e",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 80,
"avg_line_length": 24,
"alnum_prop": 0.5866402116402116,
"repo_name": "moneyadviceservice/http.rb",
"id": "2176a33ec62e93e8f406e1489acd9e48c355ecaf",
"size": "1512",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/http/response/io_body.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "175277"
}
],
"symlink_target": ""
} |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/devtools/clouderrorreporting/v1beta1/error_group_service.proto
package com.google.devtools.clouderrorreporting.v1beta1;
public interface UpdateGroupRequestOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.devtools.clouderrorreporting.v1beta1.UpdateGroupRequest)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* [Required] The group which replaces the resource on the server.
* </pre>
*
* <code>.google.devtools.clouderrorreporting.v1beta1.ErrorGroup group = 1;</code>
*/
boolean hasGroup();
/**
*
*
* <pre>
* [Required] The group which replaces the resource on the server.
* </pre>
*
* <code>.google.devtools.clouderrorreporting.v1beta1.ErrorGroup group = 1;</code>
*/
com.google.devtools.clouderrorreporting.v1beta1.ErrorGroup getGroup();
/**
*
*
* <pre>
* [Required] The group which replaces the resource on the server.
* </pre>
*
* <code>.google.devtools.clouderrorreporting.v1beta1.ErrorGroup group = 1;</code>
*/
com.google.devtools.clouderrorreporting.v1beta1.ErrorGroupOrBuilder getGroupOrBuilder();
}
| {
"content_hash": "b0ee83dfa9640d63ee9f293e4f17492c",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 113,
"avg_line_length": 29.634146341463413,
"alnum_prop": 0.7053497942386832,
"repo_name": "vam-google/google-cloud-java",
"id": "b6b94f545e0f33d1f39fc06778645286a6d6cc3c",
"size": "1215",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "google-api-grpc/proto-google-cloud-error-reporting-v1beta1/src/main/java/com/google/devtools/clouderrorreporting/v1beta1/UpdateGroupRequestOrBuilder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "128"
},
{
"name": "CSS",
"bytes": "23036"
},
{
"name": "Dockerfile",
"bytes": "127"
},
{
"name": "Go",
"bytes": "9641"
},
{
"name": "HTML",
"bytes": "16158"
},
{
"name": "Java",
"bytes": "47356483"
},
{
"name": "JavaScript",
"bytes": "989"
},
{
"name": "Python",
"bytes": "110799"
},
{
"name": "Shell",
"bytes": "9162"
}
],
"symlink_target": ""
} |
/*
* DeleteCellStateOJ.java
*/
package oj.processor.state;
import ij.gui.ImageCanvas;
import java.awt.Cursor;
import java.awt.Event;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import oj.OJ;
import oj.project.CellOJ;
import oj.project.LocationOJ;
import oj.project.YtemOJ;
import oj.graphics.CustomCanvasOJ;
import oj.gui.ShortcutManagerOJ;
import oj.plugin.GlassWindowOJ;
import oj.processor.ToolStateProcessorOJ;
public class DeleteCellStateOJ extends ToolStateAdaptorOJ {
private enum Mode {
CELL, YTEM, POINT
}
private Mode stateMode = Mode.CELL;
private boolean exDeleteCellMode = false;
Toolkit tk = Toolkit.getDefaultToolkit();
private Cursor deleteCellCursor = tk.createCustomCursor(tk.createImage(getClass().getResource("/oj/processor/state/resources/DeleteCellCursor32.png")), new Point(9, 13), "Delete Cell");
private Cursor deletePointCursor = tk.createCustomCursor(tk.createImage(getClass().getResource("/oj/processor/state/resources/DeletePointCursor32.png")), new Point(9, 13), "Delete Cell");
private Cursor deleteYtemCursor = tk.createCustomCursor(tk.createImage(getClass().getResource("/oj/processor/state/resources/DeleteYtemCursor32.png")), new Point(9, 13), "Delete Cell");
public DeleteCellStateOJ() {
setCanvasCursor();
}
public int getToolState() {
return ToolStateProcessorOJ.STATE_OBJECT_TOOL;
}
public void mousePressed(String imageName, int sliceNo, double x, double y, int flags) {
super.mousePressed(imageName, sliceNo, x, y, flags);
int imgIndex = OJ.getData().getImages().getIndexOfImage(imageName);
Object[] closestPt = OJ.getData().getCells().closestPoint(imgIndex, x, y, sliceNo);
CellOJ cell = (CellOJ) closestPt[0];
YtemOJ ytm = (YtemOJ) closestPt[1];
LocationOJ loc = (LocationOJ) closestPt[2];
if (loc != null) {
double dd = ((Double) closestPt[3]).doubleValue();//distance mouse to point in pixels: not used here
int cell_index = OJ.getData().getCells().indexOfCell(cell);
int ytem_index = cell.indexOfYtem(ytm);
int location_index = ytm.indexOf(loc);
updateState(flags);
if (ytm.getLocationsCount() == 1 && stateMode == Mode.POINT) {//27.9.2009
stateMode = Mode.YTEM;
}
if (cell.getYtemsCount() == 1 && stateMode == Mode.YTEM) {
stateMode = Mode.CELL;
}
switch (stateMode) {
case YTEM:
OJ.getDataProcessor().removeYtemByIndex(cell, ytem_index);
break;
case POINT:
OJ.getDataProcessor().removeLocation(ytm, location_index);
break;
default:
OJ.getDataProcessor().removeCellByIndex(cell_index);
}
}
setCanvasCursor();
}
public void mouseEntered(String imageName, int stackIndex, double x, double y, int flags) {
super.mouseEntered(imageName, stackIndex, x, y, flags);
setCanvasCursor();
}
public void keyPressed(String imageName, int stackIndex, int keyCode, int flags) {
//ij.IJ.log("entering: keycode ="+keyCode + " flags="+flags);
if (((flags & Event.SHIFT_MASK) == 0) && ((flags & Event.ALT_MASK) != 0)) {
stateMode = Mode.POINT;
} else if (((flags & Event.SHIFT_MASK) != 0) && ((flags & Event.ALT_MASK) == 0)) {
stateMode = Mode.YTEM;
} else {
stateMode = Mode.CELL;
}
if (keyCode == KeyEvent.VK_D) {
exDeleteCellMode = true;
}
setCanvasCursor();
}
public void keyReleased(String imageName, int stackIndex, int keyCode, int flags) {
//ij.IJ.log("exiting: keycode ="+keyCode + " flags="+flags);
stateMode = Mode.CELL;
if (keyCode == KeyEvent.VK_D) {
exDeleteCellMode = false;
}
setCanvasCursor();
}
public Cursor getDefaultCursor() {
return deleteCellCursor;
}
public boolean isExDeleteCellMode() {
return exDeleteCellMode;
}
private void updateState(int flags) {
// boolean isShift = ShortcutManagerOJ.getInstance().isShiftPressed();//didn't work on Windows 21.6.2009
// boolean isAlt = ShortcutManagerOJ.getInstance().isAltPressed();
boolean isShift = (flags & KeyEvent.SHIFT_MASK) != 0;
boolean isAlt = (flags & KeyEvent.ALT_MASK) != 0;
// ij.IJ.log("updateState: shift = " + isShift);
// ij.IJ.log("updateState: alt = " + isAlt);
if (isShift && !isAlt) {
stateMode = Mode.YTEM;
} else if (!isShift && isAlt) {
stateMode = Mode.POINT;
} else {
stateMode = Mode.CELL;
}
setCanvasCursor();
}
private void setCanvasCursor() {
ImageCanvas ic = getCanvas();
Cursor cursor = null;
if ((ic != null) && (ic instanceof CustomCanvasOJ)) {
if (ic instanceof CustomCanvasOJ) {
if (ij.IJ.isMacOSX()) {//keypressed does not work yet on Windows
switch (stateMode) {
case YTEM:
cursor = deleteYtemCursor;
break;
case POINT:
cursor = deletePointCursor;
break;
default:
cursor = deleteCellCursor;
}
} else {
cursor = deleteCellCursor;
ic.setCursor(deleteCellCursor);
}
} else {
cursor = Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR);
ic.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
}
}
if (cursor != null) {
ic.setCursor(cursor);
if (GlassWindowOJ.exists()) {
GlassWindowOJ.getInstance().setCursor(cursor);
}
}
}
}
| {
"content_hash": "42fc42d652d201fa45437a1c2c348435",
"timestamp": "",
"source": "github",
"line_count": 173,
"max_line_length": 191,
"avg_line_length": 37.3757225433526,
"alnum_prop": 0.551809464893288,
"repo_name": "steliann/objectj",
"id": "27ce029520fe4bbbca9dfbc8f9297e266722d081",
"size": "6466",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/oj/processor/state/DeleteCellStateOJ.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2099"
},
{
"name": "Java",
"bytes": "5585426"
}
],
"symlink_target": ""
} |
package gov.nih.nci.iso21090.grid.dto.transform.iso;
import static org.junit.Assert.assertEquals;
import gov.nih.nci.iso21090.EntityNamePartQualifier;
import gov.nih.nci.iso21090.EntityNamePartType;
import gov.nih.nci.iso21090.Enxp;
import gov.nih.nci.iso21090.grid.dto.transform.AbstractTransformerTestBase;
import java.util.HashSet;
public class ENXPTransformerTest extends AbstractTransformerTestBase<ENXPTransformer, org.iso._21090.ENXP, Enxp>{
@Override
public Enxp makeDtoSimple() {
Enxp dto = new Enxp(EntityNamePartType.DEL);
dto.setCode("code");
dto.setCodeSystem("code string");
dto.setCodeSystemVersion("codeSystemVersion");
dto.setValue("value");
dto.setQualifier(new HashSet<EntityNamePartQualifier>());
dto.getQualifier().add(EntityNamePartQualifier.AC);
dto.getQualifier().add(EntityNamePartQualifier.AD);
return dto;
}
@Override
public org.iso._21090.ENXP makeXmlSimple() {
org.iso._21090.ENXP xml = new org.iso._21090.ENXP();
xml.setType(org.iso._21090.EntityNamePartType.DEL);
xml.setCode("code");
xml.setCodeSystem("code string");
xml.setCodeSystemVersion("codeSystemVersion");
xml.setValue("value");
xml.getQualifiers().add(org.iso._21090.EntityNamePartQualifier.AC);
xml.getQualifiers().add(org.iso._21090.EntityNamePartQualifier.AD);
return xml;
}
@Override
public void verifyDtoSimple(Enxp x) {
assertEquals(x.getCode(), "code");
assertEquals(x.getCodeSystem(), "code string");
assertEquals(x.getCodeSystemVersion(), "codeSystemVersion");
assertEquals(x.getValue(), "value");
assertEquals(x.getQualifier().size(), 2);
}
@Override
public void verifyXmlSimple(org.iso._21090.ENXP x) {
assertEquals(x.getCode(), "code");
assertEquals(x.getCodeSystem(), "code string");
assertEquals(x.getCodeSystemVersion(), "codeSystemVersion");
assertEquals(x.getValue(), "value");
assertEquals(x.getQualifiers().size(), 2);
}
}
| {
"content_hash": "184686b24e07ac7d5bb0a5e72a809219",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 113,
"avg_line_length": 36.41379310344828,
"alnum_prop": 0.6818181818181818,
"repo_name": "NCIP/iso21090",
"id": "aaf0331ff75fbe5e3f488bb1446085d978fe2352",
"size": "2590",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "code/extensions/src/test/java/gov/nih/nci/iso21090/grid/dto/transform/iso/ENXPTransformerTest.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "599566"
},
{
"name": "XSLT",
"bytes": "20640"
}
],
"symlink_target": ""
} |
jsio('import Class, bind, jsio.logging, jsio.interfaces');
var logger = jsio.logging.getLogger('env.browser.tcp')
exports.Connector = Class(jsio.interfaces.Connector, function() {
this.connect = function() {
var conn = new Orbited.TCPSocket();
conn.onopen = bind(this, function() {
this.onConnect(new Transport(conn));
});
conn.open(this._opts.hostname, this._opts.port);
}
});
var Transport = Class(jsio.interfaces.Transport, function() {
this.init = function(socket) {
this._socket = socket;
};
this.makeConnection = function(protocol) {
this._socket.onread = bind(protocol, 'dataReceived');
this._socket.onclose = bind(protocol, 'connectionLost'); // TODO: map error codes
}
this.write = function(data, encoding) {
this._socket.send(data);
};
this.loseConnection = function() {
this._socket.close();
};
});
| {
"content_hash": "46edcdd60040ece3b00b15bdeaccee29",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 89,
"avg_line_length": 27.441176470588236,
"alnum_prop": 0.6237942122186495,
"repo_name": "mokshaproject/moksha",
"id": "0dfca23d9ada6498cab79197855c318e348a3811",
"size": "933",
"binary": false,
"copies": "2",
"ref": "refs/heads/dev",
"path": "moksha.wsgi/moksha/wsgi/widgets/api/amqp/static/jsio/env/browser/tcp.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "21145"
},
{
"name": "HTML",
"bytes": "11953"
},
{
"name": "JavaScript",
"bytes": "590544"
},
{
"name": "Makefile",
"bytes": "18249"
},
{
"name": "Python",
"bytes": "257694"
},
{
"name": "Shell",
"bytes": "4088"
}
],
"symlink_target": ""
} |
using MarketData
facts("type constructors enforce invariants") do
context("unequal length between values and timestamp fails") do
@fact_throws TimeArray(cl.timestamp, cl.values[2:end], ["Close"])
end
context("unequal length between colnames and array width fails") do
@fact_throws TimeArray(cl.timestamp, cl.values, ["Close", "Open"])
end
context("duplicate timestamp values fails") do
@fact_throws TimeArray(dupestamp, push!(cl.values, cl.values[1]), ["Close"])
end
context("mangled order of timestamp values fails") do
@fact_throws TimeArray(mangstamp, push!(cl.values, cl.values[1]), ["Close"])
end
context("flipping occurs when needed") do
@fact TimeArray(flipud(cl.timestamp), flipud(cl.values), ["Close"]).timestamp[1] => firstday
@fact TimeArray(flipud(cl.timestamp), flipud(cl.values), ["Close"]).values[1] => 105.22
end
end
facts("getindex methods") do
context("getindex on single Int and DateTime") do
@fact ohlc[1].timestamp => [firstday]
@fact ohlc[firstday].timestamp => [firstday]
end
context("getindex on array of Int and DateTime") do
@fact ohlc[[1,10]].timestamp => [firstday, tenthday]
@fact ohlc[[firstday,tenthday]].timestamp => [firstday, tenthday]
end
context("getindex on range of Int and DateTime") do
@fact ohlc[1:2].timestamp => [firstday, secondday]
@fact ohlc[firstday:days(1):secondday].timestamp => [firstday, secondday]
end
context("getindex on single column name") do
@fact size(ohlc["Open"].values, 2) => 1
@fact size(ohlc["Open"][firstday:days(1):tenthday].values, 1) => 10
end
context("getindex on multiple column name") do
@fact ohlc["Open", "Close"].values[1] => 105.76
@fact ohlc["Open", "Close"].values[2] => 105.22
end
end
| {
"content_hash": "f50b63e947abdf8cc270cd89bef3908c",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 97,
"avg_line_length": 35.15094339622642,
"alnum_prop": 0.654320987654321,
"repo_name": "milktrader/TimeArrays.jl",
"id": "87cc06c52626a5069be5120dd8504e7f32a4df03",
"size": "1863",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/timearray.jl",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Julia",
"bytes": "13400"
}
],
"symlink_target": ""
} |
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
public enum ThirdPartyLicenseAssignmentFailedReason {
licenseAssignmentFailed ("licenseAssignmentFailed"),
moduleNotInstalled ("moduleNotInstalled");
@SuppressWarnings("unused")
private final String val;
private ThirdPartyLicenseAssignmentFailedReason(String val)
{
this.val = val;
}
} | {
"content_hash": "e3b939c5ba186dc0d01611291e1668b6",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 61,
"avg_line_length": 20.25,
"alnum_prop": 0.7506172839506173,
"repo_name": "paksv/vijava",
"id": "ac74db7ae40c7404b54ea8f9d29ae303d7964033",
"size": "2045",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/vmware/vim25/ThirdPartyLicenseAssignmentFailedReason.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "7900718"
}
],
"symlink_target": ""
} |
#include <grpc/support/port_platform.h>
#include "src/cpp/ext/filters/census/grpc_plugin.h"
#include <limits.h>
#include <atomic>
#include "absl/base/attributes.h"
#include "absl/strings/string_view.h"
#include "opencensus/tags/tag_key.h"
#include "opencensus/trace/span.h"
#include <grpcpp/opencensus.h>
#include <grpcpp/server_context.h>
#include "src/core/lib/surface/channel_stack_type.h"
#include "src/cpp/common/channel_filter.h"
#include "src/cpp/ext/filters/census/channel_filter.h"
#include "src/cpp/ext/filters/census/client_filter.h"
#include "src/cpp/ext/filters/census/measures.h"
#include "src/cpp/ext/filters/census/server_filter.h"
namespace grpc {
void RegisterOpenCensusPlugin() {
RegisterChannelFilter<CensusClientChannelData,
CensusClientChannelData::CensusClientCallData>(
"opencensus_client", GRPC_CLIENT_CHANNEL, INT_MAX /* priority */,
nullptr /* condition function */);
RegisterChannelFilter<CensusChannelData, CensusServerCallData>(
"opencensus_server", GRPC_SERVER_CHANNEL, INT_MAX /* priority */,
nullptr /* condition function */);
// Access measures to ensure they are initialized. Otherwise, creating a view
// before the first RPC would cause an error.
RpcClientSentBytesPerRpc();
RpcClientReceivedBytesPerRpc();
RpcClientRoundtripLatency();
RpcClientServerLatency();
RpcClientStartedRpcs();
RpcClientSentMessagesPerRpc();
RpcClientReceivedMessagesPerRpc();
RpcClientRetriesPerCall();
RpcClientTransparentRetriesPerCall();
RpcClientRetryDelayPerCall();
RpcServerSentBytesPerRpc();
RpcServerReceivedBytesPerRpc();
RpcServerServerLatency();
RpcServerStartedRpcs();
RpcServerSentMessagesPerRpc();
RpcServerReceivedMessagesPerRpc();
}
::opencensus::trace::Span GetSpanFromServerContext(
grpc::ServerContext* context) {
if (context == nullptr) return opencensus::trace::Span::BlankSpan();
return reinterpret_cast<const grpc::experimental::CensusContext*>(
context->census_context())
->Span();
}
namespace experimental {
// These measure definitions should be kept in sync across opencensus
// implementations--see
// https://github.com/census-instrumentation/opencensus-java/blob/master/contrib/grpc_metrics/src/main/java/io/opencensus/contrib/grpc/metrics/RpcMeasureConstants.java.
::opencensus::tags::TagKey ClientMethodTagKey() {
static const auto method_tag_key =
::opencensus::tags::TagKey::Register("grpc_client_method");
return method_tag_key;
}
::opencensus::tags::TagKey ClientStatusTagKey() {
static const auto status_tag_key =
::opencensus::tags::TagKey::Register("grpc_client_status");
return status_tag_key;
}
::opencensus::tags::TagKey ServerMethodTagKey() {
static const auto method_tag_key =
::opencensus::tags::TagKey::Register("grpc_server_method");
return method_tag_key;
}
::opencensus::tags::TagKey ServerStatusTagKey() {
static const auto status_tag_key =
::opencensus::tags::TagKey::Register("grpc_server_status");
return status_tag_key;
}
// Client
ABSL_CONST_INIT const absl::string_view
kRpcClientSentMessagesPerRpcMeasureName =
"grpc.io/client/sent_messages_per_rpc";
ABSL_CONST_INIT const absl::string_view kRpcClientSentBytesPerRpcMeasureName =
"grpc.io/client/sent_bytes_per_rpc";
ABSL_CONST_INIT const absl::string_view
kRpcClientReceivedMessagesPerRpcMeasureName =
"grpc.io/client/received_messages_per_rpc";
ABSL_CONST_INIT const absl::string_view
kRpcClientReceivedBytesPerRpcMeasureName =
"grpc.io/client/received_bytes_per_rpc";
ABSL_CONST_INIT const absl::string_view kRpcClientRoundtripLatencyMeasureName =
"grpc.io/client/roundtrip_latency";
ABSL_CONST_INIT const absl::string_view kRpcClientServerLatencyMeasureName =
"grpc.io/client/server_latency";
ABSL_CONST_INIT const absl::string_view kRpcClientStartedRpcsMeasureName =
"grpc.io/client/started_rpcs";
ABSL_CONST_INIT const absl::string_view kRpcClientRetriesPerCallMeasureName =
"grpc.io/client/retries_per_call";
ABSL_CONST_INIT const absl::string_view
kRpcClientTransparentRetriesPerCallMeasureName =
"grpc.io/client/transparent_retries_per_call";
ABSL_CONST_INIT const absl::string_view kRpcClientRetryDelayPerCallMeasureName =
"grpc.io/client/retry_delay_per_call";
// Server
ABSL_CONST_INIT const absl::string_view
kRpcServerSentMessagesPerRpcMeasureName =
"grpc.io/server/sent_messages_per_rpc";
ABSL_CONST_INIT const absl::string_view kRpcServerSentBytesPerRpcMeasureName =
"grpc.io/server/sent_bytes_per_rpc";
ABSL_CONST_INIT const absl::string_view
kRpcServerReceivedMessagesPerRpcMeasureName =
"grpc.io/server/received_messages_per_rpc";
ABSL_CONST_INIT const absl::string_view
kRpcServerReceivedBytesPerRpcMeasureName =
"grpc.io/server/received_bytes_per_rpc";
ABSL_CONST_INIT const absl::string_view kRpcServerServerLatencyMeasureName =
"grpc.io/server/server_latency";
ABSL_CONST_INIT const absl::string_view kRpcServerStartedRpcsMeasureName =
"grpc.io/server/started_rpcs";
} // namespace experimental
std::atomic<bool> g_open_census_stats_enabled(true);
std::atomic<bool> g_open_census_tracing_enabled(true);
void EnableOpenCensusStats(bool enable) {
g_open_census_stats_enabled = enable;
}
void EnableOpenCensusTracing(bool enable) {
g_open_census_tracing_enabled = enable;
}
bool OpenCensusStatsEnabled() {
return g_open_census_stats_enabled.load(std::memory_order_relaxed);
}
bool OpenCensusTracingEnabled() {
return g_open_census_tracing_enabled.load(std::memory_order_relaxed);
}
} // namespace grpc
| {
"content_hash": "dd1f9491b64c8d15ad9268e695aa1221",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 168,
"avg_line_length": 32.58045977011494,
"alnum_prop": 0.7541012524254719,
"repo_name": "stanley-cheung/grpc",
"id": "25afaf9306a81cd63a7bb0a0db01d2a1649aede8",
"size": "6271",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/cpp/ext/filters/census/grpc_plugin.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "5444"
},
{
"name": "Batchfile",
"bytes": "37697"
},
{
"name": "C",
"bytes": "1340616"
},
{
"name": "C#",
"bytes": "113402"
},
{
"name": "C++",
"bytes": "17499842"
},
{
"name": "CMake",
"bytes": "29311"
},
{
"name": "CSS",
"bytes": "1519"
},
{
"name": "Cython",
"bytes": "258997"
},
{
"name": "Dockerfile",
"bytes": "181867"
},
{
"name": "Go",
"bytes": "34794"
},
{
"name": "HTML",
"bytes": "14"
},
{
"name": "Java",
"bytes": "14329"
},
{
"name": "JavaScript",
"bytes": "5572"
},
{
"name": "Objective-C",
"bytes": "724877"
},
{
"name": "Objective-C++",
"bytes": "79586"
},
{
"name": "PHP",
"bytes": "488004"
},
{
"name": "PowerShell",
"bytes": "5008"
},
{
"name": "Python",
"bytes": "3829879"
},
{
"name": "Ruby",
"bytes": "649843"
},
{
"name": "Shell",
"bytes": "774868"
},
{
"name": "Starlark",
"bytes": "874094"
},
{
"name": "Swift",
"bytes": "7487"
},
{
"name": "XSLT",
"bytes": "9846"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("HelloXamarin")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("Tony")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| {
"content_hash": "04db478330375dd3e5771e05b8e61e5d",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 81,
"avg_line_length": 36.666666666666664,
"alnum_prop": 0.7373737373737373,
"repo_name": "tonysneed/Archive.Experimental",
"id": "980fc65d95a4ee62cb9cbcd868db2ad73448c41a",
"size": "992",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Mono/HelloXamarin/HelloXamarin/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "212"
},
{
"name": "C#",
"bytes": "439475"
},
{
"name": "CSS",
"bytes": "6098"
},
{
"name": "JavaScript",
"bytes": "47523"
}
],
"symlink_target": ""
} |
package adinar.annotationsutils.objectdialog;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import java.util.List;
import adinar.annotationsutils.R;
import adinar.annotationsutils.objectdialog.validation.ValidatorBuilder;
/** Bridge between AlertDialog.Builder and DialogClassData. */
class DialogDataManager<T> {
private static final String TAG = "DialogDataManager";
private DialogClassData<T> data;
private AlertDialog.Builder builder;
private ValidatorBuilder validatorBuilder;
private T object;
public DialogDataManager(T object, DialogClassData<T> data, AlertDialog.Builder builder) {
this.data = data;
this.builder = builder;
this.object = object;
validatorBuilder = new ValidatorBuilder();
}
public void setTitle() {
builder.setTitle(data.getTitleEntry().getTitleFrom(object));
}
public void setView(Context ctx) {
List<DialogFieldEntry<T>> entries = data.getFields();
LinearLayout view = (LinearLayout) LayoutInflater.from(ctx)
.inflate(R.layout.dialog_layout, null);
for (DialogFieldEntry<T> e : entries) {
view.addView(e.generateView(object, ctx, validatorBuilder));
}
builder.setView(view);
}
public void setButtons(final AnnotationDialogListener<T> listener) {
new DialogButtonsBuilder<>(builder, data, listener).build();
}
public void setPositiveButtonListener(final AlertDialog dialog,
final AnnotationDialogListener<T> listener) {
Button dialogButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
if (dialogButton != null)
dialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (validatorBuilder.build().isValid()) {
for (DialogFieldEntry<T> e : data.getFields()) {
e.setFieldValueFromView();
}
listener.onDialogAccepted(object);
dialog.hide();
}
}
});
}
}
| {
"content_hash": "844287139793a442606da65b999429ea",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 94,
"avg_line_length": 34,
"alnum_prop": 0.6262254901960784,
"repo_name": "AdiNar/android-annotation-utils",
"id": "7bd70131bf78f813b85d5335b2d59684701856f9",
"size": "2448",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "annotations-utils/src/main/java/adinar/annotationsutils/objectdialog/DialogDataManager.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "149404"
}
],
"symlink_target": ""
} |
ROOTDIR=$(dir $(abspath $(lastword $(MAKEFILE_LIST))))
# Base path used to install.
DESTDIR=/usr/local
# Used to populate version variable in main package.
VERSION=$(shell git describe --match 'v[0-9]*' --dirty='.m' --always)
PROJECT_ROOT=github.com/superfly/wormhole
# Race detector is only supported on amd64.
RACE := $(shell test $$(go env GOARCH) != "amd64" || (echo "-race"))
# Project packages.
PACKAGES=$(shell go list ./... | grep -v /vendor/)
INTEGRATION_PACKAGE=${PROJECT_ROOT}/integration
# Project binaries.
COMMANDS=wormhole
BINARIES=$(addprefix bin/,$(COMMANDS))
GO_LDFLAGS=-ldflags "-X `go list ./config`.version=$(VERSION)"
.PHONY: clean all fmt vet lint build binaries test integration setup generate checkprotos coverage ci check help install uninstall crossbuild
.DEFAULT: default
all: check binaries test integration ## run fmt, vet, lint, build the binaries and run the tests
check: fmt vet lint ineffassign misspell ## run fmt, vet, lint, ineffassign, misspell
ci: check binaries checkprotos coverage coverage-integration ## to be used by the CI
setup: ## install dependencies
@echo "🎈 $@"
@go get -u github.com/golang/lint/golint
@go get -u github.com/gordonklaus/ineffassign
@go get -u github.com/client9/misspell/cmd/misspell
@go get -u github.com/golang/dep/cmd/dep
@dep ensure
# Depends on binaries because vet will silently fail if it can't load compiled
# imports
vet: binaries ## run go vet
@echo "🎈 $@"
@test -z "$$(go vet ${PACKAGES} 2>&1 | grep -v 'constant [0-9]* not a string in call to Errorf' | egrep -v '(timestamp_test.go|duration_test.go|exit status 1)' | tee /dev/stderr)"
misspell:
@echo "🎈 $@"
@test -z "$$(find . -type f | grep -v vendor/ | grep -v bin/ | grep -v .git/ | xargs misspell | tee /dev/stderr)"
fmt: ## run go fmt
@echo "🎈 $@"
@test -z "$$(gofmt -s -l . | grep -v vendor/ | grep -v ".pb.go$$" | tee /dev/stderr)" || \
(echo "👹 please format Go code with 'gofmt -s -w'" && false)
@test -z "$$(find . -path ./vendor -prune -o -name '*.proto' -type f -exec grep -Hn -e "^ " {} \; | tee /dev/stderr)" || \
(echo "👹 please indent proto files with tabs only" && false)
@test -z "$$(find . -path ./vendor -prune -o -name '*.proto' -type f -exec grep -Hn "Meta meta = " {} \; | grep -v '(gogoproto.nullable) = false' | tee /dev/stderr)" || \
(echo "👹 meta fields in proto files must have option (gogoproto.nullable) = false" && false)
lint: ## run go lint
@echo "🎈 $@"
@test -z "$$(golint ./... | grep -v vendor/ | grep -v ".pb.go:" | grep -v ".mock.go" | tee /dev/stderr)"
ineffassign: ## run ineffassign
@echo "🎈 $@"
@test -z "$$(ineffassign . | grep -v vendor/ | grep -v ".pb.go:" | grep -v ".mock.go" | tee /dev/stderr)"
build: ## build the go packages
@echo "🎈 $@"
@go build -i -v ${GO_LDFLAGS} ${GO_GCFLAGS} ${PACKAGES}
crossbuild: ## compile binaries for multiple archs/OSes
@echo "🎈 $@"
@exec ${ROOTDIR}scripts/build.sh
test: ## run tests, except integration tests
@echo "🎈 $@"
@go test ${RACE} $(filter-out ${INTEGRATION_PACKAGE},${PACKAGES})
integration: ## run integration tests
@echo "🎈 $@"
@go test ${RACE} ${INTEGRATION_PACKAGE}
FORCE:
# Build a binary from a cmd.
bin/%: cmd/% FORCE
@test $$(go list) = "${PROJECT_ROOT}" || \
(echo "👹 Please correctly set up your Go build environment. This project must be located at <GOPATH>/src/${PROJECT_ROOT}" && false)
@echo "🎈 $@"
@go build -i -o $@ ${GO_LDFLAGS} ${GO_GCFLAGS} ./$<
binaries: $(BINARIES) ## build binaries
@echo "🎈 $@"
clean: ## clean up binaries
@echo "🎈 $@"
@rm -f $(BINARIES)
install: $(BINARIES) ## install binaries
@echo "🎈 $@"
@mkdir -p $(DESTDIR)/bin
@install $(BINARIES) $(DESTDIR)/bin
uninstall:
@echo "🎈 $@"
@rm -f $(addprefix $(DESTDIR)/bin/,$(notdir $(BINARIES)))
coverage: ## generate coverprofiles from the unit tests
@echo "🎈 $@"
@( for pkg in $(filter-out ${INTEGRATION_PACKAGE},${PACKAGES}); do \
go test -i ${RACE} -test.short -coverprofile="../../../$$pkg/coverage.txt" -covermode=atomic $$pkg || exit; \
go test ${RACE} -test.short -coverprofile="../../../$$pkg/coverage.txt" -covermode=atomic $$pkg || exit; \
done )
coverage-integration: ## generate coverprofiles from the integration tests
@echo "🎈 $@"
go test ${RACE} -test.short -coverprofile="../../../${INTEGRATION_PACKAGE}/coverage.txt" -covermode=atomic ${INTEGRATION_PACKAGE}
help: ## this help
@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST) | sort
| {
"content_hash": "e49169c32502ea895ca02dd8a303fd8c",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 180,
"avg_line_length": 37.22314049586777,
"alnum_prop": 0.6436500888099467,
"repo_name": "superfly/wormhole",
"id": "bdfc260bcda357ff8250b160e44ffd98e87e0e2a",
"size": "4616",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Makefile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "113"
},
{
"name": "Go",
"bytes": "250018"
},
{
"name": "Makefile",
"bytes": "4616"
},
{
"name": "Shell",
"bytes": "8685"
}
],
"symlink_target": ""
} |
package gov.nih.nci.cacis.nav;
/**
* Represents exceptions encountered while receiving notifications
*
* @author <a href="mailto:joshua.phillips@semanticbits.com">Joshua Phillips</a>
* @since May 5, 2011
*
*/
public class NotificationSendException extends Exception {
private static final long serialVersionUID = 4878153586628471573L;
/**
* Takes the cause
*
* @param cause the cause of the exception
*/
public NotificationSendException(Throwable cause) {
super(cause);
}
/**
* Takes message and cause
*
* @param msg a message
* @param cause the cause
*/
public NotificationSendException(String msg, Throwable cause) {
super(msg, cause);
}
/**
* Default constructor
*/
public NotificationSendException() { //NOPMD
}
/**
* Takes a message
*
* @param msg a message
*/
public NotificationSendException(String msg) {
super(msg);
}
}
| {
"content_hash": "40e10b534667ca07198074b6c36ef322",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 80,
"avg_line_length": 20.387755102040817,
"alnum_prop": 0.6186186186186187,
"repo_name": "NCIP/cacis",
"id": "e26f8fcc46e7852f9aef4d0a2468447b280457f0",
"size": "1275",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "nav/src/main/java/gov/nih/nci/cacis/nav/NotificationSendException.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "932731"
},
{
"name": "JavaScript",
"bytes": "21590"
},
{
"name": "Shell",
"bytes": "946"
},
{
"name": "XSLT",
"bytes": "2353609"
}
],
"symlink_target": ""
} |
module Babelicious
class HashMap < BaseMap
attr_accessor :path_translator
class << self
def initial_target
{}
end
def filter_source(source)
source
end
end
def initialize(path_translator, opts={})
@path_translator, @opts = path_translator, opts
end
def value_from(source)
hash = {}
element = ""
return source if (@path_translator.full_path == "" || @path_translator.full_path == "/")
@path_translator.inject_with_index(hash) do |hsh, element, index|
return source_element(hsh, element) if (index == @path_translator.last_index && index != 0)
if hsh.empty?
source_element(source, element)
else
source_element(hsh, element)
end
end
end
protected
def map_output(hash_output, source_value)
catch :no_value do
@path_translator.inject_with_index(hash_output) do |hsh, element, index|
if(hsh[element])
hsh[element]
else
hsh[element] = (index == @path_translator.last_index ? map_source_value(source_value) : {})
end
end
end
end
private
def source_element(source, element)
source[element.to_sym] || source[element.to_s] || ''
rescue TypeError => e
# This method deals with `source` being a string by abusing a strange
# behavior in ruby 1.8.7. Namely that `""[:foo] => nil` and `""["foo"]
# => nil`. So in ruby 1.8.7 when a string is passed for the source
# parameter, the first two checks will yield nil, and the result will be
# the empty string. In ruby 1.9.3, however, `""[:foo]` raises a
# TypeError.
if /can't convert Symbol into Integer/ === e.message
""
else
raise e
end
end
def map_source_value(source_value)
if(@customized_map)
@customized_map.call(source_value)
else
source_value
end
end
end
end
| {
"content_hash": "da117b57013d14d43cfc8df9675163d3",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 103,
"avg_line_length": 26.428571428571427,
"alnum_prop": 0.5705159705159705,
"repo_name": "cwyckoff/babel_icious",
"id": "d2a48e42688e34057824dbf9e945d4d9bce727fd",
"size": "2035",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/babel_icious/mappers/hash_map.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "73133"
}
],
"symlink_target": ""
} |
namespace Azure.Management.Resources.Models
{
/// <summary> Microsoft.Features operation. </summary>
public partial class OperationAutoGenerated
{
/// <summary> Initializes a new instance of OperationAutoGenerated. </summary>
internal OperationAutoGenerated()
{
}
/// <summary> Initializes a new instance of OperationAutoGenerated. </summary>
/// <param name="name"> Operation name: {provider}/{resource}/{operation}. </param>
/// <param name="display"> The object that represents the operation. </param>
internal OperationAutoGenerated(string name, OperationDisplayAutoGenerated display)
{
Name = name;
Display = display;
}
/// <summary> Operation name: {provider}/{resource}/{operation}. </summary>
public string Name { get; }
/// <summary> The object that represents the operation. </summary>
public OperationDisplayAutoGenerated Display { get; }
}
}
| {
"content_hash": "c02b737b3c38ee3992ee37934328d304",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 91,
"avg_line_length": 40.32,
"alnum_prop": 0.6408730158730159,
"repo_name": "hyonholee/azure-sdk-for-net",
"id": "d60c1f19497d26f3777bdb350522b36dbd1a3bb8",
"size": "1146",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sdk/resources/Azure.Management.Resources/src/Generated/Models/OperationAutoGenerated.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "16774"
},
{
"name": "C#",
"bytes": "37415276"
},
{
"name": "HTML",
"bytes": "234899"
},
{
"name": "JavaScript",
"bytes": "7875"
},
{
"name": "PowerShell",
"bytes": "273940"
},
{
"name": "Shell",
"bytes": "13061"
},
{
"name": "Smarty",
"bytes": "11135"
},
{
"name": "TypeScript",
"bytes": "143209"
}
],
"symlink_target": ""
} |
<?php
namespace Zoba\HolidaysManagerBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Zoba\HolidaysManagerBundle\Entity\ExtraTime;
use Zoba\HolidaysManagerBundle\Form\ExtraTimeType;
/**
* ExtraTime controller.
*
* @Route("/extra_time_admin")
*/
class ExtraTimeController extends Controller
{
/**
* Lists all ExtraTime entities.
*
* @Route("/", name="extra_time_admin")
* @Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('ZobaHolidaysManagerBundle:ExtraTime')->findAll();
return array(
'entities' => $entities,
);
}
/**
* Finds and displays a ExtraTime entity.
*
* @Route("/{id}/show", name="extra_time_admin_show")
* @Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ZobaHolidaysManagerBundle:ExtraTime')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find ExtraTime entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Displays a form to create a new ExtraTime entity.
*
* @Route("/new", name="extra_time_admin_new")
* @Template()
*/
public function newAction()
{
$entity = new ExtraTime();
$form = $this->createForm(new ExtraTimeType(), $entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a new ExtraTime entity.
*
* @Route("/create", name="extra_time_admin_create")
* @Method("POST")
* @Template("ZobaHolidaysManagerBundle:ExtraTime:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new ExtraTime();
$form = $this->createForm(new ExtraTimeType(), $entity);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('extra_time_admin_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Displays a form to edit an existing ExtraTime entity.
*
* @Route("/{id}/edit", name="extra_time_admin_edit")
* @Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ZobaHolidaysManagerBundle:ExtraTime')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find ExtraTime entity.');
}
$editForm = $this->createForm(new ExtraTimeType(), $entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Edits an existing ExtraTime entity.
*
* @Route("/{id}/update", name="extra_time_admin_update")
* @Method("POST")
* @Template("ZobaHolidaysManagerBundle:ExtraTime:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ZobaHolidaysManagerBundle:ExtraTime')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find ExtraTime entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createForm(new ExtraTimeType(), $entity);
$editForm->bind($request);
if ($editForm->isValid()) {
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('extra_time_admin_edit', array('id' => $id)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a ExtraTime entity.
*
* @Route("/{id}/delete", name="extra_time_admin_delete")
* @Method("POST")
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ZobaHolidaysManagerBundle:ExtraTime')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find ExtraTime entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('extra_time_admin'));
}
private function createDeleteForm($id)
{
return $this->createFormBuilder(array('id' => $id))
->add('id', 'hidden')
->getForm()
;
}
}
| {
"content_hash": "375b225775ae3b6c0deb05cc7323e4f5",
"timestamp": "",
"source": "github",
"line_count": 199,
"max_line_length": 113,
"avg_line_length": 28.060301507537687,
"alnum_prop": 0.5573065902578797,
"repo_name": "giovanniledda/Holidays-manager",
"id": "183518d15d057858499c69de02454a3366698470",
"size": "5584",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Zoba/HolidaysManagerBundle/Controller/ExtraTimeController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "114152"
},
{
"name": "PHP",
"bytes": "114202"
},
{
"name": "Perl",
"bytes": "6737"
}
],
"symlink_target": ""
} |
[](https://travis-ci.org/travisbrown/scala-json)
[](https://coveralls.io/r/travisbrown/scala-json?branch=develop)
[](#status)
This project is a toolkit for working with JSON in Scala that is based on
[example code](http://booksites.artima.com/programming_in_scala_2ed/examples/)
from [Programming in Scala](http://www.artima.com/shop/programming_in_scala_2ed)
by Martin Odersky, Lex Spoon, and Bill Venners. We've tightened up some edge
cases and added complete test coverage.
## Status
This library is deprecated! It should not be used for new projects, and is
maintained only because it is used in
[Twitter's Ostrich 9.x](https://github.com/twitter/ostrich).
## License
The original code and Twitter's modifications are available under the
[Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0).
| {
"content_hash": "0ba10602ad1669a26beaa03301fde30a",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 151,
"avg_line_length": 53.1,
"alnum_prop": 0.7711864406779662,
"repo_name": "travisbrown/scala-json",
"id": "42d4993067f3011cb1ad986a0499446c3705962b",
"size": "1076",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "495"
},
{
"name": "Scala",
"bytes": "29183"
},
{
"name": "Shell",
"bytes": "1184"
}
],
"symlink_target": ""
} |
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ThreeColumnsComponent } from './three-columns.component';
describe('ThreeColumnsComponent', () => {
let component: ThreeColumnsComponent;
let fixture: ComponentFixture<ThreeColumnsComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ThreeColumnsComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ThreeColumnsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
});
| {
"content_hash": "6d74e42d69aec607fe0cbdf590cd089a",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 73,
"avg_line_length": 27,
"alnum_prop": 0.6903703703703704,
"repo_name": "edouardr/angular-kentico-headless",
"id": "52de847d7c6ad35fffafd5588293c9667906f2d5",
"size": "675",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/components/three-columns/three-columns.component.spec.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "15360"
},
{
"name": "HTML",
"bytes": "3219"
},
{
"name": "JavaScript",
"bytes": "1996"
},
{
"name": "TypeScript",
"bytes": "24435"
}
],
"symlink_target": ""
} |
Read the related wiki pages to learn about:
- [Project Governance Model] (https://github.com/virareports/ProjectGuidelines/wiki/Project-Governance-Model)
- [How to Become a Contributor](https://github.com/virareports/ProjectGuidelines/wiki/How-to-Become-a-Contributor)
| {
"content_hash": "0a942c3c352ac23f64734e6ceefe906a",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 114,
"avg_line_length": 67.5,
"alnum_prop": 0.8037037037037037,
"repo_name": "virareports/ProjectGuidelines",
"id": "983afd924ef09e323bb89d1d7a07d00d8c52080a",
"size": "291",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.earthtime.utilities;
import org.earthtime.Tripoli.fractions.TripoliFraction;
/**
*
* @author samuelbowring
*/
public interface DragAndDropListItemInterface extends Comparable<TripoliFraction> {
}
| {
"content_hash": "77b16b972b0381762b1003e52d4b6fab",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 83,
"avg_line_length": 18.25,
"alnum_prop": 0.7808219178082192,
"repo_name": "clementparizot/ET_Redux",
"id": "a4bac6ea1c9527e050ef8aa01cbf2ee0b4d479c3",
"size": "899",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/org/earthtime/utilities/DragAndDropListItemInterface.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "24186"
},
{
"name": "Java",
"bytes": "8223128"
}
],
"symlink_target": ""
} |
package org.symphonyoss.client.services;
import org.symphonyoss.symphony.clients.model.SymMessage;
/**
* Callback interface for message events on the {@link org.symphonyoss.client.model.Chat} object.
* <p>
* Created by Frank Tarsillo on 5/22/2016.
*/
public interface ChatListener {
/**
* Callback for chat messages
*
* @param message Incoming message from feed
*/
void onChatMessage(SymMessage message);
}
| {
"content_hash": "c69cd1e9f8169f5ba2d3207c5782c7cc",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 97,
"avg_line_length": 22.2,
"alnum_prop": 0.704954954954955,
"repo_name": "symphonyoss/symphony-java-client",
"id": "c593869d439d58a76217fdfb0b141bb3de0cf629",
"size": "1310",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "symphony-client/src/main/java/org/symphonyoss/client/services/ChatListener.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "695383"
},
{
"name": "Shell",
"bytes": "1987"
}
],
"symlink_target": ""
} |
import React, { PropTypes } from 'react';
import { Link } from 'react-router';
import format from 'date-fns/format';
import PropertyListItem from './PropertyListItem';
import '../style/FormList.less';
const DATE_FORMAT = 'M/D/YY h:mm a';
const FormItem = ({ form }) => (
<div className="form-item">
<h4><Link to={`/forms/${form.form_key}`}>{form.form_label}</Link></h4>
<div className="properties">
<PropertyListItem name={'Version'} value={form.version} />
<PropertyListItem name={'Team'} value={form.team_name} />
{form.metadata
? <div>
<PropertyListItem name={'Number of Records'} value={form.metadata.count} />
{form.metadata.lastActivity
? <PropertyListItem
name={'Last Activity'}
value={format(form.metadata.lastActivity, DATE_FORMAT)}
/>
: null}
</div>
: null}
</div>
</div>
);
FormItem.propTypes = {
form: PropTypes.object.isRequired,
};
const FormsList = ({ forms, selectedTeamId }) => (
<div className="form-list">
{Object.keys(forms).map(key => {
const form = forms[key];
if (selectedTeamId === form.team_id) {
return <FormItem form={form} key={form.id} />;
}
return null;
})}
</div>
);
FormsList.propTypes = {
forms: PropTypes.object.isRequired,
selectedTeamId: PropTypes.number.isRequired,
};
export default FormsList;
| {
"content_hash": "ca0b7d30662a35ec38c783c197611955",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 87,
"avg_line_length": 28.470588235294116,
"alnum_prop": 0.5943526170798898,
"repo_name": "mrcnc/spatialconnect-server",
"id": "89386ea027f630ac9a1e2764b56bd7415294cf03",
"size": "1452",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "web/components/FormsList.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "12233"
},
{
"name": "Clojure",
"bytes": "166745"
},
{
"name": "Dockerfile",
"bytes": "293"
},
{
"name": "HTML",
"bytes": "671"
},
{
"name": "JavaScript",
"bytes": "144700"
},
{
"name": "PLpgSQL",
"bytes": "7522"
},
{
"name": "Shell",
"bytes": "2410"
}
],
"symlink_target": ""
} |
<?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?>
<?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="title" content="Connectiv8 - Web Dev, Wild and Tame">
<meta name="description" content="Wild and Tame, a sustainability consulting company, is looking for a student to develop a website as part of a fresh new brand.">
<meta name="keywords" content="<?php echoGeneralKeywords(); ?>,wild and tame,david see,shari hughson,web design,web development">
<meta name="author" content="Connectivate Corporation">
<!-- favicon/icon import -->
<?php favicons(); ?>
<title>Connectiv8 - Web Dev, Wild and Tame</title>
<!-- CSS import -->
<?php css(); ?>
</head>
<body id="page-top">
<!-- Google Tag Manager -->
<?php analytics(); ?>
<!-- Navbar -->
<?php navbar(); ?>
<section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project">
<div style="height: 100%;" class="container-fluid">
<div style="height: 100%;" class="row">
<div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4">
<div style="text-align:center; height: 100%; overflow-x: hidden;">
<img class="project-image-wide hidden-sm-down" src="../img/project/laptop.jpg" alt="Project Picture"/> <!--project picture-->
</div>
<div>
<img class="img-responsive hidden-md-up" src="../img/project/laptop.jpg" alt="Project Picture" /> <!--project picture-->
</div>
</div>
<div id="description-column" class="col-md-8">
<div style="margin: 20px;">
<!-- Project Header -->
<div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px">
<div class="row">
<h2 class="col-md-8 project-title">Web Development</h2>
<div class="col-md-4">
<h2 class="project-price-wide hidden-sm-down">$375.00</h2>
<h2 class="project-price-narrow hidden-md-up">$375.00</h2>
</div>
</div>
</div>
<p class="project-descriptive-text" style="margin-bottom: 5px;">Wild and Tame</p>
<br />
<p><strong>Description</strong></p>
<p class="project-descriptive-text">David See and Shari Hughson inspire, teach and consult for people and communities to create self-reliant and self-sustaining lifestyles.
They base this work on their experience living off the land in the remote wilderness of British Columbia.
In order to help with their work, they need a strong web presence!</p>
<p>Important: You will be working very closely with another student, focusing on the design aspects outlined <a href="wildandtame-design.php">here</a>.
If you know someone you would like to work with, mention each other when you both apply!</p>
<p><strong>Learning Opportunities</strong></p>
<ul class="project-descriptive-text">
<li>
Create a professional website and develop a new brand
</li>
<li>
Learn about e-commerce platforms for selling goods online
</li>
<li>
Discover Shari and David's adventures surviving in the wilderness
</li>
</ul>
<p><strong>Responsibilities</strong></p>
<ol class="project-descriptive-text">
<li>
Meet with David and Shari to discuss their business and their goals.
</li>
<li>
Build them a manageable website with a landing page, an about page, photos, and a blog.
</li>
<li>
Create a company Facebook page and plan a social media marketing strategy. Use analytics to track your effectiveness.
</li>
<li>
Research and provide recommendations for developing an e-commerce platform for selling goods on the new site.
</li>
<li>
Teach David and Shari how to use the systems you have setup for them.
</li>
</ol>
<p><strong>Required Skills</strong></p>
<ul class="project-descriptive-text">
<li>
Experience with web design and development
</li>
<li>
Creativity and motivation
</li>
<li>
Strong communication and teamwork skills
</li>
</ul>
<p><strong>Applications are closed for this project.</strong></p>
</div>
</div>
</div>
</div>
</section>
<!-- Contact us and copyright -->
<?php footer(); ?>
<!-- JS -->
<?php js(); ?>
</body>
</html>
| {
"content_hash": "27d01fd5280b3912316ad0b2e14120dc",
"timestamp": "",
"source": "github",
"line_count": 122,
"max_line_length": 196,
"avg_line_length": 47.040983606557376,
"alnum_prop": 0.5098449207178951,
"repo_name": "alexanderkuznetsov96/Connectivate-Info",
"id": "866eb264779560f95a2da9ee66f0d92fed014521",
"size": "5741",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "projects/wildandtame-webdev.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "172665"
},
{
"name": "JavaScript",
"bytes": "12507"
},
{
"name": "PHP",
"bytes": "250599"
}
],
"symlink_target": ""
} |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* ===== xulscrollbars.css ==============================================
== Styles used by XUL scrollbar-related elements.
======================================================================= */
@namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");
@namespace html url("http://www.w3.org/1999/xhtml"); /* namespace for HTML elements */
/* ::::: scrollbar ::::: */
scrollbar {
-moz-binding: url("chrome://global/content/bindings/scrollbar.xml#scrollbar");
cursor: default;
background: scrollbar;
border: 1px solid;
-moz-border-top-colors: ThreeDShadow;
-moz-border-right-colors: ThreeDHighlight;
-moz-border-bottom-colors: ThreeDHighlight;
-moz-border-left-colors: ThreeDShadow;
min-height: 14px;
}
scrollbar[orient="vertical"]
{
min-width: 14px;
}
/* ::::: borders for thumb and buttons ::::: */
thumb,
scrollbarbutton {
border: 2px solid;
-moz-border-top-colors: ThreeDHighlight ThreeDHighlight;
-moz-border-right-colors: ThreeDDarkShadow ThreeDShadow;
-moz-border-bottom-colors: ThreeDDarkShadow ThreeDShadow;
-moz-border-left-colors: ThreeDHighlight ThreeDHighlight;
background: -moz-Dialog no-repeat 50% 50%;
}
thumb:active,
scrollbarbutton:hover:active,
scrollbarbutton[active="true"] {
-moz-border-top-colors: ThreeDDarkShadow ThreeDShadow;
-moz-border-right-colors: ThreeDHighlight ThreeDHighlight;
-moz-border-bottom-colors: ThreeDHighlight ThreeDHighlight;
-moz-border-left-colors: ThreeDDarkShadow ThreeDShadow;
}
thumb {
background-image: url("chrome://global/skin/arrow/thumb-vrt.gif");
min-height: 17px;
min-width: 0;
}
thumb[orient="horizontal"] {
background-image: url("chrome://global/skin/arrow/thumb-hrz.gif");
min-height: 0;
min-width: 17px;
}
/* ::::: square at the corner of two scrollbars ::::: */
scrollcorner {
-moz-binding: url(chrome://global/content/bindings/scrollbar.xml#scrollbar-base);
width: 14px;
cursor: default;
background-color: -moz-Dialog;
}
/* ..... increment .... */
scrollbarbutton[type="increment"] {
min-width: 17px;
min-height: 12px;
background-image: url("chrome://global/skin/arrow/arrow-rit.gif");
}
scrollbarbutton[type="increment"][disabled="true"] {
background-image: url("chrome://global/skin/arrow/arrow-rit-dis.gif");
}
scrollbar[orient="vertical"] > scrollbarbutton[type="increment"] {
min-width: 12px;
min-height: 17px;
background-image: url("chrome://global/skin/arrow/arrow-dn.gif");
}
scrollbar[orient="vertical"] > scrollbarbutton[type="increment"][disabled="true"] {
background-image: url("chrome://global/skin/arrow/arrow-dn-dis.gif");
}
/* ..... decrement .... */
scrollbarbutton[type="decrement"] {
min-width: 17px;
min-height: 12px;
background-image: url("chrome://global/skin/arrow/arrow-lft.gif");
}
scrollbarbutton[type="decrement"][disabled="true"] {
background-image: url("chrome://global/skin/arrow/arrow-lft-dis.gif");
}
scrollbar[orient="vertical"] > scrollbarbutton[type="decrement"] {
min-width: 12px;
min-height: 17px;
background-image: url("chrome://global/skin/arrow/arrow-up.gif");
}
scrollbar[orient="vertical"] > scrollbarbutton[type="decrement"][disabled="true"] {
background-image: url("chrome://global/skin/arrow/arrow-up-dis.gif");
}
/* :::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
/* ::::::::::::::::::::: MEDIA PRINT :::::::::::::::::::::: */
/* :::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
@media print {
/* ::::: scrollbar ::::: */
html|div scrollbar {
-moz-binding: url("chrome://global/content/bindings/scrollbar.xml#scrollbar");
cursor: default;
background: scrollbar;
border: 1px solid;
-moz-border-top-colors: ThreeDLightShadow;
-moz-border-right-colors: ThreeDHighlight;
-moz-border-bottom-colors: ThreeDHighlight;
-moz-border-left-colors: ThreeDShadow;
min-height: 14px;
}
html|div scrollbar[orient="vertical"]
{
min-width: 14px;
}
/* ::::: borders for thumb and buttons ::::: */
html|div thumb,
html|div scrollbarbutton {
border: 2px solid;
-moz-border-top-colors: ThreeDHighlight ThreeDHighlight;
-moz-border-right-colors: ThreeDDarkShadow ThreeDShadow;
-moz-border-bottom-colors: ThreeDDarkShadow ThreeDShadow;
-moz-border-left-colors: ThreeDHighlight ThreeDHighlight;
background: -moz-Dialog no-repeat 50% 50%;
}
html|div thumb:hover:active,
html|div scrollbarbutton:hover:active,
html|div scrollbarbutton[active="true"] {
-moz-border-top-colors: ThreeDDarkShadow ThreeDShadow;
-moz-border-right-colors: ThreeDHighlight ThreeDHighlight;
-moz-border-bottom-colors: ThreeDHighlight ThreeDHighlight;
-moz-border-left-colors: ThreeDDarkShadow ThreeDShadow;
}
/* ::::: square at the corner of two scrollbars ::::: */
html|div scrollcorner {
-moz-binding: url(chrome://global/content/bindings/scrollbar.xml#scrollbar-base);
width: 14px;
cursor: default;
background-color: -moz-Dialog;
}
/* ..... increment .... */
html|div scrollbarbutton[type="increment"] {
min-width: 17px;
min-height: 12px;
background-image: url("chrome://global/skin/arrow/arrow-rit.gif");
}
html|div scrollbarbutton[type="increment"][disabled="true"] {
background-image: url("chrome://global/skin/arrow/arrow-rit-dis.gif");
}
html|div scrollbar[orient="vertical"] > scrollbarbutton[type="increment"] {
min-width: 12px;
min-height: 17px;
background-image: url("chrome://global/skin/arrow/arrow-dn.gif");
}
html|div scrollbar[orient="vertical"] > scrollbarbutton[type="increment"][disabled="true"] {
background-image: url("chrome://global/skin/arrow/arrow-dn-dis.gif");
}
/* ..... decrement .... */
html|div scrollbarbutton[type="decrement"] {
min-width: 17px;
min-height: 12px;
background-image: url("chrome://global/skin/arrow/arrow-lft.gif");
}
html|div scrollbarbutton[type="decrement"][disabled="true"] {
background-image: url("chrome://global/skin/arrow/arrow-lft-dis.gif");
}
html|div scrollbar[orient="vertical"] > scrollbarbutton[type="decrement"] {
min-width: 12px;
min-height: 17px;
background-image: url("chrome://global/skin/arrow/arrow-up.gif");
}
html|div scrollbar[orient="vertical"] > scrollbarbutton[type="decrement"][disabled="true"] {
background-image: url("chrome://global/skin/arrow/arrow-up-dis.gif");
}
} /* media print */
| {
"content_hash": "6811e80d796df7ce65ca45e9fa2dfc49",
"timestamp": "",
"source": "github",
"line_count": 212,
"max_line_length": 94,
"avg_line_length": 31.514150943396228,
"alnum_prop": 0.6623259991019308,
"repo_name": "sergecodd/FireFox-OS",
"id": "4d72b804bc9d99f900ff6e4c5f7b354392373e87",
"size": "6681",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "B2G/gecko/toolkit/themes/pmstripe/global/xulscrollbars.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ada",
"bytes": "443"
},
{
"name": "ApacheConf",
"bytes": "85"
},
{
"name": "Assembly",
"bytes": "5123438"
},
{
"name": "Awk",
"bytes": "46481"
},
{
"name": "Batchfile",
"bytes": "56250"
},
{
"name": "C",
"bytes": "101720951"
},
{
"name": "C#",
"bytes": "38531"
},
{
"name": "C++",
"bytes": "148896543"
},
{
"name": "CMake",
"bytes": "23541"
},
{
"name": "CSS",
"bytes": "2758664"
},
{
"name": "DIGITAL Command Language",
"bytes": "56757"
},
{
"name": "Emacs Lisp",
"bytes": "12694"
},
{
"name": "Erlang",
"bytes": "889"
},
{
"name": "FLUX",
"bytes": "34449"
},
{
"name": "GLSL",
"bytes": "26344"
},
{
"name": "Gnuplot",
"bytes": "710"
},
{
"name": "Groff",
"bytes": "447012"
},
{
"name": "HTML",
"bytes": "43343468"
},
{
"name": "IDL",
"bytes": "1455122"
},
{
"name": "Java",
"bytes": "43261012"
},
{
"name": "JavaScript",
"bytes": "46646658"
},
{
"name": "Lex",
"bytes": "38358"
},
{
"name": "Logos",
"bytes": "21054"
},
{
"name": "Makefile",
"bytes": "2733844"
},
{
"name": "Matlab",
"bytes": "67316"
},
{
"name": "Max",
"bytes": "3698"
},
{
"name": "NSIS",
"bytes": "421625"
},
{
"name": "Objective-C",
"bytes": "877657"
},
{
"name": "Objective-C++",
"bytes": "737713"
},
{
"name": "PHP",
"bytes": "17415"
},
{
"name": "Pascal",
"bytes": "6780"
},
{
"name": "Perl",
"bytes": "1153180"
},
{
"name": "Perl6",
"bytes": "1255"
},
{
"name": "PostScript",
"bytes": "1139"
},
{
"name": "PowerShell",
"bytes": "8252"
},
{
"name": "Protocol Buffer",
"bytes": "26553"
},
{
"name": "Python",
"bytes": "8453201"
},
{
"name": "Ragel in Ruby Host",
"bytes": "3481"
},
{
"name": "Ruby",
"bytes": "5116"
},
{
"name": "Scilab",
"bytes": "7"
},
{
"name": "Shell",
"bytes": "3383832"
},
{
"name": "SourcePawn",
"bytes": "23661"
},
{
"name": "TeX",
"bytes": "879606"
},
{
"name": "WebIDL",
"bytes": "1902"
},
{
"name": "XSLT",
"bytes": "13134"
},
{
"name": "Yacc",
"bytes": "112744"
}
],
"symlink_target": ""
} |
include ../Makefile.mk
run: link
$(ECHO) -e "\nLOADING SPEC TESTS\n"
tput setaf 2; $(ECHO) "(load_ini.c)Can load form .ini file correctly."; tput setaf 1;
./load_ini
tput setaf 2; $(ECHO) "(error_ini.c)Throw a syntax error loading from a corrupt .ini file."; tput setaf 1
./error_ini
tput setaf 2; $(ECHO) "(missing_bitmap.c)Throw an error if the bitmap section is missing."; tput setaf 1
./missing_bitmap
tput setaf 2; $(ECHO) "(missing_mti.c)Throw an error if the mti section is missing."; tput setaf 1
./missing_mti
tput setaf 2; $(ECHO) "(section_error.c)Throw an error if a unrecognized section is fetched."; tput setaf 1
./section_error
tput sgr0; $(ECHO) "Done."
| {
"content_hash": "50ea0338c955f25415117ea7028da38f",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 108,
"avg_line_length": 45.6,
"alnum_prop": 0.695906432748538,
"repo_name": "MaG21/lib8583",
"id": "7c8bf074ba6c29ae772b485ae90be2ca7a63748a",
"size": "684",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/load/Makefile",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "9718"
},
{
"name": "Makefile",
"bytes": "3035"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<title>Follow scroll | anime.js</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta property="og:title" content="anime.js">
<meta property="og:url" content="https://animejs.com">
<meta property="og:description" content="Javascript Animation Engine">
<meta property="og:image" content="https://animejs.com/documentation/assets/img/icons/og.png">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="anime.js">
<meta name="twitter:site" content="@juliangarnier">
<meta name="twitter:description" content="Javascript Animation Engine">
<meta name="twitter:image" content="https://animejs.com/documentation/assets/img/icons/twitter.png">
<link rel="apple-touch-icon-precomposed" href="../assets/img/social-media-image.png">
<link rel="icon" type="image/png" href="../assets/img/favicon.png" >
<link href="../assets/css/animejs.css" rel="stylesheet">
<link href="../assets/css/documentation.css" rel="stylesheet">
<!-- <script src="../../lib/anime.min.js"></script> -->
<!-- <script src="../assets/js/anime/anime.2.2.0.js"></script> -->
<style>
.scroll-area {
width: 100%;
height: 700vh;
}
.animation-wrapper {
position: fixed;
top: 0;
left: 0;
width: 100%;
}
.pane {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
top: 100vh;
left: 0;
width: 100%;
height: 100vh;
background-color: #000;
font-size: 40vw;
}
</style>
</head>
<body>
<div class="scroll-area"></div>
<div class="animation-wrapper">
<div class="pane pane-01">01</div>
<div class="pane pane-02">02</div>
<div class="pane pane-03">03</div>
<div class="pane pane-04">04</div>
<div class="pane pane-05">05</div>
<div class="pane pane-06">06</div>
<div class="pane pane-07">07</div>
<div class="pane pane-08">08</div>
<div class="pane pane-09">09</div>
<div class="pane pane-10">10</div>
<div class="pane pane-11">11</div>
<div class="pane pane-12">12</div>
<div class="pane pane-13">13</div>
<div class="pane pane-14">14</div>
</div>
</body>
<script type="module">
import anime from '../../src/index.js';
import animePlayer from '../assets/js/anime.player.js'
// Scrolling helper
function onScroll(cb) {
var isTicking = false;
var scrollY = 0;
var body = document.body;
var html = document.documentElement;
var scrollHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
function scroll() {
scrollY = window.scrollY;
if (cb) cb(scrollY, scrollHeight);
requestTick();
}
function requestTick() {
if (!isTicking) requestAnimationFrame(updateScroll);
isTicking = true;
}
function updateScroll() {
isTicking = false;
var currentScrollY = scrollY;
}
scroll();
window.onscroll = scroll;
}
var began = 0;
var completed = 0;
function logChangeBegan(instance) {
began++;
// console.log(instance.id, 'CHANGE BEGAN', instance.changeBegan);
}
function logChangeComplete(instance) {
completed++;
// console.log(instance.id, 'CHANGE COMPLETE', instance.changeCompleted);
}
window.tl = anime.timeline({
easing: 'easeInOutSine',
autoplay: false,
duration: 1000,
// delay: 500,
// endDelay: 500,
update: function(instane) {
console.log(instane.reversePlayback);
}
})
.add({
targets: '.pane-01',
translateY: '-100vh',
background: '#FF1461',
changeBegin: logChangeBegan,
changeComplete: logChangeComplete
})
.set('.pane-02', {'translateY': '-100vh'})
.add({
targets: '.pane-02',
translateX: ['100%', 0],
background: '#FF1461',
changeBegin: logChangeBegan,
changeComplete: logChangeComplete
}, '-=500')
.set('.pane-03', {'translateY': '-200vh'})
.add({
targets: '.pane-03',
translateY: '-100vh',
background: '#FF1461',
changeBegin: logChangeBegan,
changeComplete: logChangeComplete
}, '-=500')
.set('.pane-04', {'translateY': '-100vh'})
.add({
targets: '.pane-04',
scale: [0, 1],
background: '#FF1461',
changeBegin: logChangeBegan,
changeComplete: logChangeComplete,
}, '-=500')
.add({
targets: '.pane-05',
translateY: '-100vh',
rotate: [-180, 0],
background: '#FF1461',
changeBegin: logChangeBegan,
changeComplete: logChangeComplete,
}, '-=500')
.add({
targets: '.pane-06',
translateY: '-100vh',
background: '#FF1461',
changeBegin: logChangeBegan,
changeComplete: logChangeComplete,
}, '-=500')
.add({
targets: '.pane-07',
translateY: '-100vh',
background: '#FF1461',
changeBegin: logChangeBegan,
changeComplete: logChangeComplete,
}, '-=500')
.add({
targets: '.pane-08',
translateY: '-100vh',
background: '#FF1461',
changeBegin: logChangeBegan,
changeComplete: logChangeComplete,
}, '-=500')
.add({
targets: '.pane-09',
translateY: '-100vh',
background: '#FF1461',
changeBegin: logChangeBegan,
changeComplete: logChangeComplete,
}, '-=500')
.add({
targets: '.pane-10',
translateY: '-100vh',
background: '#FF1461',
changeBegin: logChangeBegan,
changeComplete: logChangeComplete,
}, '-=500')
.add({
targets: '.pane-11',
translateY: '-100vh',
background: '#FF1461',
changeBegin: logChangeBegan,
changeComplete: logChangeComplete,
}, '-=500')
.add({
targets: '.pane-12',
translateY: '-100vh',
background: '#FF1461',
changeBegin: logChangeBegan,
changeComplete: logChangeComplete,
}, '-=500')
.add({
targets: '.pane-13',
translateY: '-100vh',
background: '#FF1461',
changeBegin: logChangeBegan,
changeComplete: logChangeComplete,
}, '-=500')
.add({
targets: '.pane-14',
translateY: '-100vh',
background: '#FF1461',
changeBegin: logChangeBegan,
changeComplete: logChangeComplete,
}, '-=500')
onScroll(function(top, scrollHeight) {
var currentTime = tl.duration * (top / (scrollHeight - window.innerHeight));
tl.seek(currentTime);
});
</script>
<!-- <script src="../assets/js/vendors/stats.min.js"></script> -->
</html>
| {
"content_hash": "9576e5a6cfa63c01c5522f707b028eba",
"timestamp": "",
"source": "github",
"line_count": 238,
"max_line_length": 127,
"avg_line_length": 27.067226890756302,
"alnum_prop": 0.6220117975783918,
"repo_name": "juliangarnier/anime",
"id": "d5c1d6a95396ae2e5a7f14ff46051dc862a1f005",
"size": "6442",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "documentation/examples/follow-scroll.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "125954"
}
],
"symlink_target": ""
} |
<?php
class Login extends CI_Controller {
function __construct() {
parent::__construct();
(!isset($_SESSION)) ? session_start() : '';
$this->load->model('login_model');
if ($this->session->userdata('username')) {
redirect('dashboard');
}
}
function index() {
$this->load->view('login');
}
function process() {
$this->form_validation->set_rules('username', 'username', 'required|trim|xss_clean');
$this->form_validation->set_rules('password', 'password', 'required|trim|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login');
}else {
echo $this->input->post('username');
echo $this->input->post('password');
$username = trim($this->input->post('username'));
$password = md5(trim($this->input->post('password')));
$getLogin = $this->login_model->getLogin($username, $password);
if ($getLogin->num_rows() > 0) {
//login is true, create session
foreach ($getLogin->result() as $user) {
$sess_data['id_user'] = $user->id_user;
$sess_data['name'] = $user->name;
$sess_data['lastname'] = $user->lastname;
$sess_data['username'] = $user->username;
$sess_data['email'] = $user->email;
$sess_data['profile'] = $user->profile_id;
$sess_data['picture'] = $user->picture;
$query = $this->db->get_where('profiles', array('id_profile ' => $sess_data['profile']))->row_array();
$sess_data['profile_name'] = $query['name'];
$sess_data['fullname'] = $user->name.' '.$user->lastname;
$this->session->set_userdata($sess_data);
}
redirect('dashboard');
} else {
$this->session->set_flashdata('result_login', '<br>El usuario o contraseña son incorrectas.');
redirect('login');
}
}
}
function logout() {
$this->session->sess_destroy();
redirect('login');
}
}
| {
"content_hash": "2c310ab084adb28a1c5df6109fb0aa0a",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 122,
"avg_line_length": 36.73015873015873,
"alnum_prop": 0.4736387208297321,
"repo_name": "davidj882/tasks",
"id": "5aeaa65fdb04cd8b6f83f829235206a3123df6d3",
"size": "2315",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/controllers/Login.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "612970"
},
{
"name": "HTML",
"bytes": "12616"
},
{
"name": "JavaScript",
"bytes": "3051035"
},
{
"name": "PHP",
"bytes": "2185251"
}
],
"symlink_target": ""
} |
package persist;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.Named;
import com.googlecode.objectify.Key;
import entity.Auth;
import entity.Presentation;
import entity.User;
import java.util.List;
import java.util.logging.Logger;
import static persist.OfyService.ofy;
/**
* Created by vku131 on 1/21/17.
*/
public class UserOfy {
public static final Logger logger = Logger.getLogger(UserOfy.class.getName());
//we do not need instance of this class.
private UserOfy() {
}
public static Key<User> save(User user) {
// TODO logging missing.
return ofy().save().entity(user).now();
}
public static User loadByKey(Key<User> key) {
logger.info("key=" + key);
return ofy().load().key(key).safe();
}
public static User loadByFbId(String fbId) {
logger.warning("fbId=" + fbId);
User user = ofy().load().type(User.class).filter("fbId =", fbId).first().now();
return user;
}
public static User loadBySenderId(String senderId) {
logger.warning("senderId=" + senderId);
User user = ofy().load().type(User.class).filter("senderId =", senderId).first().now();
return user;
}
}
| {
"content_hash": "f889127ae24ab7c90e1476d66fa69416",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 95,
"avg_line_length": 27.108695652173914,
"alnum_prop": 0.6511627906976745,
"repo_name": "vinaymavi/session",
"id": "fc507531ba3ec6c701e10107f441bfe0659a70db",
"size": "1247",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/persist/UserOfy.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "48278"
},
{
"name": "CSS",
"bytes": "21175"
},
{
"name": "HTML",
"bytes": "14153"
},
{
"name": "Java",
"bytes": "22773"
},
{
"name": "JavaScript",
"bytes": "54888"
}
],
"symlink_target": ""
} |
using ExtendedXmlSerializer.Core.Sources;
namespace ExtendedXmlSerializer.ContentModel.Collections
{
interface ICollectionContents : IParameterizedSource<CollectionContentInput, ISerializer> {}
} | {
"content_hash": "f30220fc3673e955736f509644aa43b8",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 93,
"avg_line_length": 32.833333333333336,
"alnum_prop": 0.868020304568528,
"repo_name": "Mike-EEE/ExtendedXmlSerializer",
"id": "3334d6497572ffde3a3eb7c5a3ae3727b9975b2d",
"size": "197",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/ExtendedXmlSerializer/ContentModel/Collections/ICollectionContents.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1426654"
},
{
"name": "HTML",
"bytes": "41908"
},
{
"name": "PowerShell",
"bytes": "2402"
},
{
"name": "Smalltalk",
"bytes": "3"
}
],
"symlink_target": ""
} |
namespace Google.Cloud.Compute.V1.Snippets
{
// [START compute_v1_generated_VpnGateways_TestIamPermissions_async_flattened]
using Google.Cloud.Compute.V1;
using System.Threading.Tasks;
public sealed partial class GeneratedVpnGatewaysClientSnippets
{
/// <summary>Snippet for TestIamPermissionsAsync</summary>
/// <remarks>
/// This snippet has been automatically generated and should be regarded as a code template only.
/// It will require modifications to work:
/// - It may require correct/in-range values for request initialization.
/// - It may require specifying regional endpoints when creating the service client as shown in
/// https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
/// </remarks>
public async Task TestIamPermissionsAsync()
{
// Create client
VpnGatewaysClient vpnGatewaysClient = await VpnGatewaysClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string resource = "";
TestPermissionsRequest testPermissionsRequestResource = new TestPermissionsRequest();
// Make the request
TestPermissionsResponse response = await vpnGatewaysClient.TestIamPermissionsAsync(project, region, resource, testPermissionsRequestResource);
}
}
// [END compute_v1_generated_VpnGateways_TestIamPermissions_async_flattened]
}
| {
"content_hash": "0b932e16b9cc917e8ab4dd81e708c3da",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 154,
"avg_line_length": 49.38709677419355,
"alnum_prop": 0.6838667537557153,
"repo_name": "googleapis/google-cloud-dotnet",
"id": "26d363d89fb667b939f01024a9096543a393a0cc",
"size": "2153",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "apis/Google.Cloud.Compute.V1/Google.Cloud.Compute.V1.GeneratedSnippets/VpnGatewaysClient.TestIamPermissionsAsyncSnippet.g.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "767"
},
{
"name": "C#",
"bytes": "319820004"
},
{
"name": "Dockerfile",
"bytes": "3415"
},
{
"name": "PowerShell",
"bytes": "3303"
},
{
"name": "Python",
"bytes": "2744"
},
{
"name": "Shell",
"bytes": "65881"
}
],
"symlink_target": ""
} |
2.4.4 / 2012-09-12
==================
* Fixed `RuntimeException` namespacing error
* Added `FormatterManager::disableFormatter(s)` method
* Updated Gherkin parser and fixed couple of helper bugs
2.4.3 / 2012-07-28
==================
* Fixed broken `output_path` setting ([issue #169](https://github.com/Behat/Behat/issues/169))
* Added shellbang to phar executable ([issue #167](https://github.com/Behat/Behat/issues/167))
* Added feature title to progress exceptions ([issue #166](https://github.com/Behat/Behat/issues/166))
* Tuned failed formatter to print only failed examples in outline ([issue #154](https://github.com/Behat/Behat/issues/154))
* Small bugfixes
2.4.2 / 2012-06-26
==================
* Fixed broken autoloading with Composer installation
2.4.1 / 2012-06-26
==================
* Force custom context class usage if user changed it from `FeatureContext`
* Clarified `Context class not found` exception
* Use CWD for CLI options, basepath (config path) for everything else
* Pass `behat.extension.classes` container param to extensions during their load
* Tuned `event_subscriber` priorities
* Use `require_once` instead of `require` in closured loaders
* Fixed transformers bug with falsy transformations (that return **falsy** values)
* Fixed custom formatters definition bug
* Fixed formatter manager exception bug
* Fixed czech translation
* Fixed CS to be PSR2 compliant
2.4.0 / 2012-05-15
==================
* New extension system based on Symfony2 DIC component
* Refactored paths reading system (now relative paths are fully supported)
* Support latest Composer changes
* Removed static constraint for transformations
* Updated to latest Gherkin with immutable AST
* Fixed couple of definition snippet generator bugs
* Option for HTML formatter to provide step definition links
* Added fallback locale (in case if provided lang is unsupported yet)
* Print step snippets in HTML formatter only if they're enabled
* Escape placeholder brackets in HTML formatter
* Use different names for examples in JUnit formatter
* Major core cleanup
2.3.5 / 2012-03-30
==================
* Fixed formatter language configuration and locale guesser
2.3.4 / 2012-03-28
==================
* Added `StepEvent::getLogicalParent()`. Fixed issue #115
2.3.3 / 2012-03-09
==================
* Implemented Gherkin caching support ([--cache](https://github.com/Behat/Behat/commit/753c4f6e392a873a640543306191d92e6dc91099))
* Line ranges filtering support (`behat features/some.feature:12-19`. Thanks @headrevision)
* `behat.yml.dist` configs support out of the box
* Minor bug fixes
* Updated Gherkin
2.3.2 / 2012-01-29
==================
* Fixed bug in `ErrorException`, that caused wrong exceptions on warnings and notices
2.3.1 / 2012-01-26
==================
* Updated error handler to avoid suppressed exceptions
* Autoload bootstrap scripts in their name order
* Updated Gherkin dependency to v2.0.1
2.3.0 / 2012-01-19
==================
* Switch to the Behat\Gherkin 2.0 usage
* Migration to the single-file translation
* Support for callables inside steps chains
* Support for `*.yml` and `*.php` as definition translations
* Added opposite options to option switchers (`--[no-]colors`, `--[no-]multiline`, etc.)
* Redesigned `--story-syntax`
* Refactored Runner
* Performance improvements
* Bugfixes
2.2.7 / 2012-01-13
==================
* Added ability to search translated definitions with `--definitions`
* Fixed custom formatters use bug
2.2.6 / 2012-01-09
==================
* Fixed pretty and html formatters printing of undefined steps in outlines
2.2.5 / 2012-01-07
==================
* `BEHAT_PARAMS` env variable support (083092e)
* HTML formatter print styles optimization (@davedevelopment)
2.2.4 / 2012-01-04
==================
* Prevent method name duplication with definition snippets
2.2.3 / 2012-01-04
==================
* Fixed couple of `--append-snippets` bugs
2.2.2 / 2011-12-21
==================
* Fixed Composer deps
2.2.1 / 2011-12-21
==================
* Fixed Composer package bin
2.2.0 / 2011-12-14
==================
* Multiple formats and outputs support
* New `snippets` formatter
* New `failed` formatter
* Updated output of `-d` option
* Search abilities added to `-d` option
* New `--dry-run` option
* New `--append-snippets` option
* Rerun functionality refactored to use `failed` formatter internally
* Overall code refactoring and cleaning
* Polish translation added (Joseph Bielawski)
* Spanish translation updated (Andrés Botero)
* Locale autodetect
2.1.3 / 2011-11-04
==================
* Substep translations support
* Correctly print undefined substeps in pretty printer
* @Transform callback now gets all provided matches
* Always set proper encoding (UTF8)
2.1.2 / 2011-10-12
==================
* Fixed filtered feature hooks
* Fixed JUnit formatter time output in some locales
2.1.1 / 2011-10-09
==================
* Fixed multiline titles printing bug
* Fixed outline parameter inside step argument printing bug
2.1.0 / 2011-09-12
==================
* Totally revamped HTML formatter template
* Added transliteration support to definition snippets (for most langs)
* Written missed features and fixed some bugs
* Stabilization fixes for 3 major OS: MacOS/Ubuntu/Windows
2.0.5 / 2011-08-07
==================
* Cleaned ContextDispatcher extension points
* Cleaned context-parameters passing behavior
2.0.4 / 2011-08-02
==================
* Subcontexts aliasing and retrieving
* Multiple steps chaining
* `--snippets-paths` option to show steps alongside the snippets
* getContextParameters() method in SuiteEvent and FeatureEvent
* Updated to Symfony2 stable components
* Spanish translation
* Dutch translation
2.0.3 / 2011-07-20
==================
* Fixed JUnit formatter CDATA output
2.0.2 / 2011-07-17
==================
* Added extra checks to context instance mapper
* Fixed i18n support in definitions printer
* Refactored Gherkin tags inheritance
2.0.1 / 2011-07-12
==================
* Exception prefix added to statuses. Now you should throw `PendingException` instead of just
`Pending`
2.0.0 / 2011-07-12
==================
* Brand new Context-oriented architecture
* Refactored --definitions (--steps) to print more useful info
* Rafactored --story-syntax (--usage) to print more useful info
* Refactored Command to use separate processors
* Added --no-paths option
* Added --no-snippets option
* Added --expand option to expand outlines
* phar package
* Faster autoloader
* Steps chaining added
* Added BEHAT_ERROR_REPORTING constant to change error_repoting level
* Fixed some Gherkin bugs
* Fixed lots of bugs in Behat itself
1.1.9 / 2011-06-17
==================
* Updated to the latest Symfony components
1.1.8 / 2011-06-09
==================
* Fixed empty match printing in Pretty and HTML formatters
* Updated to latest Symfony components
1.1.7 / 2011-06-03
==================
* Fixed steps colorization bug in outline
* Additional checks in config import routine
1.1.6 / 2011-05-27
==================
* Updated Symfony vendors
* Refactored console formatters
1.1.5 / 2011-05-17
==================
* Fixed CWD path finding
* Fixed HTML formatter (thanks @glenjamin)
1.1.4 / 2011-05-03
==================
* Fixed `--out` option usage critical bug
* Added ability to specify `output_path` from config file
1.1.3 / 2011-04-28
==================
* JUnit formatter fix
* Formatters basePath fix. Now formatters uses CWD as path trimmer
* Relative paths locator bug fix
* Show table argument header in HTML formatter
1.1.2 / 2011-04-27
==================
* Fixed custom features path locator bug(issue #020)
1.1.1 / 2011-04-21
==================
* Fixed paths finding routines
* Totally refactored BehatCommand
* Added rerun functionality (`--rerun`)
* Ability to remove previously specified paths in `behat.yml`
* Bugfixes and little tweaks
1.1.0 / 2011-04-04
==================
* New configuration system with profiles and imports support
* New event system
* Environment parameters support
* Named regex arguments support
* Japanese translation for formatters
* JUnit formatter bugfixes
* HTML and Pretty formatters multiple arguments print bugfix
* Step snippets (proposals) bugfixes
* Updated vendor libraries
1.0.0 / 2011-03-08
==================
* Changed XSD
* Updated vendors
1.0.0RC6 / 2011-03-03
=====================
* Cleaned command options
* Added --init option
* Multiple paths support in behat.yml
* Application options refactoring
1.0.0RC5 / 2011-02-25
=====================
* Windows support
* Bundled features hooks optimizations
1.0.0RC4 / 2011-02-23
=====================
* Pretty formatter tag printing fix
* Custom formatter specification fix in `behat.yml`
* Symfony components updated
* Extension configuration manager (Symfony\Component\Config component)
* Cleaning of `behat.yml` configurator (thanks to Symfony\Component\Config)
* Additional formatter parameters support in `behat.yml`
1.0.0RC3 / 2011-02-18
=====================
* Event dispatcher binding optimizations
* Command API optimizations for easier overloading
* Formatter path trimming bugfix
* BehatExtension config merging support
1.0.0RC2 / 2011-02-15
=====================
* Step printing option bugfix
1.0.0RC1 / 2011-02-15
=====================
* Gherkin DSL parser is standalone project
* Own Behat namespace for both Behat & Gherkin
* Fully rewritten formatters (much cleaner & beautifull API)
* Big refactoring of whole Behat code (clean code DRYing)
* Config file is now handled by standart-driven DIC extension (cleaner `behat.yml`)
* API documentation retouched
* New `--strict` option
* New `--no-multiline` option
* Feature examples in your language with `--usage`
* Available definitions listing with `--steps`
* Definition i18n
* Command refactoring (much cleaner API & actions)
* Event system refactoring
* 42 new languages with new Gherkin DSL parser
0.3.6 / 2010-12-07
==================
* [Behat,Gherkin] Fixed French support includes (fr)
0.3.6 / 2010-12-06
==================
* [Behat] Updated Symfony2 Components to latest PR4
* [Gherkin] Added French support (fr)
* [Gherkin] Added German support (de)
* [Behat] Small bugfixes
0.3.5 / 2010-11-19
==================
* [Behat] Refactored EnvironmentBuilder to allow Environment service definition overload
0.3.4 / 2010-11-18
==================
* [Behat] Introduced environment builder
* [Gherkin,Behat] id locale support
0.3.3 / 2010-11-07
==================
* [Gherkin] Added ability to create Table & PyString nodes with hands (in your step to step calls for example)
* [Gherkin] Added getRowsHash() method to TableNode, so now you can "rotate" given tables
* [Gherkin] You now can add comments before language specification in your feature files
0.3.2 / 2010-11-06
==================
* [Gherkin] Added ability to specify extended langs (en-US)
* [Behat,Gherkin] Added pt-BR translation
0.3.1 / 2010-11-02
==================
* [Behat] JUnit formatter
* [Behat] Pretty & HTML formatter background hooks fix
* [Behat] Other small fixes
0.3.0 / 2010-11-02
==================
* [Behat] Refactored tags filter
* [Behat] Added name filter
* [Behat] Refactored hooks
* [Behat] Added tagged/named hooks
* [Behat] Customizable HTML formatter with w3c valid default markup
* [Behat] Ability to specify out path for formatters
* [Behat] Bunch of new options
* [Behat] DIC optimisations
0.2.5 / 2010-10-22
==================
* [Behat] Format manager introduced
* [Behat] Formatters refactoring
* [Behat] Optmized container parameters to support EverzetBehatBundle
* [Behat] --no-color => --no-colors
0.2.4 / 2010-10-19
==================
* [Behat] Autoguess of colors support
* [Behat] Formatter setup bugfix (properl casing)
0.2.3 / 2010-10-19
==================
* [Behat] Filters optimisations
* [Behat] Changed Core Loaders with topic-specific (`StepDefinition\Loader\PHPLoader`,
`Features\Loader\GherkinLoader`)
* [Behat] Simplified TestCommand in prepare of Symfony2 BehatBundle
* [Behat] Configuration file/path setting update (you can now create `behat.yml` inside `./config/behat.yml` & Behat
will load it
* [Behat] Updated Redundant & Ambiguous exceptions behavior
0.2.2 / 2010-10-10
==================
* [Behat] Configuration file/path setting update
0.2.1 / 2010-10-10
==================
* [PEAR] Fix path to phpbin on installation
0.2.0 / 2010-10-08
==================
* [Behat] Brand new stateless testers, based on Visitor pattern
* [Behat] Refactored event listeners & event names
* [Behat] Refactored formatters to confirm with new stateless testers (statuses now sent as event parameters)
* [Behat] Refactored ConsoleFormatter (and removed base formatter)
* [Behat] Removed custom I18n classes & refactored Translator routines in flavor of Symfony\Component\Translation
* [Behat] Added missed translation strings into XLIFF files
* [Behat] Optimised multiline arguments (Node instances are sent to definitions instead of their plain representations)
* [Behat] Support for Scenario Outline tokens replace in multiline arguments (tables & pystrings)
* [Behat] Step arguments transformations (including table transformations)
* [Behat] Colorize inline step arguments
* [Behat] Optimized exit statuses of CLI
* [Behat] Added ability to turn-off colors
* [Behat] Added ability to translate formatters output with `--i18n` option
* [Behat] Bunch of new core feature tests
* [Gherkin] Parser now uses Symfony Dependency Injection to
* [Gherkin] Refactored parser to be like AST (Nodes that supports Visitor pattern)
* [Gherkin] Comments support
* [Gherkin] Fixed PHPUnit warnings
* [Behat,Gherkin] PEAR release script to support http://pear.everzet.com release model
* [Behat,Gherkin] DIC naming refactoring
* [Behat,Gherkin] Autoloader refactoring
* [Behat,Gherkin] Removed Zend & Goutte depencies
0.1.5 / 2010-09-25
==================
* Added ability to call other steps inside step definition
* Added profiles
* Refactored container creation routine
* Single quotes support in step definitions
* Added tests for hooks, profiles, inline steps
0.1.4 / 2010-09-16
==================
* Refactored code
* Removed logic from object constructors
* Added Loader & Filter interfaces
0.1.3 / 2010-09-14
==================
* Ability to specify arrays of paths/files for loaders
* Event hooks and support for `support/hooks.php`
* Formatters listens events with smallest priority
* Don't try to load steps if `steps` folder doesn't exists
* Bugfixes/refactoring
0.1.2 / 2010-09-10
==================
* Added ability to read from `behat.yml` and `behat.xml`
* Moved tags filter to separate object
* Refactored injection controller
* Optimized event names in event dispatcher
* Other small fixes/refactorings
0.1.1 / 2010-09-09
==================
* Added `--tags` option
* Changed environment (world) routines
* Added lots of core tests (writed in Behat itself)
0.1.0 / 2010-09-08
==================
* Initial release
| {
"content_hash": "c8d646523b159bcd08c00e03386d7eca",
"timestamp": "",
"source": "github",
"line_count": 522,
"max_line_length": 131,
"avg_line_length": 30.68007662835249,
"alnum_prop": 0.652138620043709,
"repo_name": "lrt/lrt",
"id": "939d61a445226a604ec510714d387138505593e1",
"size": "16016",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/behat/behat/CHANGES.md",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "143710"
},
{
"name": "PHP",
"bytes": "256054"
},
{
"name": "Perl",
"bytes": "1091"
},
{
"name": "Shell",
"bytes": "2275"
}
],
"symlink_target": ""
} |
import { Iterable, IteratorCallback} from './Iterable';
import { LinkedList } from './LinkedList';
export class Stack<T> implements Iterable<T>
{
private list:LinkedList<T>;
constructor(contents:T[] = null)
{
this.list = new LinkedList<T>(contents);
}
public each(e:IteratorCallback<T>):void
{
this.list.each(e);
}
public peek():T
{
return this.list.first();
}
public pop():T
{
var item = this.list.last();
if (item)
{
this.list.remove(item);
}
return item;
}
public push(item:T):void
{
if (this.list.count())
{
this.list.insertBefore(this.list.first(), item);
}
else
{
this.list.add(item);
}
}
public count():number
{
return this.list.count();
}
public toArray():T[]
{
return this.list.toArray();
}
} | {
"content_hash": "facde524f125b555eee8fe81b05a4f3d",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 60,
"avg_line_length": 17.196428571428573,
"alnum_prop": 0.5015576323987538,
"repo_name": "swhitf/paladin-collections",
"id": "a0c8b116824f20a0a8d94ea5bde88362f3d4810d",
"size": "963",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Stack.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "TypeScript",
"bytes": "23411"
}
],
"symlink_target": ""
} |
<!doctype html>
<html lang="en">
<html>
<head>
<meta charset="utf-8">
<title>BikeBuddy</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="shortcut icon" href="/favicon.png">
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Bike buddy</h1>
<!--Navigation, ej uppdaterad kod-->
<nav class="navbar navbar-default">
<div class="container-fluid">
<ul class="nav navbar-nav">
<li class="active"><a href="/index">Home</a></li>
<li><a href="/api">API Examples</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="/login">Login</a></li>
<li><a href="/signup">Create Account</a></li>
</ul>
</div>
</nav>
<!--den högra bilden på skärmen -->
<div id="pip-pano"></div>
<!--kartan till vänster-->
<div id="map-canvas"></div>
<footer>
<div class="footer navbar-fixed-bottom">
<div class="container text-center">
<p class="pull-left">© 2016 Malmö Högskola, Inc. All Rights Reserved</p>
<ul class="pull-right list-inline">
<li><a href="http://www.malmotown.com">Malmö stad</a></li>
<li><a href="http://mah.se">MAH</a></li>
</ul>
</div>
</div>
</footer>
<!--script used for google maps-->
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="markercluster.js"></script>
<script src="List.js"></script>
<script src="Mapster.js"></script>
<script src="mapoptions.js"></script>
<script src="jquery.mapster.js"></script>
<script src="script.js"></script>
</body>
</html> | {
"content_hash": "3222a5a69d7f4a5d200d41eb08afbebb",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 100,
"avg_line_length": 30.942028985507246,
"alnum_prop": 0.62903981264637,
"repo_name": "henkeklein/MalmoeCykel",
"id": "a59540931c9d3048301801065713893170b0fe31",
"size": "2143",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "views/maps/google.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "152918"
},
{
"name": "HTML",
"bytes": "20680"
},
{
"name": "JavaScript",
"bytes": "67266"
}
],
"symlink_target": ""
} |
package org.jetbrains.plugins.scala
package lang
package psi
package stubs
package elements
import _root_.org.jetbrains.plugins.scala.lang.psi.impl.statements.ScTypeAliasDefinitionImpl
import api.statements.ScTypeAlias
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
/**
* User: Alexander Podkhalyuzin
* Date: 18.10.2008
*/
class ScTypeAliasDefinitionElementType extends ScTypeAliasElementType[ScTypeAlias]("type alias definition"){
def createElement(node: ASTNode): PsiElement = new ScTypeAliasDefinitionImpl(node)
def createPsi(stub: ScTypeAliasStub) = new ScTypeAliasDefinitionImpl(stub)
} | {
"content_hash": "2e2b4cf1d65c247cd95992c508528a89",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 108,
"avg_line_length": 29.666666666666668,
"alnum_prop": 0.8218298555377207,
"repo_name": "consulo/consulo-scala",
"id": "25937c159eccf4ded02ba06083757f661d05cf4f",
"size": "623",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/org/jetbrains/plugins/scala/lang/psi/stubs/elements/ScTypeAliasDefinitionElementType.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "997934"
},
{
"name": "Scala",
"bytes": "6655362"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.jforum</groupId>
<artifactId>jforum</artifactId>
<version>2.4.1-snapshot</version>
<packaging>war</packaging>
<name>JForum</name>
<description>JForum is a powerful and robust discussion board system implemented in Javatm. It provides an attractive interface, an efficient forum engine, an easy to use administrative panel, an advanced permission control system and much more. </description>
<url>http://jforum2.googlecode.com</url>
<issueManagement>
<system>Google Code</system>
<url>http://code.google.com/p/jforum2/issues/list</url>
</issueManagement>
<scm>
<connection>svn</connection>
<url>http://jforum2.googlecode.com/svn/</url>
</scm>
<repositories>
<repository>
<id>jboss</id>
<name>jboss public</name>
<url>https://repository.jboss.org/nexus/content/groups/public/</url>
</repository>
<repository>
<id>jahia</id>
<name>jahia</name>
<url>http://maven.jahia.org/maven2/</url>
</repository>
<repository>
<id>codelds</id>
<url>https://code.lds.org/nexus/content/groups/main-repo</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>dumbster</groupId>
<artifactId>dumbster</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>mail</artifactId>
<groupId>javax.mail</groupId>
</exclusion>
</exclusions>
<version>1.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.3</version>
</dependency>
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
<version>2.0.6</version>
<exclusions>
<exclusion>
<artifactId>maven-findbugs-plugin</artifactId>
<groupId>maven-plugins</groupId>
</exclusion>
<exclusion>
<artifactId>maven-cobertura-plugin</artifactId>
<groupId>maven-plugins</groupId>
</exclusion>
<exclusion>
<artifactId>xom</artifactId>
<groupId>xom</groupId>
</exclusion>
<exclusion>
<artifactId>jaxen</artifactId>
<groupId>jaxen</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
<type>jar</type>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.22</version>
</dependency>
<dependency>
<groupId>org.htmlparser</groupId>
<artifactId>htmlparser</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers</artifactId>
<version>3.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-highlighter</artifactId>
<version>3.6.2</version>
</dependency>
<dependency>
<groupId>org.beanshell</groupId>
<artifactId>bsh</artifactId>
<version>2.0b5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
<exclusions>
<exclusion>
<artifactId>c3p0</artifactId>
<groupId>c3p0</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.jboss.cache</groupId>
<artifactId>jbosscache-core</artifactId>
<version>3.2.7.GA</version>
<exclusions>
<exclusion>
<artifactId>jgroups</artifactId>
<groupId>jgroups</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.jboss</groupId>
<artifactId>jboss-common-core</artifactId>
<version>2.2.22.GA</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging-spi</artifactId>
<version>2.1.2.GA</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.4.8</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-jgroupsreplication</artifactId>
<version>1.4</version>
<type>jar</type>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.jgroups</groupId>
<artifactId>jgroups</artifactId>
<version>2.12.3.Final</version>
</dependency>
<dependency>
<groupId>com.octo.captcha</groupId>
<artifactId>jcaptcha</artifactId>
<version>1.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1201-jdbc4</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>12.1.0.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-parsers</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>org.owasp</groupId>
<artifactId>csrfguard</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
<build>
<finalName>jforum</finalName>
<resources>
<resource>
<directory>src/main/resources/templates</directory>
<excludes>
<exclude>**/*</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<archiveClasses>true</archiveClasses>
<packagingExcludes>WEB-INF/web.xml</packagingExcludes>
<webResources>
<resource>
<directory>.</directory>
<includes>
<include>license.txt</include>
</includes>
</resource>
</webResources>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.7</version>
<executions>
<execution>
<id>copy-config</id>
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/config</outputDirectory>
<resources>
<resource>
<directory>src/main/config</directory>
<filtering>false</filtering>
</resource>
</resources>
</configuration>
</execution>
<execution>
<id>copy-templates</id>
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/${project.build.finalName}/templates</outputDirectory>
<resources>
<resource>
<directory>src/main/resources/templates</directory>
<filtering>false</filtering>
</resource>
</resources>
</configuration>
</execution>
<execution>
<id>copy-upgrade</id>
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/${project.build.finalName}/upgrade</outputDirectory>
<resources>
<resource>
<directory>upgrade</directory>
<filtering>false</filtering>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
| {
"content_hash": "3065bd01de49b731b8bcaebb210be08e",
"timestamp": "",
"source": "github",
"line_count": 353,
"max_line_length": 261,
"avg_line_length": 28.8328611898017,
"alnum_prop": 0.6449204165847907,
"repo_name": "mheinzerling/jforum2",
"id": "a280be0df7691aba8d6207e9f00f4da3bc1e1392",
"size": "10178",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "pom.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "53145"
},
{
"name": "HTML",
"bytes": "384195"
},
{
"name": "Java",
"bytes": "2000664"
},
{
"name": "JavaScript",
"bytes": "40736"
},
{
"name": "PLSQL",
"bytes": "49172"
}
],
"symlink_target": ""
} |
import { TX_TYPES } from "../constants";
import BLOCKCHAIN_INFO from "../../../../env";
import { convertTimestampToTime, shortenBigNumber, formatAddress, splitArrayToChunks } from "../../utils/converter";
import { validateResultObject, returnResponseObject, validateTransferTx, validateSwapTx, validateApproveTx, validateUndefinedTx } from "../portfolioService"
import {getResolutionForTimeRange, getFromTimeForTimeRange, parseTxsToTimeFrame, isEmptyWallet,
mappingBalanceChange, mappingTotalBalance, getArrayTradedTokenSymbols, timelineLabels,
CHART_RANGE_IN_SECOND, TIME_EPSILON} from "./portfolioChartUtils"
export async function getLastestBalance(ethereum, userAddr, supportTokens) {
try {
const lastestBlock = await ethereum.call("getLatestBlock", userAddr, supportTokens)
const balances = await ethereum.call("getAllBalancesTokenAtSpecificBlock", userAddr, supportTokens, lastestBlock)
return balances
} catch (error) {
return {inQueue: true}
}
}
function getTokenByAddress(tokens){
return Object.values(tokens).reduce((result, token) => {
Object.assign(result, {[token.address]: token.symbol});
return result
}, {});
}
export async function render(ethereum, address, tokens, rangeType) {
const now = Math.floor(new Date().getTime() / 1000) - TIME_EPSILON
const innitTime = now - CHART_RANGE_IN_SECOND[rangeType]
const addrTxs = await getBalanceTransactionHistoryByTime(address, innitTime, now)
const isEmpty = isEmptyWallet(addrTxs)
if (addrTxs.isError || addrTxs.inQueue) {
// todo handle history no txs
return { isError: addrTxs.isError, inQueue: addrTxs.inQueue}
}
const txs = addrTxs.data
if (!txs) return {isError: true}
const balanceTokens = await getLastestBalance(ethereum, address, tokens)
if(balanceTokens.inQueue){
return { inQueue: balanceTokens.inQueue}
}
const tokenByAddress = getTokenByAddress(tokens)
const chartResolution = getResolutionForTimeRange(rangeType)
const chartFromTime = getFromTimeForTimeRange(rangeType, now)
const txByResolution = parseTxsToTimeFrame(txs, chartResolution, chartFromTime, now)
const arrayTradedTokenSymbols = getArrayTradedTokenSymbols(txs, tokenByAddress, balanceTokens)
const balanceChange = mappingBalanceChange(txByResolution, balanceTokens, tokenByAddress, tokens, address)
const priceInResolution = await fetchTradedTokenPrice(chartFromTime, now, chartResolution, arrayTradedTokenSymbols)
const totalBalance = mappingTotalBalance(balanceChange, priceInResolution)
const labelSeries = timelineLabels(chartFromTime, now, chartResolution)
return {
...totalBalance,
label: labelSeries,
isEmpty: isEmpty
}
}
export async function getBalanceTransactionHistoryByTime(address, from, to) {
const response = await fetch(`${BLOCKCHAIN_INFO.portfolio_api}/transactions?address=${address}&startTime=${from}&endTime=${to}`);
const result = await response.json();
const isValidResult = validateResultObject(result);
if (!isValidResult) return returnResponseObject([], 0, false, true);
const kyberContract = BLOCKCHAIN_INFO.network.toLowerCase();
const bigAllowance = 1000000;
let txs = [];
for (let i = 0; i < result.data.length; i++) {
const tx = result.data[i];
let isValidTx = false;
if (tx.type === TX_TYPES.send || tx.type === TX_TYPES.receive) {
isValidTx = validateTransferTx(tx);
} else if (tx.type === TX_TYPES.swap) {
isValidTx = validateSwapTx(tx);
} else if (tx.type === TX_TYPES.approve) {
isValidTx = validateApproveTx(tx);
if (isValidTx) {
const allowance = tx.approve_allowance;
const spender = tx.approve_spender.toLowerCase();
const isKyberContract = spender === kyberContract;
let formattedAllowance = allowance;
if (allowance > bigAllowance) {
formattedAllowance = isKyberContract ? '' : shortenBigNumber(allowance);
}
tx.formattedContract = isKyberContract ? 'Kyber Contract' : formatAddress(spender, 10);
tx.formattedAllowance = formattedAllowance;
}
} else if (tx.type === TX_TYPES.undefined) {
isValidTx = validateUndefinedTx(tx);
}
if(+tx.timeStamp < from || +tx.timeStamp > to){
isValidTx = false
}
if (isValidTx) {
tx.time = convertTimestampToTime(+tx.timeStamp);
txs.push(tx);
}
}
return returnResponseObject(txs, result.count, result.in_queue);
}
export async function fetchTradedTokenPrice(fromTime, toTime, resolution, arrayTradedTokensSymbol){
const arrayTokensSplited = splitArrayToChunks(arrayTradedTokensSymbol)
let summaryData = {}
const arrayFunc = arrayTokensSplited.map(async arr => {
const arraySymbolParams = arr.map(symbol => "&symbol=" + symbol).join("")
const response = await fetch(`${BLOCKCHAIN_INFO.tracker}/internal/history_prices?from=${fromTime}&to=${toTime}&resolution=${resolution}&` + arraySymbolParams);
return await response.json();
})
const arrayData = await Promise.all(arrayFunc)
for(let i=0; i < arrayData.length; i++){
if(arrayData[i].error){
return {inQueue: true}
}
summaryData = {...summaryData, ...arrayData[i].data}
}
return summaryData
} | {
"content_hash": "2412a626624edbb0ae2194313ca5889d",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 165,
"avg_line_length": 37.61643835616438,
"alnum_prop": 0.6880917698470502,
"repo_name": "KyberNetwork/KyberWallet",
"id": "3c4d595bd3036326de02e7410b9b19990471407d",
"size": "5493",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/js/services/portfolio_balance/portfolioChartService.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "479415"
},
{
"name": "CoffeeScript",
"bytes": "1122"
},
{
"name": "HTML",
"bytes": "12645"
},
{
"name": "JavaScript",
"bytes": "887285"
},
{
"name": "PowerShell",
"bytes": "471"
},
{
"name": "Ruby",
"bytes": "1030"
},
{
"name": "Shell",
"bytes": "139"
}
],
"symlink_target": ""
} |
/*! Scroller 2.1.0
* ©2011-2022 SpryMedia Ltd - datatables.net/license
*/
(function( factory ){
if ( typeof define === 'function' && define.amd ) {
// AMD
define( ['jquery', 'datatables.net'], function ( $ ) {
return factory( $, window, document );
} );
}
else if ( typeof exports === 'object' ) {
// CommonJS
module.exports = function (root, $) {
if ( ! root ) {
// CommonJS environments without a window global must pass a
// root. This will give an error otherwise
root = window;
}
if ( ! $ ) {
$ = typeof window !== 'undefined' ? // jQuery's factory checks for a global window
require('jquery') :
require('jquery')( root );
}
if ( ! $.fn.dataTable ) {
require('datatables.net')(root, $);
}
return factory( $, root, root.document );
};
}
else {
// Browser
factory( jQuery, window, document );
}
}(function( $, window, document, undefined ) {
'use strict';
var DataTable = $.fn.dataTable;
/**
* @summary Scroller
* @description Virtual rendering for DataTables
* @version 2.1.0
* @author SpryMedia Ltd (www.sprymedia.co.uk)
* @contact www.sprymedia.co.uk/contact
* @copyright SpryMedia Ltd.
*
* This source file is free software, available under the following license:
* MIT license - http://datatables.net/license/mit
*
* This source file 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 license files for details.
*
* For details please refer to: http://www.datatables.net
*/
/**
* Scroller is a virtual rendering plug-in for DataTables which allows large
* datasets to be drawn on screen every quickly. What the virtual rendering means
* is that only the visible portion of the table (and a bit to either side to make
* the scrolling smooth) is drawn, while the scrolling container gives the
* visual impression that the whole table is visible. This is done by making use
* of the pagination abilities of DataTables and moving the table around in the
* scrolling container DataTables adds to the page. The scrolling container is
* forced to the height it would be for the full table display using an extra
* element.
*
* Note that rows in the table MUST all be the same height. Information in a cell
* which expands on to multiple lines will cause some odd behaviour in the scrolling.
*
* Scroller is initialised by simply including the letter 'S' in the sDom for the
* table you want to have this feature enabled on. Note that the 'S' must come
* AFTER the 't' parameter in `dom`.
*
* Key features include:
* <ul class="limit_length">
* <li>Speed! The aim of Scroller for DataTables is to make rendering large data sets fast</li>
* <li>Full compatibility with deferred rendering in DataTables for maximum speed</li>
* <li>Display millions of rows</li>
* <li>Integration with state saving in DataTables (scrolling position is saved)</li>
* <li>Easy to use</li>
* </ul>
*
* @class
* @constructor
* @global
* @param {object} dt DataTables settings object or API instance
* @param {object} [opts={}] Configuration object for Scroller. Options
* are defined by {@link Scroller.defaults}
*
* @requires jQuery 1.7+
* @requires DataTables 1.10.0+
*
* @example
* $(document).ready(function() {
* $('#example').DataTable( {
* "scrollY": "200px",
* "ajax": "media/dataset/large.txt",
* "scroller": true,
* "deferRender": true
* } );
* } );
*/
var Scroller = function ( dt, opts ) {
/* Sanity check - you just know it will happen */
if ( ! (this instanceof Scroller) ) {
alert( "Scroller warning: Scroller must be initialised with the 'new' keyword." );
return;
}
if ( opts === undefined ) {
opts = {};
}
var dtApi = $.fn.dataTable.Api( dt );
/**
* Settings object which contains customisable information for the Scroller instance
* @namespace
* @private
* @extends Scroller.defaults
*/
this.s = {
/**
* DataTables settings object
* @type object
* @default Passed in as first parameter to constructor
*/
dt: dtApi.settings()[0],
/**
* DataTables API instance
* @type DataTable.Api
*/
dtApi: dtApi,
/**
* Pixel location of the top of the drawn table in the viewport
* @type int
* @default 0
*/
tableTop: 0,
/**
* Pixel location of the bottom of the drawn table in the viewport
* @type int
* @default 0
*/
tableBottom: 0,
/**
* Pixel location of the boundary for when the next data set should be loaded and drawn
* when scrolling up the way.
* @type int
* @default 0
* @private
*/
redrawTop: 0,
/**
* Pixel location of the boundary for when the next data set should be loaded and drawn
* when scrolling down the way. Note that this is actually calculated as the offset from
* the top.
* @type int
* @default 0
* @private
*/
redrawBottom: 0,
/**
* Auto row height or not indicator
* @type bool
* @default 0
*/
autoHeight: true,
/**
* Number of rows calculated as visible in the visible viewport
* @type int
* @default 0
*/
viewportRows: 0,
/**
* setTimeout reference for state saving, used when state saving is enabled in the DataTable
* and when the user scrolls the viewport in order to stop the cookie set taking too much
* CPU!
* @type int
* @default 0
*/
stateTO: null,
stateSaveThrottle: function () {},
/**
* setTimeout reference for the redraw, used when server-side processing is enabled in the
* DataTables in order to prevent DoSing the server
* @type int
* @default null
*/
drawTO: null,
heights: {
jump: null,
page: null,
virtual: null,
scroll: null,
/**
* Height of rows in the table
* @type int
* @default 0
*/
row: null,
/**
* Pixel height of the viewport
* @type int
* @default 0
*/
viewport: null,
labelHeight: 0,
xbar: 0
},
topRowFloat: 0,
scrollDrawDiff: null,
loaderVisible: false,
forceReposition: false,
baseRowTop: 0,
baseScrollTop: 0,
mousedown: false,
lastScrollTop: 0
};
// @todo The defaults should extend a `c` property and the internal settings
// only held in the `s` property. At the moment they are mixed
this.s = $.extend( this.s, Scroller.oDefaults, opts );
// Workaround for row height being read from height object (see above comment)
this.s.heights.row = this.s.rowHeight;
/**
* DOM elements used by the class instance
* @private
* @namespace
*
*/
this.dom = {
"force": document.createElement('div'),
"label": $('<div class="dts_label">0</div>'),
"scroller": null,
"table": null,
"loader": null
};
// Attach the instance to the DataTables instance so it can be accessed in
// future. Don't initialise Scroller twice on the same table
if ( this.s.dt.oScroller ) {
return;
}
this.s.dt.oScroller = this;
/* Let's do it */
this.construct();
};
$.extend( Scroller.prototype, {
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Public methods - to be exposed via the DataTables API
*/
/**
* Calculate and store information about how many rows are to be displayed
* in the scrolling viewport, based on current dimensions in the browser's
* rendering. This can be particularly useful if the table is initially
* drawn in a hidden element - for example in a tab.
* @param {bool} [redraw=true] Redraw the table automatically after the recalculation, with
* the new dimensions forming the basis for the draw.
* @returns {void}
*/
measure: function ( redraw )
{
if ( this.s.autoHeight )
{
this._calcRowHeight();
}
var heights = this.s.heights;
if ( heights.row ) {
heights.viewport = this._parseHeight($(this.dom.scroller).css('max-height'));
this.s.viewportRows = parseInt( heights.viewport / heights.row, 10 )+1;
this.s.dt._iDisplayLength = this.s.viewportRows * this.s.displayBuffer;
}
var label = this.dom.label.outerHeight();
heights.xbar = this.dom.scroller.offsetHeight - this.dom.scroller.clientHeight;
heights.labelHeight = label;
if ( redraw === undefined || redraw )
{
this.s.dt.oInstance.fnDraw( false );
}
},
/**
* Get information about current displayed record range. This corresponds to
* the information usually displayed in the "Info" block of the table.
*
* @returns {object} info as an object:
* {
* start: {int}, // the 0-indexed record at the top of the viewport
* end: {int}, // the 0-indexed record at the bottom of the viewport
* }
*/
pageInfo: function()
{
var
dt = this.s.dt,
iScrollTop = this.dom.scroller.scrollTop,
iTotal = dt.fnRecordsDisplay(),
iPossibleEnd = Math.ceil(this.pixelsToRow(iScrollTop + this.s.heights.viewport, false, this.s.ani));
return {
start: Math.floor(this.pixelsToRow(iScrollTop, false, this.s.ani)),
end: iTotal < iPossibleEnd ? iTotal-1 : iPossibleEnd-1
};
},
/**
* Calculate the row number that will be found at the given pixel position
* (y-scroll).
*
* Please note that when the height of the full table exceeds 1 million
* pixels, Scroller switches into a non-linear mode for the scrollbar to fit
* all of the records into a finite area, but this function returns a linear
* value (relative to the last non-linear positioning).
* @param {int} pixels Offset from top to calculate the row number of
* @param {int} [intParse=true] If an integer value should be returned
* @param {int} [virtual=false] Perform the calculations in the virtual domain
* @returns {int} Row index
*/
pixelsToRow: function ( pixels, intParse, virtual )
{
var diff = pixels - this.s.baseScrollTop;
var row = virtual ?
(this._domain( 'physicalToVirtual', this.s.baseScrollTop ) + diff) / this.s.heights.row :
( diff / this.s.heights.row ) + this.s.baseRowTop;
return intParse || intParse === undefined ?
parseInt( row, 10 ) :
row;
},
/**
* Calculate the pixel position from the top of the scrolling container for
* a given row
* @param {int} iRow Row number to calculate the position of
* @returns {int} Pixels
*/
rowToPixels: function ( rowIdx, intParse, virtual )
{
var pixels;
var diff = rowIdx - this.s.baseRowTop;
if ( virtual ) {
pixels = this._domain( 'virtualToPhysical', this.s.baseScrollTop );
pixels += diff * this.s.heights.row;
}
else {
pixels = this.s.baseScrollTop;
pixels += diff * this.s.heights.row;
}
return intParse || intParse === undefined ?
parseInt( pixels, 10 ) :
pixels;
},
/**
* Calculate the row number that will be found at the given pixel position (y-scroll)
* @param {int} row Row index to scroll to
* @param {bool} [animate=true] Animate the transition or not
* @returns {void}
*/
scrollToRow: function ( row, animate )
{
var that = this;
var ani = false;
var px = this.rowToPixels( row );
// We need to know if the table will redraw or not before doing the
// scroll. If it will not redraw, then we need to use the currently
// displayed table, and scroll with the physical pixels. Otherwise, we
// need to calculate the table's new position from the virtual
// transform.
var preRows = ((this.s.displayBuffer-1)/2) * this.s.viewportRows;
var drawRow = row - preRows;
if ( drawRow < 0 ) {
drawRow = 0;
}
if ( (px > this.s.redrawBottom || px < this.s.redrawTop) && this.s.dt._iDisplayStart !== drawRow ) {
ani = true;
px = this._domain( 'virtualToPhysical', row * this.s.heights.row );
// If we need records outside the current draw region, but the new
// scrolling position is inside that (due to the non-linear nature
// for larger numbers of records), we need to force position update.
if ( this.s.redrawTop < px && px < this.s.redrawBottom ) {
this.s.forceReposition = true;
animate = false;
}
}
if ( animate === undefined || animate )
{
this.s.ani = ani;
$(this.dom.scroller).animate( {
"scrollTop": px
}, function () {
// This needs to happen after the animation has completed and
// the final scroll event fired
setTimeout( function () {
that.s.ani = false;
}, 250 );
} );
}
else
{
$(this.dom.scroller).scrollTop( px );
}
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Constructor
*/
/**
* Initialisation for Scroller
* @returns {void}
* @private
*/
construct: function ()
{
var that = this;
var dt = this.s.dtApi;
/* Sanity check */
if ( !this.s.dt.oFeatures.bPaginate ) {
this.s.dt.oApi._fnLog( this.s.dt, 0, 'Pagination must be enabled for Scroller' );
return;
}
/* Insert a div element that we can use to force the DT scrolling container to
* the height that would be required if the whole table was being displayed
*/
this.dom.force.style.position = "relative";
this.dom.force.style.top = "0px";
this.dom.force.style.left = "0px";
this.dom.force.style.width = "1px";
this.dom.scroller = $('div.'+this.s.dt.oClasses.sScrollBody, this.s.dt.nTableWrapper)[0];
this.dom.scroller.appendChild( this.dom.force );
this.dom.scroller.style.position = "relative";
this.dom.table = $('>table', this.dom.scroller)[0];
this.dom.table.style.position = "absolute";
this.dom.table.style.top = "0px";
this.dom.table.style.left = "0px";
// Add class to 'announce' that we are a Scroller table
$(dt.table().container()).addClass('dts DTS');
// Add a 'loading' indicator
if ( this.s.loadingIndicator )
{
this.dom.loader = $('<div class="dataTables_processing dts_loading">'+this.s.dt.oLanguage.sLoadingRecords+'</div>')
.css('display', 'none');
$(this.dom.scroller.parentNode)
.css('position', 'relative')
.append( this.dom.loader );
}
this.dom.label.appendTo(this.dom.scroller);
/* Initial size calculations */
if ( this.s.heights.row && this.s.heights.row != 'auto' )
{
this.s.autoHeight = false;
}
// Scrolling callback to see if a page change is needed
this.s.ingnoreScroll = true;
$(this.dom.scroller).on( 'scroll.dt-scroller', function (e) {
that._scroll.call( that );
} );
// In iOS we catch the touchstart event in case the user tries to scroll
// while the display is already scrolling
$(this.dom.scroller).on('touchstart.dt-scroller', function () {
that._scroll.call( that );
} );
$(this.dom.scroller)
.on('mousedown.dt-scroller', function () {
that.s.mousedown = true;
})
.on('mouseup.dt-scroller', function () {
that.s.labelVisible = false;
that.s.mousedown = false;
that.dom.label.css('display', 'none');
});
// On resize, update the information element, since the number of rows shown might change
$(window).on( 'resize.dt-scroller', function () {
that.measure( false );
that._info();
} );
// Add a state saving parameter to the DT state saving so we can restore the exact
// position of the scrolling.
var initialStateSave = true;
var loadedState = dt.state.loaded();
dt.on( 'stateSaveParams.scroller', function ( e, settings, data ) {
if ( initialStateSave && loadedState ) {
data.scroller = loadedState.scroller;
initialStateSave = false;
if (data.scroller) {
that.s.lastScrollTop = data.scroller.scrollTop;
}
}
else {
// Need to used the saved position on init
data.scroller = {
topRow: that.s.topRowFloat,
baseScrollTop: that.s.baseScrollTop,
baseRowTop: that.s.baseRowTop,
scrollTop: that.s.lastScrollTop
};
}
} );
dt.on( 'stateLoadParams.scroller', function( e, settings, data ) {
if (data.scroller !== undefined) {
that.scrollToRow(data.scroller.topRow);
}
});
if ( loadedState && loadedState.scroller ) {
this.s.topRowFloat = loadedState.scroller.topRow;
this.s.baseScrollTop = loadedState.scroller.baseScrollTop;
this.s.baseRowTop = loadedState.scroller.baseRowTop;
}
this.measure( false );
that.s.stateSaveThrottle = that.s.dt.oApi._fnThrottle( function () {
that.s.dtApi.state.save();
}, 500 );
dt.on( 'init.scroller', function () {
that.measure( false );
// Setting to `jump` will instruct _draw to calculate the scroll top
// position
that.s.scrollType = 'jump';
that._draw();
// Update the scroller when the DataTable is redrawn
dt.on( 'draw.scroller', function () {
that._draw();
});
} );
// Set height before the draw happens, allowing everything else to update
// on draw complete without worry for roder.
dt.on( 'preDraw.dt.scroller', function () {
that._scrollForce();
} );
// Destructor
dt.on( 'destroy.scroller', function () {
$(window).off( 'resize.dt-scroller' );
$(that.dom.scroller).off('.dt-scroller');
$(that.s.dt.nTable).off( '.scroller' );
$(that.s.dt.nTableWrapper).removeClass('DTS');
$('div.DTS_Loading', that.dom.scroller.parentNode).remove();
that.dom.table.style.position = "";
that.dom.table.style.top = "";
that.dom.table.style.left = "";
} );
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Private methods
*/
/**
* Automatic calculation of table row height. This is just a little tricky here as using
* initialisation DataTables has tale the table out of the document, so we need to create
* a new table and insert it into the document, calculate the row height and then whip the
* table out.
* @returns {void}
* @private
*/
_calcRowHeight: function ()
{
var dt = this.s.dt;
var origTable = dt.nTable;
var nTable = origTable.cloneNode( false );
var tbody = $('<tbody/>').appendTo( nTable );
var container = $(
'<div class="'+dt.oClasses.sWrapper+' DTS">'+
'<div class="'+dt.oClasses.sScrollWrapper+'">'+
'<div class="'+dt.oClasses.sScrollBody+'"></div>'+
'</div>'+
'</div>'
);
// Want 3 rows in the sizing table so :first-child and :last-child
// CSS styles don't come into play - take the size of the middle row
$('tbody tr:lt(4)', origTable).clone().appendTo( tbody );
var rowsCount = $('tr', tbody).length;
if ( rowsCount === 1 ) {
tbody.prepend('<tr><td> </td></tr>');
tbody.append('<tr><td> </td></tr>');
}
else {
for (; rowsCount < 3; rowsCount++) {
tbody.append('<tr><td> </td></tr>');
}
}
$('div.'+dt.oClasses.sScrollBody, container).append( nTable );
// If initialised using `dom`, use the holding element as the insert point
var insertEl = this.s.dt.nHolding || origTable.parentNode;
if ( ! $(insertEl).is(':visible') ) {
insertEl = 'body';
}
// Remove form element links as they might select over others (particularly radio and checkboxes)
container.find("input").removeAttr("name");
container.appendTo( insertEl );
this.s.heights.row = $('tr', tbody).eq(1).outerHeight();
container.remove();
},
/**
* Draw callback function which is fired when the DataTable is redrawn. The main function of
* this method is to position the drawn table correctly the scrolling container for the rows
* that is displays as a result of the scrolling position.
* @returns {void}
* @private
*/
_draw: function ()
{
var
that = this,
heights = this.s.heights,
iScrollTop = this.dom.scroller.scrollTop,
iTableHeight = $(this.s.dt.nTable).height(),
displayStart = this.s.dt._iDisplayStart,
displayLen = this.s.dt._iDisplayLength,
displayEnd = this.s.dt.fnRecordsDisplay(),
viewportEndY = iScrollTop + heights.viewport;
// Disable the scroll event listener while we are updating the DOM
this.s.skip = true;
// If paging is reset
if ( (this.s.dt.bSorted || this.s.dt.bFiltered) && displayStart === 0 && !this.s.dt._drawHold ) {
this.s.topRowFloat = 0;
}
iScrollTop = this.s.scrollType === 'jump' ?
this._domain( 'virtualToPhysical', this.s.topRowFloat * heights.row ) :
iScrollTop;
// Store positional information so positional calculations can be based
// upon the current table draw position
this.s.baseScrollTop = iScrollTop;
this.s.baseRowTop = this.s.topRowFloat;
// Position the table in the virtual scroller
var tableTop = iScrollTop - ((this.s.topRowFloat - displayStart) * heights.row);
if ( displayStart === 0 ) {
tableTop = 0;
}
else if ( displayStart + displayLen >= displayEnd ) {
tableTop = heights.scroll - iTableHeight;
}
else {
var iTableBottomY = tableTop + iTableHeight;
if (iTableBottomY < viewportEndY) {
// The last row of the data is above the end of the viewport.
// This means the background is visible, which is not what the user expects.
var newTableTop = viewportEndY - iTableHeight;
var diffPx = newTableTop - tableTop;
this.s.baseScrollTop += diffPx + 1; // Update start row number in footer.
tableTop = newTableTop; // Move table so last line of data is at the bottom of the viewport.
}
}
this.dom.table.style.top = tableTop+'px';
/* Cache some information for the scroller */
this.s.tableTop = tableTop;
this.s.tableBottom = iTableHeight + this.s.tableTop;
// Calculate the boundaries for where a redraw will be triggered by the
// scroll event listener
var boundaryPx = (iScrollTop - this.s.tableTop) * this.s.boundaryScale;
this.s.redrawTop = iScrollTop - boundaryPx;
this.s.redrawBottom = iScrollTop + boundaryPx > heights.scroll - heights.viewport - heights.row ?
heights.scroll - heights.viewport - heights.row :
iScrollTop + boundaryPx;
this.s.skip = false;
if(that.s.ingnoreScroll) {
// Restore the scrolling position that was saved by DataTable's state
// saving Note that this is done on the second draw when data is Ajax
// sourced, and the first draw when DOM soured
if ( this.s.dt.oFeatures.bStateSave && this.s.dt.oLoadedState !== null &&
typeof this.s.dt.oLoadedState.scroller != 'undefined' )
{
// A quirk of DataTables is that the draw callback will occur on an
// empty set if Ajax sourced, but not if server-side processing.
var ajaxSourced = (this.s.dt.sAjaxSource || that.s.dt.ajax) && ! this.s.dt.oFeatures.bServerSide ?
true :
false;
if ( ( ajaxSourced && this.s.dt.iDraw >= 2) ||
(!ajaxSourced && this.s.dt.iDraw >= 1) )
{
setTimeout( function () {
$(that.dom.scroller).scrollTop( that.s.dt.oLoadedState.scroller.scrollTop );
// In order to prevent layout thrashing we need another
// small delay
setTimeout( function () {
that.s.ingnoreScroll = false;
}, 0 );
}, 0 );
}
}
else {
that.s.ingnoreScroll = false;
}
}
// Because of the order of the DT callbacks, the info update will
// take precedence over the one we want here. So a 'thread' break is
// needed. Only add the thread break if bInfo is set
if ( this.s.dt.oFeatures.bInfo ) {
setTimeout( function () {
that._info.call( that );
}, 0 );
}
$(this.s.dt.nTable).triggerHandler('position.dts.dt', tableTop);
// Hide the loading indicator
if ( this.dom.loader && this.s.loaderVisible ) {
this.dom.loader.css( 'display', 'none' );
this.s.loaderVisible = false;
}
},
/**
* Convert from one domain to another. The physical domain is the actual
* pixel count on the screen, while the virtual is if we had browsers which
* had scrolling containers of infinite height (i.e. the absolute value)
*
* @param {string} dir Domain transform direction, `virtualToPhysical` or
* `physicalToVirtual`
* @returns {number} Calculated transform
* @private
*/
_domain: function ( dir, val )
{
var heights = this.s.heights;
var diff;
var magic = 10000; // the point at which the non-linear calculations start to happen
// If the virtual and physical height match, then we use a linear
// transform between the two, allowing the scrollbar to be linear
if ( heights.virtual === heights.scroll ) {
return val;
}
// In the first 10k pixels and the last 10k pixels, we want the scrolling
// to be linear. After that it can be non-linear. It would be unusual for
// anyone to mouse wheel through that much.
if ( val < magic ) {
return val;
}
else if ( dir === 'virtualToPhysical' && val >= heights.virtual - magic ) {
diff = heights.virtual - val;
return heights.scroll - diff;
}
else if ( dir === 'physicalToVirtual' && val >= heights.scroll - magic ) {
diff = heights.scroll - val;
return heights.virtual - diff;
}
// Otherwise, we want a non-linear scrollbar to take account of the
// redrawing regions at the start and end of the table, otherwise these
// can stutter badly - on large tables 30px (for example) scroll might
// be hundreds of rows, so the table would be redrawing every few px at
// the start and end. Use a simple linear eq. to stop this, effectively
// causing a kink in the scrolling ratio. It does mean the scrollbar is
// non-linear, but with such massive data sets, the scrollbar is going
// to be a best guess anyway
var m = (heights.virtual - magic - magic) / (heights.scroll - magic - magic);
var c = magic - (m*magic);
return dir === 'virtualToPhysical' ?
(val-c) / m :
(m*val) + c;
},
/**
* Update any information elements that are controlled by the DataTable based on the scrolling
* viewport and what rows are visible in it. This function basically acts in the same way as
* _fnUpdateInfo in DataTables, and effectively replaces that function.
* @returns {void}
* @private
*/
_info: function ()
{
if ( !this.s.dt.oFeatures.bInfo )
{
return;
}
var
dt = this.s.dt,
language = dt.oLanguage,
iScrollTop = this.dom.scroller.scrollTop,
iStart = Math.floor( this.pixelsToRow(iScrollTop, false, this.s.ani)+1 ),
iMax = dt.fnRecordsTotal(),
iTotal = dt.fnRecordsDisplay(),
iPossibleEnd = Math.ceil( this.pixelsToRow(iScrollTop+this.s.heights.viewport, false, this.s.ani) ),
iEnd = iTotal < iPossibleEnd ? iTotal : iPossibleEnd,
sStart = dt.fnFormatNumber( iStart ),
sEnd = dt.fnFormatNumber( iEnd ),
sMax = dt.fnFormatNumber( iMax ),
sTotal = dt.fnFormatNumber( iTotal ),
sOut;
if ( dt.fnRecordsDisplay() === 0 &&
dt.fnRecordsDisplay() == dt.fnRecordsTotal() )
{
/* Empty record set */
sOut = language.sInfoEmpty+ language.sInfoPostFix;
}
else if ( dt.fnRecordsDisplay() === 0 )
{
/* Empty record set after filtering */
sOut = language.sInfoEmpty +' '+
language.sInfoFiltered.replace('_MAX_', sMax)+
language.sInfoPostFix;
}
else if ( dt.fnRecordsDisplay() == dt.fnRecordsTotal() )
{
/* Normal record set */
sOut = language.sInfo.
replace('_START_', sStart).
replace('_END_', sEnd).
replace('_MAX_', sMax).
replace('_TOTAL_', sTotal)+
language.sInfoPostFix;
}
else
{
/* Record set after filtering */
sOut = language.sInfo.
replace('_START_', sStart).
replace('_END_', sEnd).
replace('_MAX_', sMax).
replace('_TOTAL_', sTotal) +' '+
language.sInfoFiltered.replace(
'_MAX_',
dt.fnFormatNumber(dt.fnRecordsTotal())
)+
language.sInfoPostFix;
}
var callback = language.fnInfoCallback;
if ( callback ) {
sOut = callback.call( dt.oInstance,
dt, iStart, iEnd, iMax, iTotal, sOut
);
}
var n = dt.aanFeatures.i;
if ( typeof n != 'undefined' )
{
for ( var i=0, iLen=n.length ; i<iLen ; i++ )
{
$(n[i]).html( sOut );
}
}
// DT doesn't actually (yet) trigger this event, but it will in future
$(dt.nTable).triggerHandler( 'info.dt' );
},
/**
* Parse CSS height property string as number
*
* An attempt is made to parse the string as a number. Currently supported units are 'px',
* 'vh', and 'rem'. 'em' is partially supported; it works as long as the parent element's
* font size matches the body element. Zero is returned for unrecognized strings.
* @param {string} cssHeight CSS height property string
* @returns {number} height
* @private
*/
_parseHeight: function(cssHeight) {
var height;
var matches = /^([+-]?(?:\d+(?:\.\d+)?|\.\d+))(px|em|rem|vh)$/.exec(cssHeight);
if (matches === null) {
return 0;
}
var value = parseFloat(matches[1]);
var unit = matches[2];
if ( unit === 'px' ) {
height = value;
}
else if ( unit === 'vh' ) {
height = ( value / 100 ) * $(window).height();
}
else if ( unit === 'rem' ) {
height = value * parseFloat($(':root').css('font-size'));
}
else if ( unit === 'em' ) {
height = value * parseFloat($('body').css('font-size'));
}
return height ?
height :
0;
},
/**
* Scrolling function - fired whenever the scrolling position is changed.
* This method needs to use the stored values to see if the table should be
* redrawn as we are moving towards the end of the information that is
* currently drawn or not. If needed, then it will redraw the table based on
* the new position.
* @returns {void}
* @private
*/
_scroll: function ()
{
var
that = this,
heights = this.s.heights,
iScrollTop = this.dom.scroller.scrollTop,
iTopRow;
if ( this.s.skip ) {
return;
}
if ( this.s.ingnoreScroll ) {
return;
}
if ( iScrollTop === this.s.lastScrollTop ) {
return;
}
/* If the table has been sorted or filtered, then we use the redraw that
* DataTables as done, rather than performing our own
*/
if ( this.s.dt.bFiltered || this.s.dt.bSorted ) {
this.s.lastScrollTop = 0;
return;
}
/* Update the table's information display for what is now in the viewport */
this._info();
/* We don't want to state save on every scroll event - that's heavy
* handed, so use a timeout to update the state saving only when the
* scrolling has finished
*/
clearTimeout( this.s.stateTO );
this.s.stateTO = setTimeout( function () {
that.s.dtApi.state.save();
}, 250 );
this.s.scrollType = Math.abs(iScrollTop - this.s.lastScrollTop) > heights.viewport ?
'jump' :
'cont';
this.s.topRowFloat = this.s.scrollType === 'cont' ?
this.pixelsToRow( iScrollTop, false, false ) :
this._domain( 'physicalToVirtual', iScrollTop ) / heights.row;
if ( this.s.topRowFloat < 0 ) {
this.s.topRowFloat = 0;
}
/* Check if the scroll point is outside the trigger boundary which would required
* a DataTables redraw
*/
if ( this.s.forceReposition || iScrollTop < this.s.redrawTop || iScrollTop > this.s.redrawBottom ) {
var preRows = Math.ceil( ((this.s.displayBuffer-1)/2) * this.s.viewportRows );
iTopRow = parseInt(this.s.topRowFloat, 10) - preRows;
this.s.forceReposition = false;
if ( iTopRow <= 0 ) {
/* At the start of the table */
iTopRow = 0;
}
else if ( iTopRow + this.s.dt._iDisplayLength > this.s.dt.fnRecordsDisplay() ) {
/* At the end of the table */
iTopRow = this.s.dt.fnRecordsDisplay() - this.s.dt._iDisplayLength;
if ( iTopRow < 0 ) {
iTopRow = 0;
}
}
else if ( iTopRow % 2 !== 0 ) {
// For the row-striping classes (odd/even) we want only to start
// on evens otherwise the stripes will change between draws and
// look rubbish
iTopRow++;
}
// Store calcuated value, in case the following condition is not met, but so
// that the draw function will still use it.
this.s.targetTop = iTopRow;
if ( iTopRow != this.s.dt._iDisplayStart ) {
/* Cache the new table position for quick lookups */
this.s.tableTop = $(this.s.dt.nTable).offset().top;
this.s.tableBottom = $(this.s.dt.nTable).height() + this.s.tableTop;
var draw = function () {
that.s.dt._iDisplayStart = that.s.targetTop;
that.s.dt.oApi._fnDraw( that.s.dt );
};
/* Do the DataTables redraw based on the calculated start point - note that when
* using server-side processing we introduce a small delay to not DoS the server...
*/
if ( this.s.dt.oFeatures.bServerSide ) {
this.s.forceReposition = true;
clearTimeout( this.s.drawTO );
this.s.drawTO = setTimeout( draw, this.s.serverWait );
}
else {
draw();
}
if ( this.dom.loader && ! this.s.loaderVisible ) {
this.dom.loader.css( 'display', 'block' );
this.s.loaderVisible = true;
}
}
}
else {
this.s.topRowFloat = this.pixelsToRow( iScrollTop, false, true );
}
this.s.lastScrollTop = iScrollTop;
this.s.stateSaveThrottle();
if ( this.s.scrollType === 'jump' && this.s.mousedown ) {
this.s.labelVisible = true;
}
if (this.s.labelVisible) {
var labelFactor = (heights.viewport-heights.labelHeight - heights.xbar) / heights.scroll;
this.dom.label
.html( this.s.dt.fnFormatNumber( parseInt( this.s.topRowFloat, 10 )+1 ) )
.css( 'top', iScrollTop + (iScrollTop * labelFactor) )
.css( 'right', 10 - this.dom.scroller.scrollLeft)
.css( 'display', 'block' );
}
},
/**
* Force the scrolling container to have height beyond that of just the
* table that has been drawn so the user can scroll the whole data set.
*
* Note that if the calculated required scrolling height exceeds a maximum
* value (1 million pixels - hard-coded) the forcing element will be set
* only to that maximum value and virtual / physical domain transforms will
* be used to allow Scroller to display tables of any number of records.
* @returns {void}
* @private
*/
_scrollForce: function ()
{
var heights = this.s.heights;
var max = 1000000;
heights.virtual = heights.row * this.s.dt.fnRecordsDisplay();
heights.scroll = heights.virtual;
if ( heights.scroll > max ) {
heights.scroll = max;
}
// Minimum height so there is always a row visible (the 'no rows found'
// if reduced to zero filtering)
this.dom.force.style.height = heights.scroll > this.s.heights.row ?
heights.scroll+'px' :
this.s.heights.row+'px';
}
} );
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Statics
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Scroller default settings for initialisation
* @namespace
* @name Scroller.defaults
* @static
*/
Scroller.defaults = {
/**
* Scroller uses the boundary scaling factor to decide when to redraw the table - which it
* typically does before you reach the end of the currently loaded data set (in order to
* allow the data to look continuous to a user scrolling through the data). If given as 0
* then the table will be redrawn whenever the viewport is scrolled, while 1 would not
* redraw the table until the currently loaded data has all been shown. You will want
* something in the middle - the default factor of 0.5 is usually suitable.
* @type float
* @default 0.5
* @static
*/
boundaryScale: 0.5,
/**
* The display buffer is what Scroller uses to calculate how many rows it should pre-fetch
* for scrolling. Scroller automatically adjusts DataTables' display length to pre-fetch
* rows that will be shown in "near scrolling" (i.e. just beyond the current display area).
* The value is based upon the number of rows that can be displayed in the viewport (i.e.
* a value of 1), and will apply the display range to records before before and after the
* current viewport - i.e. a factor of 3 will allow Scroller to pre-fetch 1 viewport's worth
* of rows before the current viewport, the current viewport's rows and 1 viewport's worth
* of rows after the current viewport. Adjusting this value can be useful for ensuring
* smooth scrolling based on your data set.
* @type int
* @default 7
* @static
*/
displayBuffer: 9,
/**
* Show (or not) the loading element in the background of the table. Note that you should
* include the dataTables.scroller.css file for this to be displayed correctly.
* @type boolean
* @default false
* @static
*/
loadingIndicator: false,
/**
* Scroller will attempt to automatically calculate the height of rows for it's internal
* calculations. However the height that is used can be overridden using this parameter.
* @type int|string
* @default auto
* @static
*/
rowHeight: "auto",
/**
* When using server-side processing, Scroller will wait a small amount of time to allow
* the scrolling to finish before requesting more data from the server. This prevents
* you from DoSing your own server! The wait time can be configured by this parameter.
* @type int
* @default 200
* @static
*/
serverWait: 200
};
Scroller.oDefaults = Scroller.defaults;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Constants
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Scroller version
* @type String
* @default See code
* @name Scroller.version
* @static
*/
Scroller.version = "2.1.0";
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Initialisation
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
// Attach a listener to the document which listens for DataTables initialisation
// events so we can automatically initialise
$(document).on( 'preInit.dt.dtscroller', function (e, settings) {
if ( e.namespace !== 'dt' ) {
return;
}
var init = settings.oInit.scroller;
var defaults = DataTable.defaults.scroller;
if ( init || defaults ) {
var opts = $.extend( {}, init, defaults );
if ( init !== false ) {
new Scroller( settings, opts );
}
}
} );
// Attach Scroller to DataTables so it can be accessed as an 'extra'
$.fn.dataTable.Scroller = Scroller;
$.fn.DataTable.Scroller = Scroller;
// DataTables 1.10 API method aliases
var Api = $.fn.dataTable.Api;
Api.register( 'scroller()', function () {
return this;
} );
// Undocumented and deprecated - is it actually useful at all?
Api.register( 'scroller().rowToPixels()', function ( rowIdx, intParse, virtual ) {
var ctx = this.context;
if ( ctx.length && ctx[0].oScroller ) {
return ctx[0].oScroller.rowToPixels( rowIdx, intParse, virtual );
}
// undefined
} );
// Undocumented and deprecated - is it actually useful at all?
Api.register( 'scroller().pixelsToRow()', function ( pixels, intParse, virtual ) {
var ctx = this.context;
if ( ctx.length && ctx[0].oScroller ) {
return ctx[0].oScroller.pixelsToRow( pixels, intParse, virtual );
}
// undefined
} );
// `scroller().scrollToRow()` is undocumented and deprecated. Use `scroller.toPosition()
Api.register( ['scroller().scrollToRow()', 'scroller.toPosition()'], function ( idx, ani ) {
this.iterator( 'table', function ( ctx ) {
if ( ctx.oScroller ) {
ctx.oScroller.scrollToRow( idx, ani );
}
} );
return this;
} );
Api.register( 'row().scrollTo()', function ( ani ) {
var that = this;
this.iterator( 'row', function ( ctx, rowIdx ) {
if ( ctx.oScroller ) {
var displayIdx = that
.rows( { order: 'applied', search: 'applied' } )
.indexes()
.indexOf( rowIdx );
ctx.oScroller.scrollToRow( displayIdx, ani );
}
} );
return this;
} );
Api.register( 'scroller.measure()', function ( redraw ) {
this.iterator( 'table', function ( ctx ) {
if ( ctx.oScroller ) {
ctx.oScroller.measure( redraw );
}
} );
return this;
} );
Api.register( 'scroller.page()', function() {
var ctx = this.context;
if ( ctx.length && ctx[0].oScroller ) {
return ctx[0].oScroller.pageInfo();
}
// undefined
} );
return DataTable;
}));
| {
"content_hash": "94f71331f3225d08668cee36cd1b7122",
"timestamp": "",
"source": "github",
"line_count": 1345,
"max_line_length": 118,
"avg_line_length": 29.73457249070632,
"alnum_prop": 0.6380116520391068,
"repo_name": "cdnjs/cdnjs",
"id": "28340e06058263a263b354c585174efeea5e410d",
"size": "39994",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ajax/libs/datatables.net-scroller/2.1.0/dataTables.scroller.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
#define RF69_IRQ_PIN 2
#define RF69_IRQ_NUM 0
#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega1284P__)
#define RF69_IRQ_PIN 2
#define RF69_IRQ_NUM 2
#elif defined(__AVR_ATmega32U4__)
#define RF69_IRQ_PIN 3
#define RF69_IRQ_NUM 0
#elif defined(__arm__)//Use pin 10 or any pin you want
#define RF69_IRQ_PIN PA3
#define RF69_IRQ_NUM 3
#else
#define RF69_IRQ_PIN 2
#define RF69_IRQ_NUM 0
#endif
#define CSMA_LIMIT -90 // upper RX signal sensitivity threshold in dBm for carrier sense access
#define RF69_MODE_SLEEP 0 // XTAL OFF
#define RF69_MODE_STANDBY 1 // XTAL ON
#define RF69_MODE_SYNTH 2 // PLL ON
#define RF69_MODE_RX 3 // RX MODE
#define RF69_MODE_TX 4 // TX MODE
// available frequency bands
#define RF69_315MHZ 31 // non trivial values to avoid misconfiguration
#define RF69_433MHZ 43
#define RF69_868MHZ 86
#define RF69_915MHZ 91
#define null 0
#define COURSE_TEMP_COEF -90 // puts the temperature reading in the ballpark, user can fine tune the returned value
#define RF69_BROADCAST_ADDR 255
#define RF69_CSMA_LIMIT_MS 1000
#define RF69_TX_LIMIT_MS 1000
#define RF69_FSTEP 61.03515625 // == FXOSC / 2^19 = 32MHz / 2^19 (p13 in datasheet)
// TWS: define CTLbyte bits
#define RFM69_CTL_SENDACK 0x80
#define RFM69_CTL_REQACK 0x40
class RFM69 {
public:
static volatile uint8_t DATA[RF69_MAX_DATA_LEN]; // recv/xmit buf, including header & crc bytes
static volatile uint8_t DATALEN;
static volatile uint8_t SENDERID;
static volatile uint8_t TARGETID; // should match _address
static volatile uint8_t PAYLOADLEN;
static volatile uint8_t ACK_REQUESTED;
static volatile uint8_t ACK_RECEIVED; // should be polled immediately after sending a packet with ACK request
static volatile int16_t RSSI; // most accurate RSSI during reception (closest to the reception)
static volatile uint8_t _mode; // should be protected?
RFM69(uint8_t slaveSelectPin=RF69_SPI_CS, uint8_t interruptPin=RF69_IRQ_PIN, bool isRFM69HW=false, uint8_t interruptNum=RF69_IRQ_NUM) {
_slaveSelectPin = slaveSelectPin;
_interruptPin = interruptPin;
_interruptNum = interruptNum;
_mode = RF69_MODE_STANDBY;
_promiscuousMode = false;
_powerLevel = 31;
_isRFM69HW = isRFM69HW;
}
bool initialize(uint8_t freqBand, uint8_t ID, uint8_t networkID=1);
void setAddress(uint8_t addr);
void setNetwork(uint8_t networkID);
bool canSend();
virtual void send(uint8_t toAddress, const void* buffer, uint8_t bufferSize, bool requestACK=false);
virtual bool sendWithRetry(uint8_t toAddress, const void* buffer, uint8_t bufferSize, uint8_t retries=2, uint8_t retryWaitTime=40); // 40ms roundtrip req for 61byte packets
virtual bool receiveDone();
bool ACKReceived(uint8_t fromNodeID);
bool ACKRequested();
virtual void sendACK(const void* buffer = "", uint8_t bufferSize=0);
uint32_t getFrequency();
void setFrequency(uint32_t freqHz);
void encrypt(const char* key);
void setCS(uint8_t newSPISlaveSelect);
int16_t readRSSI(bool forceTrigger=false);
void promiscuous(bool onOff=true);
virtual void setHighPower(bool onOFF=true); // has to be called after initialize() for RFM69HW
virtual void setPowerLevel(uint8_t level); // reduce/increase transmit power level
void sleep();
uint8_t readTemperature(uint8_t calFactor=0); // get CMOS temperature (8bit)
void rcCalibration(); // calibrate the internal RC oscillator for use in wide temperature variations - see datasheet section [4.3.5. RC Timer Accuracy]
// allow hacking registers by making these public
uint8_t readReg(uint8_t addr);
void writeReg(uint8_t addr, uint8_t val);
void readAllRegs();
void readAllRegsCompact();
protected:
static void isr0();
void virtual interruptHandler();
virtual void interruptHook(uint8_t CTLbyte) {};
static volatile bool _inISR;
virtual void sendFrame(uint8_t toAddress, const void* buffer, uint8_t size, bool requestACK=false, bool sendACK=false);
static RFM69* selfPointer;
uint8_t _slaveSelectPin;
uint8_t _interruptPin;
uint8_t _interruptNum;
uint8_t _address;
bool _promiscuousMode;
uint8_t _powerLevel;
bool _isRFM69HW;
#if defined (SPCR) && defined (SPSR)
uint8_t _SPCR;
uint8_t _SPSR;
#endif
virtual void receiveBegin();
virtual void setMode(uint8_t mode);
virtual void setHighPowerRegs(bool onOff);
virtual void select();
virtual void unselect();
inline void maybeInterrupts();
};
#endif
| {
"content_hash": "35e863cd6599387a1febb77a2352e2de",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 176,
"avg_line_length": 39.78333333333333,
"alnum_prop": 0.6820276497695853,
"repo_name": "hvos234/raspberrypi.home",
"id": "a48413e41ff2fcd20dbbb2e6ab09216368136f33",
"size": "6942",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vendor/home/Arduino/libraries/RFM69/RFM69.h",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "515"
},
{
"name": "CSS",
"bytes": "1253514"
},
{
"name": "HTML",
"bytes": "8172658"
},
{
"name": "JavaScript",
"bytes": "7555240"
},
{
"name": "PHP",
"bytes": "1017370"
}
],
"symlink_target": ""
} |
// Theater.cpp: implementation of the Theater class.
//
//////////////////////////////////////////////////////////////////////
#include "Theater.h"
#include "game.h"
#include "AssetList.h"
#include "Sound.h"
#include "MusicManager.h"
#include "AssetListNew.h"
#include "AppConfig.h"
//#include <UIKit/UIKit.h>
using namespace CR;
using namespace CR::Sound;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
extern HPTGraphicsEngine *graphics_engine;
///extern HPTSoundEngine* sound_engine;
extern Input_Engine *input_engine;
//extern CRMusicPlayer *musicPlayer;
extern Game* game_class;
extern char path[256];
extern char *hptstrcat(char *x,char *y);
Theater::Theater()
{
done = true;
scene_timer = 1;
movie_sprite = graphics_engine->CreateSprite1();
movie_sprite1 = graphics_engine->CreateSprite1();
movie_sprite2 = graphics_engine->CreateSprite1();
movie_sprite3= graphics_engine->CreateSprite1();
movie_sprite4 = graphics_engine->CreateSprite1();
movie_sprite5 = graphics_engine->CreateSprite1();
movie_sprite6 = graphics_engine->CreateSprite1();
movie_sprite7 = graphics_engine->CreateSprite1();
movie_sprite8 = graphics_engine->CreateSprite1();
movie_sprite9 = graphics_engine->CreateSprite1();
movie_sprite10 = graphics_engine->CreateSprite1();
movie_sprite11 = graphics_engine->CreateSprite1();
background = graphics_engine->CreateHPTBackground();
// Create the Skip Movie Button
skipMovieButton = new Input_Button();
skipMovieButton->SetButtonBounds(0, 0, 480, 320);
skipMovieButton->OnClicked += Delegate(this,&Theater::StopMovie);
skipMovieButton->Disabled(true);
skipMovieButton->SetSoundOn(true);
input_objects.push_back(skipMovieButton);
prevMovieButton = new Input_Button();
prevMovieButton->SetButtonBounds(0, 0, 480, 320);
prevMovieButton->OnClicked += Delegate(this,&Theater::OnPrev);
prevMovieButton->Disabled(true);
prevMovieButton->SetSoundOn(true);
input_objects.push_back(prevMovieButton);
nextMovieButton = new Input_Button();
nextMovieButton->SetButtonBounds(0, 0, 480, 320);
nextMovieButton->OnClicked += Delegate(this,&Theater::OnNext);
nextMovieButton->Disabled(true);
nextMovieButton->SetSoundOn(true);
input_objects.push_back(nextMovieButton);
#ifdef BOB_LITE
buyGameScreenTime = 0;
buyGameButton = new Input_Button();
buyGameButton->SetSpriteAndBounds(250, 210, CR::AssetList::buy_button_2);
//buyGameButton->OnClicked += Delegate(this,&Theater::OnBuyGame);
buyGameButton->Disabled(true);
buyGameButton->SetSoundOn(true);
input_objects.push_back(buyGameButton);
returnToMenuButton = new Input_Button();
returnToMenuButton->SetSpriteAndBounds(20, 210, CR::AssetList::return_to_menu_button);
//buyGameButton->OnClicked += Delegate(this,&Theater::OnBuyGame);
returnToMenuButton->Disabled(true);
returnToMenuButton->SetSoundOn(true);
input_objects.push_back(returnToMenuButton);
#endif
}
Theater::~Theater()
{
movie_sprite->Release();
movie_sprite2->Release();
movie_sprite3->Release();
if(background)
background->Release();
delete skipMovieButton;
delete prevMovieButton;
delete nextMovieButton;
}
void Theater::OnNext()
{
if(current_scene < (scenes.size() - 1))
current_scene++;
}
void Theater::OnPrev()
{
if(current_scene>0)
current_scene--;
}
/*#ifdef BOB_LITE
void Theater::OnBuyGame()
{
[[UIApplication sharedApplication] openURL:[[NSURL alloc] initWithString: [NSString stringWithCString:"itms://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=308315671&mt=8"]]];
}
#endif*/
void Theater::InputChanged()
{
#ifdef BOB_LITE
if (current_movie == 2)
{
if (buyGameButton->WasPressed())
{
[[UIApplication sharedApplication] openURL:[[NSURL alloc] initWithString: [NSString stringWithCString:"itms://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=308315671&mt=8"]]];
}
else if (returnToMenuButton->WasPressed())
{
StopMovie();
}
}
#endif
}
void Theater::StartMovie(int arg)
{
input_engine->RegisterInputController(this);
done_b = false;
next_b = false;
prev_b = false;
if(arg > 17) arg = 17;
done = false;
current_movie = arg;
current_scene = 0;
black_font = graphics_engine->CreateFont1();
/*NSString * path1 = [[NSBundle mainBundle] pathForResource: @"arial20" ofType: @"HFF"];
const char *blackfont = [path1 cStringUsingEncoding:1];
black_font->LoadHFFFont(const_cast<char*>(blackfont));*/
black_font->LoadHFFFont("arial20.HFF");
white_font = graphics_engine->CreateFont1();
/*path1 = [[NSBundle mainBundle] pathForResource: @"arial20w" ofType: @"HFF"];
const char *whitefont = [path1 cStringUsingEncoding:1];
white_font->LoadHFFFont(const_cast<char*>(whitefont));*/
white_font->LoadHFFFont("arial20w.HFF");
background = graphics_engine->CreateHPTBackground();
switch(arg)
{
case 0:
current_image = 0;
max_scene = 1;
time_to_go = 3.0f;
set_time = 1.5f;
background->SetImage(AssetList::splash_screen_01);
graphics_engine->SetBackgroundImage(background);
skipMovieButton->SetButtonBounds(0, 0, 480, 320);
skipMovieButton->SetSoundOn(false);
skipMovieButton->Disabled(false);
// sound_engine->LoadHSF(hptstrcat(path, ("sounds//intro.hsf")), 1);
// music = sound_engine->CreateSoundObject(0, 1);
// if((music != 0) && (game->mute_music != true)) music->HPTPlaySound();
break;
case 1:
CreateScene1a();
//CreateSceneFinal();
break;
case 2:
#ifdef BOB_LITE
CreateSceneLite();
#else
CreateScene1b();
#endif
break;
case 3:
CreateScene1c();
break;
case 4:
CreateScene2a();
break;
case 5:
CreateScene2b();
break;
case 6:
CreateScene2c();
break;
case 7:
CreateScene3a();
break;
case 8:
CreateScene3b();
break;
case 9:
CreateScene3c();
break;
case 10:
CreateSceneFinal();
break;
case 11:
CreateSceneBonus1();
break;
}
if(arg >= 1)
{
background->SetImage(scenes[current_scene].background);
graphics_engine->SetBackgroundImage(background);
if(AppConfig::Instance().IsIpad())
skipMovieButton->SetSpriteAndBounds(192, 274, AssetList::button_skip);
else
skipMovieButton->SetSpriteAndBounds(210, 279, AssetList::button_skip);
skipMovieButton->SetSoundOn(true);
skipMovieButton->Disabled(false);
if(AppConfig::Instance().IsIpad())
skipMovieButton->DesignSize(96,47);
if(AppConfig::Instance().IsIpad())
prevMovieButton->SetSpriteAndBounds(104, 274, AssetList::button_previous);
else
prevMovieButton->SetSpriteAndBounds(5, 279, AssetList::button_previous);
prevMovieButton->SetSoundOn(true);
prevMovieButton->Disabled(true);
if(AppConfig::Instance().IsIpad())
prevMovieButton->DesignSize(78,47);
if(AppConfig::Instance().IsIpad())
nextMovieButton->SetSpriteAndBounds(298, 274, AssetList::button_next);
else
nextMovieButton->SetSpriteAndBounds(420, 279, AssetList::button_next);
nextMovieButton->SetSoundOn(true);
nextMovieButton->Disabled(false);
if(AppConfig::Instance().IsIpad())
nextMovieButton->DesignSize(78,47);
if (arg == 10)
{
MusicManager::Instance().PlaySong(MusicManager::Finale);
// musicPlayer->ChangeSong(MUSIC_CREDITS);
}
else
{
MusicManager::Instance().PlaySong(MusicManager::Cutscene);
// musicPlayer->ChangeSong(MUSIC_CUTSCENE);
}
// musicPlayer->Play();
}
text_dialog_sprite = graphics_engine->CreateSprite1();
text_dialog_sprite->SetImage(AssetList::cutscene_text_box);
text_dialog_sprite->SetFrame(0);
text_dialog_sprite->SetPositionAbsalute(240,160);
if(AppConfig::Instance().IsIpad())
text_dialog_sprite->SetDesignSize(323,105);
char_dialog_sprite_top = graphics_engine->CreateSprite1();
char_dialog_sprite_top->SetImage(AssetList::cutscene_balloon);
char_dialog_sprite_top->SetFrame(0);
char_dialog_sprite_top->SetPositionAbsalute(165,50);
if(AppConfig::Instance().IsIpad())
char_dialog_sprite_top->SetDesignSize(336,100);
char_dialog_sprite_bot = graphics_engine->CreateSprite1();
char_dialog_sprite_bot->SetImage(AssetList::cutscene_balloon);
char_dialog_sprite_bot->SetFrame(0);
char_dialog_sprite_bot->SetPositionAbsalute(75,250);
if(AppConfig::Instance().IsIpad())
{
char_dialog_sprite_bot->SetDesignSize(336,100);
}
}
void Theater::Update(float time)
{
#ifdef BOB_LITE
if (current_movie == 2)
{
buyGameScreenTime -= time;
}
#endif
this->time = time;
if(done) return;
time_to_go -= time;
switch(current_movie)
{
case 0:
switch(current_image)
{
case 0:
if(time_to_go <= 0)
{
time_to_go = 32.0f;
current_image++;
loc1 = 340.0f;
loc2 = 0;
}
break;
case 1:
// if((music != 0) && (game->mute_music != true)) music->HPTStopSound();
done = true;
break;
}
break;
/* case 16:
scene_timer -= time;
if(scene_timer < 0)
{
if(current_image == 26) return;
current_image++;
switch(current_image)
{
case 0:
scene_timer = 5;
break;
case 1:
scene_timer = 5;
break;
case 2:
scene_timer = 5;
break;
case 3:
scene_panning = 0;
scene_timer = 10;
break;
case 4:
scene_timer = 10;
break;
case 5:
scene_timer = 5;
break;
case 6:
movie_sprite5->SetFrameRate(1);
movie_sprite5->SetAutoAnimate(true);
movie_sprite5->AutoStopAnimate();
scene_timer = 5;
break;
case 7:
scene_timer = 5;
break;
case 8:
scene_timer = 5;
break;
case 9:
scene_timer = 5;
break;
case 10:
scene_timer = 5;
break;
case 11:
scene_timer = 10;
break;
case 12:
scene_panning = 0;
scene_timer = 38;
break;
case 13:
scene_timer = 5;
break;
case 14:
scene_timer = 5;
break;
case 15:
scene_timer = 5;
break;
case 16:
scene_timer = 5;
break;
case 17:
scene_timer = 5;
break;
case 18:
scene_timer = 5;
break;
case 19:
scene_timer = 5;
break;
case 20:
scene_timer = 5;
break;
case 21:
scene_timer = 5;
break;
case 22:
scene_timer = 5;
break;
case 23:
scene_timer = 5;
break;
case 24:
scene_timer = 5;
break;
case 25:
scene_panning = 10;
scene_timer = 14;
break;
case 26:
scene_panning = 0;
scene_timer = 100;
// sound_engine->LoadHSF(hptstrcat(path, ("sounds//level1c-m.hsf")), 1);
// music = sound_engine->CreateSoundObject(0, 1);
// if((music != 0) && (game->mute_music != true)) music->HPTPlaySound(true);
break;
};
};
break;*/
default:
background->SetImage(scenes[current_scene].background);
break;
}
}
void Theater::Render()
{
if(done) return;
switch(current_movie)
{
case 0:
switch(current_image)
{
case 0:
case 1:
//movie_sprite->SetPositionAbsalute(0,0);
//movie_sprite->SetFrame(0);
//movie_sprite->Render();
//graphics_engine->Position(120,90);
//(*graphics_engine) << black_font << "HPT Interactive";
break;
/*case 1:
movie_sprite->SetPositionAbsalute(480-loc2,160);
movie_sprite->SetFrame(0);
movie_sprite->Render();
movie_sprite1->SetPositionAbsalute(240,160);
//movie_sprite1->Render();
graphics_engine->Position(25,(int)loc1);
(*graphics_engine) << white_font << "It is the near future...\n\n Two weapon manufacturers struggle"
<< "\nto become the favored supplier to\nthe government...\n\n"
<< " NagolaCorp, headed by Suke Hato\ndeals with chemical and biological\nweapons...\n\n"
<< " Fortified Industries, owned and\ncontrolled by James and Jacob\nCorinth produces traditional arms...\n\n"
<< " The government comes to favor \nFortified Industries and NagolaCorp\nis threatened with bankruptcy...\n\n"
<< " Desperate, Suke Hato attempts to\nform a partnership with the Corinth\nbrothers but he fails...\n\n"
<< " James ends up dead, his murderer\nunknown...\n\n"
<< " Spencer Corinth, the only son of\nJames, vows to uncover those guilty\nand avenge his father...";
break;
case 2:
movie_sprite2->SetPositionAbsalute(240,160);
movie_sprite2->SetFrame(0);
movie_sprite2->Render();
movie_sprite3->SetPositionAbsalute(214,loc2);
movie_sprite3->SetFrame(0);
movie_sprite3->Render();
break;
case 3:
movie_sprite4->SetPositionAbsalute(240,160);
movie_sprite4->SetFrame(0);
movie_sprite4->Render();
break;
case 4:
movie_sprite->SetPositionAbsalute(161,160);
movie_sprite->SetFrame(0);
movie_sprite->Render();
movie_sprite2->SetPositionAbsalute(78,161);
movie_sprite2->SetFrame(0);
movie_sprite2->Render();
movie_sprite3->SetPositionAbsalute(120,62);
movie_sprite3->SetFrame(0);
movie_sprite3->Render();
graphics_engine->Position(30,70);
break;*/
}
break;
/* if(scene_panning < 1250) scene_panning += 16 * time;
if(scene_panning > 1250) scene_panning = 1250;
movie_sprite11->SetPositionAbsalute(120, -120 + 480);
movie_sprite11->Render();
graphics_engine->Position(10,270 - static_cast<int>(scene_panning));
(*graphics_engine) << black_font << "Thanks for playing Blade of Betrayal!\n\n\n"
<< "HPT Interactive Team\n\n"
<< "Game Concept & Story:\n"
<< "Billy Garretsen\n\n"
<< "Artwork:\n"
<< "Billy Garretsen\n\n"
<< "Level Programming:\n"
<< "Eric Duhon\n\n"
<< "Character Programming:\n"
<< "Matthew Shoemate\n\n"
<< "AI Programming:\n"
<< "David Harms\n\n"
<< "Enemy Behavior Design:\n"
<< "Billy Garretsen\n"
<< "David Harms\n\n"
<< "Cut Scene Programming:\n"
<< "Eric Duhon\n"
<< "Matthew Shoemate\n\n"
<< "Cut Scene Artwork:\n"
<< "Billy Garretsen\n\n"
<< "Game Programming:\n"
<< "Eric Duhon\n"
<< "Matthew Shoemate\n"
<< "David Harms\n\n"
<< "Sound, Music & Programming:\n"
<< "Matthew Shoemate\n\n"
<< "Tools Programming:\n"
<< "David Harms\n"
<< "Eric Duhon\n\n"
<< "Misc. Programming:\n"
<< "Eric Duhon\n"
<< "Matthew Shoemate\n"
<< "David Harms\n\n"
<< "Misc. Artwork:\n"
<< "Billy Garretsen\n\n"
<< "Game Documentation:\n"
<< "David Harms\n\n"
<< "Special Thanks:\n"
<< "Billy Holland (Billy Evil)\n"
<< "William Ramby (VRam)\n"
<< "Barry Morgan (GreyWolf)\n"
<< "www.ppx3k.com\n"
<< "ppx3k community\n\n"
<< "Beth Lang (blang)\n"
<< "Shanna Shoemate\n\n\n\n";*/
//Though Spencer's old family is gone, he feels
//a strong sense of unity growing among his new one.
//The pain he felt for so long after his father's
//death slowly fades away as he exhales, liberated from vengeance...
default:
if(scenes[current_scene].dialog_box)
{
text_dialog_sprite->SetPositionAbsalute(240,160);
text_dialog_sprite->Render();
graphics_engine->Position(105,120+scenes[current_scene].yOffsetDialog);
(*graphics_engine) << white_font << scenes[current_scene].dialog;
}
if(scenes[current_scene].top_portrait != NONE && scenes[current_scene].top[0] != 0)
{
char_dialog_sprite_top->SetPositionAbsalute(285,70);
char_dialog_sprite_top->Render();
/*movie_sprite->SetImage(scenes[current_scene].top_portrait);
movie_sprite->SetFrame(0);
movie_sprite->SetPositionAbsalute(75,160);
movie_sprite->Render();*/
graphics_engine->Position(160,31+scenes[current_scene].yOffsetTop);
(*graphics_engine) << black_font << scenes[current_scene].top;
}
if(scenes[current_scene].bot_portrait != NONE && scenes[current_scene].bottom[0] != 0)
{
char_dialog_sprite_bot->SetPositionAbsalute(195,210);
char_dialog_sprite_bot->RenderHFlip();
/*movie_sprite->SetImage(scenes[current_scene].bot_portrait);
movie_sprite->SetFrame(0);
movie_sprite->SetPositionAbsalute(405,160);
movie_sprite->Render();*/
graphics_engine->Position(50,172+scenes[current_scene].yOffsetBot);
(*graphics_engine) << black_font << scenes[current_scene].bottom;
}
if(scenes[current_scene].top_portrait != NONE)
{
portraits[scenes[current_scene].top_portrait]->SetPositionAbsalute(60,70);
portraits[scenes[current_scene].top_portrait]->Render();
}
if(scenes[current_scene].bot_portrait != NONE)
{
if(AppConfig::Instance().IsIpad())
portraits[scenes[current_scene].bot_portrait]->SetPositionAbsalute(411,208);
else
portraits[scenes[current_scene].bot_portrait]->SetPositionAbsalute(420,210);
portraits[scenes[current_scene].bot_portrait]->Render();
}
#ifdef BOB_LITE
if(current_scene != 0 && !(current_movie == 2 && current_scene == (scenes.size() - 1)))
{
prevMovieButton->Disabled(false);
prevMovieButton->Render();
}
else
prevMovieButton->Disabled(true);
if(current_scene != (scenes.size() - 1) && !(current_movie == 2 && current_scene == (scenes.size() - 1)))
{
nextMovieButton->Disabled(false);
nextMovieButton->Render();
skipMovieButton->SetSprite(CR::AssetList::button_skip);
}
else
{
nextMovieButton->Disabled(true);
skipMovieButton->SetSprite(CR::AssetList::button_done);
}
if (current_movie != 2)
{
skipMovieButton->Disabled(false);
skipMovieButton->Render();
}
else
{
skipMovieButton->Disabled(true);
}
if (current_movie == 2)
{
buyGameButton->Disabled(false);
buyGameButton->Render();
returnToMenuButton->Disabled(false);
returnToMenuButton->Render();
}
else
{
buyGameButton->Disabled(true);
returnToMenuButton->Disabled(true);
}
if (current_movie == 2 && buyGameScreenTime <= 0)
StopMovie();
#else
if(current_scene != 0 && !(current_movie == 10 && current_scene == (scenes.size() - 1)))
{
prevMovieButton->Disabled(false);
prevMovieButton->Render();
}
else
prevMovieButton->Disabled(true);
if(current_scene != (scenes.size() - 1))
{
nextMovieButton->Disabled(false);
nextMovieButton->Render();
skipMovieButton->SetSprite(CR::AssetList::button_skip);
}
else
{
nextMovieButton->Disabled(true);
skipMovieButton->SetSprite(CR::AssetList::button_done);
}
// Final scene of game
if (current_movie == 10 && current_scene == (scenes.size() - 1))
{
skipMovieButton->SetPosition(380, 265);
/*
if (game_class->GetCompletionPercent() <= 9)
graphics_engine->Position(447, 175);
else if (game_class->GetCompletionPercent() < 100)
graphics_engine->Position(434, 175);
else
graphics_engine->Position(421, 175);
(*graphics_engine) << game_class->bankGothic << game_class->GetCompletionPercent() << "%";
*/
if (game_class->GetAchievementsCount() <= 9)
graphics_engine->Position(430, 175);
else
graphics_engine->Position(417, 175);
(*graphics_engine) << game_class->bankGothic << game_class->GetAchievementsCount() << "/30";
}
skipMovieButton->Render();
#endif
break;
}
}
bool Theater::IsDone()
{
// if(done) black_font->Release();
/*if((current_movie == 0) && done)
{
movie_sprite->SetImage(86);
movie_sprite1->SetImage(86);
movie_sprite2->SetImage(86);
movie_sprite3->SetImage(86);
}*/
//if(done) FreePortraits();
return done;
}
void Theater::StopMovie()
{
if(current_movie != 16)
{
done = true;
// if((music != 0) && (game->mute_music != true)) music->HPTStopSound();
}
else
{
// if((music != 0) && (game->mute_music != true)) music->HPTStopSound();
//if(game->HaveAllItems()) StartMovie(17);
/*else*/ done = true;
}
/*text_dialog_sprite->Release();
char_dialog_sprite_top->Release();
char_dialog_sprite_bot->Release();
// buttons_dialog_sprite->Release();
black_font->Release();
white_font->Release();
background->Release();
FreePortraits();*/
skipMovieButton->Disabled(true);
//skipMovieButton->FreeResources();
prevMovieButton->Disabled(true);
//prevMovieButton->FreeResources();
nextMovieButton->Disabled(true);
//nextMovieButton->FreeResources();
}
void Theater::FreeAssets()
{
skipMovieButton->FreeResources();
prevMovieButton->FreeResources();
nextMovieButton->FreeResources();
if (text_dialog_sprite != NULL){
text_dialog_sprite->Release();
text_dialog_sprite = NULL;
}
if (char_dialog_sprite_top != NULL){
char_dialog_sprite_top->Release();
char_dialog_sprite_top = NULL;
}
if (char_dialog_sprite_bot != NULL){
char_dialog_sprite_bot->Release();
char_dialog_sprite_bot = NULL;
}
// buttons_dialog_sprite->Release();
if (black_font != NULL){
black_font->Release();
black_font = NULL;
}
if (white_font != NULL){
white_font->Release();
white_font = NULL;
}
if (background != NULL){
background->Release();
background = NULL;
}
FreePortraits();
}
void Theater::SetGame(IGame *lpGame)
{
game = lpGame;
}
void Theater::CreateScene1a()
{
HPTSprite1 *tempp;
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(AssetList::cutscene_spencer);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(AssetList::cutscene_jacob);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
scenes.clear();
/*It is the near future... Two weapon manufacturers struggle to become the favored supplier to the government...NCorp,
headed by Suke Hato deals with chemical and biological weapons... Fortified Industries, owned and controlled by
James and Jacob Corinth produces traditional arms... The government comes to favor Fortified Industries and NCorp is
threatened with bankruptcy... Desperate, Suke Hato attempts to form a partnership with the Corinth brothers but he fails...
James ends up dead, his murderer unknown... Spencer Corinth, the only son of James, vows to uncover those guilty and avenge his father...
A month has gone by and no new information has been discovered about the death of James Corinth... Spencer has almost given up hope... */
Scene temp;
temp.background = 73;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," It is the near future... Two weapon \n"
" manufacturers struggle to become\n"
" the favored supplier to the\n"
" government... NCorp, headed by \n"
" Suke Hato deals with chemical ");
scenes.push_back(temp);
temp.background = 73;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"and biological weapons... Fortified\n"
"Industries, owned and controlled by\n"
"James and Jacob Corinth, produces\n"
"traditional arms... The government\n"
"comes to favor Fortified Industries");
scenes.push_back(temp);
temp.background = 73;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 12;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," and NCorp is threatened with\n"
"bankruptcy... Desperate, Suke Hato\n"
"attempts to form a partnership with\n"
"the Corinth brothers, but he fails...");
scenes.push_back(temp);
temp.background = 73;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"James ends up dead, his murderer\n"
" unknown... Spencer Corinth, the\n"
"only son of James, vows to uncover\n"
"those guilty and avenge his father...");
scenes.push_back(temp);
temp.background = AssetList::cutscene_1a1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = false;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_1a1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," A month has gone by and no new\n"
" information has been discovered\n"
"about the death of James Corinth...\n"
"Spencer has almost given up hope... ");
scenes.push_back(temp);
/*SPENCER: You called, Uncle Jacob?
JACOB: I have some interesting news for you my boy. My informant has been searching for leads and it seems that your father's murder traces itself back to Suke Hato.
SPENCER: Hato!? Him? Why?
JACOB: That is what I would like to know. We need to question him before turning him over to the authorities. I want you to break into NCorp and bring him back here.
Spencer arrives outside of the NCorp complex...
SPENCER: It's too risky going in through the front. I will have to find some way around.*/
temp.background = AssetList::cutscene_1a1;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 39;
temp.yOffsetBot = 0;
sprintf(temp.top," You called, Uncle Jacob?\n");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_1a1;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
sprintf(temp.top," You called, Uncle Jacob?\n");
sprintf(temp.bottom," I have some interesting news for\n"
"you my boy. My informant has been\n"
" searching for leads and it seems\n"
" that your father's murder traces\n"
" itself back to Suke Hato.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_1a1;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
sprintf(temp.top," Hato!? Him? Why?");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_1a1;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
sprintf(temp.top," Hato!? Him? Why?");
sprintf(temp.bottom," That is what I would like to know.\n"
" We need to question him before\n"
"turning him over to the authorities.\n"
"I want you to break into NCorp and\n"
" bring him back here.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = 71;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = false;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = 71;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 30;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," Spencer arrives outside of the\n"
" NCorp complex...");
scenes.push_back(temp);
temp.background = 71;
temp.bot_portrait = NONE;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 19;
temp.yOffsetBot = 0;
sprintf(temp.top," It's too risky going in through\n"
" the front. I will have to find\n"
" some way around.");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
current_scene = 0;
// graphics_engine->LoadHGF(1,hptstrcat(path,("cutscenes//1a.hgf")));
// sound_engine->LoadHSF(hptstrcat(path, ("sounds//title.hsf")), 1);
// music = sound_engine->CreateSoundObject(0, 1);
// if((music != 0) && (game->mute_music != true)) music->HPTPlaySound(true);
}
void Theater::CreateScene1b()
{
HPTSprite1 *tempp;
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(AssetList::cutscene_spencer);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
scenes.clear();
/*Spencer finds his way into the main building where Suke Hato is located.
Spencer: I need to find a way up to that bastard's penthouse and get to the bottom of this. */
Scene temp;
temp.background = AssetList::cutscene_black;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 20;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," Spencer finds his way into\n"
" the main building where Suke\n"
" Hato is located.");
scenes.push_back(temp);
temp.background = AssetList::cutscene_1b1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = false;
temp.yOffsetDialog = 20;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_1b1;
temp.bot_portrait = NONE;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 19;
temp.yOffsetBot = 0;
sprintf(temp.top," I need to find a way up to that\n"
" bastard's penthouse and get to\n"
" the bottom of this.");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
current_scene = 0;
// graphics_engine->LoadHGF(1,hptstrcat(path,("cutscenes//1b.hgf")));
// sound_engine->LoadHSF(hptstrcat(path, ("sounds//title.hsf")), 1);
// music = sound_engine->CreateSoundObject(0, 1);
// if((music != 0) && (game->mute_music != true)) music->HPTPlaySound(true);
}
void Theater::CreateScene1c()
{
HPTSprite1 *tempp;
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(AssetList::cutscene_spencer);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(AssetList::cutscene_mr_thomas);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
/*Spencer rides the elevator up to Suke Hato's penthouse, only to find a man in sunglasses awaiting his arrival.
Spencer: Who are you?
Thomas: The name's Thomas.
Spencer: Tell me where Suke Hato is.
Thomas: I'm afraid I can't. It is my duty to protect him.
Spencer: My business is with Hato. Don't make me hurt you.
Thomas: Sorry, friend. I can't let you pass. */
scenes.clear();
Scene temp;
temp.background = AssetList::cutscene_black;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 12;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," Spencer rides the elevator up\n"
" to Suke Hato's penthouse only\n"
" to find a man in sunglasses\n"
" awaiting his arrival.");
scenes.push_back(temp);
temp.background = AssetList::cutscene_1c1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = false;
temp.yOffsetDialog = 12;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_1c1;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 39;
temp.yOffsetBot = 0;
sprintf(temp.top," Who are you?");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_1c1;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 39;
temp.yOffsetBot = 39;
sprintf(temp.top," Who are you?");
sprintf(temp.bottom," The name's Thomas.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_1c1;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 39;
temp.yOffsetBot = 0;
sprintf(temp.top," Tell me where Suke Hato is.");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_1c1;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 39;
temp.yOffsetBot = 29;
sprintf(temp.top," Tell me where Suke Hato is.");
sprintf(temp.bottom," I'm afraid I can't. It\n"
" is my duty to protect him.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_1c1;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 29;
temp.yOffsetBot = 0;
sprintf(temp.top," My business is with Hato.\n"
" Don't make me hurt you.");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_1c1;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 29;
temp.yOffsetBot = 29;
sprintf(temp.top," My business is with Hato.\n"
" Don't make me hurt you.");
sprintf(temp.bottom," Sorry, friend. I can't\n"
" let you pass.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
current_scene = 0;
// graphics_engine->LoadHGF(1,hptstrcat(path,("cutscenes//1c.hgf")));
// sound_engine->LoadHSF(hptstrcat(path, ("sounds//title.hsf")), 1);
// music = sound_engine->CreateSoundObject(0, 1);
// if((music != 0) && (game->mute_music != true)) music->HPTPlaySound(true);
}
void Theater::CreateScene2a()
{
HPTSprite1 *tempp;
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(AssetList::cutscene_spencer);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(AssetList::cutscene_mr_thomas);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(AssetList::cutscene_jacob);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(AssetList::cutscene_hato);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(AssetList::cutscene_guard);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
scenes.clear();
/*Spencer: NOW TELL ME WHERE HATO IS BEFORE I END YOU!!!
Out of nowhere, Spencer is surrounded by dozens of Hato's elite guards. A large monitor on the wall flickers on... Suke Hato stares with a devilish grin.
Hato: Impressive.
Jacob: I told you he was not to be underestimated.
Jacob appears next to Hato on the monitor. Spencer stands silent.
Jacob: Look how confused you are. Priceless.
Spencer: Uncle Jacob? What is this?
Jacob: It was ME who ordered the hit on James.
Spencer: You? But I dont understand.
Jacob: The two of you could never understand. James was too stubborn to see the benefits of partnering with NCorp. He did not approve. I however, am more open-minded. It's just good business.
Spencer: But we are a family.
Jacob: Ha! You are so much like your father. Blinded by some sense of nobility. I will enjoy having you out of the picture.
Spencer: This whole thing, this manhunt, was all a trap? You're going to kill me aren't you?
Jacob: That is up to Mr. Hato. You are my gift to him.
Hato: I think we should make him part of the "PROGRAM". Guards, put him in a cell until we are ready to experiment.
Jacob: Goodbye Spencer.
Spencer: NOOOOOOOOO!!!!!!
Lost in a storm of emotions, Spencer allows himself to be carried away without putting up a struggle. Inside the holding area, there is much commotion.
Guard: There's been a jail break! An escapee fried the locks and all prisoners are loose. Stay here with the boy while I go check it out.
Seeing an opportunity to escape, Spencer knocks out the guards. Having no choice he runs towards the cellblocks hoping to find a way out. */
Scene temp;
temp.background = AssetList::cutscene_black;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 29;
temp.yOffsetBot = 39;
sprintf(temp.top," NOW TELL ME WHERE HATO IS\n"
" BEFORE I END YOU!!! ");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_black;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," Out of nowhere, Spencer is\n"
" surrounded by dozens of Hato's\n"
" elite guards. A large monitor\n"
" on the wall flickers on... Suke\n"
" Hato stares with a devilish grin.");
scenes.push_back(temp);
temp.background = AssetList::cutscene_2a1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_2a1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 19;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," Jacob appears next to Hato\n"
" on the monitor. Spencer\n"
" stands silent.");
scenes.push_back(temp);
temp.background = AssetList::cutscene_2a1;
temp.bot_portrait = 2;
temp.top_portrait = 3;
temp.dialog_box = false;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 39;
temp.yOffsetBot = 29;
sprintf(temp.top," Impressive.");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_2a1;
temp.bot_portrait = 2;
temp.top_portrait = 3;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 39;
temp.yOffsetBot = 29;
sprintf(temp.top," Impressive.");
sprintf(temp.bottom," I told you he was not to be\n"
" underestimated.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_2a1;
temp.bot_portrait = 2;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 29;
sprintf(temp.top,"");
sprintf(temp.bottom," Look how confused you are.\n"
" Priceless.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_2a1;
temp.bot_portrait = 2;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 39;
temp.yOffsetBot = 29;
sprintf(temp.top," Uncle Jacob? What is this?");
sprintf(temp.bottom," Look how confused you are.\n"
" Priceless.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_2a1;
temp.bot_portrait = 2;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 39;
temp.yOffsetBot = 29;
sprintf(temp.top,"");
sprintf(temp.bottom," It was ME who ordered the hit\n"
" on James. ");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_2a1;
temp.bot_portrait = 2;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 39;
temp.yOffsetBot = 29;
sprintf(temp.top," You? But I dont understand.");
sprintf(temp.bottom," It was ME who ordered the hit\n"
" on James. ");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_2a1;
temp.bot_portrait = 2;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 9;
sprintf(temp.top,"");
sprintf(temp.bottom," The two of you could never\n"
" understand. James was too\n"
" stubborn to see the benefits\n"
" of partnering with NCorp. \n");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_2a1;
temp.bot_portrait = 2;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 19;
sprintf(temp.top,"");
sprintf(temp.bottom," He did not approve. I, however,\n"
" am more open-minded. \n"
" It's just good business.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_2a1;
temp.bot_portrait = 2;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 39;
temp.yOffsetBot = 19;
sprintf(temp.top," But we are a family.");
sprintf(temp.bottom," He did not approve. I, however,\n"
" am more open-minded. \n"
" It's just good business.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_2a1;
temp.bot_portrait = 2;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 9;
sprintf(temp.top,"");
sprintf(temp.bottom," Ha! You are so much like your\n"
" father. Blinded by some sense\n"
" of nobility. I will enjoy having\n"
" you out of the picture.\n");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_2a1;
temp.bot_portrait = 2;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 19;
temp.yOffsetBot = 9;
sprintf(temp.top," This whole thing, this manhunt,\n"
" was all a trap? You're going to\n"
" kill me aren't you?");
sprintf(temp.bottom," Ha! You are so much like your\n"
" father. Blinded by some sense\n"
" of nobility. I will enjoy having\n"
" you out of the picture.\n");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_2a1;
temp.bot_portrait = 2;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 29;
sprintf(temp.top,"");
sprintf(temp.bottom," That is up to Mr. Hato.\n"
" You are my gift to him.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_2a1;
temp.bot_portrait = 2;
temp.top_portrait = 3;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 9;
temp.yOffsetBot = 29;
sprintf(temp.top," I think we should make him part of\n"
" the \"PROGRAM\". Guards, put him\n"
" in a cell until we are ready\n"
" to experiment.");
sprintf(temp.bottom," That is up to Mr. Hato.\n"
" You are my gift to him.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_2a1;
temp.bot_portrait = 2;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 39;
sprintf(temp.top,"");
sprintf(temp.bottom," Goodbye Spencer.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_2a1;
temp.bot_portrait = 2;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 39;
temp.yOffsetBot = 39;
sprintf(temp.top," NOOOOOOOOO!!!!!!");
sprintf(temp.bottom," Goodbye Spencer.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_black;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," Lost in a storm of emotions,\n"
" Spencer allows himself to be\n"
" carried away without putting up\n"
" a struggle. Inside the holding\n"
" area, there is much commotion.");
scenes.push_back(temp);
temp.background = AssetList::cutscene_black;
temp.bot_portrait = 4;
temp.top_portrait = 4;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 9;
temp.yOffsetBot = 0;
sprintf(temp.top," There's been a jail break! An \n"
" escapee fried the locks and all\n"
" prisoners are loose. Stay here\n"
" with the boy while I go check it out.");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_black;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 9;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," Seeing an opportunity to escape,\n"
" Spencer knocks out the guards.\n"
" Having no choice he runs towards\n"
" the cellblocks hoping to find a\n"
" way out.");
scenes.push_back(temp);
current_scene = 0;
// graphics_engine->LoadHGF(1,hptstrcat(path,("cutscenes//2a.hgf")));
// sound_engine->LoadHSF(hptstrcat(path, ("sounds//title.hsf")), 1);
// music = sound_engine->CreateSoundObject(0, 1);
// if((music != 0) && (game->mute_music != true)) music->HPTPlaySound(true);
}
void Theater::CreateScene2b()
{
HPTSprite1 *tempp;
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(AssetList::cutscene_spencer);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
scenes.clear();
/*The elevator only goes down. During the descent, Spencer feels a large tremor.
INTERCOM: Warning. Fire detected on all laboratory levels. Possible contamination and outbreak of specimens. Use extreme caution.
Spencer: Specimens? */
Scene temp;
temp.background = AssetList::cutscene_black;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 19;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," The elevator only goes down.\n"
" During the descent, Spencer\n"
" feels a large tremor. ");
scenes.push_back(temp);
temp.background = AssetList::cutscene_2b1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_2b1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 12;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"INTERCOM: Warning. Fire detected\n"
" on all laboratory levels. Possible\n"
" contamination and outbreak of\n"
" specimens. Use extreme caution.\n");
scenes.push_back(temp);
temp.background = AssetList::cutscene_2b1;
temp.bot_portrait = NONE;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 39;
temp.yOffsetBot = 0;
sprintf(temp.top," Specimens?");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
current_scene = 0;
// graphics_engine->LoadHGF(1,hptstrcat(path,("cutscenes//2b.hgf")));
// sound_engine->LoadHSF(hptstrcat(path, ("sounds//title.hsf")), 1);
// music = sound_engine->CreateSoundObject(0, 1);
// if((music != 0) && (game->mute_music != true)) music->HPTPlaySound(true);
}
void Theater::CreateScene2c()
{
HPTSprite1 *tempp;
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(AssetList::cutscene_spencer);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(AssetList::cutscene_agm);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
scenes.clear();
/*The waste tunnel takes Spencer directly into the city's sewers below NCorp.
Spencer: I can't believe I made it out of there. What a nightmare!
In the darkness, Spencer hears a low growling. From the shadows emerges a hideous beast with hunger in its eyes.
Creature: Grrrrrrrr....
Spencer: Oh my... */
Scene temp;
temp.background = AssetList::cutscene_black;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 19;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," The waste tunnel takes Spencer\n"
" directly into the city's sewers\n"
" below NCorp.");
scenes.push_back(temp);
temp.background = AssetList::cutscene_black;
temp.bot_portrait = NONE;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 29;
temp.yOffsetBot = 0;
sprintf(temp.top," I can't believe I made it out\n"
" of there. What a nightmare!");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_black;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 39;
sprintf(temp.top,"");
sprintf(temp.bottom," Grrrrrrrr....");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_2c1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = false;
temp.yOffsetDialog = 19;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_2c1;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 39;
temp.yOffsetBot = 39;
sprintf(temp.top," Oh my...");
sprintf(temp.bottom," Grrrrrrrr....");
sprintf(temp.dialog,"");
scenes.push_back(temp);
current_scene = 0;
// graphics_engine->LoadHGF(1,hptstrcat(path,("cutscenes//2c.hgf")));
// sound_engine->LoadHSF(hptstrcat(path, ("sounds//title.hsf")), 1);
// music = sound_engine->CreateSoundObject(0, 1);
// if((music != 0) && (game->mute_music != true)) music->HPTPlaySound(true);
}
void Theater::CreateScene3a()
{
HPTSprite1 *tempp;
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(AssetList::cutscene_spencer);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
scenes.clear();
/*Spencer carefully examines an ID tag around the creature's arm.
Spencer: “Specimen 102383 - Austin Ament”. This thing was human once? All those monsters were prisoners...lab rats. What the hell is NCorp really up to? Genetic engineering on humans? Bastards. And now Fortified Industries is mixed up in all of it. I can't believe my uncle, my own flesh and blood...he has betrayed everything my father ever worked to build. Our company. Our family...They can't get away with this!
Spencer, determined to bring justice to his betrayers, follows the maze of sewers until he finds the access tunnel that would lead him right into the water line of Fortified Industries. There is no turning back. He must put an end to Jacob's plans or die trying.
*/
Scene temp;
temp.background = AssetList::cutscene_3a1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = false;
temp.yOffsetDialog = 30;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3a1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 30;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," Spencer carefully examines an ID\n"
" tag around the creature's arm.\n");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3a1;
temp.bot_portrait = NONE;
temp.top_portrait = 0;
temp.dialog_box = false;
sprintf(temp.top,"\"Specimen 102383 - Austin Ament\".\n"
" This thing was human once? All\n"
" those monsters were prisoners...\n"
" lab rats. What the hell is NCorp\n"
" really up to? Genetic engineering");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3a1;
temp.bot_portrait = NONE;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 19;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top," on humans? Bastards. And now\n"
" Fortified Industries is mixed up\n"
" in all of it. I can't believe my\n"
" uncle, my own flesh and blood...\n"
" He has betrayed everything my");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3a1;
temp.bot_portrait = NONE;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 19;
temp.yOffsetBot = 0;
sprintf(temp.top," father ever worked to build.\n"
" Our company. Our family...\n"
" They can't get away with this!\n");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3a1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"Spencer, determined to bring justice\n"
" to his betrayers, follows the maze\n"
" of sewers until he finds the access\n"
" tunnel that leads him right into the\n"
" water line of Fortified Industries.");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3a1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 30;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," There is no turning back. He must\n"
" put an end to Jacob's plans...\n");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3a1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 39;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," ...or die trying.");
scenes.push_back(temp);
current_scene = 0;
// graphics_engine->LoadHGF(1,hptstrcat(path,("cutscenes//5a.hgf")));
// sound_engine->LoadHSF(hptstrcat(path, ("sounds//title.hsf")), 1);
// music = sound_engine->CreateSoundObject(0, 1);
// if((music != 0) && (game->mute_music != true)) music->HPTPlaySound(true);
}
void Theater::CreateScene3b()
{
HPTSprite1 *tempp;
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(AssetList::cutscene_spencer);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(AssetList::cutscene_jacob);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(AssetList::cutscene_hato);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(AssetList::cutscene_guard);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
scenes.clear();
/*Jacob sits in his office quietly, pleased with how perfectly his plans have developed.
GUARD: Sir, we have spotted your nephew on our security cameras. He appears to have wiped out our entire ground forces. We lost him somewhere in the air ducts.
JACOB: Spencer? Alive?
Jacob punches a series of numbers and Suke Hato appears on his monitor.
JACOB: Spencer escaped, Hato. He is here.
HATO: No need to worry, my friend. I will recover you immediately.
JACOB: Guard, we have an intruder in the building. Tell the men to release the creatures.
GUARD: Um, sir, is that such a wise decision? We have not experimented with them enough. Our results are inconclusive.
JACOB: I said release them!
GUARD: Right away, sir... */
Scene temp;
temp.background = AssetList::cutscene_3b1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3b1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 20;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," Jacob sits quietly in his office,\n"
"pleased with how perfectly his plans\n"
" have developed.\n");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3b1;
temp.bot_portrait = 1;
temp.top_portrait = 3;
temp.dialog_box = false;
sprintf(temp.top," Sir, we have spotted your nephew\n"
" on our security cameras. He\n"
" appears to have wiped out our\n"
" entire ground forces. We lost\n"
" him somewhere in the air ducts.");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3b1;
temp.bot_portrait = 1;
temp.top_portrait = 3;
temp.dialog_box = false;
temp.yOffsetBot = 39;
sprintf(temp.top," Sir, we have spotted your nephew\n"
" on our security cameras. He\n"
" appears to have wiped out our\n"
" entire ground forces. We lost\n"
" him somewhere in the air ducts.");
sprintf(temp.bottom," Spencer? Alive?");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3b1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 19;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," Jacob punches a series\n"
" of numbers and Suke Hato\n"
" appears on his monitor.");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3b1;
temp.bot_portrait = 1;
temp.top_portrait = 2;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 29;
sprintf(temp.top,"");
sprintf(temp.bottom," Spencer escaped, Hato.\n"
" He is here.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3b1;
temp.bot_portrait = 1;
temp.top_portrait = 2;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 19;
temp.yOffsetBot = 29;
sprintf(temp.top," No need to worry, my\n"
" friend. I will recover\n"
" you immediately.");
sprintf(temp.bottom," Spencer escaped, Hato.\n"
" He is here.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3b1;
temp.bot_portrait = 1;
temp.top_portrait = 3;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 19;
sprintf(temp.top,"");
sprintf(temp.bottom," Guard, we have an intruder\n"
" in the building. Tell the\n"
" men to release the creatures.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3b1;
temp.bot_portrait = 1;
temp.top_portrait = 3;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 8;
temp.yOffsetBot = 19;
sprintf(temp.top," Um, sir, is that such a wise\n"
" decision? We have not\n"
" experimented with them enough.\n"
" Our results are inconclusive. ");
sprintf(temp.bottom," Guard, we have an intruder\n"
" in the building. Tell the\n"
" men to release the creatures.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3b1;
temp.bot_portrait = 1;
temp.top_portrait = 3;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 39;
temp.yOffsetBot = 39;
sprintf(temp.top,"");
sprintf(temp.bottom," I said release them!");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3b1;
temp.bot_portrait = 1;
temp.top_portrait = 3;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 39;
temp.yOffsetBot = 39;
sprintf(temp.top," Right away, sir...");
sprintf(temp.bottom," I said release them!");
sprintf(temp.dialog,"");
scenes.push_back(temp);
current_scene = 0;
// graphics_engine->LoadHGF(1,hptstrcat(path,("cutscenes//5b.hgf")));
// sound_engine->LoadHSF(hptstrcat(path, ("sounds//title.hsf")), 1);
// music = sound_engine->CreateSoundObject(0, 1);
// if((music != 0) && (game->mute_music != true)) music->HPTPlaySound(true);
}
void Theater::CreateScene3c()
{
HPTSprite1 *tempp;
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(CR::AssetList::cutscene_spencer);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(AssetList::cutscene_jacob);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
scenes.clear();
/*Spencer rushes into Jacob's empty office. A helicopter can be heard in the distance. Spencer follows a stairwell to the roof. The helicopter begins its descent as Jacob waits on the helipad.
SPENCER: JACOB!!!
Spencer thrusts his sword upward, releasing a ball of energy that hits the chopper's propeller blades. In a blinding flash of light, the helicopter loses control and crashes into the roof, barely missing Jacob.
JACOB: You just killed Suke Hato. Perhaps I should thank you for that.
SPENCER: You're next.
JACOB: So, it has come to this. You are no match for me, nephew.
SPENCER: Don't call me that. We are not a family.
JACOB: No I suppose not. Let me show you something.
Jacob produces a vial of chemicals from his coat.
JACOB: Behold the true fruits of my partnership with Hato. Forget money...just one drop of this will make me immortal. Just one drop...will make me a god.
SPENCER: You are a sick man. My father did not deserve to die. Not for this.
JACOB: Your father always had the power while I stood on the side. Time after time I had to watch him make decisions and treat me like a fool. No, Spencer, now it is my turn to have the power.
Spencer rushes towards Jacob with his sword drawn. In a panic, Jacob quickly consumes the entire vial of chemicals just as Spencer runs his sword through his chest. Jacob falls to his knees, gasping for breath.
SPENCER: It is over...
Jacob's head jerks up violently, his eyes bright red. Spencer looks on in disbelief as Jacob rises to his feet and pulls the sword out of his chest. He throws it back to Spencer and smiles.
JACOB: You're right, nephew. It is over... */
Scene temp;
temp.background = AssetList::cutscene_black;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 12;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"Spencer rushes into Jacob's empty\n"
" office. A helicopter can be heard\n"
" in the distance. Spencer follows a\n"
" stairwell to the roof.");
scenes.push_back(temp);
temp.background = AssetList::cutscene_black;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 30;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"The helicopter begins its descent as\n"
" Jacob waits on the helipad.");
scenes.push_back(temp);
temp.background = AssetList::cutscene_black;
temp.bot_portrait = NONE;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 39;
temp.yOffsetBot = 0;
sprintf(temp.top," JACOB!!!");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3c1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3c1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 20;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"Spencer thrusts his sword upward,\n"
" releasing a ball of energy that\n"
" hits the chopper's propeller blades.");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3c1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 20;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," In a blinding flash of light, the\n"
"helicopter loses control and crashes\n"
" into the roof, barely missing Jacob.");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3c1;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 18;
temp.yOffsetTop = 0;
temp.yOffsetBot = 29;
sprintf(temp.top,"");
sprintf(temp.bottom,"You just killed Suke Hato. Perhaps\n"
" I should thank you for that.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3c1;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 19;
temp.yOffsetTop = 39;
temp.yOffsetBot = 29;
sprintf(temp.top," You're next.");
sprintf(temp.bottom,"You just killed Suke Hato. Perhaps\n"
" I should thank you for that.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3c1;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 29;
sprintf(temp.top,"");
sprintf(temp.bottom," So, it has come to this. You are\n"
" no match for me, nephew.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3c1;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 29;
temp.yOffsetBot = 29;
sprintf(temp.top," Don't call me that. We are\n"
" not family.");
sprintf(temp.bottom," So, it has come to this. You are\n"
" no match for me, nephew.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3c1;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 29;
temp.yOffsetBot = 29;
sprintf(temp.top,"");
sprintf(temp.bottom," No I suppose not. Let me\n"
" show you something.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3c1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 28;
temp.yOffsetTop = 29;
temp.yOffsetBot = 29;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," Jacob produces a vial of\n"
" chemicals from his coat.");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3c1;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom," Behold the true fruits of my\n"
" partnership with Hato. Forget\n"
" money...just one drop of this\n"
" will make me immortal. Just one\n"
" drop...will make me a god.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3c1;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 29;
temp.yOffsetBot = 0;
sprintf(temp.top," You are a sick man. My father\n"
" did not deserve to die. Not for this.");
sprintf(temp.bottom," Behold the true fruits of my\n"
" partnership with Hato. Forget\n"
" money...just one drop of this\n"
" will make me immortal. Just one\n"
" drop...will make me a god.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3c1;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom," Your father always had the power\n"
" while I stood on the side. Time\n"
" after time I had to watch him\n"
" make decisions and treat me\n"
" like a fool.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3c1;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 29;
sprintf(temp.top,"");
sprintf(temp.bottom," No, Spencer, now it is my turn\n"
" to have the power.");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3c1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"Spencer rushes towards Jacob with\n"
"his sword drawn. In a panic, Jacob\n"
"quickly consumes the entire vial of\n"
"chemicals just as Spencer runs his\n"
" sword through his chest.");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3c2;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = false;
temp.yOffsetDialog = 12;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3c2;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 29;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," Jacob falls to his knees,\n"
" gasping for breath.");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3c2;
temp.bot_portrait = NONE;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 39;
temp.yOffsetBot = 0;
sprintf(temp.top," It is over...");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3c2;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," Jacob's head jerks up violently,\n"
" his eyes bright red. Spencer\n"
" looks on in disbelief as Jacob\n"
" rises to his feet and pulls the\n"
" sword out of his chest. ");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3c2;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 29;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," He throws it back to Spencer\n"
" and smiles. ");
scenes.push_back(temp);
temp.background = AssetList::cutscene_3c2;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 39;
sprintf(temp.top,"");
sprintf(temp.bottom," You're right, nephew. It is over...");
sprintf(temp.dialog,"");
scenes.push_back(temp);
current_scene = 0;
// graphics_engine->LoadHGF(1,hptstrcat(path,("cutscenes//5c.hgf")));
// sound_engine->LoadHSF(hptstrcat(path, ("sounds//title.hsf")), 1);
// music = sound_engine->CreateSoundObject(0, 1);
// if((music != 0) && (game->mute_music != true)) music->HPTPlaySound(true);
}
void Theater::CreateSceneBonus1()
{
scenes.clear();
Scene temp;
//Welcome to SURVIVAL RUN - the high tech training exercise developed by Fortified Industries to toughen
//soldiers and test endurance. Your health will slowly drain as time passes. Your objective is to find
//as many glowing beacons as you can and make it to the exit before your health runs out. Each beacon
//will restore life and extend your chances for survival. Are you skilled enough to get all the
//beacons and make it out alive?
temp.background = AssetList::cutscene_black;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," Welcome to SURVIVAL RUN - the\n"
" high tech training exercise \n"
"developed by Fortified Industries to \n"
" toughen soldiers and test.\n"
" endurance \n");
scenes.push_back(temp);
temp.background = AssetList::cutscene_black;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," Your health will slowly drain as\n"
" time passes. Your objective is to\n"
" find as many glowing beacons as \n"
" you can and make it to the exit \n"
" before your health runs out.\n");
scenes.push_back(temp);
temp.background = AssetList::cutscene_black;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 10;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," Each beacon will restore life and\n"
" extend your chances for survival.\n"
"Are you skilled enough to get all the\n"
" beacons and make it out alive?\n");
scenes.push_back(temp);
current_scene = 0;
}
void Theater::CreateSceneFinal()
{
HPTSprite1 *tempp;
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(CR::AssetList::cutscene_spencer);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(AssetList::cutscene_jacob);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(AssetList::SpencerSpyPortrait);
if(AppConfig::Instance().IsIpad())
tempp->SetDesignSize(127,120);
portraits.push_back(tempp);
scenes.clear();
/*JACOB: Now my boy, you shall be reunited with your father. Ha ha ha hyack...AAAAAARRRRRRGH!
A sharp pain tears through Jacob's body. The stress of the serum is too much to handle and his heart stops beating.
JACOB: Spencer...
Spencer picks up the vial from his uncle's dead hand. The logo of NCorp is etched on the side.
SPENCER: This should be enough to put NCorp down...
By the time the NCorp facilities were inspected by the authorities, any evidence of genetic experimentation had been mysteriously burned and destroyed. The government shut down all operations at the complex despite any concrete proof of the illegal activity.
Time passes yet Spencer's mind remains troubled. As the reluctant head of Fortified Industries, he now sees the broader scope of dealing arms to the countries of the world. Evil men take power for themselves and destroy the lives of the innocent every day.
SPENCER: I can't rest. I will never rest until all the men who live only to destroy our world are brought under the justice of my blade. NCorp was only the beginning. I promise you, father, I will not let this world fall. I have the power to change it. It is all I have now...Vengeance.
*/
Scene temp;
temp.background = 73;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 9;
sprintf(temp.top,"");
sprintf(temp.bottom,"Now my boy, you shall be reunited\n"
" with your father.\n"
" Ha ha ha hyack...\n"
" AAAAAARRRRRRGH!");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_finale1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = false;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_finale1;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 12;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," A sharp pain tears through\n"
" Jacob's body. The stress of\n"
" the serum is too much to handle\n"
" and his heart stops beating.");
scenes.push_back(temp);
temp.background = AssetList::cutscene_finale1;
temp.bot_portrait = 1;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 12;
temp.yOffsetTop = 0;
temp.yOffsetBot = 39;
sprintf(temp.top,"");
sprintf(temp.bottom," Spencer...");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_black;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 20;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," Spencer picks up the vial from his\n"
" uncle's dead hand. The logo of\n"
" NCorp is etched on the side.");
scenes.push_back(temp);
temp.background = AssetList::cutscene_black;
temp.bot_portrait = NONE;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 29;
temp.yOffsetBot = 0;
sprintf(temp.top," This should be enough to put\n"
" NCorp down... ");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_black;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"By the time the NCorp facilities were\n"
" inspected by the authorities, any\n"
"evidence of genetic experimentation\n"
" had been mysteriously burned\n"
" and destroyed.");
scenes.push_back(temp);
temp.background = AssetList::cutscene_black;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 9;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," The government shut down all\n"
" operations at the complex\n"
" despite any concrete proof\n"
" of the illegal activity. ");
scenes.push_back(temp);
temp.background = AssetList::cutscene_black;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," Time passes yet Spencer's mind\n"
" remains troubled. As the\n"
" reluctant head of Fortified \n"
" Industries, he now sees the\n"
" broader scope of dealing arms");
scenes.push_back(temp);
temp.background = AssetList::cutscene_black;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
temp.yOffsetDialog = 9;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog," to the countries of the world.\n"
" Evil men take power for\n"
" themselves and destroy the\n"
" lives of the innocent every day. ");
scenes.push_back(temp);
temp.background = AssetList::cutscene_black;
temp.bot_portrait = NONE;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"I can't rest. I will never rest until all\n"
"the men who live only to destroy our\n"
"world are brought under the justice\n"
" of my blade. NCorp was only\n"
" the beginning.");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_black;
temp.bot_portrait = NONE;
temp.top_portrait = 0;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 9;
temp.yOffsetBot = 0;
sprintf(temp.top," I promise you, father, I will not\n"
" let this world fall. I have the\n"
" power to change it. It is all\n"
" I have now...");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_finale2;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = false;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = AssetList::cutscene_finale2;
temp.bot_portrait = NONE;
temp.top_portrait = 2;
temp.dialog_box = false;
temp.yOffsetDialog = 0;
temp.yOffsetTop = 39;
temp.yOffsetBot = 0;
sprintf(temp.top, " ...Vengeance.");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
if (game_class->GetAchievementsCount() < 15)
temp.background = AssetList::completion_screen_a;
else
temp.background = AssetList::completion_screen_b;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = false;
temp.yOffsetDialog = 12;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
current_scene = 0;
}
#ifdef BOB_LITE
void Theater::CreateSceneLite()
{
HPTSprite1 *tempp;
tempp = graphics_engine->CreateSprite1();
tempp->SetImage(AssetList::cutscene_spencer);
portraits.push_back(tempp);
scenes.clear();
/*Spencer finds his way into the main building where Suke Hato is located.
Spencer: I need to find a way up to that bastard's penthouse and get to the bottom of this. */
Scene temp;
temp.background = AssetList::free_attract_background;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = false;
temp.yOffsetDialog = 20;
temp.yOffsetTop = 0;
temp.yOffsetBot = 0;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
current_scene = 0;
// graphics_engine->LoadHGF(1,hptstrcat(path,("cutscenes//1b.hgf")));
// sound_engine->LoadHSF(hptstrcat(path, ("sounds//title.hsf")), 1);
// music = sound_engine->CreateSoundObject(0, 1);
// if((music != 0) && (game->mute_music != true)) music->HPTPlaySound(true);
buyGameScreenTime = 30.0f; // 30 seconds for this screen
}
#endif
/*
void Theater::CreateSceneSpecial()
{
scenes.clear();
Scene temp;
temp.background = 4;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"In a dark office on the other\n"
"side of the world...");
scenes.push_back(temp);
//In a dark office on the other side of the world.
temp.background = 4;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = false;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = 4;
temp.bot_portrait = 9;
temp.top_portrait = 10;
temp.dialog_box = false;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = 4;
temp.bot_portrait = 9;
temp.top_portrait = 10;
temp.dialog_box = false;
sprintf(temp.top,"");
sprintf(temp.bottom,"Of course this\n"
"complicates things.\n"
"Regardless, the\n"
"operation must\n"
"continue as planned..\n");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = 4;
temp.bot_portrait = 9;
temp.top_portrait = 10;
temp.dialog_box = false;
sprintf(temp.top,"");
sprintf(temp.bottom,"at the South\n"
"American and Asian\n"
"facilities.\n");
sprintf(temp.dialog,"");
scenes.push_back(temp);
//Of course this complicates things. Regardless,
//the operation must continue as planned at the South American and Asian facilities.
temp.background = 4;
temp.bot_portrait = 9;
temp.top_portrait = 10;
temp.dialog_box = false;
sprintf(temp.top,"We destroyed the\n"
"evidence at\n"
"NagolaCorp as you\n"
"requested, although\n"
"some files were...\n");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
//We destroyed the evidence at NagolaCorp
//as you requested, although some files were missing.
temp.background = 4;
temp.bot_portrait = 9;
temp.top_portrait = 10;
temp.dialog_box = false;
sprintf(temp.top,"missing.\n");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
//The ones in young Mr. Corinth's possession?
temp.background = 4;
temp.bot_portrait = 9;
temp.top_portrait = 10;
temp.dialog_box = false;
sprintf(temp.top,"missing.\n");
sprintf(temp.bottom,"The ones in young\n"
"Mr. Corinth's\n"
"possession?");
sprintf(temp.dialog,"");
scenes.push_back(temp);
//Yes sir. Do not worry, there is nothing incriminating. Only loose endsÖ
temp.background = 4;
temp.bot_portrait = 9;
temp.top_portrait = 10;
temp.dialog_box = false;
sprintf(temp.top,"Yes sir.\n"
"Do not worry, there\n"
"is nothing\n"
"incriminating.\n"
"Only loose ends.\n");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
//Loose ends that could lead them here. I want security up at the facilities. I do not like unwelcome guests.
temp.background = 4;
temp.bot_portrait = 9;
temp.top_portrait = 10;
temp.dialog_box = false;
sprintf(temp.top,"Yes sir.\n"
"Do not worry, there\n"
"is nothing\n"
"incriminating.\n"
"Only loose ends.\n");
sprintf(temp.bottom,"Loose ends that \n"
"could lead them \n"
"here. I want security\n"
"up at the facilities...\n");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = 4;
temp.bot_portrait = 9;
temp.top_portrait = 10;
temp.dialog_box = false;
sprintf(temp.top,"");
sprintf(temp.bottom,"I do not like\n"
"unwelcomed guests.\n");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = 4;
temp.bot_portrait = 9;
temp.top_portrait = 10;
temp.dialog_box = false;
sprintf(temp.top,"Yes, Mr. Hato.");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = 5;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = true;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"Somewhere over the jungles of\n"
"Peru...");
scenes.push_back(temp);
temp.background = 5;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = false;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = 5;
temp.bot_portrait = 8;
temp.top_portrait = 7;
temp.dialog_box = false;
sprintf(temp.top,"We almost there?");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = 5;
temp.bot_portrait = 8;
temp.top_portrait = 7;
temp.dialog_box = false;
sprintf(temp.top,"We almost there?");
sprintf(temp.bottom,"Yeah, according to \n"
"these files you found \n"
"we should be coming\n"
"up on one of the\n"
"testing facilities...\n");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = 5;
temp.bot_portrait = 8;
temp.top_portrait = 7;
temp.dialog_box = false;
sprintf(temp.top,"");
sprintf(temp.bottom,"shortly. \n");
sprintf(temp.dialog,"");
scenes.push_back(temp);
//Yeah, according to these files you found we should be coming up on one of the testing facilities shortly
temp.background = 5;
temp.bot_portrait = 8;
temp.top_portrait = 7;
temp.dialog_box = false;
sprintf(temp.top,"You better drop me\n"
"off a few miles out.\n"
"I don't want to set\n"
"off any alarms.\n");
sprintf(temp.bottom,"\n");
sprintf(temp.dialog,"");
scenes.push_back(temp);
//You better drop me off a few miles out. I don't want to set off any alarms.
temp.background = 5;
temp.bot_portrait = 8;
temp.top_portrait = 7;
temp.dialog_box = false;
sprintf(temp.top,"You better drop me\n"
"off a few miles out.\n"
"I don't want to set\n"
"off any alarms.\n");
sprintf(temp.bottom,"Okay, ready?\n"
"Use your comlink\n"
"to contact me if\n"
"you get into trouble.\n");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = 5;
temp.bot_portrait = 8;
temp.top_portrait = 7;
temp.dialog_box = false;
sprintf(temp.top,"");
sprintf(temp.bottom,"I'm gonna try and\n"
"crack these disks\n"
"you found and see\n"
"what more I can find\n"
"out about...\n");
sprintf(temp.dialog,"");
scenes.push_back(temp);
temp.background = 5;
temp.bot_portrait = 8;
temp.top_portrait = 7;
temp.dialog_box = false;
sprintf(temp.top,"");
sprintf(temp.bottom,"NagolaCorp's\n"
"operations. Be \n"
"careful Spencer, you \n"
"don't know what's\n"
"out there.\n");
sprintf(temp.dialog,"");
scenes.push_back(temp);
//Okay, ready? Use your comlink to contact me if you get into trouble.
//I'm gonna try and crack these disks you found and see what more I can
//find out about NagolaCorp's operations. Be careful Spencer,
//you don't know what's out there.
temp.background = 5;
temp.bot_portrait = 8;
temp.top_portrait = 7;
temp.dialog_box = false;
sprintf(temp.top,"Don't worry about me.\n"
"After what I've been\n"
"through, I think I can\n"
"handle myself.");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
//Don't worry about me. After what I've been through, I think I can handle myselfÖ
temp.background = 6;
temp.bot_portrait = NONE;
temp.top_portrait = NONE;
temp.dialog_box = false;
sprintf(temp.top,"");
sprintf(temp.bottom,"");
sprintf(temp.dialog,"");
scenes.push_back(temp);
current_scene = 0;
// graphics_engine->LoadHGF(1,hptstrcat(path,("cutscenes//end.hgf")));
// sound_engine->LoadHSF(hptstrcat(path, ("sounds//title.hsf")), 1);
// music = sound_engine->CreateSoundObject(0, 1);
// if((music != 0) && (game->mute_music != true)) music->HPTPlaySound(true);
}*/
void Theater::FreePortraits()
{
for(int count = 0;count < portraits.size();count++)
{
HPTSprite1 *temp = portraits[count];
temp->Release();
}
portraits.clear();
}
| {
"content_hash": "79d920249d464ea793177dc9a468cb5f",
"timestamp": "",
"source": "github",
"line_count": 3076,
"max_line_length": 417,
"avg_line_length": 30.11378413524057,
"alnum_prop": 0.6657130519270215,
"repo_name": "duhone/BladeofBetrayal",
"id": "cf7154a238cac95442e2d746542b58b3a3bd44d1",
"size": "92636",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Bob/Theater.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "30739"
},
{
"name": "C#",
"bytes": "74446"
},
{
"name": "C++",
"bytes": "1737400"
},
{
"name": "Objective-C",
"bytes": "547"
},
{
"name": "QMake",
"bytes": "840"
},
{
"name": "Shell",
"bytes": "451"
}
],
"symlink_target": ""
} |
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Structure;
namespace Microsoft.CodeAnalysis.CSharp.Structure
{
internal class EnumDeclarationStructureProvider : AbstractSyntaxNodeStructureProvider<EnumDeclarationSyntax>
{
protected override void CollectBlockSpans(
EnumDeclarationSyntax enumDeclaration,
ArrayBuilder<BlockSpan> spans,
CancellationToken cancellationToken)
{
CSharpStructureHelpers.CollectCommentBlockSpans(enumDeclaration, spans);
if (!enumDeclaration.OpenBraceToken.IsMissing &&
!enumDeclaration.CloseBraceToken.IsMissing)
{
spans.Add(CSharpStructureHelpers.CreateBlockSpan(
enumDeclaration,
enumDeclaration.Identifier,
autoCollapse: false,
type: BlockTypes.Enum,
isCollapsible: true));
}
// add any leading comments before the end of the type block
if (!enumDeclaration.CloseBraceToken.IsMissing)
{
var leadingTrivia = enumDeclaration.CloseBraceToken.LeadingTrivia;
CSharpStructureHelpers.CollectCommentBlockSpans(leadingTrivia, spans);
}
}
}
} | {
"content_hash": "8f7ed11320c811dd5895f67e0cd02304",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 112,
"avg_line_length": 38.388888888888886,
"alnum_prop": 0.6490593342981187,
"repo_name": "Pvlerick/roslyn",
"id": "3df45697d672851b07525b9bd0a7cbca78297965",
"size": "1544",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Features/CSharp/Portable/Structure/Providers/EnumDeclarationStructureProvider.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "1C Enterprise",
"bytes": "289100"
},
{
"name": "Batchfile",
"bytes": "17269"
},
{
"name": "C#",
"bytes": "84609568"
},
{
"name": "C++",
"bytes": "4865"
},
{
"name": "F#",
"bytes": "3632"
},
{
"name": "Groovy",
"bytes": "9630"
},
{
"name": "Makefile",
"bytes": "3606"
},
{
"name": "PowerShell",
"bytes": "57654"
},
{
"name": "Shell",
"bytes": "7239"
},
{
"name": "Visual Basic",
"bytes": "62384889"
}
],
"symlink_target": ""
} |
typedef NS_ENUM(NSUInteger, MTMetroLayoutStyle) {
MTMetroLayoutStylePivot,
MTMetroLayoutStylePanorama,
};
@class MTMetroLayout;
@interface MTMetroViewController : UIViewController
@property (nonatomic, readonly) MTMetroLayout *metroLayout;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, assign) NSUInteger selectedIndex;
@property (nonatomic, copy) NSArray *viewControllers;
- (id)initWithLayoutStyle:(MTMetroLayoutStyle)style;
- (void)setSelectedIndex:(NSUInteger)selectedIndex animated:(BOOL)animated;
- (void)setViewControllers:(NSArray *)viewControllers animated:(BOOL)animated;
@end
| {
"content_hash": "d2457173af0e6d8189bd4537832a1fdd",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 78,
"avg_line_length": 28,
"alnum_prop": 0.8059006211180124,
"repo_name": "sora0077/MTMetroLayout",
"id": "f9b4ff327929ca969956196b0d250871c7e715b3",
"size": "833",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MTMetroViewLayout/MTMetroViewController.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "45323"
},
{
"name": "Ruby",
"bytes": "1167"
}
],
"symlink_target": ""
} |
package com.github.dan4ik95dv.famousartists.model.realm;
//import org.parceler.Parcel;
//import io.realm.RealmDoubleRealmProxy;
import io.realm.RealmObject;
/**
* Created by Daniil Celikin on 10.02.2016.
*/
//@Parcel(implementations = {RealmDoubleRealmProxy.class}, value = Parcel.Serialization.BEAN, analyze = RealmDouble.class)
public class RealmFloat extends RealmObject {
private Float value;
public RealmFloat() {
}
public RealmFloat(Float value) {
this.value = value;
}
public Float getValue() {
return value;
}
public void setValue(Float value) {
this.value = value;
}
} | {
"content_hash": "537335f79820ebf378afc0b1db463f9c",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 122,
"avg_line_length": 20.28125,
"alnum_prop": 0.6841294298921418,
"repo_name": "dan4ik95dv/famousartists",
"id": "d268376b1affd93c68ba6568c535c359dd70e8cb",
"size": "649",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/github/dan4ik95dv/famousartists/model/realm/RealmFloat.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "287822"
}
],
"symlink_target": ""
} |
classdef mrimagingprops < handle
properties (AbortSet,SetObservable)
% Flip angle
%
% "fa" is the MR imaging flip angle in units of degrees
fa
% Echo time
%
% "te" is the MR imaging echo time specified in units of milliseconds
te
% Inversion time
%
% "ti" is the MR imaging inversion time specified in units of
% milliseconds
ti
% Repetition time
%
% "tr" is the MR imaging repetition time in units of milliseconds
tr
end
%---------------------------- Class Constructor ----------------------------
methods
function obj = mrimagingprops
end %mrimagingprops.mrimagingprops
end
%------------------------------- Set Methods -------------------------------
methods
function set.fa(obj,val)
validateattributes(val,{'numeric'},...
{'scalar','finite','nonnan','positive','real','nonempty'});
obj.fa = val;
notify(obj,'checkCalcReady');
notify(obj,'updateModel');
end %mrimagingprops.set.fa
function set.te(obj,val)
validateattributes(val,{'numeric'},...
{'scalar','finite','nonnan','positive','real','nonempty'});
obj.te = val;
notify(obj,'checkCalcReady');
notify(obj,'updateModel');
end %mrimagingprops.set.te
function set.ti(obj,val)
validateattributes(val,{'numeric'},...
{'scalar','finite','nonnan','positive','real','nonempty'});
obj.ti = val;
notify(obj,'checkCalcReady');
notify(obj,'updateModel');
end %mrimagingprops.set.ti
function set.tr(obj,val)
validateattributes(val,{'numeric'},...
{'scalar','finite','nonnan','positive','real','nonempty'});
obj.tr = val;
notify(obj,'checkCalcReady');
notify(obj,'updateModel');
end %mrimagingprops.set.tr
end %set methods
%------------------------------ Other Methods ------------------------------
methods (Static)
function obj = dicom2obj(obj,hdr)
%dicom2obj Converts a DICOM header to an mrimagingprops object
%
% OBJ = mrimagingprops.dicom2obj(S) converts the DICOM header stored
% in the structure S to an MRIMAGINGPROPS object OBJ
%
% OBJ = mrimagingprops.dicom2obj(OBJ,S) populates the properties of
% the object OBJ that are common to MRIMAGINGPROPS properties using
% the DICOM header stored in the structure S.
% Initialize the workspace
if isempty(obj)
obj = eval(mfilename);
end
% Apply the DICOM header
for prop = properties(mfilename)'
switch prop{1}
case 'fa'
str = 'FlipAngle';
case 'te'
str = 'EchoTime';
case 'ti'
str = 'InversionTime';
case 'tr'
str = 'RepetitionTime';
otherwise
continue
end
if isfield(hdr,str) && (hdr.(str)>0) && isprop(obj,prop{1})
obj.(prop{1}) = hdr.(str);
end
end
end
end
end %mrimagingprops | {
"content_hash": "f55b22585399b381d61f59dddccf3e43",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 80,
"avg_line_length": 29.689075630252102,
"alnum_prop": 0.4803283328615907,
"repo_name": "rjbosca/QUATTRO",
"id": "5296829cc0cec85c77c665af487b380a5f29688a",
"size": "3533",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Modeling/models/mrimagingprops.m",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "253"
},
{
"name": "C",
"bytes": "15079"
},
{
"name": "C++",
"bytes": "64350"
},
{
"name": "CMake",
"bytes": "203"
},
{
"name": "HTML",
"bytes": "100654"
},
{
"name": "M",
"bytes": "28337"
},
{
"name": "Matlab",
"bytes": "1932207"
}
],
"symlink_target": ""
} |
import functools
import os
import pkgutil
import sys
from collections import OrderedDict, defaultdict
from importlib import import_module
import django
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import (
BaseCommand, CommandError, CommandParser, handle_default_options,
)
from django.core.management.color import color_style
from django.utils import autoreload
from django.utils.encoding import force_text
def find_commands(management_dir):
"""
Given a path to a management directory, returns a list of all the command
names that are available.
Returns an empty list if no commands are defined.
"""
command_dir = os.path.join(management_dir, 'commands')
return [name for _, name, is_pkg in pkgutil.iter_modules([command_dir])
if not is_pkg and not name.startswith('_')]
def load_command_class(app_name, name):
"""
Given a command name and an application name, returns the Command
class instance. All errors raised by the import process
(ImportError, AttributeError) are allowed to propagate.
"""
module = import_module('%s.management.commands.%s' % (app_name, name))
return module.Command()
@functools.lru_cache(maxsize=None)
def get_commands():
"""
Returns a dictionary mapping command names to their callback applications.
This works by looking for a management.commands package in django.core, and
in each installed application -- if a commands package exists, all commands
in that package are registered.
Core commands are always included. If a settings module has been
specified, user-defined commands will also be included.
The dictionary is in the format {command_name: app_name}. Key-value
pairs from this dictionary can then be used in calls to
load_command_class(app_name, command_name)
If a specific version of a command must be loaded (e.g., with the
startapp command), the instantiated module can be placed in the
dictionary in place of the application name.
The dictionary is cached on the first call and reused on subsequent
calls.
"""
commands = {name: 'django.core' for name in find_commands(__path__[0])}
if not settings.configured:
return commands
for app_config in reversed(list(apps.get_app_configs())):
path = os.path.join(app_config.path, 'management')
commands.update({name: app_config.name for name in find_commands(path)})
return commands
def call_command(command_name, *args, **options):
"""
Calls the given command, with the given options and args/kwargs.
This is the primary API you should use for calling specific commands.
`name` may be a string or a command object. Using a string is preferred
unless the command object is required for further processing or testing.
Some examples:
call_command('migrate')
call_command('shell', plain=True)
call_command('sqlmigrate', 'myapp')
from django.core.management.commands import flush
cmd = flush.Command()
call_command(cmd, verbosity=0, interactive=False)
# Do something with cmd ...
"""
if isinstance(command_name, BaseCommand):
# Command object passed in.
command = command_name
command_name = command.__class__.__module__.split('.')[-1]
else:
# Load the command object by name.
try:
app_name = get_commands()[command_name]
except KeyError:
raise CommandError("Unknown command: %r" % command_name)
if isinstance(app_name, BaseCommand):
# If the command is already loaded, use it directly.
command = app_name
else:
command = load_command_class(app_name, command_name)
# Simulate argument parsing to get the option defaults (see #10080 for details).
parser = command.create_parser('', command_name)
# Use the `dest` option name from the parser option
opt_mapping = {
sorted(s_opt.option_strings)[0].lstrip('-').replace('-', '_'): s_opt.dest
for s_opt in parser._actions if s_opt.option_strings
}
arg_options = {opt_mapping.get(key, key): value for key, value in options.items()}
defaults = parser.parse_args(args=[force_text(a) for a in args])
defaults = dict(defaults._get_kwargs(), **arg_options)
# Move positional args out of options to mimic legacy optparse
args = defaults.pop('args', ())
if 'skip_checks' not in options:
defaults['skip_checks'] = True
return command.execute(*args, **defaults)
class ManagementUtility:
"""
Encapsulates the logic of the django-admin and manage.py utilities.
"""
def __init__(self, argv=None):
self.argv = argv or sys.argv[:]
self.prog_name = os.path.basename(self.argv[0])
self.settings_exception = None
def main_help_text(self, commands_only=False):
"""
Returns the script's main help text, as a string.
"""
if commands_only:
usage = sorted(get_commands().keys())
else:
usage = [
"",
"Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name,
"",
"Available subcommands:",
]
commands_dict = defaultdict(lambda: [])
for name, app in get_commands().items():
if app == 'django.core':
app = 'django'
else:
app = app.rpartition('.')[-1]
commands_dict[app].append(name)
style = color_style()
for app in sorted(commands_dict.keys()):
usage.append("")
usage.append(style.NOTICE("[%s]" % app))
for name in sorted(commands_dict[app]):
usage.append(" %s" % name)
# Output an extra note if settings are not properly configured
if self.settings_exception is not None:
usage.append(style.NOTICE(
"Note that only Django core commands are listed "
"as settings are not properly configured (error: %s)."
% self.settings_exception))
return '\n'.join(usage)
def fetch_command(self, subcommand):
"""
Tries to fetch the given subcommand, printing a message with the
appropriate command called from the command line (usually
"django-admin" or "manage.py") if it can't be found.
"""
# Get commands outside of try block to prevent swallowing exceptions
commands = get_commands()
try:
app_name = commands[subcommand]
except KeyError:
if os.environ.get('DJANGO_SETTINGS_MODULE'):
# If `subcommand` is missing due to misconfigured settings, the
# following line will retrigger an ImproperlyConfigured exception
# (get_commands() swallows the original one) so the user is
# informed about it.
settings.INSTALLED_APPS
else:
sys.stderr.write("No Django settings specified.\n")
sys.stderr.write(
"Unknown command: %r\nType '%s help' for usage.\n"
% (subcommand, self.prog_name)
)
sys.exit(1)
if isinstance(app_name, BaseCommand):
# If the command is already loaded, use it directly.
klass = app_name
else:
klass = load_command_class(app_name, subcommand)
return klass
def autocomplete(self):
"""
Output completion suggestions for BASH.
The output of this function is passed to BASH's `COMREPLY` variable and
treated as completion suggestions. `COMREPLY` expects a space
separated string as the result.
The `COMP_WORDS` and `COMP_CWORD` BASH environment variables are used
to get information about the cli input. Please refer to the BASH
man-page for more information about this variables.
Subcommand options are saved as pairs. A pair consists of
the long option string (e.g. '--exclude') and a boolean
value indicating if the option requires arguments. When printing to
stdout, an equal sign is appended to options which require arguments.
Note: If debugging this function, it is recommended to write the debug
output in a separate file. Otherwise the debug output will be treated
and formatted as potential completion suggestions.
"""
# Don't complete if user hasn't sourced bash_completion file.
if 'DJANGO_AUTO_COMPLETE' not in os.environ:
return
cwords = os.environ['COMP_WORDS'].split()[1:]
cword = int(os.environ['COMP_CWORD'])
try:
curr = cwords[cword - 1]
except IndexError:
curr = ''
subcommands = list(get_commands()) + ['help']
options = [('--help', False)]
# subcommand
if cword == 1:
print(' '.join(sorted(filter(lambda x: x.startswith(curr), subcommands))))
# subcommand options
# special case: the 'help' subcommand has no options
elif cwords[0] in subcommands and cwords[0] != 'help':
subcommand_cls = self.fetch_command(cwords[0])
# special case: add the names of installed apps to options
if cwords[0] in ('dumpdata', 'sqlmigrate', 'sqlsequencereset', 'test'):
try:
app_configs = apps.get_app_configs()
# Get the last part of the dotted path as the app name.
options.extend((app_config.label, 0) for app_config in app_configs)
except ImportError:
# Fail silently if DJANGO_SETTINGS_MODULE isn't set. The
# user will find out once they execute the command.
pass
parser = subcommand_cls.create_parser('', cwords[0])
options.extend(
(sorted(s_opt.option_strings)[0], s_opt.nargs != 0)
for s_opt in parser._actions if s_opt.option_strings
)
# filter out previously specified options from available options
prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]]
options = [opt for opt in options if opt[0] not in prev_opts]
# filter options by current input
options = sorted((k, v) for k, v in options if k.startswith(curr))
for option in options:
opt_label = option[0]
# append '=' to options which require args
if option[1]:
opt_label += '='
print(opt_label)
# Exit code of the bash completion function is never passed back to
# the user, so it's safe to always exit with 0.
# For more details see #25420.
sys.exit(0)
def execute(self):
"""
Given the command-line arguments, this figures out which subcommand is
being run, creates a parser appropriate to that command, and runs it.
"""
try:
subcommand = self.argv[1]
except IndexError:
subcommand = 'help' # Display help if no arguments were given.
# Preprocess options to extract --settings and --pythonpath.
# These options could affect the commands that are available, so they
# must be processed early.
parser = CommandParser(None, usage="%(prog)s subcommand [options] [args]", add_help=False)
parser.add_argument('--settings')
parser.add_argument('--pythonpath')
parser.add_argument('args', nargs='*') # catch-all
try:
options, args = parser.parse_known_args(self.argv[2:])
handle_default_options(options)
except CommandError:
pass # Ignore any option errors at this point.
try:
settings.INSTALLED_APPS
except ImproperlyConfigured as exc:
self.settings_exception = exc
if settings.configured:
# Start the auto-reloading dev server even if the code is broken.
# The hardcoded condition is a code smell but we can't rely on a
# flag on the command class because we haven't located it yet.
if subcommand == 'runserver' and '--noreload' not in self.argv:
try:
autoreload.check_errors(django.setup)()
except Exception:
# The exception will be raised later in the child process
# started by the autoreloader. Pretend it didn't happen by
# loading an empty list of applications.
apps.all_models = defaultdict(OrderedDict)
apps.app_configs = OrderedDict()
apps.apps_ready = apps.models_ready = apps.ready = True
# Remove options not compatible with the built-in runserver
# (e.g. options for the contrib.staticfiles' runserver).
# Changes here require manually testing as described in
# #27522.
_parser = self.fetch_command('runserver').create_parser('django', 'runserver')
_options, _args = _parser.parse_known_args(self.argv[2:])
for _arg in _args:
self.argv.remove(_arg)
# In all other cases, django.setup() is required to succeed.
else:
django.setup()
self.autocomplete()
if subcommand == 'help':
if '--commands' in args:
sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
elif len(options.args) < 1:
sys.stdout.write(self.main_help_text() + '\n')
else:
self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0])
# Special-cases: We want 'django-admin --version' and
# 'django-admin --help' to work, for backwards compatibility.
elif subcommand == 'version' or self.argv[1:] == ['--version']:
sys.stdout.write(django.get_version() + '\n')
elif self.argv[1:] in (['--help'], ['-h']):
sys.stdout.write(self.main_help_text() + '\n')
else:
self.fetch_command(subcommand).run_from_argv(self.argv)
def execute_from_command_line(argv=None):
"""
A simple method that runs a ManagementUtility.
"""
utility = ManagementUtility(argv)
utility.execute()
| {
"content_hash": "6d94c927aff7c4524310117e7ead85f1",
"timestamp": "",
"source": "github",
"line_count": 361,
"max_line_length": 98,
"avg_line_length": 40.98060941828255,
"alnum_prop": 0.602338785994322,
"repo_name": "auready/django",
"id": "d5295680ab2a583335f3eadfc31c4d1da60332b3",
"size": "14794",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "django/core/management/__init__.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "53169"
},
{
"name": "HTML",
"bytes": "173634"
},
{
"name": "JavaScript",
"bytes": "448151"
},
{
"name": "Makefile",
"bytes": "125"
},
{
"name": "Python",
"bytes": "12200962"
},
{
"name": "Shell",
"bytes": "809"
},
{
"name": "Smarty",
"bytes": "130"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.codebuild;
import javax.annotation.Generated;
import com.amazonaws.ClientConfigurationFactory;
import com.amazonaws.annotation.NotThreadSafe;
import com.amazonaws.client.builder.AwsAsyncClientBuilder;
import com.amazonaws.client.AwsAsyncClientParams;
/**
* Fluent builder for {@link com.amazonaws.services.codebuild.AWSCodeBuildAsync}. Use of the builder is preferred over
* using constructors of the client class.
**/
@NotThreadSafe
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public final class AWSCodeBuildAsyncClientBuilder extends AwsAsyncClientBuilder<AWSCodeBuildAsyncClientBuilder, AWSCodeBuildAsync> {
private static final ClientConfigurationFactory CLIENT_CONFIG_FACTORY = new ClientConfigurationFactory();;
/**
* @return Create new instance of builder with all defaults set.
*/
public static AWSCodeBuildAsyncClientBuilder standard() {
return new AWSCodeBuildAsyncClientBuilder();
}
/**
* @return Default async client using the {@link com.amazonaws.auth.DefaultAWSCredentialsProviderChain} and
* {@link com.amazonaws.regions.DefaultAwsRegionProviderChain} chain
*/
public static AWSCodeBuildAsync defaultClient() {
return standard().build();
}
private AWSCodeBuildAsyncClientBuilder() {
super(CLIENT_CONFIG_FACTORY);
}
/**
* Construct an asynchronous implementation of AWSCodeBuildAsync using the current builder configuration.
*
* @param params
* Current builder configuration represented as a parameter object.
* @return Fully configured implementation of AWSCodeBuildAsync.
*/
@Override
protected AWSCodeBuildAsync build(AwsAsyncClientParams params) {
return new AWSCodeBuildAsyncClient(params);
}
}
| {
"content_hash": "b3068dfd8deb07aaab24be2a770cf26a",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 132,
"avg_line_length": 35.07692307692308,
"alnum_prop": 0.75,
"repo_name": "dagnir/aws-sdk-java",
"id": "011a1f039289b6ce328dc1f409997b9dedaa784a",
"size": "2404",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-codebuild/src/main/java/com/amazonaws/services/codebuild/AWSCodeBuildAsyncClientBuilder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FreeMarker",
"bytes": "157317"
},
{
"name": "Gherkin",
"bytes": "25556"
},
{
"name": "Java",
"bytes": "165755153"
},
{
"name": "Scilab",
"bytes": "3561"
}
],
"symlink_target": ""
} |
package armerger.items;
import armerger.entity.GhostPlayer;
import armerger.items.armor.LinkedChest;
import armerger.items.interfaces.ILinked;
import armerger.items.interfaces.LinkedArmor;
import armerger.lib.RefStrings;
import baubles.api.IBauble;
import cofh.api.energy.EnergyStorage;
import cofh.api.energy.IEnergyHandler;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
public class TEArmorStand extends TileEntity implements IEnergyHandler, IInventory{
protected EnergyStorage storage;
private TEArmorStand[] linkedStands;
private ItemStack[] linkedArmor;
private EntityPlayer[] equippedBy;
private ItemStack[] inventory;
public EntityLiving ghost;
private boolean ischild = false;
private boolean isparent = false;
public TEArmorStand(World world)
{
storage = new EnergyStorage(0, Integer.MAX_VALUE);
inventory = new ItemStack[8];
linkedArmor = new ItemStack[8];
linkedStands = new TEArmorStand[10];
equippedBy = new EntityPlayer[8];
ghost = new GhostPlayer(world, this);
}
public void setGhost(GhostPlayer ghost){this.ghost = ghost;}
public boolean isChildStand(){return ischild;}
public boolean isParentStand(){return isparent;}
public boolean becomeParent(){return true;}
public boolean containsType(ItemStack type){return (type.getItem() instanceof ItemArmor || type.getItem() instanceof IBauble);}
public void onBlockPlaced(World world, int x, int y, int z)
{
placeGhost();
}
//ghost is only used for rendering
private void placeGhost()
{
ghost.posX = this.xCoord;
ghost.posY = this.yCoord;
ghost.posZ = this.zCoord;
}
//------------------------
// Save and Server Sync methods
//------------------------
@Override
public void readFromNBT(NBTTagCompound nbt)
{
super.readFromNBT(nbt);
storage.readFromNBT(nbt);
ghost = (EntityLiving) MinecraftServer.getServer().getEntityWorld().getEntityByID(nbt.getInteger(RefStrings.GHOSTTAG));
this.blockMetadata = nbt.getInteger(RefStrings.METADATATAG);
World world = MinecraftServer.getServer().getEntityWorld();
int[] uuids = nbt.getIntArray(RefStrings.EQUIPPEDUUIDS);
NBTTagList list= nbt.getTagList(RefStrings.TAGLIST, 9);
NBTTagList inv = list.getCompoundTagAt(0).getTagList(RefStrings.HELDARMOR, 9);
NBTTagList linked = list.getCompoundTagAt(1).getTagList(RefStrings.LINKEDARMOR, 9);
NBTTagCompound stands = list.getCompoundTagAt(2);
for(int i = 0; i < nbt.getInteger(RefStrings.TAGLIST); i++)
{
//entities
Entity ent = (uuids[i] != -1) ? world.getEntityByID(uuids[i]) : null;
equippedBy[i] = (ent instanceof EntityPlayer) ? ((EntityPlayer)ent) : null;
//heldArmor
inventory[i] = (inv.getCompoundTagAt(i).hasKey(RefStrings.HELDARMOR + i)) ? ItemStack.loadItemStackFromNBT(inv.getCompoundTagAt(i).getCompoundTag(RefStrings.HELDARMOR + i)) : null;
//linkedArmor
linkedArmor[i] = (linked.getCompoundTagAt(i).hasKey(RefStrings.LINKEDARMOR + i)) ? ItemStack.loadItemStackFromNBT(linked.getCompoundTagAt(i).getCompoundTag(RefStrings.LINKEDARMOR + i)) : null;
}
for(int i = 0; i < 10; i++)
{
if(stands.hasKey(RefStrings.LINKEDSTANDS + i))
{
int[] pos = stands.getIntArray(RefStrings.LINKEDSTANDS + i);
TileEntity ent = world.getTileEntity(pos[0], pos[1], pos[2]);
linkedStands[i] = (ent instanceof TEArmorStand) ? ((TEArmorStand)ent) : null;
}
else
linkedStands[i] = null;
}
}
@Override
public void writeToNBT(NBTTagCompound nbt)
{
super.writeToNBT(nbt);
storage.writeToNBT(nbt);
nbt.setInteger(RefStrings.GHOSTTAG, ghost.getEntityId());
nbt.setInteger(RefStrings.METADATATAG, this.blockMetadata);
int[] uuids = new int[8];
NBTTagList list = new NBTTagList();
NBTTagList inv = new NBTTagList();
NBTTagList linked = new NBTTagList();
NBTTagCompound nbttagcompound1;
int count = 1;
for(int i = 0; i < 8; i++)
{
//entities
uuids[i] = (equippedBy[i] != null) ? equippedBy[i].getEntityId() : -1;
//heldArmor
if(inventory[i] != null)
{
nbttagcompound1 = new NBTTagCompound();
inventory[i].writeToNBT(nbttagcompound1);
nbttagcompound1.setString(RefStrings.HELDARMOR + i, "");
inv.appendTag(nbttagcompound1);
count++;
}
//linkedArmor
if(linkedArmor[i] != null)
{
nbttagcompound1 = new NBTTagCompound();
inventory[i].writeToNBT(nbttagcompound1);
nbttagcompound1.setString(RefStrings.LINKEDARMOR + i, "");
linked.appendTag(nbttagcompound1);
count++;
}
}
nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setTag(RefStrings.HELDARMOR, inv);/*Encapsulate inv and append*/
list.appendTag(nbttagcompound1);
nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setTag(RefStrings.HELDARMOR, linked);/*Encapsulate linked and append*/
list.appendTag(nbttagcompound1);
nbt.setIntArray(RefStrings.EQUIPPEDUUIDS, uuids);
nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setString(RefStrings.LINKEDSTANDS, "");
for(int i = 0; i < 10; i++)
if(linkedStands[i] != null)
nbttagcompound1.setIntArray(RefStrings.LINKEDSTANDS + 1, new int[]{linkedStands[i].xCoord, linkedStands[i].yCoord,linkedStands[i].zCoord});
list.appendTag(nbttagcompound1);
nbt.setTag(RefStrings.TAGLIST, list);
nbt.setInteger(RefStrings.TAGLIST, count);
}
@Override
public Packet getDescriptionPacket()
{
NBTTagCompound info = new NBTTagCompound();
this.writeToNBT(info);
return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 0, info);
}
@Override
public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt)
{
this.readFromNBT(pkt.func_148857_g());
}
//--------------------------
// Custom Methods
//--------------------------
/*
* Only for use by Parent Stands, should only be called by a single linked armor piece
*/
public void sendTickInfoToLinkedArmor()
{
NBTTagCompound[][] info = getTickInfoFromChildren();
NBTTagCompound[] temp = this.getTickInfo();
for(int i = 0; i < 8; i++)
info[i][0] = temp[i];
for(int i = 0; i < 8; i++)
{
((LinkedArmor)linkedArmor[i].getItem()).acceptInfo(info[i], linkedArmor[i]);
}
}
private NBTTagCompound[][] getTickInfoFromChildren()
{
NBTTagCompound[][] info = new NBTTagCompound[8][11];
for(int i = 0; i < 10; i++)
{
NBTTagCompound[] temp = linkedStands[i].getTickInfo();
for(int j = 0; j < 8; j++)
info[j][i + 1] = temp[j];
}
return info;
}
public NBTTagCompound[] getTickInfo()
{
NBTTagCompound[] info = new NBTTagCompound[8];
info[0] = ghost.getEquipmentInSlot(4).getTagCompound();
info[0].setString(RefStrings.ITEMNAMETAG, ghost.getEquipmentInSlot(4).toString());
info[1] = ghost.getEquipmentInSlot(3).getTagCompound();
info[1].setString(RefStrings.ITEMNAMETAG, ghost.getEquipmentInSlot(3).toString());
info[2] = ghost.getEquipmentInSlot(2).getTagCompound();
info[2].setString(RefStrings.ITEMNAMETAG, ghost.getEquipmentInSlot(2).toString());
info[3] = ghost.getEquipmentInSlot(1).getTagCompound();
info[3].setString(RefStrings.ITEMNAMETAG, ghost.getEquipmentInSlot(1).toString());
return info;
}
public boolean onActivate(World world, int x, int y, int z, EntityPlayer player)
{
boolean toReturn = tryPlacingArmor(world,x,y,z,player);
if((!this.isparent && !this.ischild) && this.isReadyToLink())
createLinkedStandArmor();
return toReturn;
}
private void createLinkedStandArmor() {
System.arraycopy(inventory, 0, linkedArmor, 0, 8);
for(ItemStack linked : linkedArmor)
{
if(linked != null)
{
Item lItem = linked.getItem();
lItem.getClass().isInstance(lItem);
if(ILinked.class.isInstance(lItem))
((ILinked)lItem).createLink(this);
}
}
}
private boolean isReadyToLink() {
//for(ItemStack held : heldArmor)
for(int i = 0; i < 4; i++)// this for loop is until I have bauble implemented
{
ItemStack held = inventory[i];
if(held == null)
{
return false;
}
else
{
Item checking = held.getItem();
if(!ILinked.class.isInstance(checking) || ((ILinked)checking).isLinked())
return false;
}
}
return true;
}
private boolean tryPlacingArmor(World world, int x, int y, int z, EntityPlayer player)
{
ItemStack heldStack = player.getHeldItem();
if(heldStack != null && heldStack.getItem() instanceof ItemArmor)
{
Item held = heldStack.getItem();
if(((ItemArmor)held).armorType == 0)
{
if(inventory[0] == null)
{
inventory[0] = heldStack.copy();
player.destroyCurrentEquippedItem();
return true;
}
}
else if(((ItemArmor)held).armorType == 1)
{
if(inventory[1] == null)
{
inventory[1] = heldStack.copy();
player.destroyCurrentEquippedItem();
return true;
}
}
else if(((ItemArmor)held).armorType == 2)
{
if(inventory[2] == null)
{
inventory[2] = heldStack.copy();
player.destroyCurrentEquippedItem();
return true;
}
}
else if(((ItemArmor)held).armorType == 3)
{
if(inventory[3] == null)
{
inventory[3] = heldStack.copy();
player.destroyCurrentEquippedItem();
return true;
}
}
else
return false;
/*else if(heldStack.getItem() instanceof LinkedBauble)
{
Item held1 = heldStack.getItem();
if(((LinkedBauble)held1).getBaubleType(heldStack) == BaubleType.AMULET)
{
if(heldArmor[4] == null)
{
heldArmor[4] = heldStack.copy();
player.destroyCurrentEquippedItem();
return true;
}
}
else if(((LinkedBauble)held1).getBaubleType(heldStack) == BaubleType.RING)
{
if(heldArmor[5] == null || heldArmor[6] == null)
{
if(heldArmor[5] == null)
heldArmor[5] = heldStack.copy();
else
heldArmor[6] = heldStack.copy();
player.destroyCurrentEquippedItem();
return true;
}
}
else if(((LinkedBauble)held1).getBaubleType(heldStack) == BaubleType.BELT)
{
if(heldArmor[7] == null)
{
heldArmor[7] = heldStack.copy();
player.destroyCurrentEquippedItem();
return true;
}
}
else
return false;
}*/
}
return false;
}
public void setEquiped(ItemStack linkedStack, EntityLivingBase player) {
int pos = findPosition(linkedStack, linkedArmor);
if(pos != -1)
{
equippedBy[pos] = (EntityPlayer) player;
if(wearingFull())
((LinkedChest)linkedArmor[1].getItem()).startEffects(linkedArmor[1]);
}
}
public void removeEquiped(ItemStack linkedStack)
{
int pos = findPosition(linkedStack, linkedArmor);
if(pos != -1)
{
equippedBy[pos] = null;
((LinkedChest)linkedArmor[1].getItem()).stopEffects(linkedArmor[1]);
}
}
private boolean wearingFull() {
if(equippedBy[0] != null)
{
EntityPlayer player = equippedBy[0];
for(int i = 0; i < 8; i++)
if(equippedBy[i] == null || equippedBy[i] != player)
return false;
return true;
}
return false;
}
private int findPosition(ItemStack thing, ItemStack[] arr) {
for(int i = 0; i < arr.length; i ++)
{
if(arr[i].equals(thing))
return i;
}
return -1;
}
//--------------------------
// RF Energy Methods
//--------------------------
/* IEnergyConnection */
@Override
public boolean canConnectEnergy(ForgeDirection from)
{
return true;
}
/* IEnergyReceiver */
@Override
public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate)
{
return storage.receiveEnergy(maxReceive, simulate);
}
/* IEnergyProvider */
@Override
public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate)
{
return storage.extractEnergy(0, false);
}
/* IEnergyReceiver and IEnergyProvider */
@Override
public int getEnergyStored(ForgeDirection from)
{
return storage.getEnergyStored();
}
@Override
public int getMaxEnergyStored(ForgeDirection from)
{
return storage.getMaxEnergyStored();
}
//--------------------------
// Inventory Methods
//--------------------------
@Override
public int getSizeInventory() {
// TODO Auto-generated method stub
return 8;
}
@Override
public ItemStack getStackInSlot(int index) {
if (index < 0 || index >= this.getSizeInventory())
return null;
return this.inventory[index];
}
@Override
public ItemStack decrStackSize(int index, int count) {
if (this.getStackInSlot(index) != null)
{
ItemStack itemstack = this.getStackInSlot(index);
if (itemstack.stackSize <= count) {
this.setInventorySlotContents(index, null);
this.markDirty();
return itemstack;
}
else
{
itemstack = itemstack.splitStack(count);
if (itemstack.stackSize <= 0) {
this.setInventorySlotContents(index, null);
} else {
//Just to show that changes happened
this.setInventorySlotContents(index, itemstack);
}
this.markDirty();
return itemstack;
}
}
else
{
return null;
}
}
@Override
public ItemStack getStackInSlotOnClosing(int index) {
ItemStack stack = this.getStackInSlot(index);
this.setInventorySlotContents(index, null);
return stack;
}
@Override
public void setInventorySlotContents(int index, ItemStack stack) {
if (index < 0 || index >= this.getSizeInventory())
return;
if (stack != null && stack.stackSize > this.getInventoryStackLimit())
stack.stackSize = this.getInventoryStackLimit();
if (stack != null && stack.stackSize == 0)
stack = null;
this.inventory[index] = stack;
this.markDirty();
}
@Override
public String getInventoryName() {
// TODO Auto-generated method stub
return "armerger.tileentityarmorstand";
}
@Override
public boolean hasCustomInventoryName() {
// TODO Auto-generated method stub
return true;
}
@Override
public int getInventoryStackLimit() {
// TODO Auto-generated method stub
return 1;
}
@Override
public boolean isUseableByPlayer(EntityPlayer player) {
return this.worldObj.getTileEntity(this.xCoord, this.yCoord, this.zCoord) == this
&& player.getDistanceSq(this.xCoord + .5, this.yCoord + .5, this.zCoord + .5) <= 64;
}
@Override
public void openInventory() {
// TODO Auto-generated method stub
}
@Override
public void closeInventory() {
// TODO Auto-generated method stub
}
@Override
public boolean isItemValidForSlot(int index, ItemStack stack) {
Item item = stack.getItem();
if(stack.getItem() instanceof ItemArmor)
if(((ItemArmor)item).armorType == index) //helm in slot 0, boots in slot 3
return true;
else if(item instanceof IBauble)
{
;
}
return false;
}
}
| {
"content_hash": "e6c0e6f0fb2684ce04cb011ce7baec7e",
"timestamp": "",
"source": "github",
"line_count": 542,
"max_line_length": 195,
"avg_line_length": 28.535055350553506,
"alnum_prop": 0.6730246993404888,
"repo_name": "UberAffe/Armerger",
"id": "0ec977a03fe029b369beeff5de7915106269bdbc",
"size": "15466",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/armerger/items/TEArmorStand.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "104"
},
{
"name": "Java",
"bytes": "68442"
}
],
"symlink_target": ""
} |
Minimal blog theme for Hugo.
| {
"content_hash": "45c594a7db8bb67e2c01da8d10a387e4",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 28,
"avg_line_length": 29,
"alnum_prop": 0.7931034482758621,
"repo_name": "sedenardi/slim",
"id": "e4ff8996f6eab0cfe9bb83ef323ac4f7d170366b",
"size": "36",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5771"
},
{
"name": "GCC Machine Description",
"bytes": "8"
},
{
"name": "HTML",
"bytes": "3523"
},
{
"name": "JavaScript",
"bytes": "335"
}
],
"symlink_target": ""
} |
SpringSecurityAnnotation
========================
This is a sample Web Application With Spring Security With Annotation. You can learn How Spring Without XML configuration adds to security. This app is created as initialization app where we always want a sample Login Pre Configured.
| {
"content_hash": "23d114abff64db66ba56c810353cec2c",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 233,
"avg_line_length": 71.25,
"alnum_prop": 0.7614035087719299,
"repo_name": "kumarpallav/SpringSecurityAnnotation",
"id": "487fb2811a6a95fb3413e32314c73dc259a685ed",
"size": "285",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "27419"
},
{
"name": "Java",
"bytes": "9990"
},
{
"name": "JavaScript",
"bytes": "44502"
}
],
"symlink_target": ""
} |
from PyQt5.QtGui import *
import re
from decimal import Decimal
from electrum import bitcoin
from electrum.util import bfh
from .qrtextedit import ScanQRTextEdit
from .completion_text_edit import CompletionTextEdit
from . import util
RE_ADDRESS = '[1-9A-HJ-NP-Za-km-z]{26,}'
RE_ALIAS = '(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>'
frozen_style = "QWidget { background-color:none; border:none;}"
normal_style = "QPlainTextEdit { }"
class PayToEdit(CompletionTextEdit, ScanQRTextEdit):
def __init__(self, win):
CompletionTextEdit.__init__(self)
ScanQRTextEdit.__init__(self)
self.win = win
self.amount_edit = win.amount_e
self.document().contentsChanged.connect(self.update_size)
self.heightMin = 0
self.heightMax = 150
self.c = None
self.textChanged.connect(self.check_text)
self.outputs = []
self.errors = []
self.is_pr = False
self.is_alias = False
self.scan_f = win.pay_to_URI
self.update_size()
self.payto_address = None
self.previous_payto = ''
def setFrozen(self, b):
self.setReadOnly(b)
self.setStyleSheet(frozen_style if b else normal_style)
for button in self.buttons:
button.setHidden(b)
def setGreen(self):
self.setStyleSheet(util.ColorScheme.GREEN.as_stylesheet(True))
def setExpired(self):
self.setStyleSheet(util.ColorScheme.RED.as_stylesheet(True))
def parse_address_and_amount(self, line):
x, y = line.split(',')
out_type, out = self.parse_output(x)
amount = self.parse_amount(y)
return out_type, out, amount
def parse_output(self, x):
try:
address = self.parse_address(x)
return bitcoin.TYPE_ADDRESS, address
except:
script = self.parse_script(x)
return bitcoin.TYPE_SCRIPT, script
def parse_script(self, x):
from electrum.transaction import opcodes, push_script
script = ''
for word in x.split():
if word[0:3] == 'OP_':
assert word in opcodes.lookup
opcode_int = opcodes.lookup[word]
assert opcode_int < 256 # opcode is single-byte
script += bitcoin.int_to_hex(opcode_int)
else:
bfh(word) # to test it is hex data
script += push_script(word)
return script
def parse_amount(self, x):
if x.strip() == '!':
return '!'
p = pow(10, self.amount_edit.decimal_point())
return int(p * Decimal(x.strip()))
def parse_address(self, line):
r = line.strip()
m = re.match('^'+RE_ALIAS+'$', r)
address = str(m.group(2) if m else r)
assert bitcoin.is_address(address)
return address
def check_text(self):
self.errors = []
if self.is_pr:
return
# filter out empty lines
lines = [i for i in self.lines() if i]
outputs = []
total = 0
self.payto_address = None
if len(lines) == 1:
data = lines[0]
if data.startswith("bitcoin:"):
self.scan_f(data)
return
try:
self.payto_address = self.parse_output(data)
except:
pass
if self.payto_address:
self.win.lock_amount(False)
return
is_max = False
for i, line in enumerate(lines):
try:
_type, to_address, amount = self.parse_address_and_amount(line)
except:
self.errors.append((i, line.strip()))
continue
outputs.append((_type, to_address, amount))
if amount == '!':
is_max = True
else:
total += amount
self.win.is_max = is_max
self.outputs = outputs
self.payto_address = None
if self.win.is_max:
self.win.do_update_fee()
else:
self.amount_edit.setAmount(total if outputs else None)
self.win.lock_amount(total or len(lines)>1)
def get_errors(self):
return self.errors
def get_recipient(self):
return self.payto_address
def get_outputs(self, is_max):
if self.payto_address:
if is_max:
amount = '!'
else:
amount = self.amount_edit.get_amount()
_type, addr = self.payto_address
self.outputs = [(_type, addr, amount)]
return self.outputs[:]
def lines(self):
return self.toPlainText().split('\n')
def is_multiline(self):
return len(self.lines()) > 1
def paytomany(self):
self.setText("\n\n\n")
self.update_size()
def update_size(self):
lineHeight = QFontMetrics(self.document().defaultFont()).height()
docHeight = self.document().size().height()
h = docHeight * lineHeight + 11
if self.heightMin <= h <= self.heightMax:
self.setMinimumHeight(h)
self.setMaximumHeight(h)
self.verticalScrollBar().hide()
def qr_input(self):
data = super(PayToEdit,self).qr_input()
if data.startswith("bitcoin:"):
self.scan_f(data)
# TODO: update fee
def resolve(self):
self.is_alias = False
if self.hasFocus():
return
if self.is_multiline(): # only supports single line entries atm
return
if self.is_pr:
return
key = str(self.toPlainText())
if key == self.previous_payto:
return
self.previous_payto = key
if not (('.' in key) and (not '<' in key) and (not ' ' in key)):
return
parts = key.split(sep=',') # assuming single line
if parts and len(parts) > 0 and bitcoin.is_address(parts[0]):
return
try:
data = self.win.contacts.resolve(key)
except:
return
if not data:
return
self.is_alias = True
address = data.get('address')
name = data.get('name')
new_url = key + ' <' + address + '>'
self.setText(new_url)
self.previous_payto = new_url
#if self.win.config.get('openalias_autoadd') == 'checked':
self.win.contacts[key] = ('openalias', name)
self.win.contact_list.on_update()
self.setFrozen(True)
if data.get('type') == 'openalias':
self.validated = data.get('validated')
if self.validated:
self.setGreen()
else:
self.setExpired()
else:
self.validated = None
| {
"content_hash": "7fc7ebd4a4a28700a30f03962ab3278e",
"timestamp": "",
"source": "github",
"line_count": 225,
"max_line_length": 79,
"avg_line_length": 30.204444444444444,
"alnum_prop": 0.5403178340200118,
"repo_name": "kyuupichan/electrum",
"id": "716a5f58d2b712ec9805adf767959dc3bfdc2689",
"size": "7961",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gui/qt/paytoedit.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "GLSL",
"bytes": "289"
},
{
"name": "Java",
"bytes": "1574"
},
{
"name": "Makefile",
"bytes": "837"
},
{
"name": "NSIS",
"bytes": "7311"
},
{
"name": "Python",
"bytes": "1918037"
},
{
"name": "Shell",
"bytes": "17760"
}
],
"symlink_target": ""
} |
<h1><?php echo lang('forgot_password_heading');?></h1>
<p><?php echo sprintf(lang('forgot_password_subheading'), $identity_label);?></p>
<?php if(!empty($message)) echo '<div id="infoMessage" class="alert alert-warning"><i class="fa fa-warning"></i> '.$message.'</div>';?>
<?php echo form_open("auth/forgot_password", array('class' => 'form-horizontal'));?>
<div class="form-group">
<label for="email" class="col-sm-2 control-label"><?php echo sprintf(lang('forgot_password_email_label'), $identity_label);?></label>
<div class="col-sm-3"><?php echo form_input($email, NULL, 'class="form-control"');?></div>
<?php echo form_submit(array('class' => 'btn btn-primary', 'name' => 'send', 'value' => lang('forgot_password_submit_btn')));?>
</div>
<?php echo form_close();?>
| {
"content_hash": "50634d759a63f620a580d57ed0077d37",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 141,
"avg_line_length": 51.5,
"alnum_prop": 0.6152912621359223,
"repo_name": "cmstest/PREMS",
"id": "65f96eae1ec95f62965e72a9b5ce5ac17048b5e3",
"size": "825",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/views/auth/forgot_password.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "29862"
},
{
"name": "ApacheConf",
"bytes": "1245"
},
{
"name": "CSS",
"bytes": "11039"
},
{
"name": "HTML",
"bytes": "474289"
},
{
"name": "JavaScript",
"bytes": "632500"
},
{
"name": "PHP",
"bytes": "2608912"
}
],
"symlink_target": ""
} |
using ::testing::_;
using ::testing::Assign;
using ::testing::DoAll;
using ::testing::NotNull;
namespace {
const int kRenderProcessId = 1;
const int kRenderFrameId = 5;
const int kStreamId = 50;
const char kSecurityOrigin[] = "http://localhost";
const char kDefaultDeviceId[] = "";
const char kBadDeviceId[] =
"badbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadbad1";
const char kInvalidDeviceId[] = "invalid-device-id";
} // namespace
namespace content {
class MockAudioMirroringManager : public AudioMirroringManager {
public:
MockAudioMirroringManager() {}
virtual ~MockAudioMirroringManager() {}
MOCK_METHOD3(AddDiverter,
void(int render_process_id,
int render_frame_id,
Diverter* diverter));
MOCK_METHOD1(RemoveDiverter, void(Diverter* diverter));
private:
DISALLOW_COPY_AND_ASSIGN(MockAudioMirroringManager);
};
class MockAudioRendererHost : public AudioRendererHost {
public:
MockAudioRendererHost(media::AudioManager* audio_manager,
AudioMirroringManager* mirroring_manager,
MediaInternals* media_internals,
MediaStreamManager* media_stream_manager,
const ResourceContext::SaltCallback& salt_callback)
: AudioRendererHost(kRenderProcessId,
audio_manager,
mirroring_manager,
media_internals,
media_stream_manager,
salt_callback),
shared_memory_length_(0) {}
// A list of mock methods.
MOCK_METHOD3(OnDeviceAuthorized,
void(int stream_id,
media::OutputDeviceStatus device_status,
const media::AudioParameters& output_params));
MOCK_METHOD2(OnStreamCreated, void(int stream_id, int length));
MOCK_METHOD1(OnStreamPlaying, void(int stream_id));
MOCK_METHOD1(OnStreamPaused, void(int stream_id));
MOCK_METHOD1(OnStreamError, void(int stream_id));
private:
virtual ~MockAudioRendererHost() {
// Make sure all audio streams have been deleted.
EXPECT_TRUE(audio_entries_.empty());
}
// This method is used to dispatch IPC messages to the renderer. We intercept
// these messages here and dispatch to our mock methods to verify the
// conversation between this object and the renderer.
virtual bool Send(IPC::Message* message) {
CHECK(message);
// In this method we dispatch the messages to the according handlers as if
// we are the renderer.
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(MockAudioRendererHost, *message)
IPC_MESSAGE_HANDLER(AudioMsg_NotifyDeviceAuthorized,
OnNotifyDeviceAuthorized)
IPC_MESSAGE_HANDLER(AudioMsg_NotifyStreamCreated,
OnNotifyStreamCreated)
IPC_MESSAGE_HANDLER(AudioMsg_NotifyStreamStateChanged,
OnNotifyStreamStateChanged)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
EXPECT_TRUE(handled);
delete message;
return true;
}
void OnNotifyDeviceAuthorized(int stream_id,
media::OutputDeviceStatus device_status,
const media::AudioParameters& output_params) {
OnDeviceAuthorized(stream_id, device_status, output_params);
}
void OnNotifyStreamCreated(
int stream_id,
base::SharedMemoryHandle handle,
base::SyncSocket::TransitDescriptor socket_descriptor,
uint32_t length) {
// Maps the shared memory.
shared_memory_.reset(new base::SharedMemory(handle, false));
CHECK(shared_memory_->Map(length));
CHECK(shared_memory_->memory());
shared_memory_length_ = length;
// Create the SyncSocket using the handle.
base::SyncSocket::Handle sync_socket_handle =
base::SyncSocket::UnwrapHandle(socket_descriptor);
sync_socket_.reset(new base::SyncSocket(sync_socket_handle));
// And then delegate the call to the mock method.
OnStreamCreated(stream_id, length);
}
void OnNotifyStreamStateChanged(int stream_id,
media::AudioOutputIPCDelegateState state) {
switch (state) {
case media::AUDIO_OUTPUT_IPC_DELEGATE_STATE_PLAYING:
OnStreamPlaying(stream_id);
break;
case media::AUDIO_OUTPUT_IPC_DELEGATE_STATE_PAUSED:
OnStreamPaused(stream_id);
break;
case media::AUDIO_OUTPUT_IPC_DELEGATE_STATE_ERROR:
OnStreamError(stream_id);
break;
default:
FAIL() << "Unknown stream state";
break;
}
}
std::unique_ptr<base::SharedMemory> shared_memory_;
std::unique_ptr<base::SyncSocket> sync_socket_;
uint32_t shared_memory_length_;
DISALLOW_COPY_AND_ASSIGN(MockAudioRendererHost);
};
namespace {
std::string ReturnMockSalt() {
return std::string();
}
ResourceContext::SaltCallback GetMockSaltCallback() {
return base::Bind(&ReturnMockSalt);
}
void WaitForEnumeration(base::RunLoop* loop,
const AudioOutputDeviceEnumeration& e) {
loop->Quit();
}
} // namespace
class AudioRendererHostTest : public testing::Test {
public:
AudioRendererHostTest() {
audio_manager_.reset(media::AudioManager::CreateForTesting());
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kUseFakeDeviceForMediaStream);
media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
// Enable caching to make enumerations run in a single thread
media_stream_manager_->audio_output_device_enumerator()->SetCachePolicy(
AudioOutputDeviceEnumerator::CACHE_POLICY_MANUAL_INVALIDATION);
base::RunLoop().RunUntilIdle();
base::RunLoop run_loop;
media_stream_manager_->audio_output_device_enumerator()->Enumerate(
base::Bind(&WaitForEnumeration, &run_loop));
run_loop.Run();
host_ = new MockAudioRendererHost(audio_manager_.get(), &mirroring_manager_,
MediaInternals::GetInstance(),
media_stream_manager_.get(),
GetMockSaltCallback());
// Simulate IPC channel connected.
host_->set_peer_process_for_testing(base::Process::Current());
}
~AudioRendererHostTest() override {
// Simulate closing the IPC channel and give the audio thread time to close
// the underlying streams.
host_->OnChannelClosing();
SyncWithAudioThread();
// Release the reference to the mock object. The object will be destructed
// on message_loop_.
host_ = NULL;
}
protected:
void Create() {
Create(false, kDefaultDeviceId, url::Origin(GURL(kSecurityOrigin)));
}
void Create(bool unified_stream,
const std::string& device_id,
const url::Origin& security_origin) {
media::OutputDeviceStatus expected_device_status =
device_id == kDefaultDeviceId
? media::OUTPUT_DEVICE_STATUS_OK
: device_id == kBadDeviceId
? media::OUTPUT_DEVICE_STATUS_ERROR_NOT_AUTHORIZED
: media::OUTPUT_DEVICE_STATUS_ERROR_NOT_FOUND;
EXPECT_CALL(*host_.get(),
OnDeviceAuthorized(kStreamId, expected_device_status, _));
if (expected_device_status == media::OUTPUT_DEVICE_STATUS_OK) {
EXPECT_CALL(*host_.get(), OnStreamCreated(kStreamId, _));
EXPECT_CALL(mirroring_manager_,
AddDiverter(kRenderProcessId, kRenderFrameId, NotNull()))
.RetiresOnSaturation();
}
// Send a create stream message to the audio output stream and wait until
// we receive the created message.
media::AudioParameters params(
media::AudioParameters::AUDIO_FAKE, media::CHANNEL_LAYOUT_STEREO,
media::AudioParameters::kAudioCDSampleRate, 16,
media::AudioParameters::kAudioCDSampleRate / 10);
int session_id = 0;
if (unified_stream) {
// Use AudioInputDeviceManager::kFakeOpenSessionId as the session id to
// pass the permission check.
session_id = AudioInputDeviceManager::kFakeOpenSessionId;
}
host_->OnRequestDeviceAuthorization(kStreamId, kRenderFrameId, session_id,
device_id, security_origin);
if (expected_device_status == media::OUTPUT_DEVICE_STATUS_OK) {
host_->OnCreateStream(kStreamId, kRenderFrameId, params);
// At some point in the future, a corresponding RemoveDiverter() call must
// be made.
EXPECT_CALL(mirroring_manager_, RemoveDiverter(NotNull()))
.RetiresOnSaturation();
}
SyncWithAudioThread();
}
void Close() {
// Send a message to AudioRendererHost to tell it we want to close the
// stream.
host_->OnCloseStream(kStreamId);
SyncWithAudioThread();
}
void Play() {
EXPECT_CALL(*host_.get(), OnStreamPlaying(kStreamId));
host_->OnPlayStream(kStreamId);
SyncWithAudioThread();
}
void Pause() {
EXPECT_CALL(*host_.get(), OnStreamPaused(kStreamId));
host_->OnPauseStream(kStreamId);
SyncWithAudioThread();
}
void SetVolume(double volume) {
host_->OnSetVolume(kStreamId, volume);
SyncWithAudioThread();
}
void SimulateError() {
EXPECT_EQ(1u, host_->audio_entries_.size())
<< "Calls Create() before calling this method";
// Expect an error signal sent through IPC.
EXPECT_CALL(*host_.get(), OnStreamError(kStreamId));
// Simulate an error sent from the audio device.
host_->ReportErrorAndClose(kStreamId);
SyncWithAudioThread();
// Expect the audio stream record is removed.
EXPECT_EQ(0u, host_->audio_entries_.size());
}
// SyncWithAudioThread() waits until all pending tasks on the audio thread
// are executed while also processing pending task in message_loop_ on the
// current thread. It is used to synchronize with the audio thread when we are
// closing an audio stream.
void SyncWithAudioThread() {
base::RunLoop().RunUntilIdle();
base::RunLoop run_loop;
audio_manager_->GetTaskRunner()->PostTask(
FROM_HERE, media::BindToCurrentLoop(run_loop.QuitClosure()));
run_loop.Run();
}
private:
// MediaStreamManager uses a DestructionObserver, so it must outlive the
// TestBrowserThreadBundle.
std::unique_ptr<MediaStreamManager> media_stream_manager_;
TestBrowserThreadBundle thread_bundle_;
std::unique_ptr<media::AudioManager> audio_manager_;
MockAudioMirroringManager mirroring_manager_;
scoped_refptr<MockAudioRendererHost> host_;
DISALLOW_COPY_AND_ASSIGN(AudioRendererHostTest);
};
TEST_F(AudioRendererHostTest, CreateAndClose) {
Create();
Close();
}
// Simulate the case where a stream is not properly closed.
TEST_F(AudioRendererHostTest, CreateAndShutdown) {
Create();
}
TEST_F(AudioRendererHostTest, CreatePlayAndClose) {
Create();
Play();
Close();
}
TEST_F(AudioRendererHostTest, CreatePlayPauseAndClose) {
Create();
Play();
Pause();
Close();
}
TEST_F(AudioRendererHostTest, SetVolume) {
Create();
SetVolume(0.5);
Play();
Pause();
Close();
}
// Simulate the case where a stream is not properly closed.
TEST_F(AudioRendererHostTest, CreatePlayAndShutdown) {
Create();
Play();
}
// Simulate the case where a stream is not properly closed.
TEST_F(AudioRendererHostTest, CreatePlayPauseAndShutdown) {
Create();
Play();
Pause();
}
TEST_F(AudioRendererHostTest, SimulateError) {
Create();
Play();
SimulateError();
}
// Simulate the case when an error is generated on the browser process,
// the audio device is closed but the render process try to close the
// audio stream again.
TEST_F(AudioRendererHostTest, SimulateErrorAndClose) {
Create();
Play();
SimulateError();
Close();
}
TEST_F(AudioRendererHostTest, CreateUnifiedStreamAndClose) {
Create(true, kDefaultDeviceId, url::Origin(GURL(kSecurityOrigin)));
Close();
}
TEST_F(AudioRendererHostTest, CreateUnauthorizedDevice) {
Create(false, kBadDeviceId, url::Origin(GURL(kSecurityOrigin)));
Close();
}
TEST_F(AudioRendererHostTest, CreateInvalidDevice) {
Create(false, kInvalidDeviceId, url::Origin(GURL(kSecurityOrigin)));
Close();
}
// TODO(hclam): Add tests for data conversation in low latency mode.
} // namespace content
| {
"content_hash": "3d56aa16e6874d10b9e9da1a4f6f30ab",
"timestamp": "",
"source": "github",
"line_count": 383,
"max_line_length": 80,
"avg_line_length": 32.221932114882506,
"alnum_prop": 0.6707722226723928,
"repo_name": "was4444/chromium.src",
"id": "3e3b4f3d40c0bd60bc5329a0b0836e1a602e01ea",
"size": "13435",
"binary": false,
"copies": "1",
"ref": "refs/heads/nw15",
"path": "content/browser/renderer_host/media/audio_renderer_host_unittest.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
When updating your version of GWT, you should also update this DTD reference,
so that your app can take advantage of the latest GWT module capabilities.
-->
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.7.0//EN"
"http://gwtproject.org/doctype/2.7.0/gwt-module.dtd">
<module>
<!-- Other module inherits -->
<inherits name="com.google.gwt.user.User"/>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name="de.gishmo.module0812.domain.dto.Dto"/>
<inherits name="org.fusesource.restygwt.RestyGWT"/>
<!-- Specify the app entry point class. -->
<!-- Specify the paths for translatable code -->
<source path="client"/>
</module>
| {
"content_hash": "f41039cd0ff12fd92fe2cbc6f59fd14a",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 79,
"avg_line_length": 39.23809523809524,
"alnum_prop": 0.5970873786407767,
"repo_name": "FrankHossfeld/Training",
"id": "d6b80b8813925084c038849d1a0de4fd0b51d056",
"size": "824",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "GWT-OLD/Module0812DomainClient/src/de/gishmo/module0812/domain/service/Service.gwt.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "227738"
},
{
"name": "HTML",
"bytes": "73644"
},
{
"name": "Java",
"bytes": "1092442"
},
{
"name": "JavaScript",
"bytes": "9896"
}
],
"symlink_target": ""
} |
@implementation AKTPresentVCAnimation
#pragma mark - delegate
//|---------------------------------------------------------
// This is used for percent driven interactive transitions, as well as for container controllers that have companion animations that might need to
// synchronize with the main animation.
- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext {
return kTimeinterval;
}
// This method can only be a nop if the transition is interactive and not a percentDriven interactive transition.
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext {
UIView *container = transitionContext.containerView;
UIViewController *fromVc = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
UIViewController *toVc = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
if ([toVc isKindOfClass:[AKTViewController class]]) {
AKTViewController *vc = (id)toVc;
[vc orientation: fromVc.interfaceOrientation];
}
[container addSubview:fromVc.view];
[container addSubview:toVc.view];
toVc.view.frame = CGRectMake(0, mAKT_SCREENHEIGHT, mAKT_SCREENWITTH, mAKT_SCREENHEIGHT);
NSTimeInterval duration = [self transitionDuration:transitionContext];
[UIView animateWithDuration:duration delay:0 usingSpringWithDamping:1.f initialSpringVelocity:0.5f options:0 animations:^{
toVc.view.frame = CGRectMake(0, 0, mAKT_SCREENWITTH, mAKT_SCREENHEIGHT);
fromVc.view.transform = CGAffineTransformMakeScale(.96, .96);
fromVc.view.alpha = .8;
} completion:^(BOOL finished) {
fromVc.view.alpha = 1;
fromVc.view.transform = CGAffineTransformIdentity;
[transitionContext completeTransition:YES];
}];
}
@end
| {
"content_hash": "5e5b44cb9304b891096cd80cdedfaf56",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 146,
"avg_line_length": 55.84848484848485,
"alnum_prop": 0.7422680412371134,
"repo_name": "AkteamYang/AKTKit.AKTLayout",
"id": "5e5bbab3e6332b89ee5f9f2863a2e2bb7e4e73f3",
"size": "2100",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AKTKit/ARC_File/AKTClass/AKTUI/AKTViewController/AKTPresentVCAnimation.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "384765"
},
{
"name": "Ruby",
"bytes": "8143"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
Novitates Mycologicae 102 (1939)
#### Original name
Inoloma inflatum Velen.
### Remarks
null | {
"content_hash": "f983fe81af615398ff3f7aeff4868122",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 32,
"avg_line_length": 12,
"alnum_prop": 0.7243589743589743,
"repo_name": "mdoering/backbone",
"id": "54da279a0a6a0dda72775b5c46b9f944afffd573",
"size": "203",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Cortinariaceae/Inoloma/Inoloma inflatum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// La información general de un ensamblado se controla mediante el siguiente
// conjunto de atributos. Cambie estos valores de atributo para modificar la información
// asociada con un ensamblado.
[assembly: AssemblyTitle("ShySamples")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ShySamples")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Si establece ComVisible en false, los tipos de este ensamblado no estarán visibles
// para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde
// COM, establezca el atributo ComVisible en true en este tipo.
[assembly: ComVisible(false)]
//Para comenzar a compilar aplicaciones que se puedan traducir, establezca
//<UICulture>CultureYouAreCodingWith</UICulture> en el archivo .csproj
//dentro de <PropertyGroup>. Por ejemplo, si utiliza inglés de EE.UU.
//en los archivos de código fuente, establezca <UICulture> en en-US. A continuación, quite la marca de comentario
//del atributo NeutralResourceLanguage. Actualice "en-US" en
//la siguiente línea para que coincida con el valor UICulture del archivo de proyecto.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //donde se encuentran los diccionarios de recursos específicos del tema
//(se utiliza si no se encuentra ningún recurso en la página
// ni diccionarios de recursos de la aplicación)
ResourceDictionaryLocation.SourceAssembly //donde se encuentra el diccionario de recursos genérico
//(se utiliza si no se encuentra ningún recurso en la página,
// aplicación o diccionarios de recursos específicos del tema)
)]
// La información de versión de un ensamblado consta de los cuatro valores siguientes:
//
// Versión principal
// Versión secundaria
// Número de compilación
// Revisión
//
// Puede especificar todos los valores o usar los valores predeterminados de número de compilación y de revisión
// mediante el carácter '*', como se muestra a continuación:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "a50f4ce567673990e526baf9bf2040e3",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 114,
"avg_line_length": 47.981818181818184,
"alnum_prop": 0.7241379310344828,
"repo_name": "hipso99/shy",
"id": "c064f9793fe0c992b7ff50934f038289a80b9099",
"size": "2670",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ShySamples/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "48163"
},
{
"name": "PowerShell",
"bytes": "158"
}
],
"symlink_target": ""
} |
import pytest
from tests.conftest import BaseGraphCase
from tests.conftest import GraphCaseFactory
@pytest.fixture
def graph(graph_cases: GraphCaseFactory) -> BaseGraphCase:
return graph_cases('empty')
def test_set_style_key(graph: BaseGraphCase) -> None:
assert graph.eval_js_function('graphs.utils.setStyleKey', '', 'bar', 5) == 'bar=5'
assert graph.eval_js_function('graphs.utils.setStyleKey', 'style', 'bar', 5) == 'style;bar=5'
assert (
graph.eval_js_function('graphs.utils.setStyleKey', 'style;bar=7', 'bar', 5) == 'style;bar=5'
)
assert (
graph.eval_js_function('graphs.utils.setStyleKey', 'foobar=3;bar=7', 'bar', 5)
== 'foobar=3;bar=5'
)
assert (
graph.eval_js_function('graphs.utils.setStyleKey', 'foobar=3', 'bar', 5) == 'foobar=3;bar=5'
)
assert (
graph.eval_js_function('graphs.utils.setStyleKey', 'foobar=3;fizzbar=7', 'bar', 5)
== 'foobar=3;fizzbar=7;bar=5'
)
def test_remove_style_key(graph: BaseGraphCase) -> None:
assert graph.eval_js_function('graphs.utils.removeStyleKey', '', 'bar') == ''
assert graph.eval_js_function('graphs.utils.removeStyleKey', 'style;bar=7', 'bar') == 'style'
assert (
graph.eval_js_function('graphs.utils.removeStyleKey', 'style;bar=7', 'foo') == 'style;bar=7'
)
assert (
graph.eval_js_function('graphs.utils.removeStyleKey', 'style;bar=7', 'style')
== 'style;bar=7'
)
assert (
graph.eval_js_function('graphs.utils.removeStyleKey', 'foo=3;bar=7', 'style')
== 'foo=3;bar=7'
)
assert graph.eval_js_function('graphs.utils.removeStyleKey', 'foo=3;bar=7', 'foo') == 'bar=7'
assert graph.eval_js_function('graphs.utils.removeStyleKey', 'foo=3;bar=7', 'bar') == 'foo=3'
| {
"content_hash": "0bb848126bb35b1623abeaa08d626df2",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 100,
"avg_line_length": 38.84782608695652,
"alnum_prop": 0.6334639059876889,
"repo_name": "ESSS/qmxgraph",
"id": "38b4eff4a0f13a34f006df00e8059a3673a8ab94",
"size": "1787",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/test_js_utils.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1123"
},
{
"name": "HTML",
"bytes": "2717"
},
{
"name": "JavaScript",
"bytes": "108354"
},
{
"name": "Makefile",
"bytes": "2276"
},
{
"name": "Python",
"bytes": "259282"
},
{
"name": "Shell",
"bytes": "173"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>CruiseControl.NET : Filter Trigger</title>
<link rel="stylesheet" href="styles/site.css" type="text/css" />
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<table class="pagecontent" border="0" cellpadding="0" cellspacing="0" width="100%" bgcolor="#ffffff">
<tr>
<td valign="top" class="pagebody">
<div class="pageheader">
<span class="pagetitle">
CruiseControl.NET : Filter Trigger
</span>
</div>
<div class="pagesubheading">
This page last changed on Dec 02, 2009 by <font color="#0050B2">csut017</font>.
</div>
<h1><a name="FilterTrigger-FilterTrigger"></a>Filter Trigger</h1>
<p>The Filter Trigger allows you to prevent builds from occurring at certain times or on certain days (such as when your source control repository is undergoing backup). It is used to decorate an existing trigger. For example, if you have set up a <a href="Interval Trigger.html" title="Interval Trigger">Interval Trigger</a> to cause a new build every 5 minutes, you can use the Filter Trigger to create a window during which the build will not run. The filter will exclude modifications that occur between the start time and the end time on the days specified. If the start time is greater than the end time then the filtered time will span across midnight. For example, if the start time is 23:00 and the end time is 3:00 then builds will be suppressed from 23:00-23:59 and 0:00-3:00 on the days specified. </p>
<div class='panelMacro'><table class='infoMacro'><colgroup><col width='24'><col></colgroup><tr><td valign='top'><img src="images/icons/emoticons/information.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td><td>
<p>Like all triggers, the scheduleTrigger must be enclosed within a triggers element in the appropriate <a href="Project Configuration Block.html" title="Project Configuration Block">Project Configuration Block</a>. </p></td></tr></table></div>
<div class='panelMacro'><table class='warningMacro'><colgroup><col width='24'><col></colgroup><tr><td valign='top'><img src="images/icons/emoticons/forbidden.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td><td><b>Nested trigger syntax is different</b><br />
<p>As shown below, the configuration of the nested trigger is not the same as when using that trigger outside a filter trigger. When using the <filterTrigger> element, the inner trigger must be specified with the <trigger> element. You could not use the <intervalTrigger> trigger element in this example. </p></td></tr></table></div>
<h2><a name="FilterTrigger-Version"></a>Version</h2>
<p>Available from version 1.0</p>
<h2><a name="FilterTrigger-Examples"></a>Examples</h2>
<div class="code panel" style="border-style: solid;border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml"><span class="code-tag"><filterTrigger startTime=<span class="code-quote">"23:30"</span> endTime=<span class="code-quote">"23:45"</span>></span>
<span class="code-tag"><trigger type=<span class="code-quote">"intervalTrigger"</span> seconds=<span class="code-quote">"60"</span> /></span>
<span class="code-tag"><weekDays></span>
<span class="code-tag"><weekDay></span>Sunday<span class="code-tag"></weekDay></span>
<span class="code-tag"></weekDays></span>
<span class="code-tag"></filterTrigger></span></pre>
</div></div>
<h2><a name="FilterTrigger-ConfigurationElements"></a>Configuration Elements</h2>
<table class='confluenceTable'><tbody>
<tr>
<th class='confluenceTh'> Element </th>
<th class='confluenceTh'> Description </th>
<th class='confluenceTh'> Type </th>
<th class='confluenceTh'> Required </th>
<th class='confluenceTh'> Default </th>
<th class='confluenceTh'> Version </th>
</tr>
<tr>
<td class='confluenceTd'> buildCondition </td>
<td class='confluenceTd'> The condition that will be returned if a build is requested during the filter window. The default value is *NoBuild*indicating that no build will be performed </td>
<td class='confluenceTd'> String - one of:
<ul>
<li>NoBuild</li>
<li>IfModificationExists</li>
<li>ForceBuild</li>
</ul>
</td>
<td class='confluenceTd'> No </td>
<td class='confluenceTd'> NoBuild </td>
<td class='confluenceTd'> 1.0 </td>
</tr>
<tr>
<td class='confluenceTd'> endTime </td>
<td class='confluenceTd'> The end of the filter window. Builds will not occur before this time and after the start time. </td>
<td class='confluenceTd'> String </td>
<td class='confluenceTd'> No </td>
<td class='confluenceTd'> 23:59:59 </td>
<td class='confluenceTd'> 1.0 </td>
</tr>
<tr>
<td class='confluenceTd'> trigger </td>
<td class='confluenceTd'> The inner trigger to filter. </td>
<td class='confluenceTd'> <a href="Trigger Blocks.html" title="Trigger Blocks">Trigger Blocks</a> </td>
<td class='confluenceTd'> Yes </td>
<td class='confluenceTd'> <em>n/a</em> </td>
<td class='confluenceTd'> 1.0 </td>
</tr>
<tr>
<td class='confluenceTd'> startTime </td>
<td class='confluenceTd'> The start of the filter window. Builds will not occur after this time and before the end time. </td>
<td class='confluenceTd'> String </td>
<td class='confluenceTd'> No </td>
<td class='confluenceTd'> 00:00:00 </td>
<td class='confluenceTd'> 1.0 </td>
</tr>
<tr>
<td class='confluenceTd'> weekDays </td>
<td class='confluenceTd'> The week days on which the filter should be applied (eg. Monday, Tuesday). By default, all days of the week are set. The filter will have no effect on other days. </td>
<td class='confluenceTd'> String array<br clear="all" />The following values are valid:
<ul>
<li>Sunday</li>
<li>Monday</li>
<li>Tuesday</li>
<li>Wednesday</li>
<li>Thursday</li>
<li>Friday</li>
<li>Saturday</li>
</ul>
</td>
<td class='confluenceTd'> No </td>
<td class='confluenceTd'> Monday-Sunday </td>
<td class='confluenceTd'> 1.0 </td>
</tr>
</tbody></table>
<h2><a name="FilterTrigger-Notes"></a>Notes</h2>
<div class='panelMacro'><table class='infoMacro'><colgroup><col width='24'><col></colgroup><tr><td valign='top'><img src="images/icons/emoticons/information.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td><td>
<p>Times should be specified in hh:mm or hh:mm:ss 24 hour format (i.e., ranging from 00:00:00 to 23:59:59). </p></td></tr></table></div>
<h4><a name="FilterTrigger-NestedFilterTriggers"></a>Nested Filter Triggers</h4>
<p>Sometimes you would like to suppress builds that occur either between certain times or on certain days or in multiple combinations of dates and times. To acheive this, you can nest multiple filter triggers. For example, the following xml configures a trigger to filter builds between 7pm and 7am on weekdays and at any time on Saturdays and Sundays. </p>
<div class="code panel" style="border-style: solid;border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml"><span class="code-tag"><filterTrigger startTime=<span class="code-quote">"19:00"</span> endTime=<span class="code-quote">"07:00"</span>></span>
<span class="code-tag"><trigger type=<span class="code-quote">"filterTrigger"</span> startTime=<span class="code-quote">"0:00"</span> endTime=<span class="code-quote">"23:59:59"</span>></span>
<span class="code-tag"><trigger type=<span class="code-quote">"intervalTrigger"</span> name=<span class="code-quote">"continuous"</span> seconds=<span class="code-quote">"900"</span> buildCondition=<span class="code-quote">"ForceBuild"</span> /></span>
<span class="code-tag"><weekDays></span>
<span class="code-tag"><weekDay></span>Saturday<span class="code-tag"></weekDay></span>
<span class="code-tag"><weekDay></span>Sunday<span class="code-tag"></weekDay></span>
<span class="code-tag"></weekDays></span>
<span class="code-tag"></trigger></span>
<span class="code-tag"></filterTrigger></span></pre>
</div></div>
<div class='panelMacro'><table class='infoMacro'><colgroup><col width='24'><col></colgroup><tr><td valign='top'><img src="images/icons/emoticons/information.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td><td><b>Automatically Generated</b><br />
<p>Documentation generated on Wednesday, 2 Dec 2009 at 3:05:47 AM</p></td></tr></table></div>
</td>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td height="12" background="http://confluence.public.thoughtworks.org//images/border/border_bottom.gif"><img src="images/border/spacer.gif" width="1" height="1" border="0"/></td>
</tr>
<tr>
<td align="center"><font color="grey">Document generated by Confluence on Jan 30, 2010 19:06</font></td>
</tr>
</table>
</body>
</html> | {
"content_hash": "3f4de9dafa7fc556922d8a4d3eccce94",
"timestamp": "",
"source": "github",
"line_count": 151,
"max_line_length": 815,
"avg_line_length": 61.29139072847682,
"alnum_prop": 0.6761750405186385,
"repo_name": "Gallio/infrastructure",
"id": "c2f79125a73f9c5c45a350f4fa5c2d0009f24298",
"size": "9255",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ccnet/WebDashboard/doc/CCNET/Filter Trigger.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "1543"
},
{
"name": "C#",
"bytes": "110414"
},
{
"name": "CSS",
"bytes": "176691"
},
{
"name": "JavaScript",
"bytes": "40861"
},
{
"name": "Shell",
"bytes": "11478"
},
{
"name": "XSLT",
"bytes": "699714"
}
],
"symlink_target": ""
} |
#define JPEG_INTERNALS
#include "jinclude16.h"
#include "jpeglib16.h"
/*
* jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
* of a DCT block read in natural order (left to right, top to bottom).
*/
#if 0 /* This table is not actually needed in v6a */
const int jpeg_zigzag_order[DCTSIZE2] = {
0, 1, 5, 6, 14, 15, 27, 28,
2, 4, 7, 13, 16, 26, 29, 42,
3, 8, 12, 17, 25, 30, 41, 43,
9, 11, 18, 24, 31, 40, 44, 53,
10, 19, 23, 32, 39, 45, 52, 54,
20, 22, 33, 38, 46, 51, 55, 60,
21, 34, 37, 47, 50, 56, 59, 61,
35, 36, 48, 49, 57, 58, 62, 63
};
#endif
/*
* jpeg_natural_order[i] is the natural-order position of the i'th element
* of zigzag order.
*
* When reading corrupted data, the Huffman decoders could attempt
* to reference an entry beyond the end of this array (if the decoded
* zero run length reaches past the end of the block). To prevent
* wild stores without adding an inner-loop test, we put some extra
* "63"s after the real entries. This will cause the extra coefficient
* to be stored in location 63 of the block, not somewhere random.
* The worst case would be a run-length of 15, which means we need 16
* fake entries.
*/
const int jpeg_natural_order[DCTSIZE2+16] = {
0, 1, 8, 16, 9, 2, 3, 10,
17, 24, 32, 25, 18, 11, 4, 5,
12, 19, 26, 33, 40, 48, 41, 34,
27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36,
29, 22, 15, 23, 30, 37, 44, 51,
58, 59, 52, 45, 38, 31, 39, 46,
53, 60, 61, 54, 47, 55, 62, 63,
63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
63, 63, 63, 63, 63, 63, 63, 63
};
/*
* Arithmetic utilities
*/
GLOBAL(long)
jdiv_round_up (long a, long b)
/* Compute a/b rounded up to next integer, ie, ceil(a/b) */
/* Assumes a >= 0, b > 0 */
{
return (a + b - 1L) / b;
}
GLOBAL(long)
jround_up (long a, long b)
/* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
/* Assumes a >= 0, b > 0 */
{
a += b - 1L;
return a - (a % b);
}
/* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
* and coefficient-block arrays. This won't work on 80x86 because the arrays
* are FAR and we're assuming a small-pointer memory model. However, some
* DOS compilers provide far-pointer versions of memcpy() and memset() even
* in the small-model libraries. These will be used if USE_FMEM is defined.
* Otherwise, the routines below do it the hard way. (The performance cost
* is not all that great, because these routines aren't very heavily used.)
*/
#ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
#define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
#define FMEMZERO(target,size) MEMZERO(target,size)
#else /* 80x86 case, define if we can */
#ifdef USE_FMEM
#define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
#define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
#endif
#endif
GLOBAL(void)
jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
JSAMPARRAY output_array, int dest_row,
int num_rows, JDIMENSION num_cols)
/* Copy some rows of samples from one place to another.
* num_rows rows are copied from input_array[source_row++]
* to output_array[dest_row++]; these areas may overlap for duplication.
* The source and destination arrays must be at least as wide as num_cols.
*/
{
register JSAMPROW inptr, outptr;
#ifdef FMEMCOPY
register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
#else
register JDIMENSION count;
#endif
register int row;
input_array += source_row;
output_array += dest_row;
for (row = num_rows; row > 0; row--) {
inptr = *input_array++;
outptr = *output_array++;
#ifdef FMEMCOPY
FMEMCOPY(outptr, inptr, count);
#else
for (count = num_cols; count > 0; count--)
*outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
#endif
}
}
GLOBAL(void)
jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
JDIMENSION num_blocks)
/* Copy a row of coefficient blocks from one place to another. */
{
#ifdef FMEMCOPY
FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
#else
register JCOEFPTR inptr, outptr;
register long count;
inptr = (JCOEFPTR) input_row;
outptr = (JCOEFPTR) output_row;
for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
*outptr++ = *inptr++;
}
#endif
}
GLOBAL(void)
jzero_far (void FAR * target, size_t bytestozero)
/* Zero out a chunk of FAR memory. */
/* This might be sample-array data, block-array data, or alloc_large data. */
{
#ifdef FMEMZERO
FMEMZERO(target, bytestozero);
#else
register char FAR * ptr = (char FAR *) target;
register size_t count;
for (count = bytestozero; count > 0; count--) {
*ptr++ = 0;
}
#endif
}
| {
"content_hash": "e61fad01e27e8c68128b9fe827cfadab",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 101,
"avg_line_length": 28.696428571428573,
"alnum_prop": 0.6548433934868284,
"repo_name": "NCIP/annotation-and-image-markup",
"id": "79ff2f1a5769199a45d55b615d3eb2be3220499c",
"size": "5247",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "AIMToolkit_v4.0.0_rv44/source/dcmtk-3.6.1_20121102/dcmjpeg/libijg16/jutils.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "31363450"
},
{
"name": "C#",
"bytes": "5152916"
},
{
"name": "C++",
"bytes": "148605530"
},
{
"name": "CSS",
"bytes": "85406"
},
{
"name": "Java",
"bytes": "2039090"
},
{
"name": "Objective-C",
"bytes": "381107"
},
{
"name": "Perl",
"bytes": "502054"
},
{
"name": "Shell",
"bytes": "11832"
},
{
"name": "Tcl",
"bytes": "30867"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>stream_socket_service::set_option</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../stream_socket_service.html" title="stream_socket_service">
<link rel="prev" href="send.html" title="stream_socket_service::send">
<link rel="next" href="shutdown.html" title="stream_socket_service::shutdown">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="send.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../stream_socket_service.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="shutdown.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_asio.reference.stream_socket_service.set_option"></a><a class="link" href="set_option.html" title="stream_socket_service::set_option">stream_socket_service::set_option</a>
</h4></div></div></div>
<p>
<a class="indexterm" name="idm45773591827040"></a>
Set a socket option.
</p>
<pre class="programlisting"><span class="keyword">template</span><span class="special"><</span>
<span class="keyword">typename</span> <a class="link" href="../SettableSocketOption.html" title="Settable socket option requirements">SettableSocketOption</a><span class="special">></span>
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <span class="identifier">set_option</span><span class="special">(</span>
<span class="identifier">implementation_type</span> <span class="special">&</span> <span class="identifier">impl</span><span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">SettableSocketOption</span> <span class="special">&</span> <span class="identifier">option</span><span class="special">,</span>
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</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>
</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="send.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../stream_socket_service.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="shutdown.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "4b3e0d14f278e88c321effc494b8bf32",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 431,
"avg_line_length": 77.36363636363636,
"alnum_prop": 0.6498237367802585,
"repo_name": "zjutjsj1004/third",
"id": "9d2f22bbbe4e135b320484161aba355817321078",
"size": "4255",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "boost/doc/html/boost_asio/reference/stream_socket_service/set_option.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "224158"
},
{
"name": "Batchfile",
"bytes": "33175"
},
{
"name": "C",
"bytes": "5576593"
},
{
"name": "C#",
"bytes": "41850"
},
{
"name": "C++",
"bytes": "179595990"
},
{
"name": "CMake",
"bytes": "28348"
},
{
"name": "CSS",
"bytes": "331303"
},
{
"name": "Cuda",
"bytes": "26521"
},
{
"name": "FORTRAN",
"bytes": "1856"
},
{
"name": "Groff",
"bytes": "1305458"
},
{
"name": "HTML",
"bytes": "159660377"
},
{
"name": "IDL",
"bytes": "15"
},
{
"name": "JavaScript",
"bytes": "285786"
},
{
"name": "Lex",
"bytes": "1290"
},
{
"name": "Makefile",
"bytes": "1202020"
},
{
"name": "Max",
"bytes": "37424"
},
{
"name": "Objective-C",
"bytes": "3674"
},
{
"name": "Objective-C++",
"bytes": "651"
},
{
"name": "PHP",
"bytes": "60249"
},
{
"name": "Perl",
"bytes": "37297"
},
{
"name": "Perl6",
"bytes": "2130"
},
{
"name": "Python",
"bytes": "1833677"
},
{
"name": "QML",
"bytes": "613"
},
{
"name": "QMake",
"bytes": "17385"
},
{
"name": "Rebol",
"bytes": "372"
},
{
"name": "Shell",
"bytes": "1144162"
},
{
"name": "Tcl",
"bytes": "1205"
},
{
"name": "TeX",
"bytes": "38313"
},
{
"name": "XSLT",
"bytes": "564356"
},
{
"name": "Yacc",
"bytes": "20341"
}
],
"symlink_target": ""
} |
"""
iLO Inspect Interface
"""
from oslo_log import log as logging
from oslo_utils import importutils
from ironic.common import exception
from ironic.common.i18n import _
from ironic.common.i18n import _LI
from ironic.common.i18n import _LW
from ironic.common import states
from ironic.common import utils
from ironic.conductor import utils as conductor_utils
from ironic.db import api as dbapi
from ironic.drivers import base
from ironic.drivers.modules.ilo import common as ilo_common
ilo_error = importutils.try_import('proliantutils.exception')
LOG = logging.getLogger(__name__)
ESSENTIAL_PROPERTIES_KEYS = {'memory_mb', 'local_gb', 'cpus', 'cpu_arch'}
CAPABILITIES_KEYS = {'BootMode', 'secure_boot', 'rom_firmware_version',
'ilo_firmware_version', 'server_model', 'max_raid_level',
'pci_gpu_devices', 'sr_iov_devices', 'nic_capacity'}
def _create_ports_if_not_exist(node, macs):
"""Create ironic ports for the mac addresses.
Creates ironic ports for the mac addresses returned with inspection
or as requested by operator.
:param node: node object.
:param macs: A dictionary of port numbers to mac addresses
returned by node inspection.
"""
node_id = node.id
sql_dbapi = dbapi.get_instance()
for mac in macs.values():
port_dict = {'address': mac, 'node_id': node_id}
try:
sql_dbapi.create_port(port_dict)
LOG.info(_LI("Port created for MAC address %(address)s for node "
"%(node)s"), {'address': mac, 'node': node.uuid})
except exception.MACAlreadyExists:
LOG.warn(_LW("Port already exists for MAC address %(address)s "
"for node %(node)s"),
{'address': mac, 'node': node.uuid})
def _get_essential_properties(node, ilo_object):
"""Inspects the node and get essential scheduling properties
:param node: node object.
:param ilo_object: an instance of proliantutils.ilo.IloClient
:raises: HardwareInspectionFailure if any of the properties values
are missing.
:returns: The dictionary containing properties and MAC data.
The dictionary possible keys are 'properties' and 'macs'.
The 'properties' should contain keys as in
ESSENTIAL_PROPERTIES_KEYS. The 'macs' is a dictionary
containing key:value pairs of <port_numbers:mac_addresses>
"""
try:
# Retrieve the mandatory properties from hardware
result = ilo_object.get_essential_properties()
except ilo_error.IloError as e:
raise exception.HardwareInspectionFailure(error=e)
_validate(node, result)
return result
def _validate(node, data):
"""Validate the received value against the supported keys in ironic.
:param node: node object.
:param data: the dictionary received by querying server.
:raises: HardwareInspectionFailure
"""
if data.get('properties'):
if isinstance(data['properties'], dict):
valid_keys = ESSENTIAL_PROPERTIES_KEYS
missing_keys = valid_keys - set(data['properties'])
if missing_keys:
error = (_(
"Server didn't return the key(s): %(key)s") %
{'key': ', '.join(missing_keys)})
raise exception.HardwareInspectionFailure(error=error)
else:
error = (_("Essential properties are expected to be in dictionary "
"format, received %(properties)s from node "
"%(node)s.") % {"properties": data['properties'],
'node': node.uuid})
raise exception.HardwareInspectionFailure(error=error)
else:
error = (_("The node %s didn't return 'properties' as the key with "
"inspection.") % node.uuid)
raise exception.HardwareInspectionFailure(error=error)
if data.get('macs'):
if not isinstance(data['macs'], dict):
error = (_("Node %(node)s didn't return MACs %(macs)s "
"in dictionary format.")
% {"macs": data['macs'], 'node': node.uuid})
raise exception.HardwareInspectionFailure(error=error)
else:
error = (_("The node %s didn't return 'macs' as the key with "
"inspection.") % node.uuid)
raise exception.HardwareInspectionFailure(error=error)
def _create_supported_capabilities_dict(capabilities):
"""Creates a capabilities dictionary from supported capabilities in ironic.
:param capabilities: a dictionary of capabilities as returned by the
hardware.
:returns: a dictionary of the capabilities supported by ironic
and returned by hardware.
"""
valid_cap = {}
for key in CAPABILITIES_KEYS.intersection(capabilities):
valid_cap[key] = capabilities.get(key)
return valid_cap
def _get_capabilities(node, ilo_object):
"""inspects hardware and gets additional capabilities.
:param node: Node object.
:param ilo_object: an instance of ilo drivers.
:returns : a string of capabilities like
'key1:value1,key2:value2,key3:value3'
or None.
"""
capabilities = None
try:
capabilities = ilo_object.get_server_capabilities()
except ilo_error.IloError:
LOG.debug(("Node %s did not return any additional capabilities."),
node.uuid)
return capabilities
class IloInspect(base.InspectInterface):
def get_properties(self):
return ilo_common.REQUIRED_PROPERTIES
def validate(self, task):
"""Check that 'driver_info' contains required ILO credentials.
Validates whether the 'driver_info' property of the supplied
task's node contains the required credentials information.
:param task: a task from TaskManager.
:raises: InvalidParameterValue if required iLO parameters
are not valid.
:raises: MissingParameterValue if a required parameter is missing.
"""
node = task.node
ilo_common.parse_driver_info(node)
def inspect_hardware(self, task):
"""Inspect hardware to get the hardware properties.
Inspects hardware to get the essential and additional hardware
properties. It fails if any of the essential properties
are not received from the node. It doesn't fail if node fails
to return any capabilities as the capabilities differ from hardware
to hardware mostly.
:param task: a TaskManager instance.
:raises: HardwareInspectionFailure if essential properties
could not be retrieved successfully.
:raises: IloOperationError if system fails to get power state.
:returns: The resulting state of inspection.
"""
power_turned_on = False
ilo_object = ilo_common.get_ilo_object(task.node)
try:
state = task.driver.power.get_power_state(task)
except exception.IloOperationError as ilo_exception:
operation = (_("Inspecting hardware (get_power_state) on %s")
% task.node.uuid)
raise exception.IloOperationError(operation=operation,
error=ilo_exception)
if state != states.POWER_ON:
LOG.info(_LI("The node %s is not powered on. Powering on the "
"node for inspection."), task.node.uuid)
conductor_utils.node_power_action(task, states.POWER_ON)
power_turned_on = True
# get the essential properties and update the node properties
# with it.
inspected_properties = {}
result = _get_essential_properties(task.node, ilo_object)
properties = result['properties']
for known_property in ESSENTIAL_PROPERTIES_KEYS:
inspected_properties[known_property] = properties[known_property]
node_properties = task.node.properties
node_properties.update(inspected_properties)
task.node.properties = node_properties
# Inspect the hardware for additional hardware capabilities.
# Since additional hardware capabilities may not apply to all the
# hardwares, the method inspect_hardware() doesn't raise an error
# for these capabilities.
capabilities = _get_capabilities(task.node, ilo_object)
if capabilities:
valid_cap = _create_supported_capabilities_dict(capabilities)
capabilities = utils.get_updated_capabilities(
task.node.properties.get('capabilities'), valid_cap)
if capabilities:
node_properties['capabilities'] = capabilities
task.node.properties = node_properties
task.node.save()
# Create ports for the nics detected.
_create_ports_if_not_exist(task.node, result['macs'])
LOG.debug(("Node properties for %(node)s are updated as "
"%(properties)s"),
{'properties': inspected_properties,
'node': task.node.uuid})
LOG.info(_LI("Node %s inspected."), task.node.uuid)
if power_turned_on:
conductor_utils.node_power_action(task, states.POWER_OFF)
LOG.info(_LI("The node %s was powered on for inspection. "
"Powered off the node as inspection completed."),
task.node.uuid)
return states.MANAGEABLE
| {
"content_hash": "0f5fc1856089b8f816e658ee04ab3508",
"timestamp": "",
"source": "github",
"line_count": 243,
"max_line_length": 79,
"avg_line_length": 39.58024691358025,
"alnum_prop": 0.6261176959866916,
"repo_name": "Tan0/ironic",
"id": "a30207422a026906d3e2e4b50ad1de7417975ce0",
"size": "10163",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ironic/drivers/modules/ilo/inspect.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Mako",
"bytes": "412"
},
{
"name": "Python",
"bytes": "3345381"
}
],
"symlink_target": ""
} |
require 'win32ole'
urls_visited = []
running = true
def default_handler(event, *args)
case event
when "BeforeNavigate"
puts "Now Navigating to #{args[0]}..."
end
end
ie = WIN32OLE.new('InternetExplorer.Application')
ie.visible = TRUE
ie.gohome
ev = WIN32OLE_EVENT.new(ie, 'DWebBrowserEvents')
ev.on_event {|*args| default_handler(*args)}
ev.on_event("NavigateComplete") {|url| urls_visited << url }
ev.on_event("Quit") do |*args|
puts "IE has quit"
puts "You Navigated to the following URLs: "
urls_visited.each_with_index do |url, i|
puts "(#{i+1}) #{url}"
end
running = false
end
# hang around processing messages
WIN32OLE_EVENT.message_loop while running
| {
"content_hash": "3aaba84308fe48109a965f1d9d3532c6",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 60,
"avg_line_length": 22.225806451612904,
"alnum_prop": 0.6937590711175616,
"repo_name": "sunpy1106/programmingruby",
"id": "1b9416268c1de3cd41cf1609101d45db7478433a",
"size": "1083",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "win32/record_navigation.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "7970"
},
{
"name": "CSS",
"bytes": "17109"
},
{
"name": "HTML",
"bytes": "8361"
},
{
"name": "JavaScript",
"bytes": "12650"
},
{
"name": "Makefile",
"bytes": "11286"
},
{
"name": "Ruby",
"bytes": "172734"
}
],
"symlink_target": ""
} |
package com.wci.umls.server.jpa.test.content;
import static org.junit.Assert.assertTrue;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.wci.umls.server.helpers.CopyConstructorTester;
import com.wci.umls.server.helpers.EqualsHashcodeTester;
import com.wci.umls.server.helpers.GetterSetterTester;
import com.wci.umls.server.helpers.XmlSerializationTester;
import com.wci.umls.server.jpa.ModelUnitSupport;
import com.wci.umls.server.jpa.content.ComponentHistoryJpa;
import com.wci.umls.server.jpa.content.ConceptJpa;
import com.wci.umls.server.jpa.helpers.IndexedFieldTester;
import com.wci.umls.server.jpa.helpers.NullableFieldTester;
import com.wci.umls.server.model.content.ComponentHistory;
import com.wci.umls.server.model.content.Concept;
/**
* Unit testing for {@link ComponentHistoryJpa}.
*/
public class ComponentHistoryJpaUnitTest extends ModelUnitSupport {
/** The model object to test. */
private ComponentHistoryJpa object;
/**
* Setup class.
*/
@BeforeClass
public static void setupClass() {
// do nothing
}
/**
* Setup.
* @throws Exception
*/
@Before
public void setup() throws Exception {
object = new ComponentHistoryJpa();
}
/**
* Test getter and setter methods of model object.
*
* @throws Exception the exception
*/
@Test
public void testModelGetSet() throws Exception {
Logger.getLogger(getClass()).debug("TEST " + name.getMethodName());
GetterSetterTester tester = new GetterSetterTester(object);
tester.exclude("type");
tester.exclude("name");
tester.test();
}
/**
* Test equals and hascode methods.
*
* @throws Exception the exception
*/
@Test
public void testModelEqualsHashcode() throws Exception {
Logger.getLogger(getClass()).debug("TEST " + name.getMethodName());
EqualsHashcodeTester tester = new EqualsHashcodeTester(object);
tester.include("suppressible");
tester.include("obsolete");
tester.include("branch");
tester.include("terminology");
tester.include("terminologyId");
tester.include("relationshipType");
tester.include("additionalRelationshipType");
tester.include("reason");
tester.include("associatedRelease");
tester.include("referencedTerminologyId");
assertTrue(tester.testIdentityFieldEquals());
assertTrue(tester.testNonIdentityFieldEquals());
assertTrue(tester.testIdentityFieldNotEquals());
assertTrue(tester.testIdentityFieldHashcode());
assertTrue(tester.testNonIdentityFieldHashcode());
assertTrue(tester.testIdentityFieldDifferentHashcode());
}
/**
* Test copy constructor.
*
* @throws Exception the exception
*/
@Test
public void testModelCopy() throws Exception {
Logger.getLogger(getClass()).debug("TEST " + name.getMethodName());
CopyConstructorTester tester = new CopyConstructorTester(object);
assertTrue(tester.testCopyConstructor(ComponentHistory.class));
}
/**
* Test XML serialization.
*
* @throws Exception the exception
*/
@Test
public void testModelXmlSerialization() throws Exception {
Logger.getLogger(getClass()).debug("TEST " + name.getMethodName());
XmlSerializationTester tester = new XmlSerializationTester(object);
Concept c = new ConceptJpa();
c.setId(1L);
tester.proxy(Concept.class, 1, c);
assertTrue(tester.testXmlSerialization());
}
/**
* Test not null fields.
*
* @throws Exception the exception
*/
@Test
public void testModelNotNullField() throws Exception {
Logger.getLogger(getClass()).debug("TEST " + name.getMethodName());
NullableFieldTester tester = new NullableFieldTester(object);
tester.include("timestamp");
tester.include("lastModified");
tester.include("lastModifiedBy");
tester.include("suppressible");
tester.include("obsolete");
tester.include("published");
tester.include("publishable");
tester.include("terminology");
tester.include("terminologyId");
tester.include("version");
tester.include("name");
tester.include("value");
tester.include("associatedRelease");
tester.include("referencedConcept");
}
/**
* Test model indexed fields.
*
* @throws Exception the exception
*/
@Test
public void testModelIndexedFields() throws Exception {
Logger.getLogger(getClass()).debug("TEST " + name.getMethodName());
// Test analyzed fields
IndexedFieldTester tester = new IndexedFieldTester(object);
tester.include("reason");
assertTrue(tester.testAnalyzedIndexedFields());
// Test non analyzed fields
assertTrue(tester.testAnalyzedIndexedFields());
tester = new IndexedFieldTester(object);
tester.include("id");
tester.include("lastModified");
tester.include("lastModifiedBy");
tester.include("suppressible");
tester.include("obsolete");
tester.include("published");
tester.include("publishable");
tester.include("terminologyId");
tester.include("terminology");
tester.include("version");
tester.include("branch");
tester.include("referencedTerminologyId");
assertTrue(tester.testNotAnalyzedIndexedFields());
}
/**
* Teardown.
*/
@After
public void teardown() {
// do nothing
}
/**
* Teardown class.
*/
@AfterClass
public static void teardownClass() {
// do nothing
}
}
| {
"content_hash": "765aa705307925e1c3c50343e5258774",
"timestamp": "",
"source": "github",
"line_count": 200,
"max_line_length": 71,
"avg_line_length": 27.43,
"alnum_prop": 0.7083485235144003,
"repo_name": "WestCoastInformatics/UMLS-Terminology-Server",
"id": "060644e6c06aa116cca35239cfff506dfa6de249",
"size": "5538",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jpa-model/src/test/java/com/wci/umls/server/jpa/test/content/ComponentHistoryJpaUnitTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "6207"
},
{
"name": "Batchfile",
"bytes": "7621"
},
{
"name": "CSS",
"bytes": "119223"
},
{
"name": "HTML",
"bytes": "354363"
},
{
"name": "Java",
"bytes": "7709900"
},
{
"name": "JavaScript",
"bytes": "4615410"
},
{
"name": "Perl",
"bytes": "4376"
},
{
"name": "Shell",
"bytes": "173469"
}
],
"symlink_target": ""
} |
import unittest
import logging
class TestCase(unittest.TestCase):
"""
Add useful asserts to API testing
- assertIsDictionary
- assertDictionaryHasKey
- assertDictionaryHasNotKey
- assertDictionaryHasKeyIgnoringCase
- assertIsString
- assertIsInteger
- assertIsTuple
- assertIsList
- assertListLength
- assertListHasValue
"""
def __init__(self, *args, **kwargs):
super(TestCase, self).__init__(*args, **kwargs)
self.log = logging.getLogger("niav")
def assertIsDictionary(self, value):
"""
Check if the value is a dictionary
"""
self.assertTrue(isinstance(value, dict), "%s %s" % (type(value), value))
def assertDictionaryHasKey(self, dictionary, key):
"""
Check if a key is present in a dictionary
:param dictionary: Dictionary to consider
:param key: Key to search
:type dictionary: dict
:type key: string
"""
self.assertIsDictionary(dictionary)
self.assertTrue(key in dictionary, dictionary)
def assertDictionaryHasNotKey(self, dictionary, key):
"""
Check if a key is not present in dictionary
:param dictionary: Dictionary to consider
:param key: Key to search
:type dictionary: dict
:type key: string
"""
self.assertIsDictionary(dictionary)
self.assertFalse(key in dictionary, dictionary)
def assertDictionaryHasKeyIgnoringCase(self, dictionary, key):
"""
Check if a key (ignoring case) is present in a dictionary
:param dictionary: Dictionary to consider
:param key: Key to search
:type dictionary: dict
:type key: string
"""
self.assertIsDictionary(dictionary)
for current_key in dictionary:
if key.lower() == current_key.lower():
self.assertTrue(True, dictionary)
return current_key
self.assertTrue(False, dictionary)
def assertIsString(self, value):
"""
Check if the value is a string
"""
self.assertTrue(isinstance(value, str) or isinstance(value, bytes), "%s %s" % (type(value), value))
def assertIsInteger(self, value):
"""
Check if a value is an integer
"""
self.assertTrue(isinstance(value, int), "%s %s" % (type(value), value))
def assertIsTuple(self, value):
"""
Check if a value is a tuple
"""
self.assertTrue(isinstance(value, tuple), "%s %s" % (type(value), value))
def assertIsList(self, value):
"""
Check if a value is a list
"""
self.assertTrue(isinstance(value, list), "%s %s" % (type(value), value))
def assertListLength(self, llist, length):
"""
Check a list length
:param llist: List to consider
:param length: Expected length
:type llist: list
:type length: integer
"""
self.assertIsList(llist)
self.assertEqual(len(llist), length, llist)
def assertListHasValue(self, llist, value):
"""
Check if a value is present at least once in a list
:param llist: List to consider
:param value: Expected value
:type llist: list
:type value: string
"""
self.assertIsList(llist)
self.assertNotEqual(len(list(filter(lambda x: x == value, llist))), 0, (llist, value))
| {
"content_hash": "4ea277edceee4150d5782b58d17ddfee",
"timestamp": "",
"source": "github",
"line_count": 118,
"max_line_length": 107,
"avg_line_length": 30.966101694915253,
"alnum_prop": 0.5711548987411056,
"repo_name": "AffilaeTech/niav",
"id": "aff7025a22e0756c2fc8c8d143102098efc98d8a",
"size": "3654",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "niav/testcase.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "43558"
}
],
"symlink_target": ""
} |
package org.openestate.is24.restapi.xml.common;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class Adapter6
extends XmlAdapter<String, String>
{
public String unmarshal(String value) {
return (org.openestate.is24.restapi.utils.XmlUtils.parsePassword(value));
}
public String marshal(String value) {
return (org.openestate.is24.restapi.utils.XmlUtils.printPassword(value));
}
}
| {
"content_hash": "3c4135cf4e94e05af04d6ba3e4344977",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 81,
"avg_line_length": 24.166666666666668,
"alnum_prop": 0.7310344827586207,
"repo_name": "OpenEstate/OpenEstate-IS24-REST",
"id": "e761ea43d10a7f3e737e0240a7eaa27f79018f43",
"size": "436",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Core/src/main/jaxb/org/openestate/is24/restapi/xml/common/Adapter6.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1098"
},
{
"name": "Java",
"bytes": "4988575"
},
{
"name": "PHP",
"bytes": "1641"
},
{
"name": "Shell",
"bytes": "14694"
}
],
"symlink_target": ""
} |
<?php
// Original file header of PEAR::Spreadsheet_Excel_Writer_BIFFwriter (used as the base for this class):
// -----------------------------------------------------------------------------------------
// * Module written/ported by Xavier Noguer <xnoguer@rezebra.com>
// *
// * The majority of this is _NOT_ my code. I simply ported it from the
// * PERL Spreadsheet::WriteExcel module.
// *
// * The author of the Spreadsheet::WriteExcel module is John McNamara
// * <jmcnamara@cpan.org>
// *
// * I _DO_ maintain this code, and John McNamara has nothing to do with the
// * porting of this code to PHP. Any questions directly related to this
// * class library should be directed to me.
// *
// * License Information:
// *
// * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets
// * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com
// *
// * 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; either
// * version 2.1 of the License, or (at your option) any later version.
// *
// * This library is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// * Lesser General Public License for more details.
// *
// * You should have received a copy of the GNU Lesser General Public
// * License along with this library; if not, write to the Free Software
// * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// */
/**
* PHPExcel_Writer_Excel5_BIFFwriter
*
* @category PHPExcel
* @package PHPExcel_Writer_Excel5
* @copyright Copyright (c) 2006 - 2009 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class PHPExcel_Writer_Excel5_BIFFwriter
{
/**
* The BIFF/Excel version (5).
* @var integer
*/
var $_BIFF_version = 0x0500;
/**
* The byte order of this architecture. 0 => little endian, 1 => big endian
* @var integer
*/
private static $_byte_order;
/**
* The string containing the data of the BIFF stream
* @var string
*/
var $_data;
/**
* The size of the data in bytes. Should be the same as strlen($this->_data)
* @var integer
*/
var $_datasize;
/**
* The maximum length for a BIFF record (excluding record header and length field). See _addContinue()
* @var integer
* @see _addContinue()
*/
var $_limit;
/**
* Constructor
*/
public function __construct()
{
$this->_data = '';
$this->_datasize = 0;
$this->_limit = 2080;
}
/**
* Determine the byte order and store it as class data to avoid
* recalculating it for each call to new().
*
* @return int
*/
public static function getByteOrder()
{
if (!isset(self::$_byte_order)) {
// Check if "pack" gives the required IEEE 64bit float
$teststr = pack("d", 1.2345);
$number = pack("C8", 0x8D, 0x97, 0x6E, 0x12, 0x83, 0xC0, 0xF3, 0x3F);
if ($number == $teststr) {
$byte_order = 0; // Little Endian
} elseif ($number == strrev($teststr)){
$byte_order = 1; // Big Endian
} else {
// Give up. I'll fix this in a later version.
throw new Exception("Required floating point format ".
"not supported on this platform.");
}
self::$_byte_order = $byte_order;
}
return self::$_byte_order;
}
/**
* General storage function
*
* @param string $data binary data to append
* @access private
*/
function _append($data)
{
if (strlen($data) - 4 > $this->_limit) {
$data = $this->_addContinue($data);
}
$this->_data = $this->_data.$data;
$this->_datasize += strlen($data);
}
/**
* General storage function like _append, but returns string instead of modifying $this->_data
*
* @param string $data binary data to write
* @return string
*/
public function writeData($data)
{
if (strlen($data) - 4 > $this->_limit) {
$data = $this->_addContinue($data);
}
$this->_datasize += strlen($data);
return $data;
}
/**
* Writes Excel BOF record to indicate the beginning of a stream or
* sub-stream in the BIFF file.
*
* @param integer $type Type of BIFF file to write: 0x0005 Workbook,
* 0x0010 Worksheet.
* @access private
*/
function _storeBof($type)
{
$record = 0x0809; // Record identifier
// According to the SDK $build and $year should be set to zero.
// However, this throws a warning in Excel 5. So, use magic numbers.
if ($this->_BIFF_version == 0x0500) {
$length = 0x0008;
$unknown = '';
$build = 0x096C;
$year = 0x07C9;
} elseif ($this->_BIFF_version == 0x0600) {
$length = 0x0010;
// by inspection of real files, MS Office Excel 2007 writes the following
$unknown = pack("VV", 0x000100D1, 0x00000406);
$build = 0x0DBB;
$year = 0x07CC;
}
$version = $this->_BIFF_version;
$header = pack("vv", $record, $length);
$data = pack("vvvv", $version, $type, $build, $year);
$this->_append($header . $data . $unknown);
}
/**
* Writes Excel EOF record to indicate the end of a BIFF stream.
*
* @access private
*/
function _storeEof()
{
$record = 0x000A; // Record identifier
$length = 0x0000; // Number of bytes to follow
$header = pack("vv", $record, $length);
$this->_append($header);
}
/**
* Writes Excel EOF record to indicate the end of a BIFF stream.
*
* @access private
*/
public function writeEof()
{
$record = 0x000A; // Record identifier
$length = 0x0000; // Number of bytes to follow
$header = pack("vv", $record, $length);
return $this->writeData($header);
}
/**
* Excel limits the size of BIFF records. In Excel 5 the limit is 2084 bytes. In
* Excel 97 the limit is 8228 bytes. Records that are longer than these limits
* must be split up into CONTINUE blocks.
*
* This function takes a long BIFF record and inserts CONTINUE records as
* necessary.
*
* @param string $data The original binary data to be written
* @return string A very convenient string of continue blocks
* @access private
*/
function _addContinue($data)
{
$limit = $this->_limit;
$record = 0x003C; // Record identifier
// The first 2080/8224 bytes remain intact. However, we have to change
// the length field of the record.
$tmp = substr($data, 0, 2) . pack("v", $limit) . substr($data, 4, $limit);
$header = pack("vv", $record, $limit); // Headers for continue records
// Retrieve chunks of 2080/8224 bytes +4 for the header.
$data_length = strlen($data);
for ($i = $limit + 4; $i < ($data_length - $limit); $i += $limit) {
$tmp .= $header;
$tmp .= substr($data, $i, $limit);
}
// Retrieve the last chunk of data
$header = pack("vv", $record, strlen($data) - $i);
$tmp .= $header;
$tmp .= substr($data, $i, strlen($data) - $i);
return $tmp;
}
}
| {
"content_hash": "e2c787cdd2c4183aa02d2e249e9633d6",
"timestamp": "",
"source": "github",
"line_count": 246,
"max_line_length": 103,
"avg_line_length": 28.58130081300813,
"alnum_prop": 0.6203953918361542,
"repo_name": "cksong/admin.mblog.com",
"id": "67a196af5ee4494c4f8f267f89b926b21ad5b187",
"size": "8092",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "extend/PHPExcel/PHPExcel/Writer/Excel5/BIFFwriter.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "488"
},
{
"name": "CSS",
"bytes": "201307"
},
{
"name": "HTML",
"bytes": "582939"
},
{
"name": "JavaScript",
"bytes": "1603649"
},
{
"name": "PHP",
"bytes": "7368894"
},
{
"name": "PLpgSQL",
"bytes": "3807"
},
{
"name": "Smarty",
"bytes": "30022"
}
],
"symlink_target": ""
} |
package com.mongodb.reactivestreams.client.internal.gridfs;
import com.mongodb.ReadConcern;
import com.mongodb.ReadPreference;
import com.mongodb.WriteConcern;
import com.mongodb.client.gridfs.model.GridFSDownloadOptions;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.mongodb.client.gridfs.model.GridFSUploadOptions;
import com.mongodb.reactivestreams.client.ClientSession;
import com.mongodb.reactivestreams.client.MongoClients;
import com.mongodb.reactivestreams.client.MongoCollection;
import com.mongodb.reactivestreams.client.MongoDatabase;
import com.mongodb.reactivestreams.client.gridfs.GridFSBucket;
import com.mongodb.reactivestreams.client.gridfs.GridFSDownloadPublisher;
import com.mongodb.reactivestreams.client.gridfs.GridFSFindPublisher;
import com.mongodb.reactivestreams.client.gridfs.GridFSUploadPublisher;
import org.bson.BsonDocument;
import org.bson.BsonObjectId;
import org.bson.BsonValue;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import org.reactivestreams.Publisher;
import java.nio.ByteBuffer;
import static com.mongodb.assertions.Assertions.notNull;
import static com.mongodb.reactivestreams.client.internal.gridfs.GridFSPublisherCreator.createDeletePublisher;
import static com.mongodb.reactivestreams.client.internal.gridfs.GridFSPublisherCreator.createDropPublisher;
import static com.mongodb.reactivestreams.client.internal.gridfs.GridFSPublisherCreator.createGridFSDownloadPublisher;
import static com.mongodb.reactivestreams.client.internal.gridfs.GridFSPublisherCreator.createGridFSFindPublisher;
import static com.mongodb.reactivestreams.client.internal.gridfs.GridFSPublisherCreator.createGridFSUploadPublisher;
import static com.mongodb.reactivestreams.client.internal.gridfs.GridFSPublisherCreator.createRenamePublisher;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
/**
* The internal GridFSBucket implementation.
*
* <p>This class is not part of the public API and may be removed or changed at any time</p>
*/
public final class GridFSBucketImpl implements GridFSBucket {
private static final int DEFAULT_CHUNKSIZE_BYTES = 255 * 1024;
private final String bucketName;
private final int chunkSizeBytes;
private final MongoCollection<GridFSFile> filesCollection;
private final MongoCollection<Document> chunksCollection;
public GridFSBucketImpl(final MongoDatabase database) {
this(database, "fs");
}
public GridFSBucketImpl(final MongoDatabase database, final String bucketName) {
this(notNull("bucketName", bucketName), DEFAULT_CHUNKSIZE_BYTES,
getFilesCollection(notNull("database", database), bucketName),
getChunksCollection(database, bucketName));
}
GridFSBucketImpl(final String bucketName, final int chunkSizeBytes, final MongoCollection<GridFSFile> filesCollection,
final MongoCollection<Document> chunksCollection) {
this.bucketName = notNull("bucketName", bucketName);
this.chunkSizeBytes = chunkSizeBytes;
this.filesCollection = notNull("filesCollection", filesCollection);
this.chunksCollection = notNull("chunksCollection", chunksCollection);
}
private static MongoCollection<GridFSFile> getFilesCollection(final MongoDatabase database, final String bucketName) {
return database.getCollection(bucketName + ".files", GridFSFile.class).withCodecRegistry(
fromRegistries(database.getCodecRegistry(), MongoClients.getDefaultCodecRegistry())
);
}
private static MongoCollection<Document> getChunksCollection(final MongoDatabase database, final String bucketName) {
return database.getCollection(bucketName + ".chunks").withCodecRegistry(MongoClients.getDefaultCodecRegistry());
}
@Override
public String getBucketName() {
return bucketName;
}
@Override
public int getChunkSizeBytes() {
return chunkSizeBytes;
}
@Override
public ReadPreference getReadPreference() {
return filesCollection.getReadPreference();
}
@Override
public WriteConcern getWriteConcern() {
return filesCollection.getWriteConcern();
}
@Override
public ReadConcern getReadConcern() {
return filesCollection.getReadConcern();
}
@Override
public GridFSBucket withChunkSizeBytes(final int chunkSizeBytes) {
return new GridFSBucketImpl(bucketName, chunkSizeBytes, filesCollection, chunksCollection);
}
@Override
public GridFSBucket withReadPreference(final ReadPreference readPreference) {
notNull("readPreference", readPreference);
return new GridFSBucketImpl(bucketName, chunkSizeBytes, filesCollection.withReadPreference(readPreference),
chunksCollection.withReadPreference(readPreference));
}
@Override
public GridFSBucket withWriteConcern(final WriteConcern writeConcern) {
notNull("writeConcern", writeConcern);
return new GridFSBucketImpl(bucketName, chunkSizeBytes, filesCollection.withWriteConcern(writeConcern),
chunksCollection.withWriteConcern(writeConcern));
}
@Override
public GridFSBucket withReadConcern(final ReadConcern readConcern) {
notNull("readConcern", readConcern);
return new GridFSBucketImpl(bucketName, chunkSizeBytes, filesCollection.withReadConcern(readConcern),
chunksCollection.withReadConcern(readConcern));
}
@Override
public GridFSUploadPublisher<ObjectId> uploadFromPublisher(final String filename, final Publisher<ByteBuffer> source) {
return uploadFromPublisher(filename, source, new GridFSUploadOptions());
}
@Override
public GridFSUploadPublisher<ObjectId> uploadFromPublisher(final String filename,
final Publisher<ByteBuffer> source,
final GridFSUploadOptions options) {
return createGridFSUploadPublisher(chunkSizeBytes, filesCollection, chunksCollection,
null, new BsonObjectId(), filename, options, source).withObjectId();
}
@Override
public GridFSUploadPublisher<Void> uploadFromPublisher(final BsonValue id, final String filename, final Publisher<ByteBuffer> source) {
return uploadFromPublisher(id, filename, source, new GridFSUploadOptions());
}
@Override
public GridFSUploadPublisher<Void> uploadFromPublisher(final BsonValue id, final String filename, final Publisher<ByteBuffer> source,
final GridFSUploadOptions options) {
return createGridFSUploadPublisher(chunkSizeBytes, filesCollection, chunksCollection, null, id,
filename, options, source);
}
@Override
public GridFSUploadPublisher<ObjectId> uploadFromPublisher(final ClientSession clientSession, final String filename,
final Publisher<ByteBuffer> source) {
return uploadFromPublisher(clientSession, filename, source, new GridFSUploadOptions());
}
@Override
public GridFSUploadPublisher<ObjectId> uploadFromPublisher(final ClientSession clientSession, final String filename,
final Publisher<ByteBuffer> source, final GridFSUploadOptions options) {
return createGridFSUploadPublisher(chunkSizeBytes, filesCollection, chunksCollection,
notNull("clientSession", clientSession), new BsonObjectId(), filename, options, source)
.withObjectId();
}
@Override
public GridFSUploadPublisher<Void> uploadFromPublisher(final ClientSession clientSession, final BsonValue id,
final String filename, final Publisher<ByteBuffer> source) {
return uploadFromPublisher(clientSession, id, filename, source, new GridFSUploadOptions());
}
@Override
public GridFSUploadPublisher<Void> uploadFromPublisher(final ClientSession clientSession, final BsonValue id,
final String filename,
final Publisher<ByteBuffer> source,
final GridFSUploadOptions options) {
return createGridFSUploadPublisher(chunkSizeBytes, filesCollection, chunksCollection,
notNull("clientSession", clientSession), new BsonObjectId(), filename, options, source);
}
@Override
public GridFSDownloadPublisher downloadToPublisher(final ObjectId id) {
return downloadToPublisher(new BsonObjectId(id));
}
@Override
public GridFSDownloadPublisher downloadToPublisher(final BsonValue id) {
return createGridFSDownloadPublisher(chunksCollection, null,
createGridFSFindPublisher(filesCollection, null, new BsonDocument("_id", id)));
}
@Override
public GridFSDownloadPublisher downloadToPublisher(final String filename) {
return downloadToPublisher(filename, new GridFSDownloadOptions());
}
@Override
public GridFSDownloadPublisher downloadToPublisher(final String filename, final GridFSDownloadOptions options) {
return createGridFSDownloadPublisher(chunksCollection, null,
createGridFSFindPublisher(filesCollection, null, filename, options));
}
@Override
public GridFSDownloadPublisher downloadToPublisher(final ClientSession clientSession, final ObjectId id) {
return downloadToPublisher(clientSession, new BsonObjectId(id));
}
@Override
public GridFSDownloadPublisher downloadToPublisher(final ClientSession clientSession, final BsonValue id) {
return createGridFSDownloadPublisher(chunksCollection, notNull("clientSession", clientSession),
createGridFSFindPublisher(filesCollection, clientSession, new BsonDocument("_id", id)));
}
@Override
public GridFSDownloadPublisher downloadToPublisher(final ClientSession clientSession, final String filename) {
return downloadToPublisher(clientSession, filename, new GridFSDownloadOptions());
}
@Override
public GridFSDownloadPublisher downloadToPublisher(final ClientSession clientSession,
final String filename,
final GridFSDownloadOptions options) {
return createGridFSDownloadPublisher(chunksCollection, notNull("clientSession", clientSession),
createGridFSFindPublisher(filesCollection, clientSession, filename, options));
}
@Override
public GridFSFindPublisher find() {
return createGridFSFindPublisher(filesCollection, null, null);
}
@Override
public GridFSFindPublisher find(final Bson filter) {
return createGridFSFindPublisher(filesCollection, null, notNull("filter", filter));
}
@Override
public GridFSFindPublisher find(final ClientSession clientSession) {
return createGridFSFindPublisher(filesCollection, notNull("clientSession", clientSession), null);
}
@Override
public GridFSFindPublisher find(final ClientSession clientSession, final Bson filter) {
return createGridFSFindPublisher(filesCollection, notNull("clientSession", clientSession), notNull("filter", filter));
}
@Override
public Publisher<Void> delete(final ObjectId id) {
return delete(new BsonObjectId(id));
}
@Override
public Publisher<Void> delete(final BsonValue id) {
return createDeletePublisher(filesCollection, chunksCollection, null, id);
}
@Override
public Publisher<Void> delete(final ClientSession clientSession, final ObjectId id) {
return delete(clientSession, new BsonObjectId(id));
}
@Override
public Publisher<Void> delete(final ClientSession clientSession, final BsonValue id) {
return createDeletePublisher(filesCollection, chunksCollection, notNull("clientSession", clientSession), id);
}
@Override
public Publisher<Void> rename(final ObjectId id, final String newFilename) {
return rename(new BsonObjectId(id), newFilename);
}
@Override
public Publisher<Void> rename(final BsonValue id, final String newFilename) {
return createRenamePublisher(filesCollection, null, id, newFilename);
}
@Override
public Publisher<Void> rename(final ClientSession clientSession, final ObjectId id, final String newFilename) {
return rename(clientSession, new BsonObjectId(id), newFilename);
}
@Override
public Publisher<Void> rename(final ClientSession clientSession, final BsonValue id, final String newFilename) {
return createRenamePublisher(filesCollection, notNull("clientSession", clientSession), id, newFilename);
}
@Override
public Publisher<Void> drop() {
return createDropPublisher(filesCollection, chunksCollection, null);
}
@Override
public Publisher<Void> drop(final ClientSession clientSession) {
return createDropPublisher(filesCollection, chunksCollection, notNull("clientSession", clientSession));
}
}
| {
"content_hash": "b551f49f163d9ebbe370cc94de2002ce",
"timestamp": "",
"source": "github",
"line_count": 299,
"max_line_length": 139,
"avg_line_length": 45.76254180602007,
"alnum_prop": 0.7081049477453775,
"repo_name": "jyemin/mongo-java-driver",
"id": "d92f68154dc83111d5787e4cc3a61875c7df1b46",
"size": "14286",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSBucketImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "2678050"
},
{
"name": "Java",
"bytes": "9719214"
},
{
"name": "Scala",
"bytes": "1253739"
},
{
"name": "Shell",
"bytes": "37374"
}
],
"symlink_target": ""
} |
<?php
namespace Bolt\Storage\Entity;
use Bolt\Helpers\Excerpt;
use Bolt\Helpers\Input;
use Bolt\Legacy;
use Bolt\Storage\Field\Collection\RepeatingFieldCollection;
/**
* Trait class for ContentType relations.
*
* This is a breakout of the old Bolt\Content class and serves two main purposes:
* * Maintain backward compatibility for Bolt\Content through the remainder of
* the 2.x development/release life-cycle
* * Attempt to break up former functionality into sections of code that more
* resembles Single Responsibility Principles
*
* These traits should be considered transitional, the functionality in the
* process of refactor, and not representative of a valid approach.
*
* @author Gawain Lynch <gawain.lynch@gmail.com>
*/
trait ContentValuesTrait
{
/** @var boolean Whether this is a "real" ContentType or an embedded ones */
protected $isRootType;
/**
* Pseudo-magic function, used for when templates use {{ content.get(title) }},
* so we can map it to $this->values['title'].
*
* @param string $name
*
* @return mixed
*/
public function get($name)
{
// For fields that are stored as arrays, like 'video'
if (strpos($name, '.') > 0) {
list($name, $attr) = explode('.', $name);
if (!empty($attr) && isset($this->values[$name][$attr])) {
return $this->values[$name][$attr];
}
}
if (isset($this->values[$name])) {
return $this->values[$name];
} else {
return false;
}
}
/**
* Alias for getExcerpt()
*/
public function excerpt($length = 200, $includeTitle = false, $focus = null)
{
return $this->getExcerpt($length, $includeTitle, $focus);
}
/**
* Create an excerpt for the content.
*
* @param integer $length
* @param boolean $includeTitle
* @param string|array $focus
*
* @return \Twig_Markup
*/
public function getExcerpt($length = 200, $includeTitle = false, $focus = null)
{
$excerptParts = [];
if (!empty($this->contenttype['fields'])) {
foreach ($this->contenttype['fields'] as $key => $field) {
// Skip empty fields, and fields used as 'title'.
if (!isset($this->values[$key]) || in_array($key, $this->getTitleColumnName())) {
continue;
}
// add 'text', 'html' and 'textarea' fields.
if (in_array($field['type'], ['text', 'html', 'textarea'])) {
$excerptParts[] = $this->values[$key];
}
// add 'markdown' field
if ($field['type'] === 'markdown') {
$excerptParts[] = $this->app['markdown']->text($this->values[$key]);
}
}
}
$excerpter = new Excerpt(implode(' ', $excerptParts), $this->getTitle());
$excerpt = $excerpter->getExcerpt($length, $includeTitle, $focus);
return new \Twig_Markup($excerpt, 'UTF-8');
}
/**
* Return a content objects values.
*
* @param boolean $json Set to TRUE to return JSON encoded values for arrays
* @param boolean $stripped Set to true to strip all of the base fields
*
* @return array
*/
public function getValues($json = false, $stripped = false)
{
// Prevent 'slug may not be NULL'
if (!isset($this->values['slug'])) {
$this->values['slug'] = '';
}
// Return raw values
if ($json === false) {
return $this->values;
}
$contenttype = $this->contenttype;
if (!$stripped) {
$newvalue = $this->values;
} else {
$newvalue = [];
}
// add the fields for this contenttype,
if (is_array($contenttype)) {
foreach ($contenttype['fields'] as $field => $property) {
if (!isset($this->values[$field])) {
continue;
}
switch ($property['type']) {
// Set the slug, while we're at it
case 'slug':
if (!empty($property['uses']) && empty($this->values[$field])) {
$uses = '';
foreach ($property['uses'] as $usesField) {
$uses .= $this->values[$usesField] . ' ';
}
$newvalue[$field] = $this->app['slugify']->slugify($uses);
} elseif (!empty($this->values[$field])) {
$newvalue[$field] = $this->app['slugify']->slugify($this->values[$field]);
} elseif (empty($this->values[$field]) && $this->values['id']) {
$newvalue[$field] = $this->values['id'];
}
break;
case 'video':
foreach (['html', 'responsive'] as $subkey) {
if (!empty($this->values[$field][$subkey])) {
$this->values[$field][$subkey] = (string) $this->values[$field][$subkey];
}
}
if (!empty($this->values[$field]['url'])) {
$newvalue[$field] = json_encode($this->values[$field]);
} else {
$newvalue[$field] = '';
}
break;
case 'geolocation':
if (!empty($this->values[$field]['latitude']) && !empty($this->values[$field]['longitude'])) {
$newvalue[$field] = json_encode($this->values[$field]);
} else {
$newvalue[$field] = '';
}
break;
case 'image':
if (!empty($this->values[$field]['file'])) {
$newvalue[$field] = json_encode($this->values[$field]);
} else {
$newvalue[$field] = '';
}
break;
case 'imagelist':
case 'filelist':
if (is_array($this->values[$field])) {
$newvalue[$field] = json_encode($this->values[$field]);
} elseif (!empty($this->values[$field]) && strlen($this->values[$field]) < 3) {
// Don't store '[]'
$newvalue[$field] = '';
}
break;
case 'integer':
$newvalue[$field] = round($this->values[$field]);
break;
case 'select':
if (is_array($this->values[$field])) {
$newvalue[$field] = json_encode($this->values[$field]);
} else {
$newvalue[$field] = $this->values[$field];
}
break;
case 'html':
// Remove characters from CKEditor, unless configured to leave them in.
if (!$this->app['config']->get('general/wysiwyg/ck/allowNbsp')) {
$newvalue[$field] = str_replace(' ', ' ', $this->values[$field]);
}
break;
default:
$newvalue[$field] = $this->values[$field];
break;
}
}
}
if (!$stripped) {
if (!empty($this['templatefields'])) {
$newvalue['templatefields'] = json_encode($this->values['templatefields']->getValues(true, true));
} else {
$newvalue['templatefields'] = '';
}
}
return $newvalue;
}
/**
* Set a ContentType record's individual value.
*
* @param string $key
* @param mixed $value
*/
public function setValue($key, $value)
{
// Don't set templateFields if not a real contenttype
if (($key === 'templatefields') && (!$this->isRootType)) {
return;
}
// Check if the value need to be unserialized.
if (is_string($value) && substr($value, 0, 2) === 'a:') {
try {
$unserdata = \GuzzleHttp\json_decode($value, true);
} catch (\InvalidArgumentException $e) {
$unserdata = false;
}
if ($unserdata !== false) {
$value = $unserdata;
}
}
if ($key === 'id') {
$this->id = $value;
}
// Set the user in the object.
if ($key === 'ownerid' && !empty($value)) {
$this->user = $this->app['users']->getUser($value);
}
// Only set values if they have are actually a field.
$allowedcolumns = self::getBaseColumns();
$allowedcolumns[] = 'taxonomy';
if (!isset($this->contenttype['fields'][$key]) && !in_array($key, $allowedcolumns)) {
return;
}
/**
* This Block starts introducing new-style hydration into the legacy content object.
* To do this we fetch the new field from the manager and hydrate a temporary entity.
*
* We don't return at this point so continue to let other transforms happen below so the
* old behaviour will still happen where adjusted.
*/
if (isset($this->contenttype['fields'][$key]['type']) && $this->app['storage.field_manager']->hasCustomHandler($this->contenttype['fields'][$key]['type'])) {
$newFieldType = $this->app['storage.field_manager']->getFieldFor($this->contenttype['fields'][$key]['type']);
$newFieldType->mapping['fieldname'] = $key;
$entity = new Content();
// Note: Extensions _should_ implement \Bolt\Storage\Field\Type\FieldTypeInterface,
// but if they don't, 'hydrate' doesn't exist.
if (method_exists($newFieldType, 'hydrate')) {
$newFieldType->hydrate([$key => $value], $entity);
}
$value = $entity->$key;
}
if (in_array($key, ['datecreated', 'datechanged', 'datepublish', 'datedepublish'])) {
if (!preg_match("/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/", $value)) {
// @todo Try better date-parsing, instead of just setting it to
// 'now' (or 'the past' for datedepublish)
if ($key === 'datedepublish') {
$value = null;
} else {
$value = date('Y-m-d H:i:s');
}
}
}
if ($key === 'templatefields') {
if ((is_string($value)) || (is_array($value))) {
if (is_string($value)) {
try {
$unserdata = \GuzzleHttp\json_decode($value, true);
} catch (\InvalidArgumentException $e) {
$unserdata = false;
}
} else {
$unserdata = $value;
}
if (is_array($unserdata)) {
if (is_a($this, Legacy\Content::class)) {
$value = new static($this->app, $this->getTemplateFieldsContentType(), [], false);
} else {
$value = new Legacy\Content($this->app, $this->getTemplateFieldsContentType(), [], false);
}
$value->setValues($unserdata);
} else {
$value = null;
}
}
}
if (!isset($this->values['datechanged']) ||
!preg_match("/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/", $this->values['datechanged'])) {
$this->values['datechanged'] = date('Y-m-d H:i:s');
}
$this->values[$key] = $value;
}
/**
* Set a ContentType record's values.
*
* @param array $values
*/
public function setValues(array $values)
{
// Since Bolt 1.4, we use 'ownerid' instead of 'username' in the DB tables. If we get an array that has an
// empty 'ownerid', attempt to set it from the 'username'. In $this->setValue the user will be set, regardless
// of ownerid is an 'id' or a 'username'.
if (empty($values['ownerid']) && !empty($values['username'])) {
$values['ownerid'] = $values['username'];
unset($values['username']);
}
foreach ($values as $key => $value) {
if ($key !== 'templatefields') {
$this->setValue($key, $value);
}
}
// If default status is set in contentttype.
if (empty($this->values['status']) && isset($this->contenttype['default_status'])) {
$this->values['status'] = $this->contenttype['default_status'];
}
$serializedFieldTypes = [
'geolocation',
'imagelist',
'image',
'file',
'filelist',
'video',
'select',
'templateselect',
'checkbox',
'repeater',
];
// Check if the values need to be unserialized, and pre-processed.
foreach ($this->values as $key => $value) {
if ((in_array($this->fieldtype($key), $serializedFieldTypes)) || ($key === 'templatefields')) {
if (!empty($value) && is_string($value) && (substr($value, 0, 2) === 'a:' || $value[0] === '[' || $value[0] === '{')) {
try {
$unserdata = \GuzzleHttp\json_decode($value, true);
} catch (\InvalidArgumentException $e) {
$unserdata = false;
}
if ($unserdata !== false) {
$this->values[$key] = $unserdata;
}
}
}
if ($this->fieldtype($key) === 'video' && is_array($this->values[$key]) && !empty($this->values[$key]['url'])) {
$video = $this->values[$key];
// update the HTML, according to given width and height
if (!empty($video['width']) && !empty($video['height'])) {
$video['html'] = preg_replace("/width=(['\"])([0-9]+)(['\"])/i", 'width=${1}' . $video['width'] . '${3}', $video['html']);
$video['html'] = preg_replace("/height=(['\"])([0-9]+)(['\"])/i", 'height=${1}' . $video['height'] . '${3}', $video['html']);
}
$responsiveclass = 'responsive-video';
// See if it's widescreen or not.
if (!empty($video['height']) && (($video['width'] / $video['height']) > 1.76)) {
$responsiveclass .= ' widescreen';
}
if (strpos($video['url'], 'vimeo') !== false) {
$responsiveclass .= ' vimeo';
}
$video['responsive'] = sprintf('<div class="%s">%s</div>', $responsiveclass, $video['html']);
// Mark them up as Twig_Markup.
$video['html'] = new \Twig_Markup($video['html'], 'UTF-8');
$video['responsive'] = new \Twig_Markup($video['responsive'], 'UTF-8');
$this->values[$key] = $video;
}
if ($this->fieldtype($key) === 'repeater' && is_array($this->values[$key]) && !$this->isRootType) {
$originalMapping = null;
$originalMapping[$key]['fields'] = $this->contenttype['fields'][$key]['fields'];
$originalMapping[$key]['type'] = 'repeater';
$mapping = $this->app['storage.metadata']->getRepeaterMapping($originalMapping);
$repeater = new RepeatingFieldCollection($this->app['storage'], $mapping);
$repeater->setName($key);
foreach ($this->values[$key] as $subValue) {
$repeater->addFromArray($subValue);
}
$this->values[$key] = $repeater;
}
if ($this->fieldtype($key) === 'date' || $this->fieldtype($key) === 'datetime') {
if ($this->values[$key] === '') {
$this->values[$key] = null;
}
}
}
// Template fields need to be done last
// As the template has to have been selected
if ($this->isRootType) {
if (empty($values['templatefields'])) {
$this->setValue('templatefields', []);
} else {
$this->setValue('templatefields', $values['templatefields']);
}
}
}
/**
* Set a ContentType record values from a HTTP POST.
*
* @param array $values
* @param string $contenttype
*
* @throws \Exception
*
* @return void
*/
public function setFromPost($values, $contenttype)
{
$values = Input::cleanPostedData($values);
$values += ['status' => 'draft'];
if (!$this->id) {
// this is a new record: current user becomes the owner.
$user = $this->app['users']->getCurrentUser();
$this['ownerid'] = $user['id'];
}
// If the owner is set explicitly, check if the current user is allowed
// to do this.
if (isset($values['ownerid'])) {
if ($this['ownerid'] != $values['ownerid']) {
if (!$this->app['users']->isAllowed("contenttype:{$contenttype['slug']}:change-ownership:{$this->id}")) {
throw new \Exception('Changing ownership is not allowed.');
}
$this['ownerid'] = intval($values['ownerid']);
}
}
// Make sure we have a proper status.
if (!isset($values['status']) || (isset($values['status']) && !in_array($values['status'], ['published', 'timed', 'held', 'draft']))) {
if ($this['status']) {
$values['status'] = $this['status'];
} else {
$values['status'] = 'draft';
}
}
// Make sure we only get the current taxonomies, not those that were fetched from the DB.
$this->taxonomy = [];
if (!empty($values['taxonomy'])) {
foreach ($values['taxonomy'] as $taxonomytype => $value) {
if (isset($values['taxonomy-order'][$taxonomytype])) {
foreach ($value as $k => $v) {
$value[$k] = $v . '#' . $values['taxonomy-order'][$taxonomytype];
}
}
$taxonomyOptions = $this->app['config']->get('taxonomy/' . $taxonomytype . '/options');
if ($taxonomyOptions && is_array($value)) {
foreach ($value as $k => $v) {
if (isset($taxonomyOptions[$v])) {
$this->setTaxonomy($taxonomytype, $v, $taxonomyOptions[$v], $k);
}
}
} elseif ($taxonomyOptions && isset($taxonomyOptions[$value])) {
$this->setTaxonomy($taxonomytype, $value, $taxonomyOptions[$value], 0);
} else {
$this->setTaxonomy($taxonomytype, $value, $value, 0);
}
}
unset($values['taxonomy']);
unset($values['taxonomy-order']);
}
// Get the relations from the POST-ed values.
if (!empty($values['relation']) && is_array($values['relation'])) {
foreach ($values['relation'] as $key => $relationValues) {
$this->clearRelation($key);
foreach ($relationValues as $value) {
$this->setRelation($key, $value);
}
}
unset($values['relation']);
} else {
$this->relation = [];
}
$this->setValues($values);
}
/**
* Get the first image in the content.
*
* @return string
*/
public function getImage()
{
// No fields, no image.
if (empty($this->contenttype['fields'])) {
return '';
}
// Grab the first field of type 'image', and return that.
foreach ($this->contenttype['fields'] as $key => $field) {
if ($field['type'] === 'image' && isset($this->values[$key])) {
// After v1.5.1 we store image data as an array
if (is_array($this->values[$key])) {
return isset($this->values[$key]['file']) ? $this->values[$key]['file'] : '';
}
return $this->values[$key];
}
}
// otherwise, no image.
return '';
}
/**
* Get the title, name, caption or subject.
*
* @param bool $allowBasicTags
*
* @return string
*/
public function getTitle($allowBasicTags = false)
{
$titleParts = [];
if ($allowBasicTags === true) {
$allowedTags = '<b><del><em><i><strong><s>';
} else {
$allowedTags = '';
}
foreach ($this->getTitleColumnName() as $fieldName) {
if (strip_tags($this->values[$fieldName], $allowedTags) !== '') {
$titleParts[] = strip_tags($this->values[$fieldName], $allowedTags);
}
}
if (!empty($titleParts)) {
$title = implode(' ', $titleParts);
} else {
// nope, no title was found.
$title = '';
}
return $title;
}
/**
* Get the columnname of the title, name, caption or subject.
*
* @return array
*/
public function getTitleColumnName()
{
// If we specified a specific fieldname or array of fieldnames as 'title'.
if (!empty($this->contenttype['title_format'])) {
if (!is_array($this->contenttype['title_format'])) {
$this->contenttype['title_format'] = [$this->contenttype['title_format']];
}
return $this->contenttype['title_format'];
}
// Sets the names of some 'common' names for the 'title' column.
$names = ['title', 'name', 'caption', 'subject'];
// Some localised options as well
$names = array_merge($names, ['titel', 'naam', 'onderwerp']); // NL
$names = array_merge($names, ['nom', 'sujet']); // FR
$names = array_merge($names, ['nombre', 'sujeto']); // ES
foreach ($names as $name) {
if (isset($this->values[$name])) {
return [$name];
}
}
// Otherwise, grab the first field of type 'text', and assume that's the title.
if (!empty($this->contenttype['fields'])) {
foreach ($this->contenttype['fields'] as $key => $field) {
if ($field['type'] === 'text') {
return [$key];
}
}
}
// Nope, no title was found.
return [];
}
/**
* Check if a ContentType field has a template set.
*
* @return boolean
*/
public function hasTemplateFields()
{
if (!is_array($this->contenttype)) {
return false;
}
return !$this->contenttype['viewless'] && $this->getTemplateFieldConfig();
}
/**
* Get the template associate with a ContentType field.
*
* @return string
*/
protected function getTemplateFieldsContentType()
{
if (!is_array($this->contenttype)) {
return '';
}
if ($config = $this->getTemplateFieldConfig()) {
return $config;
}
return '';
}
private function getTemplateFieldConfig()
{
if (!$templateFieldsConfig = $this->app['config']->get('theme/templatefields')) {
return null;
}
/** @var \Bolt\TemplateChooser $templateChooser */
$templateChooser = $this->app['templatechooser'];
$templates = $templateChooser->record($this);
/** @var \Twig_Environment $twig */
$twig = $this->app['twig'];
try {
$template = $twig->resolveTemplate($templates);
} catch (\Twig_Error_Loader $e) {
return null;
}
$name = $template->getSourceContext()->getName();
if (!array_key_exists($name, $templateFieldsConfig)) {
return null;
}
return $templateFieldsConfig[$name];
}
}
| {
"content_hash": "96a13dd2e2c95dbc2156d080f4c07013",
"timestamp": "",
"source": "github",
"line_count": 695,
"max_line_length": 165,
"avg_line_length": 36.06043165467626,
"alnum_prop": 0.4634107413614237,
"repo_name": "electrolinux/bolt",
"id": "f6a6b0ca561fa34a679cf966af88ed8d03747258",
"size": "25062",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Storage/Entity/ContentValuesTrait.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3175"
},
{
"name": "CSS",
"bytes": "266671"
},
{
"name": "HTML",
"bytes": "445536"
},
{
"name": "JavaScript",
"bytes": "518082"
},
{
"name": "PHP",
"bytes": "2759857"
},
{
"name": "Shell",
"bytes": "2115"
}
],
"symlink_target": ""
} |
<?php
include('xenapi.php');
$url = "https://172.16.10.121"; /* URL of the Citrix XenSerer Xapi */
$login = "root"; /* login/user for the citrix box */
$password = 'Pa$$w0rd'; /* password for the user */
/* Establish session with Xenserver */
$xenserver = new XenApi($url, $login, $password);
/* Once sucessfully logged in - any method (valid or not) is passed to the XenServer.
Replace the first period (.) of the method with a underscore (_) - because PHP doesnt like
periods in the function names.
All the methods (other then logging in) require passing the session_id as the first parameter,
however this is done automatically - so you do not need to pass it.
For example, to do VM.get_all(session_id) and get all the vms as an array, then get/print the details of each
using VM.get_record(session_id, self) (self = VM object):
*/
$vms_array = $xenserver->VM_get_all();
foreach ($vms_array as $vm) {
$record = $xenserver->VM_get_record($vm);
print_r($record);
}
$xenserver->vm_export();
function uuidsanitize($uuid){
return (str_replace("OpaqueRef:","",$uuid));
}
?>
| {
"content_hash": "7dfc0e008018ff6c22e49e1cc7c781c7",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 109,
"avg_line_length": 29.56756756756757,
"alnum_prop": 0.6882998171846435,
"repo_name": "rbicelli/xebackup",
"id": "8fed164b3d46f9372d4ee12c7bf9abd47fce2fe3",
"size": "1094",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/third_party/example.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "240"
},
{
"name": "CSS",
"bytes": "607328"
},
{
"name": "HTML",
"bytes": "9995124"
},
{
"name": "JavaScript",
"bytes": "2958980"
},
{
"name": "PHP",
"bytes": "1830071"
},
{
"name": "Shell",
"bytes": "78"
}
],
"symlink_target": ""
} |
require 'test_helper'
class TasksControllerTest < ActionController::TestCase
setup do
@task = tasks(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:tasks)
end
test "should get new" do
get :new
assert_response :success
end
test "should create task" do
assert_difference('Task.count') do
post :create, task: { comment: @task.comment, due_date: @task.due_date, duration: @task.duration, list_id: @task.list_id, name: @task.name }
end
assert_redirected_to task_path(assigns(:task))
end
test "should show task" do
get :show, id: @task
assert_response :success
end
test "should get edit" do
get :edit, id: @task
assert_response :success
end
test "should update task" do
patch :update, id: @task, task: { comment: @task.comment, due_date: @task.due_date, duration: @task.duration, list_id: @task.list_id, name: @task.name }
assert_redirected_to task_path(assigns(:task))
end
test "should destroy task" do
assert_difference('Task.count', -1) do
delete :destroy, id: @task
end
assert_redirected_to tasks_path
end
end
| {
"content_hash": "59de6d669572eb167efae9f65183ea22",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 156,
"avg_line_length": 24.142857142857142,
"alnum_prop": 0.665257819103973,
"repo_name": "plombix/PortFolio_template",
"id": "7d62f88cec3991dbc69923c0922c36b4d7c5b00a",
"size": "1183",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/controllers/tasks_controller_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9405"
},
{
"name": "CoffeeScript",
"bytes": "1776"
},
{
"name": "HTML",
"bytes": "76771"
},
{
"name": "JavaScript",
"bytes": "1153"
},
{
"name": "Ruby",
"bytes": "92399"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
import frappe
import json, urlparse
from frappe.utils import get_request_session
from frappe import _
def make_get_request(url, auth=None, headers=None, data=None):
if not auth:
auth = ''
if not data:
data = {}
if not headers:
headers = {}
try:
s = get_request_session()
frappe.flags.integration_request = s.get(url, data={}, auth=auth, headers=headers)
frappe.flags.integration_request.raise_for_status()
return frappe.flags.integration_request.json()
except Exception as exc:
frappe.log_error(frappe.get_traceback())
raise exc
def make_post_request(url, auth=None, headers=None, data=None):
if not auth:
auth = ''
if not data:
data = {}
if not headers:
headers = {}
try:
s = get_request_session()
frappe.flags.integration_request = s.post(url, data=data, auth=auth, headers=headers)
frappe.flags.integration_request.raise_for_status()
if frappe.flags.integration_request.headers.get("content-type") == "text/plain; charset=utf-8":
return urlparse.parse_qs(frappe.flags.integration_request.text)
return frappe.flags.integration_request.json()
except Exception as exc:
frappe.log_error()
raise exc
def create_request_log(data, integration_type, service_name, name=None):
if isinstance(data, basestring):
data = json.loads(data)
integration_request = frappe.get_doc({
"doctype": "Integration Request",
"integration_type": integration_type,
"integration_request_service": service_name,
"reference_doctype": data.get("reference_doctype"),
"reference_docname": data.get("reference_docname"),
"data": json.dumps(data)
})
if name:
integration_request.flags._name = name
integration_request.insert(ignore_permissions=True)
frappe.db.commit()
return integration_request
def get_payment_gateway_controller(payment_gateway):
'''Return payment gateway controller'''
try:
return frappe.get_doc("{0} Settings".format(payment_gateway))
except Exception:
frappe.throw(_("{0} Settings not found".format(payment_gateway)))
@frappe.whitelist(allow_guest=True, xss_safe=True)
def get_checkout_url(**kwargs):
try:
if kwargs.get('payment_gateway'):
doc = frappe.get_doc("{0} Settings".format(kwargs.get('payment_gateway')))
return doc.get_payment_url(**kwargs)
else:
raise Exception
except Exception:
frappe.respond_as_web_page(_("Something went wrong"),
_("Looks like something is wrong with this site's payment gateway configuration. No payment has been made."),
indicator_color='red',
http_status_code=frappe.ValidationError.http_status_code)
def create_payment_gateway(gateway):
# NOTE: we don't translate Payment Gateway name because it is an internal doctype
if not frappe.db.exists("Payment Gateway", gateway):
payment_gateway = frappe.get_doc({
"doctype": "Payment Gateway",
"gateway": gateway
})
payment_gateway.insert(ignore_permissions=True)
| {
"content_hash": "679a1670cb11faa991b62d984b4265e2",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 112,
"avg_line_length": 30.63157894736842,
"alnum_prop": 0.7281786941580756,
"repo_name": "bcornwellmott/frappe",
"id": "4d6d6c0ec41e1498921e4523ba60cd5ca8980481",
"size": "3044",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "frappe/integrations/utils.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "387069"
},
{
"name": "HTML",
"bytes": "206997"
},
{
"name": "JavaScript",
"bytes": "1664389"
},
{
"name": "Python",
"bytes": "1863544"
},
{
"name": "Shell",
"bytes": "517"
}
],
"symlink_target": ""
} |
package com.opensearchserver.client.common.search.query;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@XmlAccessorType(XmlAccessType.FIELD)
@JsonInclude(Include.NON_EMPTY)
public class SearchField {
public static enum SearchFieldMode {
PATTERN, TERM, PHRASE, TERM_AND_PHRASE;
}
public String field;
public SearchFieldMode mode;
public Double boost;
public Double phraseBoost;
public Integer phraseSlop;
public Integer booleanGroup;
public SearchField() {
field = null;
mode = null;
boost = null;
phraseBoost = null;
phraseSlop = null;
booleanGroup = null;
}
/**
* @param field
* the field to set
* @return this instance
*/
public SearchField setField(String field) {
this.field = field;
return this;
}
/**
* @param mode
* the mode to set
* @return this instance
*/
public SearchField setMode(SearchFieldMode mode) {
this.mode = mode;
return this;
}
/**
* @param boost
* the boost to set
* @return this instance
*/
public SearchField setBoost(Double boost) {
this.boost = boost;
return this;
}
/**
* @param phraseBoost
* the phraseBoost to set
* @return this instance
*/
public SearchField setPhraseBoost(Double phraseBoost) {
this.phraseBoost = phraseBoost;
return this;
}
/**
* @param phraseSlop
* the phraseSlop to set
* @return this instance
*/
public SearchField setPhraseSlop(Integer phraseSlop) {
this.phraseSlop = phraseSlop;
return this;
}
/**
* @param booleanGroup
* the booleanGroup to set
* @return this instance
*/
public SearchField setBooleanGroup(Integer booleanGroup) {
this.booleanGroup = booleanGroup;
return this;
}
} | {
"content_hash": "e4d3ef0c7f0e82b5d1ae7f23ddf8a6dd",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 60,
"avg_line_length": 20.387096774193548,
"alnum_prop": 0.6914556962025317,
"repo_name": "jaeksoft/oss-java-client",
"id": "5c3424f77b1701c5f65665a166e3a1a4aebb8604",
"size": "2505",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/com/opensearchserver/client/common/search/query/SearchField.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "155866"
}
],
"symlink_target": ""
} |
package io.crate.execution.jobs;
import javax.annotation.Nonnull;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;
public abstract class AbstractTask implements Task {
protected final int id;
private final AtomicBoolean firstClose = new AtomicBoolean(false);
private final CompletableFuture<Void> future = new CompletableFuture<>();
protected AbstractTask(int id) {
this.id = id;
}
public int id() {
return id;
}
protected static BiConsumer<? super Object, Throwable> closeOrKill(AbstractTask t) {
return (result, err) -> {
if (err == null) {
t.close();
} else {
t.kill(err);
}
};
}
protected void innerStart() {
}
@Override
public final void start() {
if (!firstClose.get()) {
try {
innerStart();
} catch (Throwable t) {
kill(t);
}
}
}
protected void innerClose() {
}
protected void close() {
if (firstClose.compareAndSet(false, true)) {
try {
innerClose();
future.complete(null);
} catch (Throwable t) {
future.completeExceptionally(t);
}
}
}
protected void innerKill(@Nonnull Throwable t) {
}
@Override
public final void kill(@Nonnull Throwable t) {
if (firstClose.compareAndSet(false, true)) {
try {
innerKill(t);
} finally {
future.completeExceptionally(t);
}
}
}
@Override
public CompletableFuture<Void> completionFuture() {
return future;
}
protected synchronized boolean isClosed() {
return firstClose.get() || future.isDone();
}
}
| {
"content_hash": "a1cef55d8ddda150012c920f6efd6004",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 88,
"avg_line_length": 22.811764705882354,
"alnum_prop": 0.5451263537906137,
"repo_name": "EvilMcJerkface/crate",
"id": "f2f0391e7996e7bd62573d2c95724e8092b068a7",
"size": "2936",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/src/main/java/io/crate/execution/jobs/AbstractTask.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "29877"
},
{
"name": "Batchfile",
"bytes": "4123"
},
{
"name": "Java",
"bytes": "24908818"
},
{
"name": "Python",
"bytes": "64030"
},
{
"name": "Shell",
"bytes": "9028"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
namespace Heisenslaught.Infrastructure.MongoDb
{
public class UserCreationSettings
{
public List<string> AutoGrantSuperUserToBattleTags { get; set; }
}
}
| {
"content_hash": "4f81f6912764255d97a2cf2bd569e38e",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 72,
"avg_line_length": 21.1,
"alnum_prop": 0.7345971563981043,
"repo_name": "chetjan/heisenslaught",
"id": "75c46a6fdbd97605a7a1467181444d9019375b03",
"size": "213",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Heisenslaught/Infrastructure/MongoDb/Config/UserCreationSettings.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "170600"
},
{
"name": "CSS",
"bytes": "44807"
},
{
"name": "HTML",
"bytes": "21245"
},
{
"name": "JavaScript",
"bytes": "1892"
},
{
"name": "Shell",
"bytes": "232"
},
{
"name": "TypeScript",
"bytes": "149615"
}
],
"symlink_target": ""
} |
var crypto = require('crypto');
var config = require('cloud/config/weixin.js');
var debug = require('debug')('AV:weixin');
var request = require('request');
exports.exec = function (params, cb) {
if (params.signature) {
checkSignature(params.signature, params.timestamp, params.nonce, params.echostr, cb);
} else {
console.log("type: " + params.xml.MsgType);
switch (params.xml.MsgType.toString()) {
case "text":
//receiveMessage(params, cb);
requestRobot(params, cb);
break;
case "event":
receiveEvent(params, cb);
break;
default:
break;
}
}
};
// 验证签名
var checkSignature = function (signature, timestamp, nonce, echostr, cb) {
var oriStr = [config.token, timestamp, nonce].sort().join('');
var code = crypto.createHash('sha1').update(oriStr).digest('hex');
debug('code:', code);
if (code == signature) {
cb(null, echostr);
} else {
var err = new Error('Unauthorized');
err.code = 401;
cb(err);
}
};
// 接收普通消息
var receiveMessage = function (msg, cb) {
var result = {
xml: {
ToUserName: msg.xml.FromUserName[0],
FromUserName: '' + msg.xml.ToUserName + '',
CreateTime: new Date().getTime(),
MsgType: 'text',
Content: getReceiveMessage(msg.xml.Content)
}
};
cb(null, result);
};
// 接收事件消息
var receiveEvent = function (msg, cb) {
var result = {
xml: {
ToUserName: msg.xml.FromUserName[0],
FromUserName: '' + msg.xml.ToUserName + '',
CreateTime: new Date().getTime(),
MsgType: 'text',
Content: getEventMessage(msg.xml.Event)
}
};
cb(null, result);
};
var getReceiveMessage = function (receiveMessage) {
switch (receiveMessage.toString()) {
case "hi":
return "hello android";
default :
return "";
}
};
// 请求智能机器人
var requestRobot = function (msg, cb) {
console.log("开启智能机器人");
request.get("http://www.tuling123.com/openapi/api?key=247f9381e19327aa4b988aa50ab23281&info=" + msg.xml.Content,
function (error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
if (info.code == 100000) {
var result = {
xml: {
ToUserName: msg.xml.FromUserName[0],
FromUserName: '' + msg.xml.ToUserName + '',
CreateTime: new Date().getTime(),
MsgType: 'text',
Content: info.text
}
};
cb(null, result);
}
}
});
};
var getEventMessage = function (event) {
switch (event.toString()) {
case "subscribe":
return "您好,谢谢关注。";
break;
default :
break;
}
}; | {
"content_hash": "a72183c1eb876e6293fb106938707295",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 116,
"avg_line_length": 29.233644859813083,
"alnum_prop": 0.4984015345268542,
"repo_name": "Heywenwen/cocoweixin",
"id": "857b55923559dbc6beecdb1a1fe884690d07b27b",
"size": "3204",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cloud/weixin.js",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "25"
},
{
"name": "JavaScript",
"bytes": "5437"
}
],
"symlink_target": ""
} |
/*
* THE FILE HAS BEEN AUTOGENERATED BY THE IJH TOOL.
* Please be aware that all changes made to this file manually
* will be overwritten by the tool if it runs again.
*/
#include <jni.h>
/* Header for class org.apache.harmony.test.stress.jni.arrays.ArraysTest10 */
#ifndef _ORG_APACHE_HARMONY_TEST_STRESS_JNI_ARRAYS_ARRAYSTEST10_H
#define _ORG_APACHE_HARMONY_TEST_STRESS_JNI_ARRAYS_ARRAYSTEST10_H
#ifdef __cplusplus
extern "C" {
#endif
/* Static final fields */
#undef org_apache_harmony_test_stress_jni_arrays_ArraysTest10_TM_ERROR_NONE
#define org_apache_harmony_test_stress_jni_arrays_ArraysTest10_TM_ERROR_NONE 0L
#undef org_apache_harmony_test_stress_jni_arrays_ArraysTest10_TM_ERROR_INTERRUPT
#define org_apache_harmony_test_stress_jni_arrays_ArraysTest10_TM_ERROR_INTERRUPT 52L
#undef org_apache_harmony_test_stress_jni_arrays_ArraysTest10_TM_ERROR_ILLEGAL_STATE
#define org_apache_harmony_test_stress_jni_arrays_ArraysTest10_TM_ERROR_ILLEGAL_STATE 118L
/* Native methods */
/*
* Method: org.apache.harmony.test.stress.jni.arrays.ArraysTest10.init()V
*/
JNIEXPORT void JNICALL
Java_org_apache_harmony_test_stress_jni_arrays_ArraysTest10_init(JNIEnv *, jclass);
/*
* Method: org.apache.harmony.test.stress.jni.arrays.ArraysTest10.doNativeCalc(II[[I)V
*/
JNIEXPORT void JNICALL
Java_org_apache_harmony_test_stress_jni_arrays_ArraysTest10_doNativeCalc(JNIEnv *, jobject,
jint, jint, jobjectArray);
#ifdef __cplusplus
}
#endif
#endif /* _ORG_APACHE_HARMONY_TEST_STRESS_JNI_ARRAYS_ARRAYSTEST10_H */
| {
"content_hash": "510dc25d544196df8b60ee6e73e2cd07",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 92,
"avg_line_length": 28.48148148148148,
"alnum_prop": 0.7678803641092328,
"repo_name": "freeVM/freeVM",
"id": "491cb1d72ed8c58869b5e7820780f3d07731690e",
"size": "2345",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "enhanced/buildtest/tests/stress/qa/src/test/stress/org/apache/harmony/test/stress/jni/arrays/ArraysTest10.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "116828"
},
{
"name": "C",
"bytes": "17860389"
},
{
"name": "C++",
"bytes": "19007206"
},
{
"name": "CSS",
"bytes": "217777"
},
{
"name": "Java",
"bytes": "152108632"
},
{
"name": "Objective-C",
"bytes": "106412"
},
{
"name": "Objective-J",
"bytes": "11029421"
},
{
"name": "Perl",
"bytes": "305690"
},
{
"name": "Scilab",
"bytes": "34"
},
{
"name": "Shell",
"bytes": "153821"
},
{
"name": "XSLT",
"bytes": "152859"
}
],
"symlink_target": ""
} |
//This file is automatically rebuilt by the Cesium build process.
/*global define*/
define(function() {
"use strict";
return "/**\n\
* @license\n\
* Copyright (c) 2000-2005, Sean O'Neil (s_p_oneil@hotmail.com)\n\
* All rights reserved.\n\
* \n\
* Redistribution and use in source and binary forms, with or without\n\
* modification, are permitted provided that the following conditions\n\
* are met:\n\
* \n\
* * Redistributions of source code must retain the above copyright notice,\n\
* this list of conditions and the following disclaimer.\n\
* * Redistributions in binary form must reproduce the above copyright notice,\n\
* this list of conditions and the following disclaimer in the documentation\n\
* and/or other materials provided with the distribution.\n\
* * Neither the name of the project nor the names of its contributors may be\n\
* used to endorse or promote products derived from this software without\n\
* specific prior written permission.\n\
* \n\
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE\n\
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\
*\n\
* Modifications made by Analytical Graphics, Inc.\n\
*/\n\
\n\
// Code: http://sponeil.net/\n\
// GPU Gems 2 Article: http://http.developer.nvidia.com/GPUGems2/gpugems2_chapter16.html\n\
\n\
const float g = -0.95;\n\
const float g2 = g * g;\n\
\n\
varying vec3 v_rayleighColor;\n\
varying vec3 v_mieColor;\n\
varying vec3 v_toCamera;\n\
varying vec3 v_positionEC;\n\
\n\
void main (void)\n\
{\n\
// Extra normalize added for Android\n\
float fCos = dot(czm_sunDirectionWC, normalize(v_toCamera)) / length(v_toCamera);\n\
float fRayleighPhase = 0.75 * (1.0 + fCos * fCos);\n\
float fMiePhase = 1.5 * ((1.0 - g2) / (2.0 + g2)) * (1.0 + fCos * fCos) / pow(1.0 + g2 - 2.0 * g * fCos, 1.5);\n\
\n\
const float fExposure = 2.0;\n\
\n\
vec3 rgb = fRayleighPhase * v_rayleighColor + fMiePhase * v_mieColor;\n\
rgb = vec3(1.0) - exp(-fExposure * rgb);\n\
float l = czm_luminance(rgb);\n\
gl_FragColor = vec4(rgb, min(smoothstep(0.0, 0.1, l), 1.0) * smoothstep(0.0, 1.0, czm_morphTime));\n\
}\n\
";
}); | {
"content_hash": "15749350c1e7aacbb991edbf65c1ced1",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 117,
"avg_line_length": 44.859375,
"alnum_prop": 0.6924416579588993,
"repo_name": "petrushy/CesiumWidget",
"id": "c2090a20ed1ce483a3f833fedc1bfa978fe186bc",
"size": "4528",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "CesiumWidget/static/CesiumWidget/cesium/Source/Shaders/SkyAtmosphereFS.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "658868"
},
{
"name": "Erlang",
"bytes": "2222"
},
{
"name": "GLSL",
"bytes": "161710"
},
{
"name": "HTML",
"bytes": "1264005"
},
{
"name": "JavaScript",
"bytes": "47017551"
},
{
"name": "Python",
"bytes": "6029"
},
{
"name": "Shell",
"bytes": "297"
}
],
"symlink_target": ""
} |
'use strict';
const models = require('./index');
/**
* Specifies information about the Shared Image Gallery that you want to create
* or update.
*
* @extends models['Resource']
*/
class Gallery extends models['Resource'] {
/**
* Create a Gallery.
* @property {string} [description] The description of this Shared Image
* Gallery resource. This property is updatable.
* @property {object} [identifier]
* @property {string} [identifier.uniqueName] The unique name of the Shared
* Image Gallery. This name is generated automatically by Azure.
* @property {string} [provisioningState] The current state of the gallery.
* The provisioning state, which only appears in the response. Possible
* values include: 'Creating', 'Updating', 'Failed', 'Succeeded', 'Deleting',
* 'Migrating'
*/
constructor() {
super();
}
/**
* Defines the metadata of Gallery
*
* @returns {object} metadata of Gallery
*
*/
mapper() {
return {
required: false,
serializedName: 'Gallery',
type: {
name: 'Composite',
className: 'Gallery',
modelProperties: {
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'String'
}
},
name: {
required: false,
readOnly: true,
serializedName: 'name',
type: {
name: 'String'
}
},
type: {
required: false,
readOnly: true,
serializedName: 'type',
type: {
name: 'String'
}
},
location: {
required: true,
serializedName: 'location',
type: {
name: 'String'
}
},
tags: {
required: false,
serializedName: 'tags',
type: {
name: 'Dictionary',
value: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
description: {
required: false,
serializedName: 'properties.description',
type: {
name: 'String'
}
},
identifier: {
required: false,
serializedName: 'properties.identifier',
type: {
name: 'Composite',
className: 'GalleryIdentifier'
}
},
provisioningState: {
required: false,
readOnly: true,
serializedName: 'properties.provisioningState',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = Gallery;
| {
"content_hash": "47dd0510558132bb8171a59a55ee6772",
"timestamp": "",
"source": "github",
"line_count": 118,
"max_line_length": 79,
"avg_line_length": 24.872881355932204,
"alnum_prop": 0.47155025553662694,
"repo_name": "xingwu1/azure-sdk-for-node",
"id": "e9df7c4d87528f16c52460097648e16135766ff9",
"size": "3252",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/services/computeManagement2/lib/models/gallery.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "661"
},
{
"name": "JavaScript",
"bytes": "122792600"
},
{
"name": "Shell",
"bytes": "437"
},
{
"name": "TypeScript",
"bytes": "2558"
}
],
"symlink_target": ""
} |
@charset "gb2312";
/* CSS Document */
* { margin: 0; padding: 0 }
body { font: 16px "ËÎÌå", Arial, Helvetica, sans-serif; color: #756F71 }
img { border: 0; display: block }
ul { list-style: none; }
a:link, a:visited {text-decoration: none; color: #333;}
.left { float: left; }
.right { float: right; }
.blank { height: 5px; overflow: hidden; width: 100%; margin: auto; clear: both }
.box{ width:1000px; margin:auto; overflow:hidden}
header { width: 1000px; margin: auto; height: 80px; position: relative; overflow: hidden }
#logo a { width: 260px; height: 60px; margin: 10px 0 0 0; position: absolute; background: url(../images/logo.jpg) no-repeat; display: block }
nav { float: right; width: 100%; margin: 30px 0 0 0; text-align: right }
nav a { position: relative; display: inline-block; font-size: 18px; font-family: "΢ÈíÑźÚ", Arial, Helvetica, sans-serif; }
nav a:hover { text-decoration: none }
.topnav a { margin: 0 5px; padding: 0 8px; }
.topnav a span:first-child { z-index: 2; display: block; }
.topnav a span:last-child { z-index: 1; display: block; color: #999; font: 12px Georgia, serif; opacity: 0; -webkit-transition: -webkit-transform 0.3s, opacity 0.3s; -moz-transition: -moz-transform 0.3s, opacity 0.3s; transition: transform 0.3s, opacity 0.3s; -webkit-transform: translateY(-100%); -moz-transform: translateY(-100%); transform: translateY(-100%); text-align: center }
.topnav a:hover span:last-child, .topnav a:focus span:last-child { opacity: 1; -webkit-transform: translateY(0%); -moz-transform: translateY(0%); transform: translateY(0%); }
#topnav_current { color: #e15782; }
.en { color: #999; font-size: 12px; z-index: 1; display: block; }/* ie */
article { width: 1000px; margin: 20px auto; overflow: hidden }
aside { width: 250px; }
footer { text-align: center; line-height: 40px; border-top: #E8E8E8 1px solid ; width:1000px; margin:auto}
| {
"content_hash": "92c451e681b322c1e727bdfb50ad32ab",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 383,
"avg_line_length": 64.58620689655173,
"alnum_prop": 0.6935397757608115,
"repo_name": "blacksea3/medit",
"id": "7e0f9e31a4b133558afae8c6ae3296aa0019e96e",
"size": "1873",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "medit/main/static/main/css/base.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "3055"
},
{
"name": "Batchfile",
"bytes": "31"
},
{
"name": "C#",
"bytes": "16030"
},
{
"name": "CSS",
"bytes": "540861"
},
{
"name": "HTML",
"bytes": "674351"
},
{
"name": "Java",
"bytes": "38326"
},
{
"name": "JavaScript",
"bytes": "4916049"
},
{
"name": "PHP",
"bytes": "30690"
},
{
"name": "Python",
"bytes": "41164"
},
{
"name": "Shell",
"bytes": "699"
}
],
"symlink_target": ""
} |
package org.apache.hadoop.hbase.replication.regionserver;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.regionserver.wal.WALActionsListener;
import org.apache.hadoop.hbase.replication.ReplicationUtils;
import org.apache.hadoop.hbase.wal.WALEdit;
import org.apache.hadoop.hbase.wal.WALKey;
import org.apache.hadoop.hbase.wal.WALKeyImpl;
import org.apache.yetus.audience.InterfaceAudience;
import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
/**
* Used to receive new wals.
*/
@InterfaceAudience.Private
class ReplicationSourceWALActionListener implements WALActionsListener {
private final Configuration conf;
private final ReplicationSourceManager manager;
public ReplicationSourceWALActionListener(Configuration conf, ReplicationSourceManager manager) {
this.conf = conf;
this.manager = manager;
}
@Override
public void preLogRoll(Path oldPath, Path newPath) throws IOException {
manager.preLogRoll(newPath);
}
@Override
public void postLogRoll(Path oldPath, Path newPath) throws IOException {
manager.postLogRoll(newPath);
}
@Override
public void visitLogEntryBeforeWrite(WALKey logKey, WALEdit logEdit) throws IOException {
scopeWALEdits(logKey, logEdit, conf);
}
/**
* Utility method used to set the correct scopes on each log key. Doesn't set a scope on keys from
* compaction WAL edits and if the scope is local.
* @param logKey Key that may get scoped according to its edits
* @param logEdit Edits used to lookup the scopes
*/
@VisibleForTesting
static void scopeWALEdits(WALKey logKey, WALEdit logEdit, Configuration conf) {
// For bulk load replication we need meta family to know the file we want to replicate.
if (ReplicationUtils.isReplicationForBulkLoadDataEnabled(conf)) {
return;
}
// For replay, or if all the cells are markers, do not need to store replication scope.
if (logEdit.isReplay() ||
logEdit.getCells().stream().allMatch(c -> WALEdit.isMetaEditFamily(c))) {
((WALKeyImpl) logKey).clearReplicationScope();
}
}
}
| {
"content_hash": "70e2c7ab7dafc646b25dcd233c55c76d",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 100,
"avg_line_length": 34.15625,
"alnum_prop": 0.7621225983531564,
"repo_name": "ChinmaySKulkarni/hbase",
"id": "d25ab072eb1e46490581f37eb70ed4a306b6b4ef",
"size": "2992",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "hbase-server/src/main/java/org/apache/hadoop/hbase/replication/regionserver/ReplicationSourceWALActionListener.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "25330"
},
{
"name": "C",
"bytes": "28534"
},
{
"name": "C++",
"bytes": "56085"
},
{
"name": "CMake",
"bytes": "13186"
},
{
"name": "CSS",
"bytes": "37063"
},
{
"name": "Dockerfile",
"bytes": "4842"
},
{
"name": "Groovy",
"bytes": "37692"
},
{
"name": "HTML",
"bytes": "17275"
},
{
"name": "Java",
"bytes": "35158950"
},
{
"name": "JavaScript",
"bytes": "2694"
},
{
"name": "Makefile",
"bytes": "1359"
},
{
"name": "PHP",
"bytes": "8385"
},
{
"name": "Perl",
"bytes": "383739"
},
{
"name": "Python",
"bytes": "90226"
},
{
"name": "Ruby",
"bytes": "664576"
},
{
"name": "Shell",
"bytes": "254684"
},
{
"name": "Thrift",
"bytes": "52351"
},
{
"name": "XSLT",
"bytes": "6764"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_socket::lowest_layer (2 of 2 overloads)</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../lowest_layer.html" title="basic_socket::lowest_layer">
<link rel="prev" href="overload1.html" title="basic_socket::lowest_layer (1 of 2 overloads)">
<link rel="next" href="../lowest_layer_type.html" title="basic_socket::lowest_layer_type">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload1.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../lowest_layer.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../lowest_layer_type.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h5 class="title">
<a name="boost_asio.reference.basic_socket.lowest_layer.overload2"></a><a class="link" href="overload2.html" title="basic_socket::lowest_layer (2 of 2 overloads)">basic_socket::lowest_layer
(2 of 2 overloads)</a>
</h5></div></div></div>
<p>
Get a const reference to the lowest layer.
</p>
<pre class="programlisting"><span class="keyword">const</span> <span class="identifier">lowest_layer_type</span> <span class="special">&</span> <span class="identifier">lowest_layer</span><span class="special">()</span> <span class="keyword">const</span><span class="special">;</span>
</pre>
<p>
This function returns a const reference to the lowest layer in a stack
of layers. Since a <a class="link" href="../../basic_socket.html" title="basic_socket"><code class="computeroutput"><span class="identifier">basic_socket</span></code></a> cannot contain
any further layers, it simply returns a reference to itself.
</p>
<h6>
<a name="boost_asio.reference.basic_socket.lowest_layer.overload2.h0"></a>
<span class="phrase"><a name="boost_asio.reference.basic_socket.lowest_layer.overload2.return_value"></a></span><a class="link" href="overload2.html#boost_asio.reference.basic_socket.lowest_layer.overload2.return_value">Return
Value</a>
</h6>
<p>
A const reference to the lowest layer in the stack of layers. Ownership
is not transferred to the caller.
</p>
</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-2013 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="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../lowest_layer.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../lowest_layer_type.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "e716a18145ef5c9d87f7604cd4dc4ee4",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 454,
"avg_line_length": 69.01587301587301,
"alnum_prop": 0.6281048758049678,
"repo_name": "NixaSoftware/CVis",
"id": "4352f22b13742140650a2bb59f7a5c1b83f736dd",
"size": "4348",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "venv/bin/doc/html/boost_asio/reference/basic_socket/lowest_layer/overload2.html",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "160965"
},
{
"name": "Batchfile",
"bytes": "45451"
},
{
"name": "C",
"bytes": "4818355"
},
{
"name": "C#",
"bytes": "40804"
},
{
"name": "C++",
"bytes": "145737889"
},
{
"name": "CMake",
"bytes": "53495"
},
{
"name": "CSS",
"bytes": "287550"
},
{
"name": "CWeb",
"bytes": "174166"
},
{
"name": "Cuda",
"bytes": "26749"
},
{
"name": "Fortran",
"bytes": "9668"
},
{
"name": "HTML",
"bytes": "155266453"
},
{
"name": "IDL",
"bytes": "14"
},
{
"name": "JavaScript",
"bytes": "225380"
},
{
"name": "Lex",
"bytes": "1231"
},
{
"name": "M4",
"bytes": "29689"
},
{
"name": "Makefile",
"bytes": "1560105"
},
{
"name": "Max",
"bytes": "36857"
},
{
"name": "Objective-C",
"bytes": "4303"
},
{
"name": "Objective-C++",
"bytes": "218"
},
{
"name": "PHP",
"bytes": "59030"
},
{
"name": "Perl",
"bytes": "23580"
},
{
"name": "Perl 6",
"bytes": "7975"
},
{
"name": "Python",
"bytes": "28662237"
},
{
"name": "QML",
"bytes": "593"
},
{
"name": "Rebol",
"bytes": "354"
},
{
"name": "Roff",
"bytes": "8039"
},
{
"name": "Shell",
"bytes": "376471"
},
{
"name": "Smarty",
"bytes": "2045"
},
{
"name": "Tcl",
"bytes": "1172"
},
{
"name": "TeX",
"bytes": "13404"
},
{
"name": "XSLT",
"bytes": "746813"
},
{
"name": "Yacc",
"bytes": "18910"
}
],
"symlink_target": ""
} |
// Copyright (c) 2022, WNProject Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// clang-format off
#include "WidgetDropDown.h"
#include "../../Include/Rocket/Controls/ElementFormControl.h"
#include "../../Include/Rocket/Core/ElementUtilities.h"
#include "../../Include/Rocket/Core/Event.h"
#include "../../Include/Rocket/Core/Factory.h"
#include "../../Include/Rocket/Core/Input.h"
#include "../../Include/Rocket/Core/Math.h"
#include "../../Include/Rocket/Core/Property.h"
#include "../../Include/Rocket/Core/StyleSheetKeywords.h"
namespace Rocket {
namespace Controls {
WidgetDropDown::WidgetDropDown(
Core::Context* _context, ElementFormControl* element) {
m_context = _context;
parent_element = element;
box_layout_dirty = false;
value_layout_dirty = false;
selected_option = -1;
// Create the button and selection elements.
button_element = Core::Factory::InstanceElement(m_context, parent_element,
"*", "selectarrow", Rocket::Core::XMLAttributes());
value_element = Core::Factory::InstanceElement(
m_context, element, "*", "selectvalue", Rocket::Core::XMLAttributes());
selection_element = Core::Factory::InstanceElement(m_context, parent_element,
"*", "selectbox", Rocket::Core::XMLAttributes());
value_element->SetProperty("overflow", "hidden");
selection_element->SetProperty("visibility", "hidden");
selection_element->SetProperty(
"z-index", Core::Property(1.0f, Core::Property::NUMBER));
selection_element->SetProperty("clip", "none");
parent_element->AddEventListener("click", this, true);
parent_element->AddEventListener("blur", this);
parent_element->AddEventListener("focus", this);
parent_element->AddEventListener("keydown", this, true);
// Add the elements to our parent element.
parent_element->AppendChild(button_element, false);
parent_element->AppendChild(selection_element, false);
parent_element->AppendChild(value_element, false);
}
WidgetDropDown::~WidgetDropDown() {
ClearOptions();
parent_element->RemoveEventListener("click", this, true);
parent_element->RemoveEventListener("blur", this);
parent_element->RemoveEventListener("focus", this);
parent_element->RemoveEventListener("keydown", this, true);
button_element->RemoveReference();
selection_element->RemoveReference();
value_element->RemoveReference();
}
// Updates the selection box layout if necessary.
void WidgetDropDown::OnRender() {
if (box_layout_dirty) {
Core::Box box;
Core::ElementUtilities::BuildBox(
box, parent_element->GetBox().GetSize(), selection_element);
// Layout the selection box.
Core::ElementUtilities::FormatElement(
selection_element, parent_element->GetBox().GetSize(Core::Box::BORDER));
selection_element->SetOffset(
Rocket::Core::Vector2f(box.GetEdge(Core::Box::MARGIN, Core::Box::LEFT),
parent_element->GetBox().GetSize(Core::Box::BORDER).y +
box.GetEdge(Core::Box::MARGIN, Core::Box::TOP)),
parent_element);
box_layout_dirty = false;
}
if (value_layout_dirty) {
Core::ElementUtilities::FormatElement(
value_element, parent_element->GetBox().GetSize(Core::Box::BORDER));
value_element->SetOffset(
parent_element->GetBox().GetPosition(Core::Box::CONTENT),
parent_element);
value_layout_dirty = false;
}
}
void WidgetDropDown::OnLayout() {
if (parent_element->IsDisabled()) {
// Propagate disabled state to selectvalue and selectarrow
value_element->SetPseudoClass("disabled", true);
button_element->SetPseudoClass("disabled", true);
}
// Layout the button and selection boxes.
Core::Box parent_box = parent_element->GetBox();
Core::ElementUtilities::PositionElement(button_element,
Rocket::Core::Vector2f(0, 0), Core::ElementUtilities::TOP_RIGHT);
Core::ElementUtilities::PositionElement(selection_element,
Rocket::Core::Vector2f(0, 0), Core::ElementUtilities::TOP_LEFT);
// Calculate the value element position and size.
Rocket::Core::Vector2f size;
size.x = parent_element->GetBox().GetSize(Core::Box::CONTENT).x -
button_element->GetBox().GetSize(Core::Box::MARGIN).x;
size.y = parent_element->GetBox().GetSize(Core::Box::CONTENT).y;
value_element->SetOffset(
parent_element->GetBox().GetPosition(Core::Box::CONTENT), parent_element);
value_element->SetBox(Core::Box(size));
box_layout_dirty = true;
value_layout_dirty = true;
}
// Sets the value of the widget.
void WidgetDropDown::SetValue(const Rocket::Core::String& _value) {
for (size_t i = 0; i < options.size(); ++i) {
if (options[i].GetValue() == _value) {
SetSelection((int)i);
return;
}
}
value = _value;
value_element->SetInnerRML(value);
value_layout_dirty = true;
selected_option = -1;
}
// Returns the current value of the widget.
const Rocket::Core::String& WidgetDropDown::GetValue() const {
return value;
}
// Sets the index of the selection. If the new index lies outside of the bounds,
// it will be clamped.
void WidgetDropDown::SetSelection(int selection, bool force) {
Rocket::Core::String new_value;
if (selection < 0 || selection >= (int)options.size()) {
selection = -1;
} else {
new_value = options[selection].GetValue();
}
if (force || selection != selected_option || value != new_value) {
selected_option = selection;
value = new_value;
Rocket::Core::String value_rml;
if (selected_option >= 0)
options[selected_option].GetElement()->GetInnerRML(value_rml);
value_element->SetInnerRML(value_rml);
value_layout_dirty = true;
Rocket::Core::Dictionary parameters;
parameters.Set("value", value);
parent_element->DispatchEvent("change", parameters);
}
}
// Returns the index of the currently selected item.
int WidgetDropDown::GetSelection() const {
return selected_option;
}
// Adds a new option to the select control.
int WidgetDropDown::AddOption(const Rocket::Core::String& rml,
const Rocket::Core::String& _value, int before, bool select,
bool selectable) {
// Instance a new element for the option.
Core::Element* element = Core::Factory::InstanceElement(m_context,
selection_element, "*", "option", Rocket::Core::XMLAttributes());
// Force to block display and inject the RML. Register a click handler so we
// can be notified of selection.
element->SetProperty("display", "block");
element->SetProperty("clip", "auto");
element->SetInnerRML(rml);
element->AddEventListener("click", this);
int option_index;
if (before < 0 || before >= (int)options.size()) {
selection_element->AppendChild(element);
options.push_back(SelectOption(element, _value, selectable));
option_index = (int)options.size() - 1;
} else {
selection_element->InsertBefore(
element, selection_element->GetChild(before));
options.insert(
options.begin() + before, SelectOption(element, _value, selectable));
option_index = before;
}
element->RemoveReference();
// Select the option if appropriate.
if (select)
SetSelection(option_index);
box_layout_dirty = true;
return option_index;
}
// Removes an option from the select control.
void WidgetDropDown::RemoveOption(int index) {
if (index < 0 || index >= (int)options.size())
return;
// Remove the listener and delete the option element.
options[index].GetElement()->RemoveEventListener("click", this);
selection_element->RemoveChild(options[index].GetElement());
options.erase(options.begin() + index);
box_layout_dirty = true;
}
// Removes all options from the list.
void WidgetDropDown::ClearOptions() {
while (!options.empty())
RemoveOption((int)options.size() - 1);
}
// Returns on of the widget's options.
SelectOption* WidgetDropDown::GetOption(int index) {
if (index < 0 || index >= GetNumOptions())
return NULL;
return &options[index];
}
// Returns the number of options in the widget.
int WidgetDropDown::GetNumOptions() const {
return (int)options.size();
}
void WidgetDropDown::ProcessEvent(Core::Event& event) {
if (parent_element->IsDisabled())
return;
// Process the button onclick
if (event == "click") {
if (event.GetCurrentElement()->GetParentNode() == selection_element) {
// Find the element in the options and fire the selection event
for (size_t i = 0; i < options.size(); i++) {
if (options[i].GetElement() == event.GetCurrentElement()) {
if (options[i].IsSelectable()) {
SetSelection((int)i);
event.StopPropagation();
ShowSelectBox(false);
parent_element->Focus();
}
}
}
} else {
// We have to check that this event isn't targeted to an element
// inside the selection box as we'll get all events coming from our
// root level select element as well as the ones coming from options
// (which
// get caught in the above if)
Core::Element* element = event.GetTargetElement();
while (element && element != parent_element) {
if (element == selection_element)
return;
element = element->GetParentNode();
}
if (selection_element->GetProperty<int>("visibility") ==
Core::VISIBILITY_HIDDEN)
ShowSelectBox(true);
else
ShowSelectBox(false);
}
} else if (event == "blur" && event.GetTargetElement() == parent_element) {
ShowSelectBox(false);
} else if (event == "keydown") {
if (!options.empty()) {
Core::Input::KeyIdentifier key_identifier =
(Core::Input::KeyIdentifier)event.GetParameter<int>(
"key_identifier", 0);
switch (key_identifier) {
case Core::Input::KI_UP:
SetSelection((selected_option - 1 + (int)options.size()) %
(int)options.size());
break;
case Core::Input::KI_DOWN:
SetSelection((selected_option + 1) % (int)options.size());
break;
default:
break;
}
}
}
if (event.GetTargetElement() == parent_element) {
if (event == "focus") {
value_element->SetPseudoClass("focus", true);
button_element->SetPseudoClass("focus", true);
} else if (event == "blur") {
value_element->SetPseudoClass("focus", false);
button_element->SetPseudoClass("focus", false);
}
}
}
// Shows or hides the selection box.
void WidgetDropDown::ShowSelectBox(bool show) {
if (show) {
selection_element->SetProperty("visibility", "visible");
value_element->SetPseudoClass("checked", true);
button_element->SetPseudoClass("checked", true);
} else {
selection_element->SetProperty("visibility", "hidden");
value_element->SetPseudoClass("checked", false);
button_element->SetPseudoClass("checked", false);
}
}
} // namespace Controls
} // namespace Rocket
| {
"content_hash": "da0a64b535515bfe74fd8fb637b5a10c",
"timestamp": "",
"source": "github",
"line_count": 338,
"max_line_length": 80,
"avg_line_length": 32.49112426035503,
"alnum_prop": 0.667364778728829,
"repo_name": "WNProject/WNFramework",
"id": "9d0928b29d519813df55baa72c8ea16c0394d280",
"size": "12271",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "externals/librocket/Source/Controls/WidgetDropDown.cpp",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Assembly",
"bytes": "21585"
},
{
"name": "C",
"bytes": "178806"
},
{
"name": "C++",
"bytes": "4268348"
},
{
"name": "CMake",
"bytes": "163273"
},
{
"name": "GAP",
"bytes": "40323"
},
{
"name": "GLSL",
"bytes": "1516"
},
{
"name": "HLSL",
"bytes": "6436"
},
{
"name": "Objective-C",
"bytes": "14271"
},
{
"name": "PostScript",
"bytes": "394"
},
{
"name": "PowerShell",
"bytes": "3448"
},
{
"name": "Python",
"bytes": "66228"
},
{
"name": "Shell",
"bytes": "5208"
}
],
"symlink_target": ""
} |
static const int loopCount = 10000;
static int entryPointProducer(void* data)
{
drLockFreeFIFO* f = (drLockFreeFIFO*)data;
for (int i = 0; i < loopCount; i++)
{
int success = drLockFreeFIFO_push(f, &i);
//printf("pushed %d (success %d)\n", i, success);
}
return 0;
}
static int entryPointConsumer(void* data)
{
drLockFreeFIFO* f = (drLockFreeFIFO*)data;
for (int i = 0; i < loopCount; i++)
{
int val = 0;
int success = drLockFreeFIFO_pop(f, &val);
//printf("popped %d (success %d)\n", val, success);
}
return 0;
}
static void testTwoThreads()
{
start_test("Lock free FIFO - producer/consumer threads");
//TODO: actually check stuff
const int es = sizeof(int);
const int c = 100;
drLockFreeFIFO f;
drLockFreeFIFO_init(&f, c, es);
thrd_t t1, t2;
thrd_create(&t1, entryPointConsumer, &f);
thrd_create(&t2, entryPointProducer, &f);
int joinRes1, joinRes2;
thrd_join(t1, &joinRes1);
thrd_join(t2, &joinRes2);
}
static void testSize()
{
start_test("Lock free FIFO - size");
const int es = sizeof(int);
const int c = 100;
const int nCases = 5;
int nPush[nCases] = {10, 20, 30, 5, 90};
int nPop[nCases] = {5, 1, 60, 10, 90};
for (int i = 0; i < nCases; i++)
{
drLockFreeFIFO f;
drLockFreeFIFO_init(&f, c, es);
for (int j = 0; j < nPush[i]; j++)
{
int success = drLockFreeFIFO_push(&f, &j);
}
for (int j = 0; j < nPop[i]; j++)
{
int val = 0;
int success = drLockFreeFIFO_pop(&f, &val);
}
const int expectedSize = fmaxf(0.0f, nPush[i] - nPop[i]);
const int size = drLockFreeFIFO_getNumElements(&f);
fail_unless(expectedSize == size, "FIFO size should be the same after pushing and popping the same number of items");
drLockFreeFIFO_deinit(&f);
}
}
void testPushUntilFull()
{
start_test("Lock free FIFO - push until full");
const int es = sizeof(int);
const int c = 100;
drLockFreeFIFO f;
drLockFreeFIFO_init(&f, c, es);
for (int i = 0; i < c; i++)
{
int success = drLockFreeFIFO_push(&f, &i);
if (!success)
{
fail_unless(success == 1, "push to FIFO with free slots should succeed");
}
}
int success = drLockFreeFIFO_push(&f, &c);
fail_unless(success == 0, "push to full FIFO should fail");
const int full = drLockFreeFIFO_isFull(&f);
fail_unless(full == 1, "full FIFO should report that it's full");
const int empty = drLockFreeFIFO_isEmpty(&f);
fail_unless(empty == 0, "full FIFO should not report that it's empty");
}
static void testPushUntilFullAndPopUntilEmpty()
{
start_test("Lock free FIFO - push until full and pop until empty");
const int es = sizeof(int);
const int c = 100;
drLockFreeFIFO f;
drLockFreeFIFO_init(&f, c, es);
for (int i = 0; i < c; i++)
{
int success = drLockFreeFIFO_push(&f, &i);
if (!success)
{
fail_unless(success == 1, "push to FIFO with free slots should succeed");
}
}
int success = drLockFreeFIFO_push(&f, &c);
fail_unless(success == 0, "push to full FIFO should fail");
int full = drLockFreeFIFO_isFull(&f);
fail_unless(full == 1, "full FIFO should report that it's full");
int empty = drLockFreeFIFO_isEmpty(&f);
fail_unless(empty == 0, "full FIFO should not report that it's empty");
for (int i = 0; i < c; i++)
{
int val = 0;
int success = drLockFreeFIFO_pop(&f, &val);
if (success != 1)
{
fail_unless(success == 1, "popping from FIFO with one or more elements should succeed");
}
if (val != i)
{
fail_unless(val == i, "popped element should have the expected value");
}
}
full = drLockFreeFIFO_isFull(&f);
fail_unless(full == 0, "empty FIFO should not report that it's full");
empty = drLockFreeFIFO_isEmpty(&f);
fail_unless(empty == 1, "empty FIFO should report that it's empty");
}
void testLockFreeFIFO()
{
testTwoThreads();
testSize();
testPushUntilFull();
testPushUntilFullAndPopUntilEmpty();
} | {
"content_hash": "e6fd8ea0efbae7323640c5ce905edcb6",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 125,
"avg_line_length": 25.502857142857142,
"alnum_prop": 0.5581447456867578,
"repo_name": "stuffmatic/miniosa",
"id": "3ac988099180af6bd6d0fed5846a2e6bde99257a",
"size": "4613",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/test_lock_free_fifo.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "14862"
},
{
"name": "Objective-C",
"bytes": "49968"
},
{
"name": "Swift",
"bytes": "12361"
}
],
"symlink_target": ""
} |
<?php
namespace spec\Aisel\SettingsBundle\Controller;
use PhpSpec\ObjectBehavior;
/**
* @author Ivan Proskoryakov <volgodark@gmail.com>
*/
class ConfigMetaControllerSpec extends ObjectBehavior
{
public function it_is_initializable()
{
$this->shouldHaveType('\Aisel\SettingsBundle\Controller\ConfigMetaController');
}
}
| {
"content_hash": "b88e1a21a0a055775412a9e134b86174",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 87,
"avg_line_length": 18.263157894736842,
"alnum_prop": 0.7377521613832853,
"repo_name": "ivanproskuryakov/AiselBackend",
"id": "ce508a1f4b6a23fbcaf2e4f020ca4da81ad59598",
"size": "554",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Aisel/SettingsBundle/spec/Aisel/SettingsBundle/Controller/ConfigMetaControllerSpec.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3235"
},
{
"name": "PHP",
"bytes": "579192"
}
],
"symlink_target": ""
} |
using Shouldly;
using StructureMap.Graph;
using System.Linq;
using Xunit;
namespace StructureMap.Testing.Bugs
{
public class ConnectImplementationsToTypesClosing_is_wonky_in_Registry_added_by_Configure
{
[Fact]
public void has_the_correct_number_by_initialize()
{
var container = Container.For<BookRegistry>();
container.GetAllInstances<IBook<SciFi>>().Count().ShouldBe(1);
}
[Fact]
public void has_the_correct_number_by_configure()
{
var container = new Container();
container.Configure(x => x.AddRegistry<BookRegistry>());
container.GetAllInstances<IBook<SciFi>>().Count().ShouldBe(1);
}
}
public class BookRegistry : Registry
{
public BookRegistry()
{
Scan(x =>
{
x.TheCallingAssembly();
x.ConnectImplementationsToTypesClosing(typeof(IBook<>));
});
}
}
public interface IBook<T>
{
}
public class SciFi
{
}
public class SciFiBook : IBook<SciFi>
{
}
public class Fantasy
{
}
public class FantasyBook : IBook<Fantasy>
{
}
} | {
"content_hash": "fbbc834fd515200dab07180929e37d92",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 93,
"avg_line_length": 22.596491228070175,
"alnum_prop": 0.5434782608695652,
"repo_name": "khellang/structuremap",
"id": "c09da77468a56c8ff35dc9c38bce658f15598303",
"size": "1290",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/StructureMap.Testing/Bugs/ConnectImplementationsToTypesClosing_is_wonky_in_Registry_added_by_Configure.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "251"
},
{
"name": "C#",
"bytes": "1517633"
},
{
"name": "Ruby",
"bytes": "3247"
}
],
"symlink_target": ""
} |
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
from ..._serialization import Serializer
from .._vendor import _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_export_request_rate_by_interval_request(location: str, subscription_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-03-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/logAnalytics/apiAccess/getRequestRateByInterval",
) # pylint: disable=line-too-long
path_format_arguments = {
"location": _SERIALIZER.url("location", location, "str", pattern=r"^[-\w\._]+$"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
def build_export_throttled_requests_request(location: str, subscription_id: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-03-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/logAnalytics/apiAccess/getThrottledRequests",
) # pylint: disable=line-too-long
path_format_arguments = {
"location": _SERIALIZER.url("location", location, "str", pattern=r"^[-\w\._]+$"),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class LogAnalyticsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.compute.v2019_03_01.ComputeManagementClient`'s
:attr:`log_analytics` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
def _export_request_rate_by_interval_initial(
self, location: str, parameters: Union[_models.RequestRateByIntervalInput, IO], **kwargs: Any
) -> Optional[_models.LogAnalyticsOperationResult]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-03-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.LogAnalyticsOperationResult]]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(parameters, (IO, bytes)):
_content = parameters
else:
_json = self._serialize.body(parameters, "RequestRateByIntervalInput")
request = build_export_request_rate_by_interval_request(
location=location,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._export_request_rate_by_interval_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize("LogAnalyticsOperationResult", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_export_request_rate_by_interval_initial.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/logAnalytics/apiAccess/getRequestRateByInterval"} # type: ignore
@overload
def begin_export_request_rate_by_interval(
self,
location: str,
parameters: _models.RequestRateByIntervalInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.LogAnalyticsOperationResult]:
"""Export logs that show Api requests made by this subscription in the given time window to show
throttling activities.
:param location: The location upon which virtual-machine-sizes is queried. Required.
:type location: str
:param parameters: Parameters supplied to the LogAnalytics getRequestRateByInterval Api.
Required.
:type parameters: ~azure.mgmt.compute.v2019_03_01.models.RequestRateByIntervalInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either LogAnalyticsOperationResult or the result
of cls(response)
:rtype:
~azure.core.polling.LROPoller[~azure.mgmt.compute.v2019_03_01.models.LogAnalyticsOperationResult]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_export_request_rate_by_interval(
self, location: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any
) -> LROPoller[_models.LogAnalyticsOperationResult]:
"""Export logs that show Api requests made by this subscription in the given time window to show
throttling activities.
:param location: The location upon which virtual-machine-sizes is queried. Required.
:type location: str
:param parameters: Parameters supplied to the LogAnalytics getRequestRateByInterval Api.
Required.
:type parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either LogAnalyticsOperationResult or the result
of cls(response)
:rtype:
~azure.core.polling.LROPoller[~azure.mgmt.compute.v2019_03_01.models.LogAnalyticsOperationResult]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_export_request_rate_by_interval(
self, location: str, parameters: Union[_models.RequestRateByIntervalInput, IO], **kwargs: Any
) -> LROPoller[_models.LogAnalyticsOperationResult]:
"""Export logs that show Api requests made by this subscription in the given time window to show
throttling activities.
:param location: The location upon which virtual-machine-sizes is queried. Required.
:type location: str
:param parameters: Parameters supplied to the LogAnalytics getRequestRateByInterval Api. Is
either a model type or a IO type. Required.
:type parameters: ~azure.mgmt.compute.v2019_03_01.models.RequestRateByIntervalInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either LogAnalyticsOperationResult or the result
of cls(response)
:rtype:
~azure.core.polling.LROPoller[~azure.mgmt.compute.v2019_03_01.models.LogAnalyticsOperationResult]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-03-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.LogAnalyticsOperationResult]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._export_request_rate_by_interval_initial( # type: ignore
location=location,
parameters=parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("LogAnalyticsOperationResult", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_export_request_rate_by_interval.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/logAnalytics/apiAccess/getRequestRateByInterval"} # type: ignore
def _export_throttled_requests_initial(
self, location: str, parameters: Union[_models.ThrottledRequestsInput, IO], **kwargs: Any
) -> Optional[_models.LogAnalyticsOperationResult]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-03-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.LogAnalyticsOperationResult]]
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(parameters, (IO, bytes)):
_content = parameters
else:
_json = self._serialize.body(parameters, "ThrottledRequestsInput")
request = build_export_throttled_requests_request(
location=location,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._export_throttled_requests_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize("LogAnalyticsOperationResult", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_export_throttled_requests_initial.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/logAnalytics/apiAccess/getThrottledRequests"} # type: ignore
@overload
def begin_export_throttled_requests(
self,
location: str,
parameters: _models.ThrottledRequestsInput,
*,
content_type: str = "application/json",
**kwargs: Any
) -> LROPoller[_models.LogAnalyticsOperationResult]:
"""Export logs that show total throttled Api requests for this subscription in the given time
window.
:param location: The location upon which virtual-machine-sizes is queried. Required.
:type location: str
:param parameters: Parameters supplied to the LogAnalytics getThrottledRequests Api. Required.
:type parameters: ~azure.mgmt.compute.v2019_03_01.models.ThrottledRequestsInput
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either LogAnalyticsOperationResult or the result
of cls(response)
:rtype:
~azure.core.polling.LROPoller[~azure.mgmt.compute.v2019_03_01.models.LogAnalyticsOperationResult]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def begin_export_throttled_requests(
self, location: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any
) -> LROPoller[_models.LogAnalyticsOperationResult]:
"""Export logs that show total throttled Api requests for this subscription in the given time
window.
:param location: The location upon which virtual-machine-sizes is queried. Required.
:type location: str
:param parameters: Parameters supplied to the LogAnalytics getThrottledRequests Api. Required.
:type parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either LogAnalyticsOperationResult or the result
of cls(response)
:rtype:
~azure.core.polling.LROPoller[~azure.mgmt.compute.v2019_03_01.models.LogAnalyticsOperationResult]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def begin_export_throttled_requests(
self, location: str, parameters: Union[_models.ThrottledRequestsInput, IO], **kwargs: Any
) -> LROPoller[_models.LogAnalyticsOperationResult]:
"""Export logs that show total throttled Api requests for this subscription in the given time
window.
:param location: The location upon which virtual-machine-sizes is queried. Required.
:type location: str
:param parameters: Parameters supplied to the LogAnalytics getThrottledRequests Api. Is either
a model type or a IO type. Required.
:type parameters: ~azure.mgmt.compute.v2019_03_01.models.ThrottledRequestsInput or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling. Pass in False for this
operation to not poll, or pass in your own initialized polling object for a personal polling
strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either LogAnalyticsOperationResult or the result
of cls(response)
:rtype:
~azure.core.polling.LROPoller[~azure.mgmt.compute.v2019_03_01.models.LogAnalyticsOperationResult]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-03-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
cls = kwargs.pop("cls", None) # type: ClsType[_models.LogAnalyticsOperationResult]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._export_throttled_requests_initial( # type: ignore
location=location,
parameters=parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("LogAnalyticsOperationResult", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method = cast(
PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_export_throttled_requests.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/logAnalytics/apiAccess/getThrottledRequests"} # type: ignore
| {
"content_hash": "492aa8e4e81006c6112b72939ccdef88",
"timestamp": "",
"source": "github",
"line_count": 512,
"max_line_length": 211,
"avg_line_length": 50.248046875,
"alnum_prop": 0.6684028452598437,
"repo_name": "Azure/azure-sdk-for-python",
"id": "2342f021cc956daaa2ffec33c86ec1714c69bef3",
"size": "26227",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2019_03_01/operations/_log_analytics_operations.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1224"
},
{
"name": "Bicep",
"bytes": "24196"
},
{
"name": "CSS",
"bytes": "6089"
},
{
"name": "Dockerfile",
"bytes": "4892"
},
{
"name": "HTML",
"bytes": "12058"
},
{
"name": "JavaScript",
"bytes": "8137"
},
{
"name": "Jinja",
"bytes": "10377"
},
{
"name": "Jupyter Notebook",
"bytes": "272022"
},
{
"name": "PowerShell",
"bytes": "518535"
},
{
"name": "Python",
"bytes": "715484989"
},
{
"name": "Shell",
"bytes": "3631"
}
],
"symlink_target": ""
} |
The documents in this unit dive into the details of how TensorFlow
works. The units are as follows:
## High Level APIs
* @{$programmers_guide/estimators}, which introduces a high-level
TensorFlow API that greatly simplifies ML programming.
* @{$programmers_guide/datasets}, which explains how to
set up data pipelines to read data sets into your TensorFlow program.
## Low Level APIs
* @{$programmers_guide/low_level_intro}, which introduces the
basics of how you can use TensorFlow outside of the high Level APIs.
* @{$programmers_guide/tensors}, which explains how to create,
manipulate, and access Tensors--the fundamental object in TensorFlow.
* @{$programmers_guide/variables}, which details how
to represent shared, persistent state in your program.
* @{$programmers_guide/graphs}, which explains:
* dataflow graphs, which are TensorFlow's representation of computations
as dependencies between operations.
* sessions, which are TensorFlow's mechanism for running dataflow graphs
across one or more local or remote devices.
If you are programming with the low-level TensorFlow API, this unit
is essential. If you are programming with a high-level TensorFlow API
such as Estimators or Keras, the high-level API creates and manages
graphs and sessions for you, but understanding graphs and sessions
can still be helpful.
* @{$programmers_guide/saved_model}, which
explains how to save and restore variables and models.
## Accelerators
* @{$using_gpu} explains how TensorFlow assigns operations to
devices and how you can change the arrangement manually.
* @{$using_tpu} explains how to modify `Estimator` programs to run on a TPU.
## ML Concepts
* @{$programmers_guide/embedding}, which introduces the concept
of embeddings, provides a simple example of training an embedding in
TensorFlow, and explains how to view embeddings with the TensorBoard
Embedding Projector.
## Debugging
* @{$programmers_guide/debugger}, which
explains how to use the TensorFlow debugger (tfdbg).
## TensorBoard
TensorBoard is a utility to visualize different aspects of machine learning.
The following guides explain how to use TensorBoard:
* @{$programmers_guide/summaries_and_tensorboard},
which introduces TensorBoard.
* @{$programmers_guide/graph_viz}, which
explains how to visualize the computational graph.
* @{$programmers_guide/tensorboard_histograms} which demonstrates the how to
use TensorBoard's histogram dashboard.
## Misc
* @{$programmers_guide/version_compat},
which explains backward compatibility guarantees and non-guarantees.
* @{$programmers_guide/faq}, which contains frequently asked
questions about TensorFlow.
| {
"content_hash": "e1562cdac55e14ecbc0942c793449e65",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 78,
"avg_line_length": 40.289855072463766,
"alnum_prop": 0.7492805755395684,
"repo_name": "Xeralux/tensorflow",
"id": "e8c2fa6990c8ecfca1cfe76b3f813b4ae6917742",
"size": "2802",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tensorflow/docs_src/programmers_guide/index.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "9274"
},
{
"name": "C",
"bytes": "340972"
},
{
"name": "C++",
"bytes": "39479562"
},
{
"name": "CMake",
"bytes": "194702"
},
{
"name": "Go",
"bytes": "1046987"
},
{
"name": "HTML",
"bytes": "4680032"
},
{
"name": "Java",
"bytes": "567239"
},
{
"name": "Jupyter Notebook",
"bytes": "1940883"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "Makefile",
"bytes": "48231"
},
{
"name": "Objective-C",
"bytes": "12456"
},
{
"name": "Objective-C++",
"bytes": "94385"
},
{
"name": "PHP",
"bytes": "2140"
},
{
"name": "Perl",
"bytes": "6179"
},
{
"name": "Perl 6",
"bytes": "1357"
},
{
"name": "PureBasic",
"bytes": "25356"
},
{
"name": "Python",
"bytes": "33675501"
},
{
"name": "Ruby",
"bytes": "533"
},
{
"name": "Shell",
"bytes": "425916"
}
],
"symlink_target": ""
} |
<p>Containing:</p>
<p><a href="url">link containing <em>em</em> text</a></p>
<p><a href="url">link containing <strong>strong</strong> text</a></p>
<p><a href="url">link containing <em>em</em> text</a></p>
<p><a href="url">link containing <strong>strong</strong> text</a></p>
<p>Contained:</p>
<p>em enclosing <em><a href="url">link</a></em></p>
<p>strong enclosing <strong><a href="url">link</a></strong></p>
<p>em enclosing <em><a href="url">link</a></em></p>
<p>strong enclosing <strong><a href="url">link</a></strong></p>
<p>Intertwined:</p>
<p><a href="url">link *intertwined</a> with em text*</p>
<p>link <em>intertwined [with em</em> text](url)</p>
<p><a href="url">link **intertwined</a> with strong text**</p>
<p>link <strong>intertwined [with strong</strong> text](url)</p>
<p><a href="url">link _intertwined</a> with em text_</p>
<p>link <em>intertwined [with em</em> text](url)</p>
<p><a href="url">link __intertwined</a> with strong text__</p>
<p>link <strong>intertwined [with strong</strong> text](url)</p>
| {
"content_hash": "fde5d2e3ceb736f540dd2e462b9f77b8",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 69,
"avg_line_length": 28.08108108108108,
"alnum_prop": 0.631376323387873,
"repo_name": "vfmd/vfmd-test",
"id": "54073c48a5a9e2c8be601b5f1310b4d0543b9597",
"size": "1039",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/span_level/link/expected/vs_emph.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "GCC Machine Description",
"bytes": "7307"
},
{
"name": "HTML",
"bytes": "58304"
},
{
"name": "Python",
"bytes": "7449"
}
],
"symlink_target": ""
} |
package rpc
import (
context "context"
fmt "fmt"
http "net/http"
"sort"
"strconv"
"time"
twirp "github.com/twitchtv/twirp"
"go.skia.org/infra/go/allowed"
"go.skia.org/infra/go/git/repograph"
"go.skia.org/infra/go/now"
"go.skia.org/infra/go/sklog"
"go.skia.org/infra/go/swarming"
"go.skia.org/infra/go/twirp_auth"
"go.skia.org/infra/task_scheduler/go/db"
"go.skia.org/infra/task_scheduler/go/skip_tasks"
"go.skia.org/infra/task_scheduler/go/task_cfg_cache"
"go.skia.org/infra/task_scheduler/go/types"
"google.golang.org/protobuf/types/known/timestamppb"
)
// Generate the go code from the protocol buffer definitions.
//go:generate bazelisk run --config=mayberemote //:protoc -- --go_opt=paths=source_relative --twirp_out=. --go_out=. ./rpc.proto
//go:generate mv ./go.skia.org/infra/task_scheduler/go/rpc/rpc.twirp.go ./rpc.twirp.go
//go:generate rm -rf ./go.skia.org
//go:generate bazelisk run --config=mayberemote //:goimports "--run_under=cd $PWD &&" -- -w rpc.pb.go
//go:generate bazelisk run --config=mayberemote //:goimports "--run_under=cd $PWD &&" -- -w rpc.twirp.go
//go:generate bazelisk run --config=mayberemote //:protoc -- --twirp_typescript_out=../../modules/rpc ./rpc.proto
// NewTaskSchedulerServer creates and returns a Twirp HTTP server.
func NewTaskSchedulerServer(ctx context.Context, db db.DB, repos repograph.Map, skipTasks *skip_tasks.DB, taskCfgCache task_cfg_cache.TaskCfgCache, swarm swarming.ApiClient, viewers, editors, admins allowed.Allow) http.Handler {
impl := newTaskSchedulerServiceImpl(ctx, db, repos, skipTasks, taskCfgCache, swarm, viewers, editors, admins)
srv := NewTaskSchedulerServiceServer(impl, nil)
return twirp_auth.Middleware(srv)
}
// taskSchedulerServiceImpl implements TaskSchedulerService.
type taskSchedulerServiceImpl struct {
*twirp_auth.AuthHelper
db db.DB
repos repograph.Map
skipTasks *skip_tasks.DB
taskCfgCache task_cfg_cache.TaskCfgCache
swarming swarming.ApiClient
}
// newTaskSchedulerServiceImpl returns a taskSchedulerServiceImpl instance.
func newTaskSchedulerServiceImpl(ctx context.Context, db db.DB, repos repograph.Map, skipTasks *skip_tasks.DB, taskCfgCache task_cfg_cache.TaskCfgCache, swarm swarming.ApiClient, viewers, editors, admins allowed.Allow) *taskSchedulerServiceImpl {
return &taskSchedulerServiceImpl{
AuthHelper: twirp_auth.NewAuthHelper(viewers, editors, admins),
db: db,
repos: repos,
skipTasks: skipTasks,
taskCfgCache: taskCfgCache,
swarming: swarm,
}
}
// TriggerJobs triggers the given jobs.
func (s *taskSchedulerServiceImpl) TriggerJobs(ctx context.Context, req *TriggerJobsRequest) (*TriggerJobsResponse, error) {
if _, err := s.GetEditor(ctx); err != nil {
return nil, err
}
jobs := make([]*types.Job, 0, len(req.Jobs))
for _, j := range req.Jobs {
_, repoName, _, err := s.repos.FindCommit(j.CommitHash)
if err != nil {
sklog.Error(err)
return nil, twirp.NotFoundError("Unable to find the given commit in any repo.")
}
job, err := task_cfg_cache.MakeJob(ctx, s.taskCfgCache, types.RepoState{
Repo: repoName,
Revision: j.CommitHash,
}, j.JobName)
if err != nil {
sklog.Error(err)
return nil, twirp.InternalError("Failed to create job.")
}
job.Requested = job.Created
job.IsForce = true
if err != nil {
return nil, twirp.InternalError("Failed to trigger jobs.")
}
jobs = append(jobs, job)
}
if err := s.db.PutJobsInChunks(ctx, jobs); err != nil {
sklog.Error(err)
return nil, twirp.InternalError("Failed to insert jobs into DB.")
}
ids := make([]string, 0, len(jobs))
for _, job := range jobs {
ids = append(ids, job.Id)
}
return &TriggerJobsResponse{
JobIds: ids,
}, nil
}
// getJob returns the given job.
func (s *taskSchedulerServiceImpl) getJob(ctx context.Context, id string) (*Job, *types.Job, error) {
if _, err := s.GetViewer(ctx); err != nil {
return nil, nil, err
}
dbJob, err := s.db.GetJobById(ctx, id)
if err == db.ErrNotFound || dbJob == nil {
sklog.Errorf("Unable to find job %q", id)
return nil, nil, twirp.NotFoundError("Unknown job")
} else if err != nil {
sklog.Error(err)
return nil, nil, twirp.InternalError("Failed to retrieve job")
}
rv, err := convertJob(dbJob)
if err != nil {
return nil, nil, err
}
// Retrieve the task specs, so that we can include the task dimensions
// in the results.
cfg, cachedErr, err := s.taskCfgCache.Get(ctx, dbJob.RepoState)
if cachedErr != nil {
err = cachedErr
}
if err != nil {
sklog.Error(err)
return nil, nil, twirp.InternalError("Failed to retrieve job dependencies")
}
taskDimensions := make([]*TaskDimensions, 0, len(rv.Dependencies))
for _, task := range rv.Dependencies {
taskSpec, ok := cfg.Tasks[task.Task]
if !ok {
err := fmt.Errorf("Job %s (%s) points to unknown task %q at repo state: %+v", rv.Id, rv.Name, task.Task, rv.RepoState)
sklog.Error(err)
return nil, nil, twirp.InternalError(err.Error())
}
taskDimensions = append(taskDimensions, &TaskDimensions{
TaskName: task.Task,
Dimensions: taskSpec.Dimensions,
})
}
rv.TaskDimensions = taskDimensions
return rv, dbJob, nil
}
// GetJob returns the given job.
func (s *taskSchedulerServiceImpl) GetJob(ctx context.Context, req *GetJobRequest) (*GetJobResponse, error) {
job, _, err := s.getJob(ctx, req.Id)
if err != nil {
return nil, err
}
return &GetJobResponse{
Job: job,
}, nil
}
// CancelJob cancels the given job.
func (s *taskSchedulerServiceImpl) CancelJob(ctx context.Context, req *CancelJobRequest) (*CancelJobResponse, error) {
if _, err := s.GetEditor(ctx); err != nil {
return nil, err
}
_, job, err := s.getJob(ctx, req.Id)
if err != nil {
sklog.Error(err)
return nil, twirp.InternalError("Failed to retrieve job.")
}
if job.Done() {
err := fmt.Errorf("Job %s is already finished with status %s", req.Id, job.Status)
return nil, twirp.InvalidArgumentError("id", err.Error())
}
job.Finished = now.Now(ctx)
job.Status = types.JOB_STATUS_CANCELED
if err := s.db.PutJob(ctx, job); err != nil {
sklog.Error(err)
return nil, twirp.InternalError("Failed to update job")
}
rv, _, err := s.getJob(ctx, req.Id)
return &CancelJobResponse{
Job: rv,
}, err
}
// SearchJobs searches the DB and returns jobs matching the given criteria.
func (s *taskSchedulerServiceImpl) SearchJobs(ctx context.Context, req *SearchJobsRequest) (*SearchJobsResponse, error) {
if _, err := s.GetViewer(ctx); err != nil {
return nil, err
}
params := &db.JobSearchParams{}
if req.HasBuildbucketBuildId {
bbID, err := strconv.ParseInt(req.BuildbucketBuildId, 10, 64)
if err != nil {
return nil, err
}
params.BuildbucketBuildID = intPtr(bbID)
}
if req.HasIsForce {
params.IsForce = boolPtr(req.IsForce)
}
if req.HasIssue {
params.Issue = stringPtr(req.Issue)
}
if req.HasName {
params.Name = stringPtr(req.Name)
}
if req.HasPatchset {
params.Patchset = stringPtr(req.Patchset)
}
if req.HasRepo {
params.Repo = stringPtr(req.Repo)
}
if req.HasRevision {
params.Revision = stringPtr(req.Revision)
}
if req.HasStatus {
status := types.JobStatus("")
switch req.Status {
case JobStatus_JOB_STATUS_IN_PROGRESS:
status = types.JOB_STATUS_IN_PROGRESS
case JobStatus_JOB_STATUS_SUCCESS:
status = types.JOB_STATUS_SUCCESS
case JobStatus_JOB_STATUS_FAILURE:
status = types.JOB_STATUS_FAILURE
case JobStatus_JOB_STATUS_MISHAP:
status = types.JOB_STATUS_MISHAP
case JobStatus_JOB_STATUS_CANCELED:
status = types.JOB_STATUS_CANCELED
}
params.Status = (*types.JobStatus)(stringPtr(string(status)))
}
if req.HasTimeEnd {
params.TimeEnd = timePtr(req.TimeEnd.AsTime())
}
if req.HasTimeStart {
params.TimeStart = timePtr(req.TimeStart.AsTime())
}
results, err := db.SearchJobs(ctx, s.db, params)
if err != nil {
sklog.Error(err)
return nil, twirp.InternalError("Failed to search jobs")
}
jobs, err := convertJobs(results)
if err != nil {
return nil, err
}
return &SearchJobsResponse{
Jobs: jobs,
}, nil
}
// getTask returns the given task.
func (s *taskSchedulerServiceImpl) getTask(ctx context.Context, id string) (*Task, *types.Task, error) {
if _, err := s.GetViewer(ctx); err != nil {
return nil, nil, err
}
dbTask, err := s.db.GetTaskById(ctx, id)
if err == db.ErrNotFound || dbTask == nil {
return nil, nil, twirp.NotFoundError("Unknown task")
} else if err != nil {
sklog.Error(err)
return nil, nil, twirp.InternalError("Failed to retrieve task")
}
rv, err := convertTask(dbTask)
if err != nil {
return nil, nil, err
}
return rv, dbTask, nil
}
// GetTask returns the given task.
func (s *taskSchedulerServiceImpl) GetTask(ctx context.Context, req *GetTaskRequest) (*GetTaskResponse, error) {
task, _, err := s.getTask(ctx, req.Id)
if err != nil {
return nil, err
}
if req.IncludeStats {
swarmingTask, err := s.swarming.GetTask(ctx, task.SwarmingTaskId, true)
if err != nil {
sklog.Error(err)
return nil, twirp.InternalError("Failed to retrieve Swarming task")
}
if swarmingTask.PerformanceStats != nil && swarmingTask.PerformanceStats.IsolatedDownload != nil && swarmingTask.PerformanceStats.IsolatedUpload != nil {
task.Stats = &TaskStats{
TotalOverheadS: float32(swarmingTask.PerformanceStats.BotOverhead),
DownloadOverheadS: float32(swarmingTask.PerformanceStats.IsolatedDownload.Duration),
UploadOverheadS: float32(swarmingTask.PerformanceStats.IsolatedUpload.Duration),
}
}
}
return &GetTaskResponse{
Task: task,
}, nil
}
// SearchTasks searches the DB and returns tasks matching the given
// criteria.
func (s *taskSchedulerServiceImpl) SearchTasks(ctx context.Context, req *SearchTasksRequest) (*SearchTasksResponse, error) {
if _, err := s.GetViewer(ctx); err != nil {
return nil, err
}
params := &db.TaskSearchParams{}
if req.HasAttempt {
params.Attempt = intPtr(int64(req.Attempt))
}
if req.HasIssue {
params.Issue = stringPtr(req.Issue)
}
if req.HasName {
params.Name = stringPtr(req.Name)
}
if req.HasPatchset {
params.Patchset = stringPtr(req.Patchset)
}
if req.HasRepo {
params.Repo = stringPtr(req.Repo)
}
if req.HasRevision {
params.Revision = stringPtr(req.Revision)
}
if req.HasStatus {
status := types.TaskStatus("")
switch req.Status {
case TaskStatus_TASK_STATUS_PENDING:
status = types.TASK_STATUS_PENDING
case TaskStatus_TASK_STATUS_RUNNING:
status = types.TASK_STATUS_RUNNING
case TaskStatus_TASK_STATUS_SUCCESS:
status = types.TASK_STATUS_SUCCESS
case TaskStatus_TASK_STATUS_FAILURE:
status = types.TASK_STATUS_FAILURE
case TaskStatus_TASK_STATUS_MISHAP:
status = types.TASK_STATUS_MISHAP
}
params.Status = (*types.TaskStatus)(stringPtr(string(status)))
}
if req.HasTimeEnd {
params.TimeEnd = timePtr(req.TimeEnd.AsTime())
}
if req.HasTimeStart {
params.TimeStart = timePtr(req.TimeStart.AsTime())
}
results, err := db.SearchTasks(ctx, s.db, params)
if err != nil {
sklog.Error(err)
return nil, twirp.InternalError("Failed to search jobs")
}
tasks, err := convertTasks(results)
if err != nil {
return nil, err
}
return &SearchTasksResponse{
Tasks: tasks,
}, nil
}
func (s *taskSchedulerServiceImpl) getSkipTaskRules() []*SkipTaskRule {
rules := s.skipTasks.GetRules()
rv := make([]*SkipTaskRule, 0, len(rules))
for _, rule := range rules {
rv = append(rv, &SkipTaskRule{
AddedBy: rule.AddedBy,
TaskSpecPatterns: rule.TaskSpecPatterns,
Commits: rule.Commits,
Description: rule.Description,
Name: rule.Name,
})
}
return rv
}
// GetSkipTaskRules returns all active rules for skipping tasks.
func (s *taskSchedulerServiceImpl) GetSkipTaskRules(ctx context.Context, req *GetSkipTaskRulesRequest) (*GetSkipTaskRulesResponse, error) {
if _, err := s.GetViewer(ctx); err != nil {
return nil, err
}
return &GetSkipTaskRulesResponse{
Rules: s.getSkipTaskRules(),
}, nil
}
// AddSkipTaskRule adds a rule for skipping tasks.
func (s *taskSchedulerServiceImpl) AddSkipTaskRule(ctx context.Context, req *AddSkipTaskRuleRequest) (*AddSkipTaskRuleResponse, error) {
user, err := s.GetEditor(ctx)
if err != nil {
return nil, err
}
rule := &skip_tasks.Rule{
AddedBy: user,
TaskSpecPatterns: req.TaskSpecPatterns,
Commits: req.Commits,
Description: req.Description,
Name: req.Name,
}
if len(rule.Commits) == 2 {
rangeRule, err := skip_tasks.NewCommitRangeRule(context.Background(), rule.Name, rule.AddedBy, rule.Description, rule.TaskSpecPatterns, rule.Commits[0], rule.Commits[1], s.repos)
if err != nil {
sklog.Error(err)
return nil, twirp.InvalidArgumentError("commits", "Failed to create commit range rule")
}
rule = rangeRule
}
if err := s.skipTasks.AddRule(ctx, rule, s.repos); err != nil {
sklog.Error(err)
return nil, twirp.InternalError("Failed to add skip task rule")
}
return &AddSkipTaskRuleResponse{
Rules: s.getSkipTaskRules(),
}, nil
}
// DeleteSkipTaskRule deletes the given rule for skipping tasks.
func (s *taskSchedulerServiceImpl) DeleteSkipTaskRule(ctx context.Context, req *DeleteSkipTaskRuleRequest) (*DeleteSkipTaskRuleResponse, error) {
if _, err := s.GetEditor(ctx); err != nil {
return nil, err
}
if err := s.skipTasks.RemoveRule(ctx, req.Id); err != nil {
sklog.Error(err)
return nil, twirp.InternalError("Failed to remove rule")
}
return &DeleteSkipTaskRuleResponse{
Rules: s.getSkipTaskRules(),
}, nil
}
// convertRepoState converts a types.RepoState to rpc.RepoState.
func convertRepoState(rs types.RepoState) *RepoState {
return &RepoState{
Patch: &RepoState_Patch{
Issue: rs.Issue,
PatchRepo: rs.PatchRepo,
Patchset: rs.Patchset,
Server: rs.Server,
},
Repo: rs.Repo,
Revision: rs.Revision,
}
}
// convertTaskStatus converts a types.TaskStatus to rpc.TaskStatus.
func convertTaskStatus(st types.TaskStatus) (TaskStatus, error) {
switch st {
case types.TASK_STATUS_PENDING:
return TaskStatus_TASK_STATUS_PENDING, nil
case types.TASK_STATUS_RUNNING:
return TaskStatus_TASK_STATUS_RUNNING, nil
case types.TASK_STATUS_SUCCESS:
return TaskStatus_TASK_STATUS_SUCCESS, nil
case types.TASK_STATUS_FAILURE:
return TaskStatus_TASK_STATUS_FAILURE, nil
case types.TASK_STATUS_MISHAP:
return TaskStatus_TASK_STATUS_MISHAP, nil
default:
return TaskStatus_TASK_STATUS_PENDING, twirp.InternalError("Invalid task status.")
}
}
// convertTask converts a types.Task to rpc.Task.
func convertTask(task *types.Task) (*Task, error) {
st, err := convertTaskStatus(task.Status)
if err != nil {
return nil, err
}
return &Task{
Attempt: int32(task.Attempt),
Commits: task.Commits,
CreatedAt: timestamppb.New(task.Created),
DbModifiedAt: timestamppb.New(task.DbModified),
FinishedAt: timestamppb.New(task.Finished),
Id: task.Id,
IsolatedOutput: task.IsolatedOutput,
Jobs: task.Jobs,
MaxAttempts: int32(task.MaxAttempts),
ParentTaskIds: task.ParentTaskIds,
Properties: task.Properties,
RetryOf: task.RetryOf,
StartedAt: timestamppb.New(task.Started),
Status: st,
SwarmingBotId: task.SwarmingBotId,
SwarmingTaskId: task.SwarmingTaskId,
TaskKey: &TaskKey{
RepoState: convertRepoState(task.RepoState),
Name: task.Name,
ForcedJobId: task.ForcedJobId,
},
}, nil
}
// convertTasks converts a slice of types.Task to rpc.Task.
func convertTasks(tasks []*types.Task) ([]*Task, error) {
rv := make([]*Task, 0, len(tasks))
for _, task := range tasks {
t, err := convertTask(task)
if err != nil {
return nil, err
}
rv = append(rv, t)
}
return rv, nil
}
// convertJobStatus converts a types.JobStatus to rpc.JobStatus.
func convertJobStatus(st types.JobStatus) (JobStatus, error) {
switch st {
case types.JOB_STATUS_IN_PROGRESS:
return JobStatus_JOB_STATUS_IN_PROGRESS, nil
case types.JOB_STATUS_SUCCESS:
return JobStatus_JOB_STATUS_SUCCESS, nil
case types.JOB_STATUS_FAILURE:
return JobStatus_JOB_STATUS_FAILURE, nil
case types.JOB_STATUS_MISHAP:
return JobStatus_JOB_STATUS_MISHAP, nil
case types.JOB_STATUS_CANCELED:
return JobStatus_JOB_STATUS_CANCELED, nil
default:
return JobStatus_JOB_STATUS_IN_PROGRESS, twirp.InternalError("Invalid job status.")
}
}
// convertJob converts a types.Job to rpc.Job.
func convertJob(job *types.Job) (*Job, error) {
depNames := make([]string, 0, len(job.Dependencies))
for name := range job.Dependencies {
depNames = append(depNames, name)
}
sort.Strings(depNames)
deps := make([]*TaskDependencies, 0, len(job.Dependencies))
for _, name := range depNames {
taskDeps := job.Dependencies[name]
deps = append(deps, &TaskDependencies{
Task: name,
Dependencies: taskDeps,
})
}
// Sort the deps by task name for determinism.
sort.Slice(deps, func(i, j int) bool {
return deps[i].Task < deps[j].Task
})
status, err := convertJobStatus(job.Status)
if err != nil {
return nil, err
}
taskNames := make([]string, 0, len(job.Tasks))
for name := range job.Tasks {
taskNames = append(taskNames, name)
}
sort.Strings(taskNames)
tasks := make([]*TaskSummaries, 0, len(job.Tasks))
for _, name := range taskNames {
taskSummaries := job.Tasks[name]
ts := make([]*TaskSummary, 0, len(tasks))
for _, taskSummary := range taskSummaries {
st, err := convertTaskStatus(taskSummary.Status)
if err != nil {
return nil, err
}
ts = append(ts, &TaskSummary{
Id: taskSummary.Id,
Attempt: int32(taskSummary.Attempt),
MaxAttempts: int32(taskSummary.MaxAttempts),
Status: st,
SwarmingTaskId: taskSummary.SwarmingTaskId,
})
}
tasks = append(tasks, &TaskSummaries{
Name: name,
Tasks: ts,
})
}
bbID := fmt.Sprintf("%d", job.BuildbucketBuildId)
bbKey := fmt.Sprintf("%d", job.BuildbucketLeaseKey)
return &Job{
BuildbucketBuildId: bbID,
BuildbucketLeaseKey: bbKey,
CreatedAt: timestamppb.New(job.Created),
DbModifiedAt: timestamppb.New(job.DbModified),
Dependencies: deps,
FinishedAt: timestamppb.New(job.Finished),
Id: job.Id,
IsForce: job.IsForce,
Name: job.Name,
Priority: float32(job.Priority),
RepoState: convertRepoState(job.RepoState),
RequestedAt: timestamppb.New(job.Requested),
Status: status,
Tasks: tasks,
}, nil
}
// convertJobs converts a slice of types.Job to rpc.Job.
func convertJobs(jobs []*types.Job) ([]*Job, error) {
rv := make([]*Job, 0, len(jobs))
for _, job := range jobs {
j, err := convertJob(job)
if err != nil {
return nil, err
}
rv = append(rv, j)
}
return rv, nil
}
func stringPtr(s string) *string {
rv := new(string)
*rv = s
return rv
}
func intPtr(i int64) *int64 {
rv := new(int64)
*rv = i
return rv
}
func boolPtr(b bool) *bool {
rv := new(bool)
*rv = b
return rv
}
func timePtr(ts time.Time) *time.Time {
rv := new(time.Time)
*rv = ts
return rv
}
var _ TaskSchedulerService = &taskSchedulerServiceImpl{}
| {
"content_hash": "afd4cd01770f1574a5c6236e8df8bbef",
"timestamp": "",
"source": "github",
"line_count": 625,
"max_line_length": 246,
"avg_line_length": 30.6928,
"alnum_prop": 0.6943126726789345,
"repo_name": "google/skia-buildbot",
"id": "337fb9a77729b74a54d5bd48b5de94ee5cb8afb3",
"size": "19183",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "task_scheduler/go/rpc/rpc.go",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "736"
},
{
"name": "C",
"bytes": "3114"
},
{
"name": "C++",
"bytes": "18072"
},
{
"name": "CSS",
"bytes": "13967"
},
{
"name": "Dockerfile",
"bytes": "18546"
},
{
"name": "Go",
"bytes": "8744467"
},
{
"name": "HTML",
"bytes": "790880"
},
{
"name": "JavaScript",
"bytes": "1186449"
},
{
"name": "Jupyter Notebook",
"bytes": "9165"
},
{
"name": "Makefile",
"bytes": "75823"
},
{
"name": "PowerShell",
"bytes": "15305"
},
{
"name": "Python",
"bytes": "126773"
},
{
"name": "SCSS",
"bytes": "128048"
},
{
"name": "Shell",
"bytes": "232449"
},
{
"name": "Starlark",
"bytes": "234929"
},
{
"name": "TypeScript",
"bytes": "1568540"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Wed Jul 17 13:50:46 MST 2019 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.wildfly.swarm.config.management.service (BOM: * : All 2.5.0.Final API)</title>
<meta name="date" content="2019-07-17">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.wildfly.swarm.config.management.service (BOM: * : All 2.5.0.Final API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.5.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/wildfly/swarm/config/management/security_realm/server_identity/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../../org/wildfly/swarm/config/messaging/activemq/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/wildfly/swarm/config/management/service/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Package" class="title">Package org.wildfly.swarm.config.management.service</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Interface Summary table, listing interfaces, and an explanation">
<caption><span>Interface Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Interface</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../org/wildfly/swarm/config/management/service/ActiveOperationConsumer.html" title="interface in org.wildfly.swarm.config.management.service">ActiveOperationConsumer</a><T extends <a href="../../../../../../org/wildfly/swarm/config/management/service/ActiveOperation.html" title="class in org.wildfly.swarm.config.management.service">ActiveOperation</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../org/wildfly/swarm/config/management/service/ActiveOperationSupplier.html" title="interface in org.wildfly.swarm.config.management.service">ActiveOperationSupplier</a><T extends <a href="../../../../../../org/wildfly/swarm/config/management/service/ActiveOperation.html" title="class in org.wildfly.swarm.config.management.service">ActiveOperation</a>></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../org/wildfly/swarm/config/management/service/ActiveOperation.html" title="class in org.wildfly.swarm.config.management.service">ActiveOperation</a><T extends <a href="../../../../../../org/wildfly/swarm/config/management/service/ActiveOperation.html" title="class in org.wildfly.swarm.config.management.service">ActiveOperation</a><T>></td>
<td class="colLast">
<div class="block">A currently executing operation.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Summary table, listing enums, and an explanation">
<caption><span>Enum Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Enum</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../org/wildfly/swarm/config/management/service/ActiveOperation.AccessMechanism.html" title="enum in org.wildfly.swarm.config.management.service">ActiveOperation.AccessMechanism</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../org/wildfly/swarm/config/management/service/ActiveOperation.ExecutionStatus.html" title="enum in org.wildfly.swarm.config.management.service">ActiveOperation.ExecutionStatus</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.5.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/wildfly/swarm/config/management/security_realm/server_identity/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../../org/wildfly/swarm/config/messaging/activemq/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/wildfly/swarm/config/management/service/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2019 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "ed68351e9a2aac7077a4b56f95c8f711",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 419,
"avg_line_length": 43.95161290322581,
"alnum_prop": 0.6530886850152905,
"repo_name": "wildfly-swarm/wildfly-swarm-javadocs",
"id": "35cf015b354dc8ebced0cb7e9f5dfa2d4369d56f",
"size": "8175",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "2.5.0.Final/apidocs/org/wildfly/swarm/config/management/service/package-summary.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
Title: Membership
Date: 2014-01-01 10:01:30
Category: news
Tags: Membership
Slug: membership
Author: SIRA
The SIRA Board of Directors passed a resolution to start a new paid membership tier based upon the results of this year's membership survey and the desire to create the foundation for a more formal professional organization. As a result, we are formally announcing the introduction of the SIRA Professional Membership (SPM).
The cost for SPM will be **$50.00USD**. SIRA will maintain current and historical records of your membership in the event you reference SPM on your CV/bio/resume. Benefits to membership include:
- Reduced registration to SIRAcon ($50.00 off total price)
- Membership through 2015
- Proceedings of 2014/2015 SIRAcons
- SIRAcon journal subscription carried through 2015
- Free access to SIRA-sponsored webinars
Future webinars will be restricted to SPM or those paying to attend.
>NOTE: The [mailing list](http://lists.societyinforisk.org/mailman/listinfo/sira) is still open to all with no cost to access/participate.
To sign-up as a SIRA Professional Member, please click "Buy Now" below.
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input name="cmd" type="hidden" value="_s-xclick" /> <input name="hosted_button_id" type="hidden" value="VWHFF7ZWU9CZW" /> <input alt="PayPal - The safer, easier way to pay online!" border="0" name="submit" src="https://www.paypalobjects.com/en_US/i/btn/btn_buynowCC_LG.gif" type="image" /> <img border="0" height="1" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" /></form>
<p> </p>
| {
"content_hash": "df71cccdc188d19dbe984423704d435f",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 396,
"avg_line_length": 62.30769230769231,
"alnum_prop": 0.7617283950617284,
"repo_name": "societyinforisk/blog",
"id": "8cad24d42392e4164ae0c5ab57ec03fdcdf8e6c4",
"size": "1620",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "content/pages/membership.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" >
<generator uri="https://jekyllrb.com/" version="3.5.2">Jekyll</generator>
<link href="http://bennettadams.net/feed.xml" rel="self" type="application/atom+xml" />
<link href="http://bennettadams.net/" rel="alternate" type="text/html" />
<updated>2017-09-26T10:54:19-04:00</updated>
<id>http://bennettadams.net/</id>
<title type="html">Design + Dev</title>
<subtitle>I'm a User Interface and User Experience (UI/UX) Designer and Engineer, I do product and visual design as well as frontend coding (HTML, CSS, JS).</subtitle>
<entry>
<title type="html">I have a side project, and so should you!</title>
<link href="http://bennettadams.net/SideProject/" rel="alternate" type="text/html" title="I have a side project, and so should you!" />
<published>2017-09-12T00:00:00-04:00</published>
<updated>2017-09-12T00:00:00-04:00</updated>
<id>http://bennettadams.net/SideProject</id>
<content type="html" xml:base="http://bennettadams.net/SideProject/"><h4>Intro</h4>
<p>I know a lot of talented designers and developers, and every single one of them has one thing in common; they're regularly working on a side project. It doesn't matter the type of project, be it a blog, starter project or something for the neighborhood taco joint, they're all beneficial to you in many different ways.</p>
<h4>What is a side project?</h4>
<p>A side project is any sort of project that is undertaken outside of your standard work commitments. There's no real requirements, they can vary from fun and silly, all the way to a secondary job that you hope to turn into something big one day.</p>
<h4>The Benefits</h4>
<p>It's been shown that creative hobbies make people more helpful, collaborative, and creative in their job performance, so off the bat it's even possible to spin a side project as a positive to your employer! But logistics aside, employees who had creative hobbies felt more relaxed and in control outside of work.</p>
<p>On a slightly more obvious level, a side project also helps to facilitate learning and even experience by tackling new things you wouldn't get a chance to do in your 9-5. This can in turn benefit your career, either by growing your portfolio or just by being able to say you have experience in a subject you didn't before. This portfolio and blog for example allowed me to learn Jekyll and brush up on my writing. From now on I can feel more comfortable discussing either topic in a professional setting, not to mention the indirect positives that are gained with the learning experience.</p>
<h4>Where to start</h4>
<p>The best place to start would be something that you're passionate about. If it's something that you truly care about it will keep you motivated and be that much more rewarding along the way. It doesn't make a lot of sense to spend your free time doing something that you couldn't care less about, regardless of the professional benefits.</p>
<p>Another way to make the side project even more fun and rewarding is to include friends, or even co-workers. This will not only help bring a fresh perspective to the project, but help with motivation, two minds is always greater than one.</p>
<h4>Get movin'!</h4>
<p>So get out there and finally get moving on that mobile app idea you've been thinking about or writing that article on Medium you've noticed no one is talking about!</p></content>
<author>
<name>Bennett Adams</name>
</author>
<category term="Projects" />
<summary type="html">Intro I know a lot of talented designers and developers, and every single one of them has one thing in common; they're regularly working on a side project. It doesn't matter the type of project, be it a blog, starter project or something for the neighborhood taco joint, they're all beneficial to you in many different ways.</summary>
</entry>
<entry>
<title type="html">UX vs. UI vs. IA vs. IXD</title>
<link href="http://bennettadams.net/UXvsUIvsIA/" rel="alternate" type="text/html" title="UX vs. UI vs. IA vs. IXD" />
<published>2017-09-10T00:00:00-04:00</published>
<updated>2017-09-10T00:00:00-04:00</updated>
<id>http://bennettadams.net/UXvsUIvsIA</id>
<content type="html" xml:base="http://bennettadams.net/UXvsUIvsIA/"><h4>Intro</h4>
<p>Once upon a time, if you said the word “design”, the odds were overwhelmingly likely you were talking about graphic design. But nowadays, the digital world is becoming increasingly more complicated and a lot of new job positions appearing, which lead to confusion for people outside or new to the design industry. Here’s a quick overview on the four different primary forms of design to help you understand what they mean.</p>
<h4>UX (User Experience Design)</h4>
<p>As is found on Wikipedia “User experience design (UXD, UED or XD) is the process of enhancing user satisfaction by improving the usability, accessibility, and pleasure provided in the interaction between the user and the product. User experience design encompasses traditional human–computer interaction (HCI) design, and extends it by addressing all aspects of a product or service as perceived by users.</p>
<p>UX designer is the person in charge with creating the products “logic” via wireframes and prototypes via software like Axure, JustInMind, Mockplus etc. Communication is one of the critical skills of the UX designers. They also conduct research, competitive analysis at the beginning as well as usability testing and A/B testing after the project has launched. UX designers are primarily concerned with how the product feels.</p>
<h4>UI Design (User Interface Design)</h4>
<p>Author and founder of Adaptive Path — a user experience consultancy, Jesse James Garrett, defines interface design as being all about selecting the right interface elements — like text, buttons, text fields, color coded lists, etc — for the task the user is trying to accomplish and arranging them on the screen in a way that will be readily understood and easily used. The goal is make the user’s interaction as efficient and simple as possible.</p>
<p><strong>Interface elements include but are not limited to:</strong><br>
Input Controls: buttons, text fields, checkboxes, radio buttons, dropdown lists, list boxes, toggles, date field</p>
<h4>IA (Information Architecture)</h4>
<p>Information architecture (IA) involves the way a website/app is structured and how the content is organized. The goal is to help users find information and complete tasks. “In other words, information architecture is the creation of a structure for a website, application, or other project, that allows us to understand where we are as users, and where the information we want is in relation to our position. Information architecture results in the creation of site maps, hierarchies, categorizations, navigation, and metadata. When a content strategist begins separating content and dividing it into categories, she is practicing information architecture. </p>
<h4>IxD (Interaction Design)</h4>
<p>IxD designer is the people in charge of the websites/apps moving elements & interactions. If you’ve seen a cool animation on a website or app, that made you say wow or that is really cool, that’s the stuff motion designers do.</p>
<p>In an Interaction Designer role, you’ll tackle complex tasks and transform them into intuitive, accessible and easy-to-use designs for billions of people around the world-from the first-time user to the sophisticated expert. </p>
<h4>In conclusion...</h4>
<p>Last but not least, the boundaries between each of these various design roles are very fluid. The IxD is quite similar to UX design in it’s approach as it’s part of the UX design cycle, so in some cases these roles may have a lot of overlap.</p></content>
<author>
<name>Vincent Xia</name>
</author>
<category term="Design" />
<summary type="html">Intro Once upon a time, if you said the word “design”, the odds were overwhelmingly likely you were talking about graphic design. But nowadays, the digital world is becoming increasingly more complicated and a lot of new job positions appearing, which lead to confusion for people outside or new to the design industry. Here’s a quick overview on the four different primary forms of design to help you understand what they mean.</summary>
</entry>
<entry>
<title type="html">Life Preserver Mobile App</title>
<link href="http://bennettadams.net/LifePreserver/" rel="alternate" type="text/html" title="Life Preserver Mobile App" />
<published>2017-09-07T00:00:00-04:00</published>
<updated>2017-09-07T00:00:00-04:00</updated>
<id>http://bennettadams.net/LifePreserver</id>
<content type="html" xml:base="http://bennettadams.net/LifePreserver/"></content>
<author>
<name></name>
</author>
<category term="UI/UX Design, Mobile App Development" />
<summary type="html"></summary>
</entry>
<entry>
<title type="html">SPARGO Rebrand</title>
<link href="http://bennettadams.net/SpargoInc/" rel="alternate" type="text/html" title="SPARGO Rebrand" />
<published>2017-08-18T00:00:00-04:00</published>
<updated>2017-08-18T00:00:00-04:00</updated>
<id>http://bennettadams.net/SpargoInc</id>
<content type="html" xml:base="http://bennettadams.net/SpargoInc/"></content>
<author>
<name></name>
</author>
<category term="UI/UX Design, Web Development" />
<summary type="html"></summary>
</entry>
<entry>
<title type="html">Universal Style Guide</title>
<link href="http://bennettadams.net/StyleGuide/" rel="alternate" type="text/html" title="Universal Style Guide" />
<published>2017-08-14T00:00:00-04:00</published>
<updated>2017-08-14T00:00:00-04:00</updated>
<id>http://bennettadams.net/StyleGuide</id>
<content type="html" xml:base="http://bennettadams.net/StyleGuide/"></content>
<author>
<name></name>
</author>
<category term="UI/UX Design" />
<summary type="html"></summary>
</entry>
<entry>
<title type="html">SPARGO Product Showcase</title>
<link href="http://bennettadams.net/SPARGOFeatures/" rel="alternate" type="text/html" title="SPARGO Product Showcase" />
<published>2017-08-10T00:00:00-04:00</published>
<updated>2017-08-10T00:00:00-04:00</updated>
<id>http://bennettadams.net/SPARGOFeatures</id>
<content type="html" xml:base="http://bennettadams.net/SPARGOFeatures/"></content>
<author>
<name></name>
</author>
<category term="UI/UX Design, Web Development" />
<summary type="html"></summary>
</entry>
<entry>
<title type="html">Careers</title>
<link href="http://bennettadams.net/Careers/" rel="alternate" type="text/html" title="Careers" />
<published>2017-07-16T00:00:00-04:00</published>
<updated>2017-07-16T00:00:00-04:00</updated>
<id>http://bennettadams.net/Careers</id>
<content type="html" xml:base="http://bennettadams.net/Careers/"></content>
<author>
<name></name>
</author>
<category term="UI/UX Design, Web Development" />
<summary type="html"></summary>
</entry>
<entry>
<title type="html">Registration Redesign</title>
<link href="http://bennettadams.net/registration/" rel="alternate" type="text/html" title="Registration Redesign" />
<published>2014-07-16T00:00:00-04:00</published>
<updated>2014-07-16T00:00:00-04:00</updated>
<id>http://bennettadams.net/registration</id>
<content type="html" xml:base="http://bennettadams.net/registration/"></content>
<author>
<name></name>
</author>
<category term="Web Development" />
<summary type="html"></summary>
</entry>
</feed>
| {
"content_hash": "64b95fa7df8fbce4cf7f0fcdb2890322",
"timestamp": "",
"source": "github",
"line_count": 328,
"max_line_length": 676,
"avg_line_length": 40.448170731707314,
"alnum_prop": 0.6670686666164167,
"repo_name": "beadams86/portfolio",
"id": "9f1f76c1cd6426a5ed3635e17bcaf612ee1b974f",
"size": "13319",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "_site/feed.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "24834"
},
{
"name": "HTML",
"bytes": "311542"
},
{
"name": "JavaScript",
"bytes": "82384"
},
{
"name": "PHP",
"bytes": "2398"
},
{
"name": "Ruby",
"bytes": "1170"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>mathcomp-analysis: Black list 🏴☠️</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.9.0 / mathcomp-analysis - 0.3.4</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
mathcomp-analysis
<small>
0.3.4
<span class="label label-default">Black list 🏴☠️</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-11-25 09:17:08 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-25 09:17:08 UTC)</em><p>
<div class="alert alert-info" role="alert">
<p>This result is black-listed as it is considered as too hard to reproduce / to solve. If you find a way to fix this package, please make a pull-request to <a class="alert-link" href="https://github.com/coq/opam-coq-archive">github.com/coq/opam-coq-archive</a>. The list of black-listed packages is in <a class="alert-link" href="https://github.com/coq-bench/make-html/blob/master/black_list.rb">black_list.rb</a>.</p>
</div>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.9.0 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.02.3 The OCaml compiler (virtual package)
ocaml-base-compiler 4.02.3 Official 4.02.3 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Reynald Affeldt <reynald.affeldt@aist.go.jp>"
version: "dev"
homepage: "https://github.com/math-comp/analysis"
dev-repo: "git+https://github.com/math-comp/analysis.git"
bug-reports: "https://github.com/math-comp/analysis/issues"
license: "CECILL-C"
synopsis: "An analysis library for mathematical components"
description: """
This repository contains an experimental library for real analysis for
the Coq proof-assistant and using the Mathematical Components library."""
build: [make "-j%{jobs}%" ]
install: [make "install"]
depends: [
"coq" { (>= "8.11" & < "8.13~") | (= "dev") }
"coq-mathcomp-ssreflect" { (>= "1.11.0" & < "1.12~") }
"coq-mathcomp-bigenough" {(>= "1.0.0")}
"coq-mathcomp-fingroup" { (>= "1.11.0" & < "1.12~") }
"coq-mathcomp-algebra" { (>= "1.11.0" & < "1.12~") }
"coq-mathcomp-solvable" { (>= "1.11.0" & < "1.12~") }
"coq-mathcomp-field" { (>= "1.11.0" & < "1.12~") }
"coq-mathcomp-finmap" { (>= "1.5.0" & < "1.6~") }
"coq-hierarchy-builder" { (>= "0.10.0" & < "0.11~") }
]
tags: [
"keyword:analysis"
"keyword:topology"
"keyword:real numbers"
"logpath:mathcomp.analysis"
]
authors: [
"Reynald Affeldt"
"Cyril Cohen"
"Marie Kerjean"
"Assia Mahboubi"
"Damien Rouhling"
"Kazuhiko Sakaguchi"
"Pierre-Yves Strub"
]
url {
http: "https://github.com/math-comp/analysis/archive/0.3.4.tar.gz"
checksum: "sha512=d17ccb9accfc2812accf3c289c89c559421823e3e96d8478d00f8d8c3518aef540674836da82f708410901e9447cc1ea654fd5c45a65f90f776b8e94f9015a41"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-mathcomp-analysis.0.3.4 coq.8.9.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.9.0).
The following dependencies couldn't be met:
- coq-mathcomp-analysis -> coq >= dev -> ocaml >= 4.05.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-mathcomp-analysis.0.3.4</code></dd>
<dt>Return code</dt>
<dd>15360</dd>
<dt>Output</dt>
<dd><pre>The following actions will be performed:
- remove coq 8.9.0
<><> Processing actions <><><><><><><><><><><><><><><><><><><><><><><><><><><><>
[WARNING] While removing coq.8.9.0: not removing files that changed since:
- bin/coqtop.opt
- bin/coqtacticworker.opt
- bin/coqtacticworker.byte
- bin/coqqueryworker.opt
- bin/coqqueryworker.byte
- bin/coqproofworker.opt
- bin/coqproofworker.byte
- bin/coqpp
- bin/coqidetop.opt
- bin/coqidetop
-> removed coq.8.9.0
Done.
# Run eval $(opam env) to update the current shell environment
[ERROR] Sorry, resolution of the request timed out.
Try to specify a simpler request, use a different solver, or increase the allowed time by setting OPAMSOLVERTIMEOUT to a bigger value (currently, it is set to 600.0 seconds).
</pre></dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "55455314af76f282a59e8981f4a1dba7",
"timestamp": "",
"source": "github",
"line_count": 209,
"max_line_length": 433,
"avg_line_length": 46.34928229665072,
"alnum_prop": 0.5689067822855374,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "830dcb55f1cd14320bace0dd1bc1291b80ba0cbe",
"size": "9724",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.02.3-2.0.6/released/8.9.0/mathcomp-analysis/0.3.4.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
code for the node.js in action book
| {
"content_hash": "0ece88641787b0dd70b057f46ca11bd4",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 35,
"avg_line_length": 36,
"alnum_prop": 0.7777777777777778,
"repo_name": "ming3000/node_in_action",
"id": "884d2cfa17ab8acbf50d6d3d51412d914c042dd3",
"size": "53",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "149"
},
{
"name": "JavaScript",
"bytes": "17887"
}
],
"symlink_target": ""
} |
#include "include/tv-callbacks.h"
#include <app-common/zap-generated/att-storage.h>
#include <app-common/zap-generated/attribute-type.h>
#include <app-common/zap-generated/attributes/Accessors.h>
#include <app/CommandHandler.h>
#include <app/clusters/identify-server/identify-server.h>
#include <app/clusters/network-commissioning/network-commissioning.h>
#include <app/server/Server.h>
#include <app/util/af.h>
#include <lib/support/CHIPMem.h>
#include <new>
#include <platform/Linux/NetworkCommissioningDriver.h>
#include <platform/PlatformManager.h>
#include <system/SystemPacketBuffer.h>
#include <transport/SessionManager.h>
#include <transport/raw/PeerAddress.h>
#include <Options.h>
using namespace chip;
using namespace chip::app;
using namespace chip::DeviceLayer;
namespace {
static LowPowerManager lowPowerManager;
} // namespace
bool emberAfBasicClusterMfgSpecificPingCallback(chip::app::CommandHandler * commandObj)
{
emberAfSendDefaultResponse(emberAfCurrentCommand(), EMBER_ZCL_STATUS_SUCCESS);
return true;
}
void OnIdentifyStart(::Identify *)
{
ChipLogProgress(Zcl, "OnIdentifyStart");
}
void OnIdentifyStop(::Identify *)
{
ChipLogProgress(Zcl, "OnIdentifyStop");
}
void OnTriggerEffect(::Identify * identify)
{
switch (identify->mCurrentEffectIdentifier)
{
case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK:
ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK");
break;
case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE:
ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE");
break;
case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY:
ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY");
break;
case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE:
ChipLogProgress(Zcl, "EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE");
break;
default:
ChipLogProgress(Zcl, "No identifier effect");
return;
}
}
static Identify gIdentify0 = {
chip::EndpointId{ 0 }, OnIdentifyStart, OnIdentifyStop, EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_VISIBLE_LED, OnTriggerEffect,
};
static Identify gIdentify1 = {
chip::EndpointId{ 1 }, OnIdentifyStart, OnIdentifyStop, EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_VISIBLE_LED, OnTriggerEffect,
};
// Network commissioning
namespace {
// This file is being used by platforms other than Linux, so we need this check to disable related features since we only
// implemented them on linux.
constexpr EndpointId kNetworkCommissioningEndpointMain = 0;
constexpr EndpointId kNetworkCommissioningEndpointSecondary = 0xFFFE;
#if CHIP_DEVICE_LAYER_TARGET_LINUX
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
NetworkCommissioning::LinuxThreadDriver sLinuxThreadDriver;
Clusters::NetworkCommissioning::Instance sThreadNetworkCommissioningInstance(kNetworkCommissioningEndpointMain,
&sLinuxThreadDriver);
#endif
#if CHIP_DEVICE_CONFIG_ENABLE_WPA
NetworkCommissioning::LinuxWiFiDriver sLinuxWiFiDriver;
Clusters::NetworkCommissioning::Instance sWiFiNetworkCommissioningInstance(kNetworkCommissioningEndpointSecondary,
&sLinuxWiFiDriver);
#endif
NetworkCommissioning::LinuxEthernetDriver sLinuxEthernetDriver;
Clusters::NetworkCommissioning::Instance sEthernetNetworkCommissioningInstance(kNetworkCommissioningEndpointMain,
&sLinuxEthernetDriver);
#else // CHIP_DEVICE_LAYER_TARGET_LINUX
Clusters::NetworkCommissioning::NullNetworkDriver sNullNetworkDriver;
Clusters::NetworkCommissioning::Instance sNullNetworkCommissioningInstance(kNetworkCommissioningEndpointMain, &sNullNetworkDriver);
#endif // CHIP_DEVICE_LAYER_TARGET_LINUX
} // namespace
void ApplicationInit()
{
(void) kNetworkCommissioningEndpointMain;
// Enable secondary endpoint only when we need it, this should be applied to all platforms.
emberAfEndpointEnableDisable(kNetworkCommissioningEndpointSecondary, false);
#if CHIP_DEVICE_LAYER_TARGET_LINUX
const bool kThreadEnabled = {
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
LinuxDeviceOptions::GetInstance().mThread
#else
false
#endif
};
const bool kWiFiEnabled = {
#if CHIP_DEVICE_CONFIG_ENABLE_WPA
LinuxDeviceOptions::GetInstance().mWiFi
#else
false
#endif
};
if (kThreadEnabled && kWiFiEnabled)
{
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
sThreadNetworkCommissioningInstance.Init();
#endif
#if CHIP_DEVICE_CONFIG_ENABLE_WPA
sWiFiNetworkCommissioningInstance.Init();
#endif
// Only enable secondary endpoint for network commissioning cluster when both WiFi and Thread are enabled.
emberAfEndpointEnableDisable(kNetworkCommissioningEndpointSecondary, true);
}
else if (kThreadEnabled)
{
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
sThreadNetworkCommissioningInstance.Init();
#endif
}
else if (kWiFiEnabled)
{
#if CHIP_DEVICE_CONFIG_ENABLE_WPA
// If we only enable WiFi on this device, "move" WiFi instance to main NetworkCommissioning cluster endpoint.
sWiFiNetworkCommissioningInstance.~Instance();
new (&sWiFiNetworkCommissioningInstance)
Clusters::NetworkCommissioning::Instance(kNetworkCommissioningEndpointMain, &sLinuxWiFiDriver);
sWiFiNetworkCommissioningInstance.Init();
#endif
}
else
#endif // CHIP_DEVICE_LAYER_TARGET_LINUX
{
#if CHIP_DEVICE_LAYER_TARGET_LINUX
sEthernetNetworkCommissioningInstance.Init();
#else
// Use NullNetworkCommissioningInstance to disable the network commissioning functions.
sNullNetworkCommissioningInstance.Init();
#endif
}
}
void emberAfLowPowerClusterInitCallback(EndpointId endpoint)
{
ChipLogProgress(Zcl, "TV Linux App: LowPower::SetDefaultDelegate");
chip::app::Clusters::LowPower::SetDefaultDelegate(endpoint, &lowPowerManager);
}
| {
"content_hash": "dc726a52ece021795a972fdb36279f28",
"timestamp": "",
"source": "github",
"line_count": 169,
"max_line_length": 131,
"avg_line_length": 35.69230769230769,
"alnum_prop": 0.7395557029177718,
"repo_name": "project-chip/connectedhomeip",
"id": "7829f3a6c1894ae5501b45e8de23a57242fb9625",
"size": "6699",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "examples/all-clusters-minimal-app/linux/main-common.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1759301"
},
{
"name": "C++",
"bytes": "19104548"
},
{
"name": "CMake",
"bytes": "140510"
},
{
"name": "Dockerfile",
"bytes": "50353"
},
{
"name": "Emacs Lisp",
"bytes": "1042"
},
{
"name": "Java",
"bytes": "167719"
},
{
"name": "JavaScript",
"bytes": "2106"
},
{
"name": "Jinja",
"bytes": "22322"
},
{
"name": "Objective-C",
"bytes": "930838"
},
{
"name": "Objective-C++",
"bytes": "435348"
},
{
"name": "Python",
"bytes": "1931007"
},
{
"name": "Shell",
"bytes": "195843"
},
{
"name": "Tcl",
"bytes": "311"
},
{
"name": "ZAP",
"bytes": "584219"
}
],
"symlink_target": ""
} |
<?php
namespace Vivo\Transliterator;
use Zend\Stdlib\ArrayUtils;
use Zend\EventManager\EventManager;
use Zend\Cache\Storage\StorageInterface as Cache;
/**
* Transliterator
* General transliterator implementation
*/
class Transliterator implements TransliteratorInterface
{
/**#@+
* Constant signalling required case change
*/
const CASE_CHANGE_TO_LOWER = -1;
const CASE_CHANGE_TO_UPPER = 1;
const CASE_CHANGE_NONE = 0;
/**#@-*/
/**
* Already transliterated results
* @var array
*/
protected $transliterated = array();
/**
* Event Manager
* @var EventManager
*/
protected $eventManager;
/**
* Cache
* @var Cache
*/
protected $cache;
/**
* Transliterator options
* @var array
*/
protected $options = array(
//Transliteration map
'map' => array(),
//String with all allowed characters
'allowedChars' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
//Character used to replace illegal characters
'replacementChar' => '-',
//Change case before processing
'caseChangePre' => self::CASE_CHANGE_NONE,
//Change case after processing
'caseChangePost' => self::CASE_CHANGE_NONE,
);
/**
* Constructor
* @param \Zend\Cache\Storage\StorageInterface $cache
* @param array $options
* @throws Exception\InvalidArgumentException
*/
public function __construct(Cache $cache = null, array $options = array())
{
$this->cache = $cache;
$this->options = ArrayUtils::merge($this->options, $options);
if (mb_strpos($this->options['allowedChars'], $this->options['replacementChar']) === false) {
throw new Exception\InvalidArgumentException(
sprintf("%s: Replacement character '%s' missing in allowed characters '%s'",
__METHOD__, $this->options['replacementChar'], $this->options['allowedChars']));
}
}
/**
* Transliterates string
* @param string $str
* @return string
*/
public function transliterate($str)
{
//Get from already transliterated
$hash = hash('md4', $str);
//Get transliterated string from results cached in memory (in this instance)
if (array_key_exists($hash, $this->transliterated)) {
$transliterated = $this->transliterated[$hash];
return $transliterated;
}
//Get transliterated string from standard cache
if ($this->cache) {
$cacheSuccess = null;
$transliterated = $this->cache->getItem($hash, $cacheSuccess);
if ($cacheSuccess) {
return $transliterated;
}
}
//Perform transliteration
$translit = $str;
//Change case PRE
switch ($this->options['caseChangePre']) {
case self::CASE_CHANGE_TO_LOWER:
$translit = mb_strtolower($translit);
break;
case self::CASE_CHANGE_TO_UPPER:
$translit = mb_strtoupper($translit);
break;
}
//Replace according to the map
//The RE processing replaced with strtr to optimize performance
// foreach ($this->options['map'] as $from => $to) {
// $re = sprintf('\\%s', $from);
// $str = mb_ereg_replace($re, $to, $str);
// }
foreach ($this->options['map'] as $from => $to) {
$translit = strtr($translit, array($from => $to));
}
$replacementCharLength = mb_strlen($this->options['replacementChar']);
//Replace illegal chars with the replacement char
$cleaned = '';
$len = mb_strlen($translit);
for ($i = 0; $i < $len; $i++) {
$chr = mb_substr($translit, $i, 1);
$cleaned .= (mb_strpos($this->options['allowedChars'], $chr) !== false)
? $chr : $this->options['replacementChar'];
}
$translit = $cleaned;
//Remove duplicated replacement chars
$re = sprintf('\\%s+', $this->options['replacementChar']);
$translit = mb_ereg_replace($re, $this->options['replacementChar'], $translit);
//Remove leading replacement char
//The RE processing replaced with mb_... functions to optimize performance
// $re = sprintf('^\\%s', $this->options['replacementChar']);
// $translit = mb_ereg_replace($re, '', $translit);
if (mb_substr($translit, 0, $replacementCharLength) == $this->options['replacementChar']) {
$translit = mb_substr($translit, $replacementCharLength);
}
//Remove trailing replacement char
//The RE processing replaced with mb_... functions to optimize performance
// $re = sprintf('\\%s$', $this->options['replacementChar']);
// $translit = mb_ereg_replace($re, '', $translit);
$translitLength = mb_strlen($translit);
if (mb_substr($translit, $translitLength - $replacementCharLength) == $this->options['replacementChar']) {
$translit = mb_substr($translit, 0, -$replacementCharLength);
}
//Change case POST
switch ($this->options['caseChangePost']) {
case self::CASE_CHANGE_TO_LOWER:
$translit = mb_strtolower($translit);
break;
case self::CASE_CHANGE_TO_UPPER:
$translit = mb_strtoupper($translit);
break;
}
//Store the result to the local cache and standard cache
$this->transliterated[$hash] = $translit;
if ($this->cache) {
$this->cache->setItem($hash, $translit);
}
return $translit;
}
/**
* Returns Event Manager
* @return \Zend\EventManager\EventManager
*/
public function getEventManager()
{
if (!$this->eventManager) {
$this->setEventManager(new EventManager());
}
return $this->eventManager;
}
/**
* Sets Event manager
* @param \Zend\EventManager\EventManager $eventManager
*/
public function setEventManager(EventManager $eventManager)
{
$this->eventManager = $eventManager;
}
}
| {
"content_hash": "a9244b921d9817b2101e335631884ed6",
"timestamp": "",
"source": "github",
"line_count": 191,
"max_line_length": 114,
"avg_line_length": 33.64921465968586,
"alnum_prop": 0.5601369223587989,
"repo_name": "miroslavhajek/vivoportal",
"id": "b76bf0b80f780c86e0728245c7cba7d095c35d7a",
"size": "6427",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/Vivo/Transliterator/Transliterator.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "435160"
},
{
"name": "JavaScript",
"bytes": "399518"
},
{
"name": "PHP",
"bytes": "1732609"
}
],
"symlink_target": ""
} |
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
<predicate lemma="frustration">
<roleset framnet="" id="frustration.01" name="cause angst" source="verb-frustrate.01" vncls="31.1">
<roles>
<role descr="causer of frustration" f="" n="0">
<vnrole vncls="31.1" vntheta="cause"/>
</role>
<role descr="experiencer, entity frustrated" f="ppt" n="1">
<vnrole vncls="31.1" vntheta="experiencer"/>
</role>
<note>This is a comparison to frustrate.01, however arg 2, target has been deleted. This is because arg 0 covers this and it is not possible to have both arguments.</note>
</roles>
<example name="both args" src="" type="">
<text>Democratic frustration with the Reagan victories and Court appointments, the contingency plans in place, and Mr. Bork 's
paper trail of vulnerable writings
</text>
<arg f="" n="1">Democratic</arg>
<rel f="">frustration</rel>
<arg f="" n="0">with the Reagan victories and Court appointments, the contingency plans in place, and Mr. Bork 's paper trail of vulnerable writings</arg>
<note/>
</example>
<example name="arg 1 only" src="" type="">
<text>their brotherly love, resentment, frustration, rage</text>
<arg f="" n="1">their</arg>
<rel f="">frustration</rel>
<note/>
</example>
<example name="Arg 1 modifying the noun" src="" type="">
<inflection aspect="ns" form="ns" person="ns" tense="ns" voice="ns"/>
<text>Much to these cities' frustration</text>
<arg f="" n="1">these cities'</arg>
<rel f="">frustration</rel>
<note/>
</example>
<note>Based on sentences in nouns-00040. Comparison to frustrate.01. Vn class amuse-31.1. Framed by Katie.</note>
</roleset>
<note/>
</predicate>
<note/>
</frameset>
| {
"content_hash": "c020536d8aae0e596b0824df69e21ba2",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 187,
"avg_line_length": 43.407407407407405,
"alnum_prop": 0.4927474402730375,
"repo_name": "TeamSPoon/logicmoo_workspace",
"id": "c2239bc509b546bd313f7877df6c4da4402a47c9",
"size": "2344",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packs_sys/logicmoo_nlu/ext/pldata/propbank-frames-2.1.5/frames/frustration-n.xml",
"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": ""
} |
export RED='\x1b[0;31m'
export GREEN='\x1b[38;5;22m'
export CYAN='\x1b[36m'
export YELLOW='\x1b[33m'
export NO_COLOR='\x1b[0m'
if [ -z "${LOG_TITLE}" ]; then
LOG_TITLE=''
fi
if [ -z "${LOG_LEVEL}" ]; then
LOG_LEVEL="INFO"
fi
debug() {
if [[ "${LOG_LEVEL}" == "DEBUG" ]]; then
local log_title
if [ -n "${LOG_TITLE}" ]; then
log_title="(${LOG_TITLE})"
else
log_title=''
fi
echo -e "${GREEN}[DEBUG]${log_title} ${NO_COLOR}$1"
fi
}
info() {
if [[ "${LOG_LEVEL}" == "DEBUG" ]] ||\
[[ "${LOG_LEVEL}" == "INFO" ]]; then
local log_title
if [ -n "${LOG_TITLE}" ]; then
log_title="(${LOG_TITLE})"
else
log_title=''
fi
echo -e "${CYAN}[INFO] ${log_title} ${NO_COLOR}$1"
fi
}
warn() {
if [[ "${LOG_LEVEL}" == "DEBUG" ]] ||\
[[ "${LOG_LEVEL}" == "INFO" ]] ||\
[[ "${LOG_LEVEL}" == "WARN" ]]; then
local log_title
if [ -n "${LOG_TITLE}" ]; then
log_title="(${LOG_TITLE})"
else
log_title=''
fi
echo -e "${YELLOW}[WARN] ${log_title} ${NO_COLOR}$1"
fi
}
error() {
if [[ "${LOG_LEVEL}" == "DEBUG" ]] ||\
[[ "${LOG_LEVEL}" == "INFO" ]] ||\
[[ "${LOG_LEVEL}" == "WARN" ]] ||\
[[ "${LOG_LEVEL}" == "ERROR" ]]; then
local log_title
if [ -n "${LOG_TITLE}" ]; then
log_title="(${LOG_TITLE})"
else
log_title=''
fi
echo -e "${RED}[ERROR]${log_title} ${NO_COLOR}$1"
fi
}
detect_node_os()
{
local pod="$1"
OS=`kubectl exec -i $pod -- nsenter --mount=/proc/1/ns/mnt -- bash -c 'grep -E "^ID_LIKE=" /etc/os-release | cut -d= -f2'`
if [[ -z "${OS}" ]]; then
OS=`kubectl exec -i $pod -- nsenter --mount=/proc/1/ns/mnt -- bash -c 'grep -E "^ID=" /etc/os-release | cut -d= -f2'`
fi
echo "$OS"
}
set_packages_and_check_cmd()
{
case $OS in
*"debian"* | *"ubuntu"* )
CHECK_CMD='dpkg -l | grep -w'
PACKAGES=(nfs-common open-iscsi)
;;
*"centos"* | *"fedora"* | *"rocky"* | *"ol"* )
CHECK_CMD='rpm -q'
PACKAGES=(nfs-utils iscsi-initiator-utils)
;;
*"suse"* )
CHECK_CMD='rpm -q'
PACKAGES=(nfs-client open-iscsi)
;;
*"arch"* )
CHECK_CMD='pacman -Q'
PACKAGES=(nfs-utils open-iscsi)
;;
*)
CHECK_CMD=''
PACKAGES=()
warn "Stop the environment check because '$OS' is not supported in the environment check script."
exit 1
;;
esac
}
check_dependencies() {
local targets=($@)
local allFound=true
for ((i=0; i<${#targets[@]}; i++)); do
local target=${targets[$i]}
if [ "$(which $target)" == "" ]; then
allFound=false
error "Not found: $target"
fi
done
if [ "$allFound" == "false" ]; then
error "Please install missing dependencies."
exit 2
else
info "Required dependencies are installed."
fi
}
create_ds() {
cat <<EOF > $TEMP_DIR/environment_check.yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
labels:
app: longhorn-environment-check
name: longhorn-environment-check
spec:
selector:
matchLabels:
app: longhorn-environment-check
template:
metadata:
labels:
app: longhorn-environment-check
spec:
hostPID: true
containers:
- name: longhorn-environment-check
image: alpine:3.12
args: ["/bin/sh", "-c", "sleep 1000000000"]
volumeMounts:
- name: mountpoint
mountPath: /tmp/longhorn-environment-check
mountPropagation: Bidirectional
securityContext:
privileged: true
volumes:
- name: mountpoint
hostPath:
path: /tmp/longhorn-environment-check
EOF
kubectl create -f $TEMP_DIR/environment_check.yaml > /dev/null
}
cleanup() {
info "Cleaning up longhorn-environment-check pods..."
kubectl delete -f $TEMP_DIR/environment_check.yaml > /dev/null
rm -rf $TEMP_DIR
info "Cleanup completed."
}
wait_ds_ready() {
while true; do
local ds=$(kubectl get ds/longhorn-environment-check -o json)
local numberReady=$(echo $ds | jq .status.numberReady)
local desiredNumberScheduled=$(echo $ds | jq .status.desiredNumberScheduled)
if [ "$desiredNumberScheduled" == "$numberReady" ] && [ "$desiredNumberScheduled" != "0" ]; then
info "All longhorn-environment-check pods are ready ($numberReady/$desiredNumberScheduled)."
return
fi
info "Waiting for longhorn-environment-check pods to become ready ($numberReady/$desiredNumberScheduled)..."
sleep 3
done
}
check_mount_propagation() {
local allSupported=true
local pods=$(kubectl -l app=longhorn-environment-check get po -o json)
local ds=$(kubectl get ds/longhorn-environment-check -o json)
local desiredNumberScheduled=$(echo $ds | jq .status.desiredNumberScheduled)
for ((i=0; i<desiredNumberScheduled; i++)); do
local pod=$(echo $pods | jq .items[$i])
local nodeName=$(echo $pod | jq -r .spec.nodeName)
local mountPropagation=$(echo $pod | jq -r '.spec.containers[0].volumeMounts[] | select(.name=="mountpoint") | .mountPropagation')
if [ "$mountPropagation" != "Bidirectional" ]; then
allSupported=false
error "node $nodeName: MountPropagation is disabled"
fi
done
if [ "$allSupported" != "true" ]; then
error "MountPropagation is disabled on at least one node. As a result, CSI driver and Base image cannot be supported."
exit 1
else
info "MountPropagation is enabled."
fi
}
check_package_installed() {
local pods=$(kubectl get pods -o name | grep longhorn-environment-check)
local allFound=true
for pod in ${pods}; do
OS=`detect_node_os $pod`
if [ x"$OS" == x"" ]; then
error "Unable to detect OS on node $node."
exit 2
fi
set_packages_and_check_cmd "$OS"
for ((i=0; i<${#PACKAGES[@]}; i++)); do
local package=${PACKAGES[$i]}
kubectl exec -i $pod -- nsenter --mount=/proc/1/ns/mnt -- timeout 30 bash -c "$CHECK_CMD $package" > /dev/null 2>&1
if [ $? != 0 ]; then
allFound=false
node=`kubectl get ${pod} --no-headers -o=custom-columns=:.spec.nodeName`
error "$package is not found in $node."
fi
done
done
if [ "$allFound" == "false" ]; then
error "Please install missing packages."
exit 2
else
info "Required packages are installed."
fi
}
check_multipathd() {
local pods=$(kubectl get pods -o name | grep longhorn-environment-check)
local allNotFound=true
for pod in ${pods}; do
kubectl exec -t $pod -- nsenter --mount=/proc/1/ns/mnt -- bash -c "systemctl status --no-pager multipathd.service" > /dev/null 2>&1
if [ $? = 0 ]; then
allNotFound=false
node=`kubectl get ${pod} --no-headers -o=custom-columns=:.spec.nodeName`
warn "multipathd is running on $node."
fi
done
if [ "$allNotFound" == "false" ]; then
warn "multipathd would probably result in the Longhorn volume mount failure. Please refer to https://longhorn.io/kb/troubleshooting-volume-with-multipath for more information."
fi
}
check_iscsid() {
local pods=$(kubectl get pods -o name | grep longhorn-environment-check)
local allFound=true
for pod in ${pods}; do
kubectl exec -t $pod -- nsenter --mount=/proc/1/ns/mnt -- bash -c "systemctl status --no-pager iscsid.service" > /dev/null 2>&1
if [ $? != 0 ]; then
allFound=false
node=`kubectl get ${pod} --no-headers -o=custom-columns=:.spec.nodeName`
error "iscsid is not running on $node."
fi
done
if [ "$allFound" == "false" ]; then
exit 2
fi
}
DEPENDENCIES=(kubectl jq mktemp)
check_dependencies ${DEPENDENCIES[@]}
TEMP_DIR=$(mktemp -d)
trap cleanup EXIT
create_ds
wait_ds_ready
check_package_installed
check_iscsid
check_multipathd
check_mount_propagation
exit 0
| {
"content_hash": "929e9a5be190eb9a7de6a773ad6cda2d",
"timestamp": "",
"source": "github",
"line_count": 296,
"max_line_length": 180,
"avg_line_length": 26.006756756756758,
"alnum_prop": 0.6062613665887243,
"repo_name": "rancher/longhorn",
"id": "a11718bcdf6cb5b35af1434b306aea64e0cd504a",
"size": "7711",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts/environment_check.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Shell",
"bytes": "4952"
},
{
"name": "Smarty",
"bytes": "715"
}
],
"symlink_target": ""
} |
Meteor.publish('wall_posts', function (count) {
return Posts.find({}, {sort: {time: -1}, limit: count});
});
Meteor.publish('wall_post_count', function (count) {
return Posts.find();
});
| {
"content_hash": "e45c84507104818c87bb134b25142dc5",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 58,
"avg_line_length": 27.428571428571427,
"alnum_prop": 0.640625,
"repo_name": "bulletproof-meteor/bullet-eight",
"id": "b75ba72f3f997910c6b851857540ee9a5e349a87",
"size": "192",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "wall_posts/server/publications.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "413"
},
{
"name": "JavaScript",
"bytes": "4838"
},
{
"name": "Shell",
"bytes": "114"
}
],
"symlink_target": ""
} |
"""This module contains GHOP logic helper modules.
"""
| {
"content_hash": "3fbcdb469e94e182668ab116cae72669",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 50,
"avg_line_length": 27.5,
"alnum_prop": 0.7272727272727273,
"repo_name": "MatthewWilkes/mw4068-packaging",
"id": "5fc826603d9a00100e3629f42c3d2db5dc7f1855",
"size": "665",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/melange/src/soc/modules/ghop/logic/helper/__init__.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "68827"
},
{
"name": "HTML",
"bytes": "586705"
},
{
"name": "JavaScript",
"bytes": "441502"
},
{
"name": "Python",
"bytes": "2136551"
},
{
"name": "Shell",
"bytes": "5667"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.