text stringlengths 2 1.04M | meta dict |
|---|---|
/* commented out files stopped automatic test run in GOGI builds 2007-03, had to be run manually. Hallvord. */
fileArray = [ "/core/standards/scripts/jstest-futhark/DOM-regression/domimplementation.html",
"/core/standards/scripts/jstest-futhark/DOM-regression/attrnode.html",
/* "/core/standards/scripts/jstest-futhark/DOM-regression/chardata.html", */
"/core/standards/scripts/jstest-futhark/DOM-regression/document.html",
/* "/core/standards/scripts/jstest-futhark/DOM-regression/importNode1.html", */
"/core/standards/scripts/jstest-futhark/DOM-regression/except.html",
/* "/core/standards/scripts/jstest-futhark/DOM-regression/node.html", */
"/core/standards/scripts/jstest-futhark/DOM-regression/node-reflow.html",
"/core/standards/scripts/jstest-futhark/DOM-regression/text.html",
"/core/standards/scripts/jstest-futhark/DOM-regression/fragment.html",
"/core/standards/scripts/jstest-futhark/DOM-regression/nodelist.html",
/* "/core/standards/scripts/jstest-futhark/DOM-regression/element.html", */
/* "/core/standards/scripts/jstest-futhark/DOM-regression/element2.html", */
"/core/standards/scripts/jstest-futhark/DOM-regression/nodemap.html" ];
| {
"content_hash": "45fed8f58abd99443563de6fe1d71ff9",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 110,
"avg_line_length": 91.66666666666667,
"alnum_prop": 0.6596363636363637,
"repo_name": "Ms2ger/presto-testo",
"id": "68e4fb320a0972ec4fa758d5f6d327d09e49392f",
"size": "1375",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "core/standards/scripts/jstest-futhark/DOM-regression/automatable_tests.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "2312"
},
{
"name": "ActionScript",
"bytes": "23470"
},
{
"name": "AutoHotkey",
"bytes": "8832"
},
{
"name": "Batchfile",
"bytes": "5001"
},
{
"name": "C",
"bytes": "116512"
},
{
"name": "C++",
"bytes": "219233"
},
{
"name": "CSS",
"bytes": "207914"
},
{
"name": "Erlang",
"bytes": "18523"
},
{
"name": "Groff",
"bytes": "674"
},
{
"name": "HTML",
"bytes": "103272540"
},
{
"name": "Haxe",
"bytes": "3874"
},
{
"name": "Java",
"bytes": "125658"
},
{
"name": "JavaScript",
"bytes": "22516936"
},
{
"name": "Makefile",
"bytes": "13409"
},
{
"name": "PHP",
"bytes": "524911"
},
{
"name": "Perl",
"bytes": "321672"
},
{
"name": "Python",
"bytes": "948191"
},
{
"name": "Ruby",
"bytes": "1006850"
},
{
"name": "Shell",
"bytes": "12140"
},
{
"name": "Smarty",
"bytes": "1860"
},
{
"name": "XSLT",
"bytes": "2567445"
}
],
"symlink_target": ""
} |
* Add Rails 5.1 support
* Add a CHANGELOG
| {
"content_hash": "900f071ed42853545d17b75fda971d91",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 23,
"avg_line_length": 21,
"alnum_prop": 0.7142857142857143,
"repo_name": "ministrycentered/maybe_so",
"id": "a70ced4bc37930a2ae285c60e07051220d8a7514",
"size": "68",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CHANGELOG.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "7199"
}
],
"symlink_target": ""
} |
(function (window, document, angular) {
"use strict";
/**
* A fileupload component
*/
angular.module('app.widgets')
.directive('fileupload', FileUploadDirective);
FileUploadDirective.$inject = ['$rootScope', 'fileuploadService'];
/* @ngInject */
function FileUploadDirective($rootScope, fileuploadService) {
var directive = {
restrict: 'A',
templateUrl: 'app/widgets/fileupload.html',
controller: FileUploadControllerInner,
controllerAs: 'vm',
bindToController: true,
transclude: true,
scope: {
maxFiles: "=?fuMaxFiles",
maxFilesText: "=?fuMaxFilesText",
maxFileSize: "=?fuMaxFileSize",
maxFileSizeError: "=?fuMaxFileSizeError",
accept: "=fuAccept"
}
};
FileUploadControllerInner.$inject = ['$scope', '$element', '$attrs'];
/* @ngInject */
function FileUploadControllerInner($scope, $element, $attrs) {
var vm = this;
$scope.change = change;
$scope.abort = abort;
$scope.filesForUpload = [];
if (!vm.maxFiles || vm.maxFiles < 0) {
vm.maxFiles = 100;
}
function change(files) {
if (files && files.length) {
if (validate(files) === false) {
return;
}
fileuploadService.uploadFiles(files);
}
}
function abort($event, fileIdx) {
var abortedFile = $scope.filesForUpload[fileIdx].file;
$scope.filesForUpload[fileIdx].upload.abort();
$scope.filesForUpload.splice(fileIdx, 1);
}
function validate(files) {
/**
* Clears model
* @returns boolean
*/
var clearFiles = function () {
$scope.files = [];
$rootScope.$apply($scope.files);
setTimeout(function () {
$scope.files = [];
$rootScope.$apply($scope.files);
}, 0);
};
if (vm.maxFiles > 0 && $scope.filesForUpload.length + files.length > vm.maxFiles) {
alert(vm.maxFilesText);
clearFiles();
return false;
}
if (vm.maxFileSize && vm.maxFileSize > 0) {
for (var i = 0; i < files.length; ++i) {
if (files[i].size > vm.maxFileSize) {
alert(vm.maxFileSizeError);
clearFiles();
return false;
}
}
}
return true;
}
}
return directive;
}
})(window, document, angular);
| {
"content_hash": "c70eb6f3e4cc65ed545ec7c273d2923c",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 87,
"avg_line_length": 21.871287128712872,
"alnum_prop": 0.609325486645541,
"repo_name": "CESNET-Integracni-portal/integracni-portal-ui",
"id": "23c5071197b638c3fec297082ce6a3d5f5b85767",
"size": "2209",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/client/app/widgets/fileuploadDropDirective.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "244"
},
{
"name": "CSS",
"bytes": "7558"
},
{
"name": "HTML",
"bytes": "35743"
},
{
"name": "JavaScript",
"bytes": "126450"
}
],
"symlink_target": ""
} |
<!--
Copyright SemanticBits, Northwestern University and Akaza Research
Distributed under the OSI-approved BSD 3-Clause License.
See http://ncip.github.com/caaers/LICENSE.txt for details.
-->
<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>
<artifactId>caaers-registration-consumer</artifactId>
<packaging>jar</packaging>
<name>caAERS registration consumer</name>
<parent>
<groupId>gov.nih.nci.cabig.caaers</groupId>
<artifactId>caaers-grid</artifactId>
<version>1.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>gov.nih.nci.cabig.caaers</groupId>
<artifactId>caaers-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>gov.nih.nci.cabig.caaers.ext</groupId>
<artifactId>cagrid-everything</artifactId>
<version>1.0</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>gov.nih.nci.ccts.grid</groupId>
<artifactId>RegistrationConsumer-client</artifactId>
<version>0.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>gov.nih.nci.ccts.grid</groupId>
<artifactId>RegistrationConsumer-common</artifactId>
<version>0.1</version>
</dependency>
<dependency>
<groupId>gov.nih.nci.ccts.grid</groupId>
<artifactId>RegistrationConsumer-stubs</artifactId>
<version>0.1</version>
</dependency>
<dependency>
<groupId>axis</groupId>
<artifactId>axis</artifactId>
<version>1.4</version> <!-- is this the right version? -->
</dependency>
<dependency>
<groupId>axis-unofficial</groupId>
<artifactId>addressing</artifactId>
<version>1.0</version> <!-- is this the right version? -->
</dependency>
<dependency>
<groupId>org.globus</groupId>
<artifactId>globus-wsrf-mds-aggregator</artifactId>
<version>4.0-cagrid1.0</version>
</dependency>
<dependency>
<groupId>org.globus</groupId>
<artifactId>globus-wsrf-mds-aggregator-stubs</artifactId>
<version>4.0-cagrid1.0</version>
</dependency>
<dependency>
<groupId>org.globus</groupId>
<artifactId>globus-wsrf-servicegroup</artifactId>
<version>4.0-cagrid1.0</version>
</dependency>
<dependency>
<groupId>org.globus</groupId>
<artifactId>globus-wsrf-servicegroup-stubs</artifactId>
<version>4.0-cagrid1.0</version>
</dependency>
<dependency>
<groupId>org.globus</groupId>
<artifactId>wsrf-core</artifactId>
<version>4.0-cagrid1.0</version>
</dependency>
<dependency>
<groupId>org.globus</groupId>
<artifactId>wsrf-core-stubs</artifactId>
<version>4.0-cagrid1.0</version>
</dependency>
<dependency>
<groupId>org.globus</groupId>
<artifactId>cog-jglobus</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.projectmobius</groupId>
<artifactId>mobius-common-client</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.projectmobius</groupId>
<artifactId>mobius-factories</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.projectmobius</groupId>
<artifactId>mobius-gme-client</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.projectmobius</groupId>
<artifactId>mobius-mako-client</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.projectmobius</groupId>
<artifactId>mobius-tools</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<artifactId>castor</artifactId>
<groupId>castor</groupId>
<version>0.9.9</version>
</dependency>
<!-- TEST-ONLY -->
<dependency>
<groupId>${groupId}</groupId>
<artifactId>caaers-core</artifactId>
<version>${project.version}</version>
<scope>test</scope>
<type>test-jar</type>
</dependency>
<dependency> <!-- this is actually a dep of caaers-core test-jar -->
<groupId>org.springframework</groupId>
<artifactId>spring-mock</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.dbunit</groupId>
<artifactId>dbunit</artifactId>
<version>2.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>xmlunit</groupId>
<artifactId>xmlunit</artifactId>
<version>1.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<executions>
<execution>
<configuration>
<source>1.5</source>
</configuration>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "5bf78891ba4b432ea730377b9027c6d0",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 204,
"avg_line_length": 35.56896551724138,
"alnum_prop": 0.5451607691064793,
"repo_name": "CBIIT/caaers",
"id": "d419910e18f7ef9c48e9e9539e32b21779bf6967",
"size": "6189",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "caAERS/software/grid/lab-consumer/pom.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AGS Script",
"bytes": "127"
},
{
"name": "AspectJ",
"bytes": "2052"
},
{
"name": "Batchfile",
"bytes": "778"
},
{
"name": "CSS",
"bytes": "150327"
},
{
"name": "Cucumber",
"bytes": "666"
},
{
"name": "Groovy",
"bytes": "19198183"
},
{
"name": "HTML",
"bytes": "78184618"
},
{
"name": "Java",
"bytes": "14455656"
},
{
"name": "JavaScript",
"bytes": "439130"
},
{
"name": "PLSQL",
"bytes": "75583"
},
{
"name": "PLpgSQL",
"bytes": "34461"
},
{
"name": "Ruby",
"bytes": "29724"
},
{
"name": "Shell",
"bytes": "14770"
},
{
"name": "XSLT",
"bytes": "1262163"
}
],
"symlink_target": ""
} |
/*********************************************************************************
* (Demonstrate TextArea properties) Write a program that demonstrates the *
* properties of a text area. The program uses a check box to indicate whether *
* the text is wrapped onto next line, as shown in Figure 16.41a. *
*********************************************************************************/
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.control.TextArea;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.geometry.Pos;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
public class Exercise_16_12 extends Application {
@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Create a text area
TextArea textArea = new TextArea();
textArea.setEditable(false);
textArea.setWrapText(false);
// Create a scrollPane
ScrollPane scrollPane = new ScrollPane(textArea);
// Create two check boxes
CheckBox chkEditable = new CheckBox("Editable");
CheckBox chkWrap = new CheckBox("Wrap");
// Create a hbox
HBox paneForButtons = new HBox(5);
paneForButtons.setAlignment(Pos.CENTER);
paneForButtons.getChildren().addAll(chkEditable, chkWrap);
// Create a pane
BorderPane pane = new BorderPane();
pane.setCenter(scrollPane);
pane.setBottom(paneForButtons);
// Create and register handlers
chkEditable.setOnAction(e -> {
textArea.setEditable(chkEditable.isSelected());
});
chkWrap.setOnAction(e -> {
textArea.setWrapText(chkWrap.isSelected());
});
// Create a scene and place it in the stage
Scene scene = new Scene(pane);
primaryStage.setTitle("Exercise_16_12"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
} | {
"content_hash": "5c0e57d2c112815df0a4bae83b1b20aa",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 82,
"avg_line_length": 34.92982456140351,
"alnum_prop": 0.6780512305374183,
"repo_name": "jsquared21/Intro-to-Java-Programming",
"id": "6787d2277fc6be72e36b2345efee9f64d6a21743",
"size": "1991",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Exercise_16/Exercise_16_12/Exercise_16_12.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1522444"
},
{
"name": "Roff",
"bytes": "79527"
}
],
"symlink_target": ""
} |
static const ossimKeyword
NUMBER_LINES("number_lines",
"Number of lines in the raster image.");
static const ossimKeyword
NUMBER_SAMPLES("number_samples",
"Number of samples in the raster image.");
static const ossimKeyword
VALID_START_LINE("valid_start_line",
"First valid line of raster image(zero based).");
static const ossimKeyword
VALID_STOP_LINE("valid_stop_line",
"Last valid line of raster image(zero based).");
static const ossimKeyword
VALID_START_SAMPLE("valid_start_sample",
"First valid sample of raster image(zero based).");
static const ossimKeyword
VALID_STOP_SAMPLE("valid_stop_sample",
"Last valid sample of raster image(zero based).");
static const ossimKeyword
SUB_IMAGE_OFFSET_LINE(
"sub_image_offset_line",
"Pixel line offset of sub-image in the full-image pixel space.");
static const ossimKeyword
SUB_IMAGE_OFFSET_SAMP(
"sub_image_offset_samp",
"Pixel sample offset of sub-image in the full-image pixel space.");
static const ossimKeyword
HEADER_SIZE("header_size",
"Header size in bytes.");
static const ossimKeyword
SET_NULLS("set_fill_to_nulls_mode",
"0 = do nothing to pixels,\n1 = all zeroes to min values,\
\n2 = zeroes to null on edges only.");
static const ossimKeyword
PIXELS_TO_CHOP("pixels_to_chop",
"Amount of pixels to chop from edge.");
static const ossimInterleaveTypeLut INTERLEAVE_TYPE_LUT;
static ossimTrace traceDebug("ossimGeneralRasterInfo:debug");
ossimGeneralRasterInfo::ossimGeneralRasterInfo()
:
theMetaData(),
theImageFileList(),
theInterleaveType(OSSIM_BIL),
theRawImageRect(),
theValidImageRect(),
theImageRect(),
theSubImageOffset(0,0),
theHeaderSize(0),
theSetNullsMode(NONE),
thePixelsToChop(0),
theImageDataByteOrder(OSSIM_LITTLE_ENDIAN)
{
theRawImageRect.makeNan();
theValidImageRect.makeNan();
theImageRect.makeNan();
}
ossimGeneralRasterInfo::ossimGeneralRasterInfo(const std::vector<ossimFilename>& imageFileList,
ossimScalarType pixelType,
ossimInterleaveType il_type,
ossim_int32 numberOfBands,
ossim_int32 lines,
ossim_int32 samples,
ossim_int32 headerSize,
ossimFillMode nullsMode,
ossim_int32 pixelsToChop)
:
theMetaData(pixelType, numberOfBands),
theImageFileList(imageFileList),
theInterleaveType(il_type),
theRawImageRect(0,0,0,0),
theValidImageRect(0,0,0,0),
theImageRect(0,0,0,0),
theSubImageOffset(0,0),
theHeaderSize(headerSize),
theSetNullsMode(nullsMode),
thePixelsToChop(pixelsToChop),
theImageDataByteOrder(OSSIM_LITTLE_ENDIAN)
{
theRawImageRect.set_lry(lines - 1);
theRawImageRect.set_lrx(samples - 1);
theValidImageRect = theRawImageRect;
theImageRect = theRawImageRect;
}
ossimGeneralRasterInfo::ossimGeneralRasterInfo(const ossimKeywordlist& kwl,
const char* prefix)
:
theImageFileList(),
theInterleaveType(OSSIM_BIL),
theRawImageRect(0,0,0,0),
theValidImageRect(0,0,0,0),
theImageRect(0,0,0,0),
theSubImageOffset(0,0),
theHeaderSize(0),
theSetNullsMode(NONE),
thePixelsToChop(0),
theImageDataByteOrder(OSSIM_LITTLE_ENDIAN)
{
theRawImageRect.makeNan();
theValidImageRect.makeNan();
theImageRect.makeNan();
loadState(kwl, prefix);
}
ossimGeneralRasterInfo::ossimGeneralRasterInfo( const ossimGeneralRasterInfo& obj )
:
theMetaData ( obj.theMetaData ),
theImageFileList ( obj.theImageFileList ),
theInterleaveType ( obj.theInterleaveType ),
theRawImageRect ( obj.theRawImageRect ),
theValidImageRect ( obj.theValidImageRect ),
theImageRect ( obj.theImageRect ),
theSubImageOffset ( obj.theSubImageOffset ),
theHeaderSize ( obj.theHeaderSize ),
theSetNullsMode ( obj.theSetNullsMode ),
thePixelsToChop ( obj.thePixelsToChop ),
theImageDataByteOrder ( obj.theImageDataByteOrder )
{
}
const ossimGeneralRasterInfo& ossimGeneralRasterInfo::operator=(
const ossimGeneralRasterInfo& rhs )
{
if ( this != &rhs )
{
theMetaData = rhs.theMetaData;
theImageFileList = rhs.theImageFileList;
theInterleaveType = rhs.theInterleaveType;
theRawImageRect = rhs.theRawImageRect;
theValidImageRect = rhs.theValidImageRect;
theImageRect = rhs.theImageRect;
theSubImageOffset = rhs.theSubImageOffset;
theHeaderSize = rhs.theHeaderSize;
theSetNullsMode = rhs.theSetNullsMode;
thePixelsToChop = rhs.thePixelsToChop;
theImageDataByteOrder = rhs.theImageDataByteOrder;
}
return *this;
}
ossimGeneralRasterInfo::~ossimGeneralRasterInfo()
{
}
void ossimGeneralRasterInfo::clear()
{
theMetaData.clear();
theImageFileList.clear();
theInterleaveType = OSSIM_BIL;
theRawImageRect.makeNan();
theValidImageRect.makeNan();
theImageRect.makeNan();
theSubImageOffset.x = 0;
theSubImageOffset.y = 0;
theHeaderSize = 0;
theSetNullsMode = NONE;
thePixelsToChop = 0;
theImageDataByteOrder = OSSIM_LITTLE_ENDIAN;
}
const ossimIrect& ossimGeneralRasterInfo::imageRect() const
{
return theImageRect;
}
const ossimIrect& ossimGeneralRasterInfo::validImageRect() const
{
return theValidImageRect;
}
const ossimIrect& ossimGeneralRasterInfo::rawImageRect() const
{
return theRawImageRect;
}
const ossimIpt& ossimGeneralRasterInfo::subImageOffset() const
{
return theSubImageOffset;
}
ossim_int32 ossimGeneralRasterInfo::headerSize() const
{
return theHeaderSize;
}
ossim_uint32 ossimGeneralRasterInfo::fillToNullsMode() const
{
return theSetNullsMode;
}
std::ostream& ossimGeneralRasterInfo::print(std::ostream& out) const
{
//---
// This will print in a keyword format that can be read by the constructor.
// that takes a keyword list.
//---
ossimKeywordlist kwl;
saveState( kwl, 0 );
out << kwl << std::endl;
return out;
}
void ossimGeneralRasterInfo::setFillToNullsMode(ossim_uint32 mode)
{
static const char MODULE[] = "ossimGeneralRasterInfo::setFillToNullMode";
if(mode < 3)
{
theSetNullsMode = (ossimFillMode)mode;
}
else
{
ossimNotify(ossimNotifyLevel_WARN)
<< MODULE << " ERROR:"
<< "\nmode out of bounds(0 - 2): " << mode << std::endl
<< "\nmode has not been changed." << std::endl;
}
}
ossim_int32 ossimGeneralRasterInfo::pixelsToChop() const
{
return thePixelsToChop;
}
ossimInterleaveType ossimGeneralRasterInfo::interleaveType() const
{
return theInterleaveType;
}
const std::vector<ossimFilename>& ossimGeneralRasterInfo::getImageFileList() const
{
return theImageFileList;
}
void ossimGeneralRasterInfo::setImageFileList(const std::vector<ossimFilename>& list)
{
theImageFileList = list;
}
void ossimGeneralRasterInfo::setImageFile(const ossimFilename& file)
{
theImageFileList.clear();
theImageFileList.push_back( file );
}
void ossimGeneralRasterInfo::setImageDataByteOrder(ossimByteOrder byteOrder)
{
theImageDataByteOrder = byteOrder;
}
void ossimGeneralRasterInfo::setHeaderSize(ossim_int32 headerSize)
{
theHeaderSize = headerSize;
}
void ossimGeneralRasterInfo::setInterleaveType(ossimInterleaveType il_type)
{
theInterleaveType = il_type;
}
void ossimGeneralRasterInfo::setImageRect(const ossimIrect& imageRect)
{
theImageRect = imageRect;
}
void ossimGeneralRasterInfo::setValidImageRect(const ossimIrect &imageRect)
{
theValidImageRect = imageRect;
}
void ossimGeneralRasterInfo::setRawImageRect(const ossimIrect &imageRect)
{
theRawImageRect = imageRect;
}
void ossimGeneralRasterInfo::setSubImageOffset(const ossimIpt& d)
{
theSubImageOffset = d;
}
ossimByteOrder ossimGeneralRasterInfo::getImageDataByteOrder() const
{
return theImageDataByteOrder;
}
bool ossimGeneralRasterInfo::saveState(ossimKeywordlist& kwl,
const char* prefix) const
{
for (ossim_uint32 i=0; i<theImageFileList.size(); ++i)
{
ossimString kw = ossimKeywordNames::FILENAME_KW;
kw += ossimString::toString(i+1);
kwl.add(prefix, theImageFileList[i].c_str());
}
theMetaData.saveState(kwl, prefix);
kwl.add(prefix,
NUMBER_LINES,
ossimString::toString( rawLines() ), true);
kwl.add(prefix,
NUMBER_SAMPLES,
ossimString::toString( rawSamples() ),
true);
kwl.add(prefix,
HEADER_SIZE,
ossimString::toString(theHeaderSize),
true);
kwl.add(prefix,
SUB_IMAGE_OFFSET_LINE,
theSubImageOffset.line,
true);
kwl.add(prefix,
SUB_IMAGE_OFFSET_SAMP,
theSubImageOffset.samp,
true);
kwl.add(prefix,
VALID_START_LINE,
theValidImageRect.ul().y,
true);
kwl.add(prefix,
VALID_STOP_LINE,
theValidImageRect.lr().y,
true);
kwl.add(prefix,
VALID_START_SAMPLE,
theValidImageRect.ul().x,
true);
kwl.add(prefix,
VALID_STOP_SAMPLE,
theValidImageRect.ur().x,
true);
kwl.add(prefix,
ossimKeywordNames::INTERLEAVE_TYPE_KW,
INTERLEAVE_TYPE_LUT.getEntryString(theInterleaveType),
true);
kwl.add(prefix,
PIXELS_TO_CHOP,
thePixelsToChop,
true);
kwl.add(prefix,
SET_NULLS,
theSetNullsMode,
true);
if (bytesPerPixel() > 1)
{
kwl.add(prefix,
ossimKeywordNames::BYTE_ORDER_KW,
(theImageDataByteOrder == OSSIM_LITTLE_ENDIAN ? "little_endian" :
"big_endian"),
true);
}
return true;
}
bool ossimGeneralRasterInfo::loadState(const ossimKeywordlist& kwl, const char* prefix)
{
static const char MODULE[] = "ossimGeneralRasterInfo::loadState";
if ( traceDebug() )
{
CLOG << "DEBUG: entered..."
<< "\nprefix: " << (prefix ? prefix : "")
<< "\nInput keyword list:\n"
<< kwl
<< std::endl;
}
bool result = false;
//---
// Look for required and option keyword. Break from loop if required
// keyword is not found.
//---
while( 1 )
{
// Check for errors in the ossimKeywordlist.
if(kwl.getErrorStatus() == ossimErrorCodes::OSSIM_ERROR)
{
if(traceDebug())
{
ossimNotify(ossimNotifyLevel_WARN)
<< MODULE << " ERROR:\n"
<< "Detected an error in the keywordlist: " << kwl
<< std::endl;
}
break;
}
std::string key;
ossimString value; // Use for keyword list lookups.
ossim_int32 lines = 0;
ossim_int32 samples = 0;
// Lines (required):
key = NUMBER_LINES;
value.string() = kwl.findKey( key ); // Required to have this.
if ( value.size() )
{
lines = value.toInt32();
if ( !lines )
{
if (traceDebug())
{
ossimNotify(ossimNotifyLevel_WARN)
<< " ERROR:\n"
<< "Required number of lines is 0!" << std::endl;
}
break;
}
}
else
{
if (traceDebug())
{
ossimNotify(ossimNotifyLevel_WARN)
<< " ERROR:\n"
<< "Required keyword not found: " << key << std::endl;
}
break;
}
// Samples (required):
key = NUMBER_SAMPLES;
value.string() = kwl.findKey( key ); // Required to have this.
if ( value.size() )
{
samples = value.toInt32();
if ( !samples )
{
if (traceDebug())
{
ossimNotify(ossimNotifyLevel_WARN)
<< " ERROR:\n"
<< "Required number of samples is 0!" << std::endl;
}
break;
}
}
else
{
if (traceDebug())
{
ossimNotify(ossimNotifyLevel_WARN)
<< " ERROR:\n"
<< "Required keyword not found: " << key << std::endl;
}
break;
}
// Bands ossimImageMetaData::loadState checks for required bands:
if(!theMetaData.loadState(kwl, prefix))
{
if (traceDebug())
{
ossimNotify(ossimNotifyLevel_WARN)
<< " Error loading meta data!\n" << std::endl;
}
break;
}
// If we get here assign the rectangles:
theRawImageRect = ossimIrect( 0, 0, samples - 1, lines - 1 );
theValidImageRect = theRawImageRect;
theImageRect = theRawImageRect;
int tmp = INTERLEAVE_TYPE_LUT.getEntryNumber(kwl);
if (tmp == ossimLookUpTable::NOT_FOUND)
{
theInterleaveType = OSSIM_BIL;
}
else
{
theInterleaveType = static_cast<ossimInterleaveType>(tmp);
}
// Get the image files.
if (theInterleaveType != OSSIM_BSQ_MULTI_FILE)
{
// Look for "filename" first, then deprecated "image_file".
key = ossimKeywordNames::FILENAME_KW;
value.string() = kwl.findKey( key );
if ( value.empty() )
{
// deprecated keyword...
key = ossimKeywordNames::IMAGE_FILE_KW;
value.string() = kwl.findKey( key );
}
if ( value.size() )
{
//---
// omd (ossim metadata) files can have just the base filename, e.g. image.ras,
// in which case open will fail if not in the image dir. So only put it in
// the list if it doesn't exits.
//---
ossimFilename f = value;
if ( f.exists() )
{
theImageFileList.clear();
theImageFileList.push_back(ossimFilename(value));
}
}
if ( theImageFileList.empty() )
{
if (traceDebug())
{
ossimNotify(ossimNotifyLevel_WARN)
<< "ERROR:\n"
<< "Required keyword not found: "
<< ossimKeywordNames::FILENAME_KW << std::endl;
}
break;
}
}
else
{
// multiple file names.
ossim_int32 count = 0;
// look for image file key word with no number.
// Required to have this.
key = ossimKeywordNames::FILENAME_KW;
value.string() = kwl.findKey( key );
if ( value.empty() )
{
// deprecated keyword...
key = ossimKeywordNames::IMAGE_FILE_KW;
value.string() = kwl.findKey( key );
}
if ( value.size() )
{
theImageFileList.push_back(ossimFilename(value));
++count;
}
ossim_int32 i = 0;
while ( (count < numberOfBands()) && (i < 1000) )
{
key = ossimKeywordNames::FILENAME_KW;
key += ossimString::toString(i).string();
value.string() = kwl.findKey( key );
if ( value.empty() )
{
// Lookup for deprecated keyword.
key = ossimKeywordNames::IMAGE_FILE_KW;
key += ossimString::toString(i).string();
value.string() = kwl.findKey( key );
}
if ( value.size() )
{
theImageFileList.push_back(ossimFilename(value));
++count;
}
++i;
}
if (count != numberOfBands()) // Error, count should equal bands!
{
if (traceDebug())
{
ossimNotify(ossimNotifyLevel_WARN)
<< " ERROR:\n"
<< "Required keyword not found: "
<< ossimKeywordNames::FILENAME_KW
<< "\nInterleave type is multi file; however,"
<< " not enough were pick up!" << std::endl;
}
break;
}
}
key = VALID_START_LINE;
value.string() = kwl.findKey( key ); // Default is zero.
if ( value.size() )
{
theValidImageRect.set_uly( value.toInt32() );
}
key = VALID_STOP_LINE;
value.string() = kwl.findKey( key ); // Default is last line.
if ( value.size() )
{
theValidImageRect.set_lry( value.toInt32() );
}
if (theValidImageRect.lr().y < theValidImageRect.ul().y)
{
ossimNotify(ossimNotifyLevel_WARN)
<< " ERROR:"
<< "\nValid stop line < start line."
<< "\nValid start line: " << theValidImageRect.ul().y
<< "\nValid stop line: " << theValidImageRect.lr().y
<< "\nError status has been set. Returning." << std::endl;
break;
}
key = VALID_START_SAMPLE;
value.string() = kwl.findKey( key ); // Default is zero.
if ( value.size() )
{
theValidImageRect.set_ulx( value.toInt32() );
}
key = VALID_STOP_SAMPLE;
value.string() = kwl.findKey( key ); // Default is last sample.
if ( value.size() )
{
theValidImageRect.set_lrx( value.toInt32() );
}
if (theValidImageRect.lr().x < theValidImageRect.ul().x)
{
ossimNotify(ossimNotifyLevel_WARN)
<< " ERROR:"
<< "\nValid stop samp < start samp."
<< "\nValid start samp: " << theValidImageRect.ul().x
<< "\nValid stop samp: " << theValidImageRect.lr().x
<< "\nError status has been set. Returning." << std::endl;
break;
}
theImageRect.set_lry(theValidImageRect.lr().y -
theValidImageRect.ul().y);
theImageRect.set_lrx(theValidImageRect.lr().x -
theValidImageRect.ul().x);
key = SUB_IMAGE_OFFSET_LINE;
value.string() = kwl.findKey( key ); // Default is zero.
if ( value.size() )
{
theSubImageOffset.line = value.toInt32();
}
key = SUB_IMAGE_OFFSET_SAMP;
value.string() = kwl.findKey( key ); // Default is zero.
if ( value.size() )
{
theSubImageOffset.samp = atoi(value);
}
key = HEADER_SIZE;
value.string() = kwl.findKey( key ); // Default is zero.
if ( value.size() )
{
theHeaderSize = value.toInt32();
}
key = SET_NULLS;
value.string() = kwl.findKey( key ); // Default is 2.
if ( value.size() )
{
int tmp;
tmp = atoi(value);
if ((tmp < 3) && (tmp > -1))
{
theSetNullsMode = (ossimFillMode)tmp;
}
else
{
theSetNullsMode = ZEROES_TO_NULL_EDGES_ONLY; // 2
ossimNotify(ossimNotifyLevel_WARN)
<< " WARNING:"
<< "\nset_fill_to_nulls_mode value out of range."
<< "\nDefaulted to 2" << std::endl;
}
}
key = PIXELS_TO_CHOP;
value.string() = kwl.findKey( key ); // Default is zero.
if ( value.size() )
{
thePixelsToChop = value.toInt32();
}
if (bytesPerPixel() > 1)
{
// get the byte order of the data.
key = ossimKeywordNames::BYTE_ORDER_KW;
value.string() = kwl.findKey( key );
if ( value.size() )
{
ossimString s(value);
if (s.trim() != "") // Check for empty string.
{
s.downcase();
if (s.contains("big"))
{
theImageDataByteOrder = OSSIM_BIG_ENDIAN;
}
else if(s.contains("little"))
{
theImageDataByteOrder = OSSIM_LITTLE_ENDIAN;
}
}
}
}
// End of while forever loop.
result = true;
break;
} // Matches: while (1)
if ( traceDebug() )
{
ossimNotify(ossimNotifyLevel_DEBUG)
<< MODULE << " Exit status: " << (result?"true":"false") << std::endl;
}
return result;
} // End: bool ossimGeneralRasterInfo::loadState
bool ossimGeneralRasterInfo::open( const ossimFilename& imageFile )
{
static const char MODULE[] = "ossimGeneralRasterInfo::open";
if ( traceDebug() )
{
ossimNotify(ossimNotifyLevel_DEBUG)
<< MODULE << " entered..." << "\nimageFile: " << imageFile << std::endl;
}
bool result = false;
// Wipe any previous state slick.
clear();
ossimFilename copyFile = imageFile;
if ( !imageFile.exists() )
{
copyFile = imageFile.expand();
}
// Look for the headrer of omd file as they are written out by img2rr.
ossimFilename hdr = copyFile;
hdr.setExtension("hdr"); // image.hdr
if ( !hdr.exists() )
{
hdr = imageFile;
hdr.string() += ".hdr"; // image.ras.hdr
if ( ! hdr.exists() )
{
hdr = imageFile;
hdr.setExtension("xml"); // image.xml
}
}
if ( hdr.exists() )
{
if ( traceDebug() )
{
ossimNotify(ossimNotifyLevel_DEBUG) << "header file: " << hdr << std::endl;
}
ossimString ext = hdr.ext().downcase();
if ( ext == "hdr" )
{
if ( ossimEnviHeader::isEnviHeader( hdr ) )
{
result = initializeFromEnviHdr( hdr );
}
else
{
result = initializeFromHdr( imageFile, hdr );
}
if ( !result )
{
// Could be an ossim meta data file:
ossimKeywordlist kwl( hdr );
result = loadState( kwl, 0 );
}
}
else if ( ext == "xml" )
{
result = initializeFromXml( imageFile, hdr );
}
}
//---
// Set the file name. Needed for ossimGeneralRasterTileSource::open.
// Note set here above loadState call to stop loadState from returning
// false if no image file found.
//---
if ( theImageFileList.empty() )
{
setImageFile( imageFile );
}
ossimFilename omd = imageFile;
omd.setExtension("omd"); // image.omd
if ( !omd.exists() )
{
omd.setExtension("kwl"); // image.kwl
}
if ( omd.exists() )
{
if ( traceDebug() )
{
ossimNotify(ossimNotifyLevel_DEBUG) << "omd file: " << omd << std::endl;
}
ossimKeywordlist kwl( omd );
if ( result && theMetaData.getNumberOfBands() )
{
//---
// Just update the band info in case it has min/max values from
// a compute min/max scan.
//---
theMetaData.updateMetaData( kwl, std::string("") );
}
else
{
// We're not initialized yet so do a loadState:
result = loadState( kwl, 0 );
}
}
if ( traceDebug() )
{
ossimNotify(ossimNotifyLevel_DEBUG)
<< MODULE << " Exit status: " << (result?"true":"false") << std::endl;
}
return result;
}
bool ossimGeneralRasterInfo::initializeFromHdr( const ossimFilename& imageFile,
const ossimFilename& headerFile )
{
bool result = false;
ossimKeywordlist kwl;
char delimeter = ' ';
kwl.change_delimiter(delimeter);
if ( kwl.addFile(headerFile) )
{
kwl.downcaseKeywords();
ossimString value;
while( 1 )
{
//---
// Go through the data members in order.
// If a required item is not found break from loop.
//--
theMetaData.clear();
// scalar ( default ) - adjusted below :
theMetaData.setScalarType( OSSIM_UINT8 );
// Image file name:
theImageFileList.clear();
theImageFileList.push_back( imageFile );
// interleave ( not required - default=BIL)
theInterleaveType = OSSIM_BIL;
value.string() = kwl.findKey( std::string("layout") );
if ( value.size() )
{
ossimInterleaveTypeLut lut;
ossim_int32 intrlv = lut.getEntryNumber( value.string().c_str(), true );
if ( intrlv != ossimLookUpTable::NOT_FOUND )
{
theInterleaveType = static_cast<ossimInterleaveType>(intrlv);
}
}
// bands ( required ):
ossim_uint32 bands = 0;
value.string() = kwl.findKey( std::string("nbands") );
if ( value.size() )
{
bands = value.toUInt32();
}
if ( !bands )
{
break;
}
theMetaData.setNumberOfBands( bands );
// lines ( required ):
ossim_int32 lines = 0;
value.string() = kwl.findKey( std::string("nrows") );
if ( value.size() )
{
lines = value.toInt32();
}
if ( !lines )
{
break;
}
// samples ( required ):
ossim_int32 samples = 0;
value.string() = kwl.findKey( std::string("ncols") );
if ( value.size() )
{
samples = value.toInt32();
}
if ( !samples )
{
break;
}
// nodata or null value ( not required )
value.string() = kwl.findKey( std::string("nodata") );
if ( value.empty() )
{
value.string() = kwl.findKey( std::string("nodata_value") );
}
if ( value.size() )
{
ossim_float64 nullValue = value.toUInt32();
for ( ossim_uint32 band = 0; band < theMetaData.getNumberOfBands(); ++band )
{
theMetaData.setNullPix( band, nullValue );
}
theMetaData.setNullValuesValid(true);
}
// Set the rectangles:
theRawImageRect = ossimIrect( 0, 0, samples - 1, lines - 1 );
theValidImageRect = theRawImageRect;
theImageRect = theRawImageRect;
// sample start ( not required ):
theSubImageOffset.x = 0;
// line start ( not required ):
theSubImageOffset.y = 0;
// header offset ( not required ):
theHeaderSize = 0;
// null mode:
theSetNullsMode = ossimGeneralRasterInfo::NONE;
// pixels to chop:
thePixelsToChop = 0;
// Byte order, ( not required - defaulted to system if not found.
theImageDataByteOrder = ossim::byteOrder();
value.string() = kwl.findKey( std::string("byteorder") );
if ( value.size() )
{
ossim_uint32 i = value.toUInt32();
if ( i == 0 )
{
theImageDataByteOrder = OSSIM_LITTLE_ENDIAN;
}
else
{
theImageDataByteOrder = OSSIM_BIG_ENDIAN;
}
}
// Pixel type used for scalar below:
std::string pixelType = "N"; // not defined
value.string() = kwl.findKey( std::string("pixeltype") );
if ( value.size() )
{
pixelType = value.string();
}
ossim_int32 nbits = -1;
value.string() = kwl.findKey( std::string("nbits") );
if ( value.size() )
{
nbits = value.toInt32();
}
else
{
nbits = getBitsPerPixel( imageFile );
}
switch( nbits )
{
case 8:
{
theMetaData.setScalarType( OSSIM_UINT8 );
break;
}
case 16:
{
if (pixelType == "S")
{
theMetaData.setScalarType( OSSIM_SINT16 );
}
else
{
theMetaData.setScalarType( OSSIM_UINT16 );
}
break;
}
case 32:
{
if( pixelType == "S")
{
theMetaData.setScalarType( OSSIM_SINT32 );
}
else if( pixelType == "F")
{
theMetaData.setScalarType( OSSIM_FLOAT32 );
}
else
{
theMetaData.setScalarType( OSSIM_UINT32 );
}
break;
}
default:
{
if( (nbits < 8) && (nbits >= 1 ) )
{
theMetaData.setScalarType( OSSIM_UINT8 );
}
break;
}
}
result = true;
break; // Trailing break to get out.
}
}
return result;
} // End: ossimGeneralRasterInfo::initializeFromHdr
bool ossimGeneralRasterInfo::initializeFromEnviHdr( const ossimFilename& headerFile )
{
bool result = false;
ossimEnviHeader hdr;
if( hdr.open( headerFile ) )
{
result = initializeFromEnviHdr( hdr );
}
return result;
}
bool ossimGeneralRasterInfo::initializeFromEnviHdr( const ossimEnviHeader& enviHdr )
{
bool result = false;
while( 1 )
{
//---
// Go through the data members in order.
// If a required item is not found break from loop.
//--
theMetaData.clear();
// scalar ( required ) :
if( enviHdr.getOssimScalarType() != OSSIM_SCALAR_UNKNOWN )
{
theMetaData.setScalarType( enviHdr.getOssimScalarType() );
}
else
{
break;
}
theImageFileList.clear();
// interleave ( required ):
theInterleaveType = enviHdr.getOssimInterleaveType();
if ( theInterleaveType == OSSIM_INTERLEAVE_UNKNOWN )
{
break;
}
// bands ( required ):
if ( !enviHdr.getBands() )
{
break;
}
theMetaData.setNumberOfBands( enviHdr.getBands() );
// lines ( required ):
ossim_uint32 lines = enviHdr.getLines();
if ( !lines )
{
break;
}
// samples ( required ):
ossim_uint32 samples = enviHdr.getSamples();
if ( !samples )
{
break;
}
// Set the rectangles:
theRawImageRect = ossimIrect( 0, 0, samples - 1, lines - 1 );
theValidImageRect = theRawImageRect;
theImageRect = theRawImageRect;
// sample start ( not required ):
theSubImageOffset.x = enviHdr.getXStart();
// line start ( not required ):
theSubImageOffset.y = enviHdr.getYStart();
// header offset ( not required ):
theHeaderSize = enviHdr.getHeaderOffset();
// null mode:
theSetNullsMode = ossimGeneralRasterInfo::NONE;
// pixels to chop:
thePixelsToChop = 0;
// Byte order, this will be system if not found.
theImageDataByteOrder = enviHdr.getByteOrder();
result = true;
break; // Trailing break to get out.
}
return result;
} // End: ossimGeneralRasterInfo::initializeFromEnviHdr( const ossimEnviHeader& )
bool ossimGeneralRasterInfo::initializeFromXml( const ossimFilename& imageFile,
const ossimFilename& headerFile )
{
bool result = false;
ossimFgdcXmlDoc file;
if (file.open( headerFile ))
{
while( 1 )
{
//---
// Go through the data members in order.
// If a required item is not found break from loop.
//--
theMetaData.clear();
// scalar ( default ) - adjusted below :
theMetaData.setScalarType( OSSIM_UINT8 );
// Image file name:
theImageFileList.clear();
theImageFileList.push_back( imageFile );
// interleave ( defaulted ):
theInterleaveType = OSSIM_BIL;
// bands ( required ):
if ( !file.getNumberOfBands() )
{
break;
}
theMetaData.setNumberOfBands( file.getNumberOfBands() );
ossimIpt size;
if ( file.getImageSize(size) ) // Lines, samples not image file size.
{
// lines, samples ( required ):
if ( !size.x || !size.y )
{
break;
}
}
else
{
break;
}
// Set the rectangles:
theRawImageRect = ossimIrect( 0, 0, size.x - 1, size.y - 1 );
theValidImageRect = theRawImageRect;
theImageRect = theRawImageRect;
// sample start ( not required ):
theSubImageOffset.x = 0;
// line start ( not required ):
theSubImageOffset.y = 0;
// header offset ( not required ):
theHeaderSize = 0;
// null mode:
theSetNullsMode = ossimGeneralRasterInfo::NONE;
// pixels to chop:
thePixelsToChop = 0;
// Byte order *** need this ***, defaulting to system for now:
theImageDataByteOrder = ossim::byteOrder();
// Adjust scalar if needed, note defaulted to 8 bit above:
ossimString eainfo;
file.getPath("/metadata/eainfo/detailed/enttyp/enttypd", eainfo);
ossim_int32 numBits = 0;
ossim_int64 fileSize = imageFile.fileSize(); // Image file size.
ossim_int32 numBytes = fileSize / size.x / size.y / numberOfBands();
if( numBytes > 0 && numBytes != 3 )
{
numBits = numBytes*8;
}
if( numBits == 16 )
{
theMetaData.setScalarType( OSSIM_UINT16 );
}
else if( numBits == 32 )
{
if(eainfo.contains("float"))
{
theMetaData.setScalarType( OSSIM_FLOAT32 );
}
else
{
theMetaData.setScalarType( OSSIM_UINT32 );
}
}
result = true;
break; // Trailing break to get out.
}
}
return result;
} // End: ossimGeneralRasterInfo::initializeFromXml
ossim_int32 ossimGeneralRasterInfo::getBitsPerPixel( const ossimFilename& imageFile ) const
{
// Note currently does not consider header size.
ossim_int32 result = 0;
ossim_int64 fileSize = imageFile.size();
ossimIpt rectSize = theRawImageRect.size();
if ( fileSize && rectSize.x && rectSize.y && numberOfBands() )
{
result = ( fileSize / rectSize.x / rectSize.y / numberOfBands() ) * 8;
}
return result;
}
| {
"content_hash": "444c6d1cecaf34486bd795b9049d6139",
"timestamp": "",
"source": "github",
"line_count": 1269,
"max_line_length": 95,
"avg_line_length": 27.69818754925138,
"alnum_prop": 0.538308344476372,
"repo_name": "ossimlabs/ossim",
"id": "f79903a2d96d361b8f89b5a6e2ee710201270e30",
"size": "36114",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "src/imaging/ossimGeneralRasterInfo.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "7742"
},
{
"name": "C",
"bytes": "851506"
},
{
"name": "C++",
"bytes": "17430702"
},
{
"name": "CMake",
"bytes": "249895"
},
{
"name": "GLSL",
"bytes": "12013"
},
{
"name": "HTML",
"bytes": "8221"
},
{
"name": "Lex",
"bytes": "3790"
},
{
"name": "Makefile",
"bytes": "44169"
},
{
"name": "POV-Ray SDL",
"bytes": "21837"
},
{
"name": "Shell",
"bytes": "92358"
}
],
"symlink_target": ""
} |
NSString* kWPAttributedStyleAction = @"WPAttributedStyleAction";
@implementation WPAttributedStyleAction
- (instancetype)initWithAction:(void (^)())action
{
self = [super init];
if (self) {
self.action = action;
}
return self;
}
+(NSArray*)styledActionWithAction:(void (^)())action
{
WPAttributedStyleAction* container = [[WPAttributedStyleAction alloc] initWithAction:action];
return [container styledAction];
}
-(NSArray*)styledAction
{
return @[ @{kWPAttributedStyleAction:self}, @"link"];
}
@end
// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com
| {
"content_hash": "0e7f26892268180849f860650c5edf9d",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 97,
"avg_line_length": 22.06896551724138,
"alnum_prop": 0.696875,
"repo_name": "koktear/WPAttributedMarkup",
"id": "8fff667caa014b74a380c8f7a0a3d4d164b9cef4",
"size": "889",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Extras/WPAttributedStyleAction.m",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "23471"
}
],
"symlink_target": ""
} |
'use strict';
/* Services */
var jcrServices = angular.module('jcrServices', []);
var base = 'http://localhost:8080/modules';
var baseAPI = base + '/api';
var byPathAPI = baseAPI + '/byPath/';
var byIdAPI = baseAPI + '/nodes/';
// Based on http://stackoverflow.com/questions/11850025/recommended-way-of-getting-data-from-the-server
jcrServices.factory('DemoSession', function ($http, $cookies) {
// CORS support
// $http.defaults.useXDomain = true;
// delete $http.defaults.headers.common['X-Requested-With'];
// Node is a class which we can use for retrieving and
// updating data on the server
var DemoSession = function (data) {
angular.extend(this, data);
var result = [];
for (var i in this.children) {
if (this.children.hasOwnProperty(i)) {
result.push(new DemoSession(this.children[i]));
}
}
this.childrenAsNode = result;
var safeName = this.name ? this.name : "root";
if (this.properties) {
var title = this.properties.jcr__title;
if (title) {
safeName = title.value;
}
}
this.safeName = safeName;
};
// todo: extract login
DemoSession.login = function($cookies) {
$http.post('http://localhost:8080/cms/login?doLogin=true&restMode=true&username=root&password=password&redirectActive=false')
.then(function (data) {
// cookie is sent with HTTP Only so cannot work here :(
// var jsessionid = $cookies.get('JSESSIONID');
// alert(jsessionid);
});
};
// a static method to retrieve a node by id
DemoSession.getById = function (id) {
return $http.get(byIdAPI + id).then(function (response) {
return new DemoSession(response.data);
});
};
// a static method to retrieve a node by its path
DemoSession.getByPath = function (path) {
return $http.get(byPathAPI + path).then(function (response) {
return new DemoSession(response.data);
});
};
// retrieve the root node
DemoSession.getRoot = function () {
return $http.get(byIdAPI).then(function (response) {
return new DemoSession(response.data);
});
};
// an instance method to create a new node
DemoSession.prototype.create = function (parent) {
var node = this;
return $http.put(byIdAPI + parent.id, node).then(function (response) {
node.id = response.data.id;
return node;
});
};
DemoSession.prototype.link = function (rel) {
return '#' + this._links[rel].href;
};
DemoSession.prototype.cleanedDescription = function () {
return String(this.properties.text.value).replace(/<(?:.|\n)*?>/gm, '').replace('&', '&')
.replace('’', '\'').replace('‘', '\'').replace(''', '\'')
.replace('“', '\"').replace('”', '"').replace(' ', '');
};
DemoSession.getSessions = function () {
return $http.get(baseAPI + '/byType/genericnt__event?depth=1').then(function (response) {
var sessions = [];
response.data.forEach(function (session) {
sessions.push(new DemoSession(session));
});
// make sure sessions are sorted by name (should be done using the query but doesn't work)
sessions.sort(function (a, b) {
return (a.name > b.name) - (b.name > a.name);
});
return sessions;
}, function(error) {
alert(error.data.message);
});
};
DemoSession.prototype.currentVotes = function () {
return this.getAndCreateIfInexistent('j__sumOfVotes', 0);
};
DemoSession.prototype.numberOfVotes = function () {
return this.getAndCreateIfInexistent('j__nbOfVotes', 0);
};
DemoSession.prototype.getAndCreateIfInexistent = function (property, initialValue) {
return this.ensure(property, initialValue).value;
};
DemoSession.prototype.ensure = function (property, initialValue) {
var prop = this.properties[property];
if (!prop) {
this.properties[property] = { 'value': initialValue};
return this.properties[property];
}
return prop;
};
DemoSession.prototype.setAndCreateIfInexistent = function (property, value) {
this.ensure(property, value).value = value;
};
DemoSession.prototype.vote = function (value) {
var nbOfVotes = this.ensure('j__nbOfVotes', 0);
var newNbOfVotes = nbOfVotes.value + 1;
var sumOfVotes = this.ensure('j__sumOfVotes', 0);
var newSumOfVotes = sumOfVotes.value + value;
// which URI we use will determine if we're creating a mixin or updating a node that already has the mixin
// either way, we're just adding / modifying properties which uses the same data
var uri = byIdAPI + this.id; // session URI
if (nbOfVotes.value === 0) {
// we don't have any votes so we need to add the jmix:rating mixin to our session node
uri += '/mixins/jmix__rating';
}
$http.put(uri,
{
'properties': {
'j__lastVote': {
'value': value
},
'j__nbOfVotes': {
'value': newNbOfVotes
},
'j__sumOfVotes': {
'value': newSumOfVotes
}
}
}
).then(function (response) {
alert('Vote recorded!');
nbOfVotes.value = newNbOfVotes;
sumOfVotes.value = newSumOfVotes;
}, function (error) {
alert(error.data.message);
}
);
};
DemoSession.prototype.resetVotes = function () {
var uri = byIdAPI + this.id + '/mixins/jmix__rating';
var nbOfVotes = this.ensure('j__nbOfVotes', 0);
var sumOfVotes = this.ensure('j__sumOfVotes', 0);
$http.delete(uri).then(function (response) {
alert('Vote reset!');
nbOfVotes.value = 0;
sumOfVotes.value = 0;
}, function (error) {
alert(error.data.message);
}
);
};
DemoSession.login();
return DemoSession;
}); | {
"content_hash": "8e4d500ce20ee9612f7d0505bdc5ef58",
"timestamp": "",
"source": "github",
"line_count": 194,
"max_line_length": 133,
"avg_line_length": 33.597938144329895,
"alnum_prop": 0.5523166615526235,
"repo_name": "metacosm/jcrestapi-angular-demo",
"id": "d26640791a4e1cbe91633a8785be7048b95b797b",
"size": "6518",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/js/services.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "25"
},
{
"name": "JavaScript",
"bytes": "8499"
}
],
"symlink_target": ""
} |
require 'fog/rackspace/core'
module Fog
module Rackspace
class Identity < Fog::Service
US_ENDPOINT = 'https://identity.api.rackspacecloud.com/v2.0'
UK_ENDPOINT = 'https://lon.identity.api.rackspacecloud.com/v2.0'
requires :rackspace_username, :rackspace_api_key
recognizes :rackspace_auth_url, :rackspace_region
model_path 'fog/rackspace/models/identity'
model :user
collection :users
model :role
collection :roles
model :credential
collection :credentials
model :tenant
collection :tenants
model :service_catalog
request_path 'fog/rackspace/requests/identity'
request :create_token
request :list_users
request :list_user_roles
request :list_credentials
request :list_tenants
request :get_user_by_id
request :get_user_by_name
request :create_user
request :update_user
request :delete_user
module Common
attr_reader :service_catalog, :auth_token
def authenticate(options={})
data = self.create_token(@rackspace_username, @rackspace_api_key).body
@service_catalog = ServiceCatalog.from_response(self, data)
@auth_token = data['access']['token']['id']
end
def apply_options(options)
@rackspace_username = options[:rackspace_username]
@rackspace_api_key = options[:rackspace_api_key]
@rackspace_region = options[:rackspace_region]
@rackspace_auth_url = options[:rackspace_auth_url] || US_ENDPOINT
@uri = URI.parse(@rackspace_auth_url)
@host = @uri.host
@path = @uri.path
@port = @uri.port
@scheme = @uri.scheme
@persistent = options[:persistent] || false
@connection_options = options[:connection_options] || {}
end
end
class Mock < Fog::Rackspace::Service
include Common
def initialize(options={})
apply_options(options)
authenticate
end
end
class Real < Fog::Rackspace::Service
include Common
def initialize(options={})
apply_options(options)
@connection = Fog::Connection.new(@uri.to_s, @persistent, @connection_options)
authenticate
end
end
end
end
end
| {
"content_hash": "db15869968e2aefbdc63fbad256505ab",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 88,
"avg_line_length": 28.011904761904763,
"alnum_prop": 0.6107097322566936,
"repo_name": "petems/fog",
"id": "742c8deb5455b4e5bb2a0788610f2609d7ae7cba",
"size": "2353",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "lib/fog/rackspace/identity.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "8146704"
},
{
"name": "Shell",
"bytes": "562"
}
],
"symlink_target": ""
} |
var Frustum = require("../tools/frustum.js").Frustum;
var XC = require("../../../xflow/interface/constants.js");
var DataNode = require("../../../xflow/interface/graph.js").DataNode;
var InputNode = require("../../../xflow/interface/graph.js").InputNode;
var BufferEntry = require("../../../xflow/interface/data.js").BufferEntry;
var ComputeRequest = require("../../../xflow/interface/request.js").ComputeRequest;
var PointLightData = {
"intensity": {type: XC.DATA_TYPE.FLOAT3, 'default': [1, 1, 1]},
"attenuation": {type: XC.DATA_TYPE.FLOAT3, 'default': [0, 0, 1]},
"position": {type: XC.DATA_TYPE.FLOAT3, 'default': [0, 0, 0]},
"shadowBias": {type: XC.DATA_TYPE.FLOAT, 'default': [0.0001]},
"direction": {type: XC.DATA_TYPE.FLOAT3, 'default': [0, 0, -1]},
"castShadow": {type: XC.DATA_TYPE.BOOL, 'default': [false]},
"on": {type: XC.DATA_TYPE.BOOL, 'default': [true]},
"matrix": {type: XC.DATA_TYPE.FLOAT4X4, 'default': [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]},
"nearFar": {type: XC.DATA_TYPE.FLOAT2, 'default': [1.0, 100.0]}
};
var SpotLightData = {
"intensity": {type: XC.DATA_TYPE.FLOAT3, 'default': [1, 1, 1]},
"attenuation": {type: XC.DATA_TYPE.FLOAT3, 'default': [0, 0, 1]},
"position": {type: XC.DATA_TYPE.FLOAT3, 'default': [0, 0, 0]},
"direction": {type: XC.DATA_TYPE.FLOAT3, 'default': [0, 0, -1]},
"falloffAngle": {type: XC.DATA_TYPE.FLOAT, 'default': [Math.PI / 4]},
"softness": {type: XC.DATA_TYPE.FLOAT, 'default': [0.0]},
"shadowBias": {type: XC.DATA_TYPE.FLOAT, 'default': [0.0001]},
"castShadow": {type: XC.DATA_TYPE.BOOL, 'default': [false]},
"matrix": {type: XC.DATA_TYPE.FLOAT4X4, 'default': [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]},
"on": {type: XC.DATA_TYPE.BOOL, 'default': [true]}
};
var DirectionalLightData = {
"intensity": {type: XC.DATA_TYPE.FLOAT3, 'default': [1, 1, 1]},
"direction": {type: XC.DATA_TYPE.FLOAT3, 'default': [0, 0, -1]},
"shadowBias": {type: XC.DATA_TYPE.FLOAT, 'default': [0.0001]},
"position": {type: XC.DATA_TYPE.FLOAT3, 'default': [0, 0, 0]},
"castShadow": {type: XC.DATA_TYPE.BOOL, 'default': [false]},
"on": {type: XC.DATA_TYPE.BOOL, 'default': [true]},
"matrix": {type: XC.DATA_TYPE.FLOAT4X4, 'default': [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]}
};
function createXflowData(config) {
var data = new DataNode();
for (var name in config) {
var entry = config[name];
createXflowValue(data, name, entry.type, entry['default']);
}
return data;
}
function createXflowValue(dataNode, name, type, value) {
var buffer = new BufferEntry(type, new XC.TYPED_ARRAY_MAP[type](value));
var inputNode = new InputNode();
inputNode.data = buffer;
inputNode.name = name;
dataNode.appendChild(inputNode);
}
/**
* Base class for light models
* @param {string} id Unique id that identifies the light model
* @param {RenderLight} light
* @param {DataNode} dataNode
* @param {Object} config Configuration that contains the light model's parameters and default values
* @constructor
*/
var LightModel = function (id, light, dataNode, config) {
this.id = id;
this.light = light;
this.configuration = config;
this.parameters = Object.keys(config);
/**
* If the light has not data, just use the default parameters
*/
if (dataNode) {
var data = new DataNode();
data.insertBefore(createXflowData(config), null);
data.insertBefore(dataNode, null);
this.dataNode = data;
} else {
this.dataNode = createXflowData(config);
}
// Horizontal opening angle of the light camera. Derived from falloffAngle in case of spot light
this.fovy = Math.PI/2.0;
this.lightParameterRequest = new ComputeRequest(this.dataNode, this.parameters, this.lightParametersChanged.bind(this));
this.lightParametersChanged(this.lightParameterRequest, null);
};
LightModel.prototype = {
/**
* Copies the light parameters in an array of the same size
* @param {Object} target Name to typed array map containing the data
* @param {number} offset Slot in the array to be filled
*/
fillLightParameters: function (target, offset) {
var result = this.lightParameterRequest.getResult();
this.parameters.forEach(function (name) {
var entry = result.getOutputData(name);
var size = XC.DATA_TYPE_TUPLE_SIZE[entry.type];
var value = entry.getValue();
target[name].set(value.subarray(0, size), offset * size);
});
this.transformParameters(target, offset);
},
allocateParameterArray: function (size) {
var parameterArrays = {};
var config = this.configuration;
this.parameters.forEach(function (name) {
var type = config[name].type;
var tupleSize = XC.DATA_TYPE_TUPLE_SIZE[type];
parameterArrays[name] = new XC.TYPED_ARRAY_MAP[type](tupleSize * size);
});
return parameterArrays;
},
getParameter: function(name) {
if(name in this.configuration) {
// No other checks required because parameters are always defined
return this.lightParameterRequest.getResult().getOutputData(name).getValue();
}
return null;
},
lightParametersChanged: function (request, changeType) {
if (changeType) {
this.light.lightValueChanged();
}
},
_expandNearFar:function(nfobject){
var expand = Math.max((nfobject.far - nfobject.near) * 0.30, 0.05);
nfobject.near -= expand;
nfobject.far += expand;
},
getLightData: function (target, offset) {
var matrix = target["matrix"].subarray(offset * 16, offset * 16 + 16);
this.getLightViewProjectionMatrix(matrix);
},
getLightViewProjectionMatrix: function (target) {
var LVM = XML3D.math.mat4.create();
var LPM = XML3D.math.mat4.create();
this.getLightViewMatrix(LVM);
this.getLightProjectionMatrix(LPM);
XML3D.math.mat4.multiply(target, LPM, LVM);
},
getLightProjectionMatrix: function (target) {
this.light.getFrustum(1).getProjectionMatrix(target);
},
getLightViewMatrix: function (mat4) {
var p_dir = this.getParameter("direction");
var p_pos = this.getParameter("position");
// Get the world matrix from the light in the transformation hierarchy
// world => light
this.light.getWorldMatrix(mat4);
// Derive rotation from the direction and standard direction (-z => no rotation)
var q_rot = XML3D.math.quat.rotationTo(XML3D.math.quat.create(),c_standardDirection, p_dir);
// Create matrix from rotation and translation
var trans = XML3D.math.mat4.fromRotationTranslation(XML3D.math.mat4.create(), q_rot, p_pos);
// Add to world matrix
XML3D.math.mat4.mul(mat4, mat4, trans);
// Invert: light => world
XML3D.math.mat4.invert(mat4, mat4);
}
};
var c_tmpWorldMatrix = XML3D.math.mat4.create();
var c_standardDirection = XML3D.math.vec3.fromValues(0,0,-1);
function transformPose(light, position, direction) {
light.getWorldMatrix(c_tmpWorldMatrix);
if (position) {
XML3D.math.vec3.transformMat4(position, position, c_tmpWorldMatrix);
}
if (direction) {
XML3D.math.vec3.transformDirection(direction, direction, c_tmpWorldMatrix);
XML3D.math.vec3.normalize(direction, direction);
}
}
function transformDefault(target, offset, light) {
target["on"][offset] = light.visible;
}
/**
* Implement XML3D's predefined point light model urn:xml3d:light:point
* @param {DataNode} dataNode
* @param {RenderLight} light
* @extends LightModel
* @constructor
*/
var PointLightModel = function (dataNode, light) {
LightModel.call(this, "point", light, dataNode, PointLightData);
};
XML3D.createClass(PointLightModel, LightModel, {
getFrustum: function (aspect, sceneBoundingBox) {
var orthogonal = false;
var entry = this.light.scene.lights.getModelEntry(this.id);
if (XML3D.math.bbox.isEmpty(sceneBoundingBox)) {
entry.parameters["nearFar"][0] = 1.0;
entry.parameters["nearFar"][1] = 110.0;
return new Frustum(1.0, 110.0, 0, this.fovy, aspect, orthogonal)
}
var t_mat = XML3D.math.mat4.create();
this.getLightViewMatrix(t_mat);
XML3D.math.bbox.transform(sceneBoundingBox, t_mat, sceneBoundingBox);
var nf = {
near: -sceneBoundingBox[5], far: -sceneBoundingBox[2]
};
// Expand the view frustum a bit to ensure 2D objects parallel to the camera are rendered
this._expandNearFar(nf);
entry.parameters["nearFar"][0] = 1.0;
entry.parameters["nearFar"][1] = nf.far;
return new Frustum(1.0, nf.far, 0, this.fovy, aspect, orthogonal);
},
transformParameters: function (target, offset) {
var position = target["position"].subarray(offset * 3, offset * 3 + 3);
transformPose(this.light, position, null);
transformDefault(target, offset, this.light);
}
});
/**
* Implement XML3D's predefined spot light model urn:xml3d:light:spot
* @param {DataNode} dataNode
* @param {RenderLight} light
* @extends LightModel
* @constructor
*/
var SpotLightModel = function (dataNode, light) {
LightModel.call(this, "spot", light, dataNode, SpotLightData);
};
XML3D.createClass(SpotLightModel, LightModel, {
getFrustum: function (aspect, sceneBoundingBox) {
if (XML3D.math.bbox.isEmpty(sceneBoundingBox)) {
return new Frustum(1.0, 110.0, 0, this.fovy, aspect, false)
}
var t_mat = XML3D.math.mat4.create();
this.getLightViewMatrix(t_mat);
XML3D.math.bbox.transform(sceneBoundingBox, t_mat, sceneBoundingBox);
var nf = {
near: -sceneBoundingBox[5], far: -sceneBoundingBox[2]
};
// Expand the view frustum a bit to ensure 2D objects parallel to the camera are rendered
this._expandNearFar(nf);
return new Frustum(1.0, nf.far, 0, this.fovy, aspect, false);
},
transformParameters: function (target, offset) {
var position = target["position"].subarray(offset * 3, offset * 3 + 3);
var direction = target["direction"].subarray(offset * 3, offset * 3 + 3);
// Transform position and direction from object to world space
transformPose(this.light, position, direction);
transformDefault(target, offset, this.light);
},
lightParametersChanged: function (request, changeType) {
this.fovy = this.getParameter("falloffAngle")[0] * 2;
LightModel.prototype.lightParametersChanged.call(this, request, changeType);
}
});
/**
* Implement XML3D's predefined spot light model urn:xml3d:light:directional
* @param {DataNode} dataNode
* @param {RenderLight} light
* @extends LightModel
* @constructor
*/
var DirectionalLightModel = function (dataNode, light) {
LightModel.call(this, "directional", light, dataNode, DirectionalLightData);
};
XML3D.createClass(DirectionalLightModel, LightModel, {
getFrustum: function(aspect, sceneBoundingBox) {
var orthogonal = true;
if (XML3D.math.bbox.isEmpty(sceneBoundingBox)) {
return new Frustum(1.0, 110.0, 0, this.fovy, aspect, orthogonal)
}
var t_mat = XML3D.math.mat4.create();
this.getLightViewMatrix(t_mat);
XML3D.math.bbox.transform(sceneBoundingBox, t_mat, sceneBoundingBox);
var nf = { near: -sceneBoundingBox[5],
far: -sceneBoundingBox[2]};
// Expand the view frustum a bit to ensure 2D objects parallel to the camera are rendered
this._expandNearFar(nf);
return new Frustum(1.0, nf.far, 0, this.fovy, aspect, orthogonal);
},
transformParameters: function (target, offset) {
var direction = target["direction"].subarray(offset * 3, offset * 3 + 3);
transformPose(this.light, null, direction);
transformDefault(target, offset, this.light);
},
getLightViewMatrix: function (mat4) {
var manager = this.light.scene.lights;
var entry = manager.getModelEntry(this.id);
var p_dir = entry.parameters["direction"];
var p_pos = entry.parameters["position"];
var bb = new XML3D.math.bbox.create();
this.light.scene.getBoundingBox(bb);
var bbSize = XML3D.math.vec3.create();
var bbCenter = XML3D.math.vec3.create();
var off = XML3D.math.vec3.create();
XML3D.math.bbox.center(bbCenter, bb);
XML3D.math.bbox.size(bbSize, bb);
var d = XML3D.math.vec3.len(bbSize); //diameter of bounding sphere of the scene
XML3D.math.vec3.scale(off, p_dir, -0.55 * d); //enlarge a bit on the radius of the scene
p_pos = XML3D.math.vec3.add(p_pos, bbCenter, off);
entry.parameters["position"] = p_pos;
//create new transformation matrix depending on the updated parameters
XML3D.math.mat4.identity(mat4);
var lookat_mat = XML3D.math.mat4.create();
var top_vec = XML3D.math.vec3.fromValues(0.0, 1.0, 0.0);
if ((p_dir[0] == 0.0) && (p_dir[2] == 0.0)) //check if top_vec colinear with direction
top_vec = XML3D.math.vec3.fromValues(0.0, 0.0, 1.0);
var up_vec = XML3D.math.vec3.create();
var dir_len = XML3D.math.vec3.len(p_dir);
XML3D.math.vec3.scale(up_vec, p_dir, -XML3D.math.vec3.dot(top_vec, p_dir) / (dir_len * dir_len));
XML3D.math.vec3.add(up_vec, up_vec, top_vec);
XML3D.math.vec3.normalize(up_vec, up_vec);
XML3D.math.mat4.lookAt(lookat_mat, XML3D.math.vec3.fromValues(0.0, 0.0, 0.0), p_dir, up_vec);
XML3D.math.mat4.invert(lookat_mat, lookat_mat);
XML3D.math.mat4.translate(mat4, mat4, p_pos);
XML3D.math.mat4.multiply(mat4, mat4, lookat_mat);
var bb = new XML3D.math.bbox.create();
this.light.scene.getBoundingBox(bb);
XML3D.math.bbox.transform(bb, mat4, bb);
var bbSize = XML3D.math.vec3.create();
XML3D.math.bbox.size(bbSize, bb);
var max = (bbSize[0] > bbSize[1]) ? bbSize[0] : bbSize[1];
max = 0.55 * (max);//enlarge 10percent to make sure nothing gets cut off
this.fovy = Math.atan(max)*2.0;
entry.parameters["direction"] = p_dir;
entry.parameters["position"] = p_pos;
XML3D.math.mat4.invert(mat4, mat4);
}
});
module.exports = {
PointLightModel: PointLightModel, SpotLightModel: SpotLightModel, DirectionalLightModel: DirectionalLightModel
};
| {
"content_hash": "0b4cc19fe9cc103c0cda3661441a75df",
"timestamp": "",
"source": "github",
"line_count": 392,
"max_line_length": 124,
"avg_line_length": 37.67857142857143,
"alnum_prop": 0.634529451591063,
"repo_name": "ariyapour/xml3d.js",
"id": "5f187da7511688c7ecd3bcd09d357276f0627d61",
"size": "14770",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/renderer/renderer/lights/light-models.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "145"
},
{
"name": "CSS",
"bytes": "6488"
},
{
"name": "HTML",
"bytes": "233459"
},
{
"name": "JavaScript",
"bytes": "4093238"
}
],
"symlink_target": ""
} |
package org.drools.model.view;
import java.util.Arrays;
import org.drools.model.Binding;
import org.drools.model.Variable;
import org.drools.model.functions.Function1;
import org.drools.model.impl.ModelComponent;
public class BindViewItem1<T> implements ViewItem<T>, Binding, ModelComponent {
private final Variable<T> boundVariable;
private final Function1 bindingFunction;
private final Variable inputVariable;
private final String[] reactOn;
private final String[] watchedProps;
public BindViewItem1( Variable<T> boundVariable, Function1 bindingFunction, Variable inputVariable, String[] reactOn, String[] watchedProps ) {
this.bindingFunction = bindingFunction;
this.boundVariable = boundVariable;
this.inputVariable = inputVariable;
this.reactOn = reactOn;
this.watchedProps = watchedProps;
}
@Override
public Variable<T> getFirstVariable() {
return boundVariable;
}
@Override
public Variable<?>[] getVariables() {
return new Variable[] { boundVariable };
}
@Override
public Variable<T> getBoundVariable() {
return boundVariable;
}
@Override
public Function1 getBindingFunction() {
return bindingFunction;
}
@Override
public Variable getInputVariable() {
return inputVariable;
}
@Override
public Variable[] getInputVariables() {
return new Variable[] { inputVariable} ;
}
@Override
public String[] getReactOn() {
return reactOn;
}
@Override
public String[] getWatchedProps() {
return watchedProps;
}
@Override
public Object eval(Object... args) {
return bindingFunction.apply(args[0]);
}
public Object eval(Object arg) {
return bindingFunction.apply(arg);
}
@Override
public boolean isEqualTo( ModelComponent o ) {
if ( this == o ) return true;
if ( !(o instanceof BindViewItem1) ) return false;
BindViewItem1<?> that = (BindViewItem1<?>) o;
if ( !ModelComponent.areEqualInModel( boundVariable, that.boundVariable )) return false;
if ( !ModelComponent.areEqualInModel( inputVariable, that.inputVariable )) return false;
if ( !bindingFunction.equals( that.bindingFunction )) return false;
return reactOn == null ? that.reactOn == null : Arrays.equals(reactOn, that.reactOn);
}
}
| {
"content_hash": "32dbf8d9d6c870fbd30dc27c9aa64034",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 147,
"avg_line_length": 27.359550561797754,
"alnum_prop": 0.6685831622176591,
"repo_name": "manstis/drools",
"id": "10be0e5f82d8ba4f1727cddc60fb82ec1afbe3e9",
"size": "3058",
"binary": false,
"copies": "9",
"ref": "refs/heads/main",
"path": "drools-model/drools-canonical-model/src/main/java/org/drools/model/view/BindViewItem1.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "16697"
},
{
"name": "Batchfile",
"bytes": "2554"
},
{
"name": "CSS",
"bytes": "1412"
},
{
"name": "GAP",
"bytes": "198078"
},
{
"name": "HTML",
"bytes": "6163"
},
{
"name": "Java",
"bytes": "36835383"
},
{
"name": "Python",
"bytes": "4555"
},
{
"name": "Ruby",
"bytes": "491"
},
{
"name": "Shell",
"bytes": "1120"
},
{
"name": "XSLT",
"bytes": "24302"
}
],
"symlink_target": ""
} |
from django.db.models import Q
from django.utils import timezone
from treebeard.mp_tree import MP_NodeQuerySet
from cms.publisher.query import PublisherQuerySet
from cms.exceptions import NoHomeFound
class PageQuerySet(PublisherQuerySet):
def on_site(self, site=None):
from cms.utils import get_current_site
if site is None:
site = get_current_site()
return self.filter(node__site=site)
def published(self, site=None, language=None):
now = timezone.now()
if language:
pub = self.on_site(site).filter(
Q(publication_date__lte=now) | Q(publication_date__isnull=True),
Q(publication_end_date__gt=now) | Q(publication_end_date__isnull=True),
title_set__published=True, title_set__language=language,
)
else:
pub = self.on_site(site).filter(
Q(publication_date__lte=now) | Q(publication_date__isnull=True),
Q(publication_end_date__gt=now) | Q(publication_end_date__isnull=True),
title_set__published=True,
)
return pub.exclude(title_set__publisher_state=4)
def get_home(self, site=None):
try:
home = self.published(site).distinct().get(is_home=True)
except self.model.DoesNotExist:
raise NoHomeFound('No Root page found. Publish at least one page!')
return home
def has_apphooks(self):
"""
Returns True if any page on this queryset has an apphook attached.
"""
return self.exclude(application_urls=None).exclude(application_urls='').exists()
class PageNodeQuerySet(MP_NodeQuerySet):
def get_descendants(self, parent=None):
if parent is None:
return self.all()
if parent.is_leaf():
# leaf nodes have no children
return self.none()
return self.filter(path__startswith=parent.path, depth__gte=parent.depth)
def delete_fast(self):
# calls django's delete instead of the one from treebeard
super(MP_NodeQuerySet, self).delete()
def root_only(self):
return self.filter(depth=1)
| {
"content_hash": "404ef677b6858f47773bbebd736f25ed",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 88,
"avg_line_length": 33.61538461538461,
"alnum_prop": 0.6210526315789474,
"repo_name": "benzkji/django-cms",
"id": "fd5494ab00893b80f6c27b5e9489f877033aed35",
"size": "2209",
"binary": false,
"copies": "4",
"ref": "refs/heads/develop",
"path": "cms/models/query.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "132972"
},
{
"name": "HTML",
"bytes": "201324"
},
{
"name": "JavaScript",
"bytes": "1238070"
},
{
"name": "Python",
"bytes": "2356866"
},
{
"name": "Shell",
"bytes": "447"
}
],
"symlink_target": ""
} |
package api
import (
cfclient "github.com/cloudfoundry-community/go-cfclient"
"os"
"log"
"strconv"
"strings"
"app-metrics-nozzle/domain"
)
var logger = log.New(os.Stdout, "", 0)
var client *cfclient.Client
func init(){
skipSsl, _ := strconv.ParseBool(os.Getenv("SKIP_SSL_VALIDATION"))
c := cfclient.Config{
ApiAddress: os.Getenv("API_ENDPOINT"),
Username: os.Getenv("FIREHOSE_USER"),
Password: os.Getenv("FIREHOSE_PASSWORD"),
SkipSslValidation: skipSsl,
}
logger.Println("Processing Cloud Controller call to " + os.Getenv("API_ENDPOINT"))
client, _ = cfclient.NewClient(&c)
}
func AnnotateWithCloudControllerData(app *domain.App) {
ccAppDetails, _ := client.AppByGuid(app.GUID)
instances, _ := client.GetAppInstances(app.GUID)
runnintCount := 0
instanceUp := "RUNNING"
space, _ := ccAppDetails.Space()
org, _ := space.Org()
app.Diego = ccAppDetails.Diego
app.Buildpack = ccAppDetails.Buildpack
app.Instances = make([]domain.Instances, int64(len(instances)))
for idx, eachInstance := range instances {
if strings.Compare(instanceUp, eachInstance.State) == 0 {
runnintCount++;
}
i, _ := strconv.ParseInt(idx, 10, 32)
app.Instances[i].InstanceIndex = i
app.Instances[i].State = eachInstance.State
app.Instances[i].Since = eachInstance.Since
app.Instances[i].Uptime = eachInstance.Uptime
}
if len(app.Buildpack) == 0 { app.Buildpack = ccAppDetails.DetectedBP }
app.Environment = ccAppDetails.Environment
app.Organization.ID = org.Guid
app.Organization.Name = org.Name
app.Space.ID = space.Guid
app.Space.Name = space.Name
app.InstanceCount.Configured = len(instances)
app.InstanceCount.Running = runnintCount
app.EnvironmentSummary.TotalDiskConfigured = ccAppDetails.DiskQuota * 1024 * 1024
app.EnvironmentSummary.TotalMemoryConfigured = ccAppDetails.MemQuota * 1024 * 1024
app.EnvironmentSummary.TotalDiskProvisioned = ccAppDetails.DiskQuota * 1024 * 1024 * int32(len(instances))
app.EnvironmentSummary.TotalMemoryProvisioned = ccAppDetails.MemQuota * 1024 * 1024 * int32(len(instances))
if 0 < len(ccAppDetails.RouteData) {
app.Routes = make([]string, len(ccAppDetails.RouteData))
for i := 0; i < len(ccAppDetails.RouteData); i++ {
app.Routes[i] = ccAppDetails.RouteData[i].Entity.Host + "." + ccAppDetails.RouteData[i].Entity.DomainData.Entity.Name
}
}
app.State = ccAppDetails.State
}
func UsersForSpace(guid string) (Users []cfclient.User) {
users, _ := client.UsersBy(guid, "spaces")
return users
}
func UsersForOrganization(guid string) (Users []cfclient.User) {
users, _ := client.UsersBy(guid, "organizations")
return users
}
func SpacesDetailsFromCloudController() (Spaces []cfclient.Space){
spaces, _ := client.ListSpaces()
return spaces
}
func OrgsDetailsFromCloudController() (Orgs []cfclient.Org){
orgs, _ := client.ListOrgs()
return orgs
}
| {
"content_hash": "ccaac311bd260fadab95599ffaa3c204",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 120,
"avg_line_length": 26.97196261682243,
"alnum_prop": 0.7217602217602218,
"repo_name": "deejross/app-metrics-nozzle",
"id": "0d08e126a86806af4e1a9660db1417681bee7542",
"size": "3439",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "api/cloud_controller.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "30834"
}
],
"symlink_target": ""
} |
class CreateSelecaoAdminPublications < ActiveRecord::Migration
def change
create_table :selecao_admin_publications do |t|
t.string :title
t.text :publication_text
t.belongs_to :publication_category
t.timestamps
end
add_index :selecao_admin_publications, :publication_category_id
end
end
| {
"content_hash": "a839c0fc38d1c86ee13b16c6676fa09a",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 67,
"avg_line_length": 27.333333333333332,
"alnum_prop": 0.7225609756097561,
"repo_name": "swayzepatryck/selecao_admin",
"id": "93cc8edab295f8595f42b42fc2ed09160ec34c39",
"size": "328",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "db/migrate/20120903143802_create_selecao_admin_publications.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "18593"
},
{
"name": "JavaScript",
"bytes": "5629"
},
{
"name": "Ruby",
"bytes": "503080"
}
],
"symlink_target": ""
} |
<!--#########################################################################-->
<!--# Copyright (c) 2015 Jonas Bjurel and others. -->
<!--# jonasbjurel@hotmail.com -->
<!--# All rights reserved. This program and the accompanying materials -->
<!--# are made available under the terms of the Apache License, Version 2.0 -->
<!--# which accompanies this distribution, and is available at -->
<!--# http://www.apache.org/licenses/LICENSE-2.0 -->
<!--#########################################################################-->
<html>
<head>
<!-- <meta http-equiv="refresh" content="10" /> -->
</head>
<body>
<p>
<?php
$config_file="../config.yaml";
$config=yaml_parse_file($config_file);
$repo_path=$config["ci_repo_path"];
$release=$_GET["release"];
$build_staging=$_GET["build_staging"];
$deploy_staging=$_GET["deploy_staging"];
$test_staging=$_GET["test_staging"];
$build_params=$_GET["build_params"];
$deploy_params=$_GET["deploy_params"];
$iso_file=$_GET["iso_file"];
if ((isset($build_staging))||(isset($deploy_staging))||(isset($test_staging))) {
$command="./ci_pipeline.sh ";
$command.="-b $release ";
if (!(isset($build_staging)))
$command.="-B ";
if (!(isset($deploy_staging)))
$command.="-D ";
if (!(isset($test_staging)))
$command.="-T ";
if ((isset($build_params)) && ($build_params=="no_cache"))
$command.="-I ";
if ((isset($deploy_params)) && ($deploy_params=="ha"))
$command.="-a ";
if (isset($iso_file) && !(empty($iso_file)))
$command.="-i $iso_file ";
echo "running $command";
exec("$repo_path/ci_fuel_opnfv/$command >/dev/null 2>/dev/null &");
//sleep(10);
//header("Location: {$_SERVER['HTTP_REFERER']}");
}
else
echo "Nothing todo";
//sleep(10);
//header("Location: {$_SERVER['HTTP_REFERER']}");
?>
</p>
</body>
</html>
| {
"content_hash": "5bf53e64d895f860dd60cc95fd9e93a7",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 89,
"avg_line_length": 37.442622950819676,
"alnum_prop": 0.4365148861646235,
"repo_name": "fdegir/OPNFV-Playground",
"id": "f54db6c454644aee03ee181c7e7e722229cb767c",
"size": "2284",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ci_fuel_opnfv/dashboard/php/ci_invoke.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "11049"
},
{
"name": "DIGITAL Command Language",
"bytes": "575"
},
{
"name": "HTML",
"bytes": "10348"
},
{
"name": "PHP",
"bytes": "24292"
},
{
"name": "Shell",
"bytes": "38780"
}
],
"symlink_target": ""
} |
package com.cognizant.devops.platformdal.dal;
import java.util.List;
import java.util.Map;
public class InsightsGraphNode {
private Map<String, Object> propertyMap;
private InsightsRelationShip relation;
private List<String> labels;
public Map<String, Object> getPropertyMap() {
return propertyMap;
}
public void setPropertyMap(Map<String, Object> propertyMap) {
this.propertyMap = propertyMap;
}
public InsightsRelationShip getRelation() {
return relation;
}
public void setRelation(InsightsRelationShip relation) {
this.relation = relation;
}
public List<String> getLabels() {
return labels;
}
public void setLabels(List<String> labels) {
this.labels = labels;
}
}
| {
"content_hash": "9814053e30693e6a975b4ad6002c9384",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 62,
"avg_line_length": 19.72222222222222,
"alnum_prop": 0.7450704225352113,
"repo_name": "CognizantOneDevOps/Insights",
"id": "65d86f7452eceb09ab550f7affb53f75e5a4eb41",
"size": "1487",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PlatformDAL/src/main/java/com/cognizant/devops/platformdal/dal/InsightsGraphNode.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "93761"
},
{
"name": "CSS",
"bytes": "362982"
},
{
"name": "Dockerfile",
"bytes": "30938"
},
{
"name": "HTML",
"bytes": "1118798"
},
{
"name": "Java",
"bytes": "4099059"
},
{
"name": "JavaScript",
"bytes": "39094"
},
{
"name": "Python",
"bytes": "1518111"
},
{
"name": "SCSS",
"bytes": "218059"
},
{
"name": "Shell",
"bytes": "541300"
},
{
"name": "TypeScript",
"bytes": "2097909"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<properties>
<Edit>true</Edit>
<Files>true</Files>
<LastModified>20080131162316</LastModified>
<Properties>true</Properties>
<RecentChanges>true</RecentChanges>
<Refactor>true</Refactor>
<Search>true</Search>
<Versions>true</Versions>
<WhereUsed>true</WhereUsed>
<saveId>1201796596808</saveId>
<ticketId>6113474945138488969</ticketId>
</properties>
| {
"content_hash": "f8dd9fc0e1012695b246d95e498633c6",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 44,
"avg_line_length": 27.285714285714285,
"alnum_prop": 0.7539267015706806,
"repo_name": "NCIP/caintegrator",
"id": "67bbada8bea3ab3da10f100cf3801c3b82608c46",
"size": "382",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "caintegrator-war/test/acceptance/FitNesseRoot/JavaExamples/PlainSeleniumTest/TearDown/properties.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "61091"
},
{
"name": "FreeMarker",
"bytes": "30688"
},
{
"name": "HTML",
"bytes": "828"
},
{
"name": "Java",
"bytes": "5239823"
},
{
"name": "JavaScript",
"bytes": "163834"
},
{
"name": "PLSQL",
"bytes": "55084"
},
{
"name": "Perl",
"bytes": "2710"
},
{
"name": "Shell",
"bytes": "3376"
},
{
"name": "TeX",
"bytes": "90"
},
{
"name": "XSLT",
"bytes": "157133"
}
],
"symlink_target": ""
} |
import torch # for torch.cat and torch.zeros
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
from nhwc.conv import Conv2d_NHWC
from nhwc.batch_norm import BatchNorm2d_NHWC
from nhwc.max_pool import MaxPool2d_NHWC
# Group batch norm
from apex.parallel import SyncBatchNorm as gbn
# Persistent group BN for NHWC case
from apex.contrib.groupbn.batch_norm import BatchNorm2d_NHWC as gbn_persistent
import apex.parallel
__all__ = ['resnet']
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
}
class Layers_NCHW:
Conv2d = nn.Conv2d
MaxPool = nn.MaxPool2d
BnAddRelu = None # will be assigned at construction
def __init__(self, bn_group, **kwargs):
super(Layers_NCHW, self).__init__()
self.nhwc = False
self.bn_group = bn_group
if (bn_group > 1):
bn_base = gbn
else:
bn_base = nn.BatchNorm2d
class BnAddRelu_(bn_base):
def __init__(self, planes, fuse_relu=False, bn_group=1):
if (bn_group > 1):
super(BnAddRelu_, self).__init__(
planes,
process_group=apex.parallel.create_syncbn_process_group(bn_group))
else:
super(BnAddRelu_, self).__init__(planes)
self.fuse_relu_flag = fuse_relu
def forward(self, x, z=None):
out = super().forward(x)
if z is not None:
out = out.add_(z)
if self.fuse_relu_flag:
out = out.relu_()
return out
# this is still Layers_NCHW::__init__
self.BnAddRelu = BnAddRelu_
def build_bn(self, planes, fuse_relu=False):
return self.BnAddRelu(planes, fuse_relu, self.bn_group)
class Layers_NHWC:
Conv2d = Conv2d_NHWC
MaxPool = MaxPool2d_NHWC
class BnAddRelu(gbn_persistent):
def __init__(self, planes, fuse_relu=False, bn_group=1):
super(Layers_NHWC.BnAddRelu, self).__init__(planes,
fuse_relu,
bn_group=bn_group)
def __init__(self, bn_group, **kwargs):
super(Layers_NHWC, self).__init__()
self.nhwc = True
self.bn_group = bn_group
def build_bn(self, planes, fuse_relu):
return self.BnAddRelu(planes, fuse_relu, self.bn_group)
def conv1x1(layer_types, in_planes, out_planes, stride=1):
"""1x1 convolution"""
return layer_types.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride,
bias=False)
def conv3x3(layer_types, in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return layer_types.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, layerImpls, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(layerImpls, inplanes, planes, stride=stride)
self.bn1 = layerImpls.build_bn(planes, fuse_relu=True)
self.conv2 = conv3x3(layerImpls, planes, planes)
self.bn2 = layerImpls.build_bn(planes, fuse_relu=True)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
if self.downsample is not None:
residual = self.downsample(x)
out = self.conv1(x)
out = self.bn1(out)
out = self.conv2(out)
out = self.bn2(out, residual)
return out
class ResNet(nn.Module):
def __init__(self, layerImpls, block, layers, num_classes=1000,
pad_input=False, ssd_mods=False, use_nhwc=False,
bn_group=1):
self.inplanes = 64
super(ResNet, self).__init__()
if pad_input:
input_channels = 4
else:
input_channels = 3
self.conv1 = layerImpls.Conv2d(input_channels, 64, kernel_size=7, stride=2,
padding=3, bias=False)
self.bn1 = layerImpls.build_bn(64, fuse_relu=True)
self.maxpool = layerImpls.MaxPool(kernel_size=3, stride=2, padding=1)
# Add conv{2,3,4}
self.layer1 = self._make_layer(layerImpls, block, 64, layers[0])
self.layer2 = self._make_layer(layerImpls, block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(layerImpls, block, 256, layers[2], stride=1)
# FIXME! This (a) fails for nhwc, and (b) is irrelevant if the user is
# also loading pretrained data (which we don't know about here, but
# know about in the caller (the "resnet()" function below).
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def _make_layer(self, layerImpls, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
layerImpls.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
layerImpls.build_bn(planes * block.expansion, fuse_relu=False),
)
layers = []
layers.append(block(layerImpls, self.inplanes, planes, stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(layerImpls, self.inplanes, planes))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.classifier(x)
return x
def _transpose_state(state, pad_input=False):
for k in state.keys():
if len(state[k].shape) == 4:
if pad_input and "conv1.weight" in k and not 'layer' in k:
s = state[k].shape
state[k] = torch.cat([state[k], torch.zeros([s[0], 1, s[2], s[3]])], dim=1)
state[k] = state[k].permute(0, 2, 3, 1).contiguous()
return state
def resnet34(pretrained=False, nhwc=False, ssd_mods=False, **kwargs):
"""Constructs a ResNet model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
if nhwc:
layerImpls = Layers_NHWC(**kwargs)
else:
layerImpls = Layers_NCHW(**kwargs)
block = BasicBlock
layer_list = [3, 4, 6, 3]
model = ResNet(layerImpls, block, layer_list, ssd_mods=ssd_mods, use_nhwc=nhwc, **kwargs)
if pretrained:
orig_state_dict = model_zoo.load_url(model_urls['resnet34'])
# Modify the state dict to remove conv5 / layer4
state_dict = {k:orig_state_dict[k] for k in orig_state_dict if (not k.startswith('layer4') and not k.startswith('fc'))}
pad_input = kwargs.get('pad_input', False)
if nhwc:
state_dict = _transpose_state(state_dict, pad_input)
model.load_state_dict(state_dict)
return nn.Sequential(model.conv1, model.bn1, model.maxpool, model.layer1, model.layer2, model.layer3)
| {
"content_hash": "ca49e8cbdcc1e4dec919ae7bc7e5aec8",
"timestamp": "",
"source": "github",
"line_count": 220,
"max_line_length": 127,
"avg_line_length": 35.804545454545455,
"alnum_prop": 0.584105623968516,
"repo_name": "mlperf/training_results_v0.7",
"id": "0030d419034e826b4e41b2f0d3cc75e34cb3a57d",
"size": "8492",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Fujitsu/benchmarks/ssd/implementations/implementation_closed/resnet.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "1731"
},
{
"name": "Awk",
"bytes": "14530"
},
{
"name": "Batchfile",
"bytes": "13130"
},
{
"name": "C",
"bytes": "172914"
},
{
"name": "C++",
"bytes": "13037795"
},
{
"name": "CMake",
"bytes": "113458"
},
{
"name": "CSS",
"bytes": "70255"
},
{
"name": "Clojure",
"bytes": "622652"
},
{
"name": "Cuda",
"bytes": "1974745"
},
{
"name": "Dockerfile",
"bytes": "149523"
},
{
"name": "Groovy",
"bytes": "160449"
},
{
"name": "HTML",
"bytes": "171537"
},
{
"name": "Java",
"bytes": "189275"
},
{
"name": "JavaScript",
"bytes": "98224"
},
{
"name": "Julia",
"bytes": "430755"
},
{
"name": "Jupyter Notebook",
"bytes": "11091342"
},
{
"name": "Lua",
"bytes": "17720"
},
{
"name": "MATLAB",
"bytes": "34903"
},
{
"name": "Makefile",
"bytes": "215967"
},
{
"name": "Perl",
"bytes": "1551186"
},
{
"name": "PowerShell",
"bytes": "13906"
},
{
"name": "Python",
"bytes": "36943114"
},
{
"name": "R",
"bytes": "134921"
},
{
"name": "Raku",
"bytes": "7280"
},
{
"name": "Ruby",
"bytes": "4930"
},
{
"name": "SWIG",
"bytes": "140111"
},
{
"name": "Scala",
"bytes": "1304960"
},
{
"name": "Shell",
"bytes": "1312832"
},
{
"name": "Smalltalk",
"bytes": "3497"
},
{
"name": "Starlark",
"bytes": "69877"
},
{
"name": "TypeScript",
"bytes": "243012"
}
],
"symlink_target": ""
} |
#ifndef HEADER_CURL_CONFIG_MAC_H
#define HEADER_CURL_CONFIG_MAC_H
/* =================================================================== */
/* Hand crafted config file for Mac OS 9 */
/* =================================================================== */
/* On Mac OS X you must run configure to generate curl_config.h file */
/* =================================================================== */
#define OS "mac"
/* Define if you want the built-in manual */
#define USE_MANUAL 1
#define HAVE_ERRNO_H 1
#define HAVE_NETINET_IN_H 1
#define HAVE_SYS_SOCKET_H 1
#define HAVE_SYS_SELECT_H 1
#define HAVE_NETDB_H 1
#define HAVE_ARPA_INET_H 1
#define HAVE_UNISTD_H 1
#define HAVE_NET_IF_H 1
#define HAVE_SYS_TYPES_H 1
#define HAVE_GETTIMEOFDAY 1
#define HAVE_FCNTL_H 1
#define HAVE_SYS_STAT_H 1
#define HAVE_ALLOCA_H 1
#define HAVE_STDLIB_H 1
#define HAVE_TIME_H 1
#define HAVE_UTIME_H 1
#define HAVE_SYS_TIME_H 1
#define HAVE_SYS_UTIME_H 1
#define TIME_WITH_SYS_TIME 1
#define HAVE_ALARM 1
#define HAVE_FTRUNCATE 1
#define HAVE_UTIME 1
#define HAVE_SETVBUF 1
#define HAVE_STRFTIME 1
#define HAVE_INET_ADDR 1
#define HAVE_MEMCPY 1
#define HAVE_SELECT 1
#define HAVE_SOCKET 1
#define HAVE_STRUCT_TIMEVAL 1
#define HAVE_SIGACTION 1
#define HAVE_SIGNAL_H 1
#define HAVE_SIG_ATOMIC_T 1
#ifdef MACOS_SSL_SUPPORT
# define USE_OPENSSL 1
#endif
#define CURL_DISABLE_LDAP 1
#define HAVE_RAND_STATUS 1
//#define HAVE_RAND_EGD 1
//#define HAVE_IOCTL 1
//#define HAVE_IOCTL_FIONBIO 1
#define HAVE_FCNTL_O_NONBLOCK 1
#define HAVE_LONGLONG 1
#define RETSIGTYPE void
#define SIZEOF_INT 4
#define SIZEOF_SHORT 2
#define SIZEOF_SIZE_T 4
#define HAVE_GETNAMEINFO 1
#define GETNAMEINFO_QUAL_ARG1 const
#define GETNAMEINFO_TYPE_ARG1 struct sockaddr *
#define GETNAMEINFO_TYPE_ARG2 socklen_t
#define GETNAMEINFO_TYPE_ARG46 size_t
#define GETNAMEINFO_TYPE_ARG7 int
#define HAVE_RECV 1
#define RECV_TYPE_ARG1 int
#define RECV_TYPE_ARG2 void *
#define RECV_TYPE_ARG3 size_t
#define RECV_TYPE_ARG4 int
#define RECV_TYPE_RETV ssize_t
#define HAVE_RECVFROM 1
#define RECVFROM_TYPE_ARG1 int
#define RECVFROM_TYPE_ARG2 void
#define RECVFROM_TYPE_ARG3 size_t
#define RECVFROM_TYPE_ARG4 int
#define RECVFROM_TYPE_ARG5 struct sockaddr
#define RECVFROM_TYPE_ARG6 int
#define RECVFROM_TYPE_RETV ssize_t
#define RECVFROM_TYPE_ARG2_IS_VOID 1
#define HAVE_SEND 1
#define SEND_TYPE_ARG1 int
#define SEND_QUAL_ARG2 const
#define SEND_TYPE_ARG2 void *
#define SEND_TYPE_ARG3 size_t
#define SEND_TYPE_ARG4 int
#define SEND_TYPE_RETV ssize_t
//#define HAVE_EXTRA_STRICMP_H 1
//#define HAVE_EXTRA_STRDUP_H 1
#endif /* HEADER_CURL_CONFIG_MAC_H */
| {
"content_hash": "8bf7a1b4854cb7ed3b92aea3c6778f90",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 73,
"avg_line_length": 28.485981308411215,
"alnum_prop": 0.5980971128608924,
"repo_name": "rhomobile/rhodes",
"id": "ba9f357ba78218cfb687ce6f3df07c996fd615a4",
"size": "4073",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "platform/shared/curl/lib/config-mac.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "6291"
},
{
"name": "Batchfile",
"bytes": "115330"
},
{
"name": "C",
"bytes": "61309502"
},
{
"name": "C#",
"bytes": "702078"
},
{
"name": "C++",
"bytes": "16790255"
},
{
"name": "COBOL",
"bytes": "187"
},
{
"name": "CSS",
"bytes": "641054"
},
{
"name": "GAP",
"bytes": "76344"
},
{
"name": "HTML",
"bytes": "1827679"
},
{
"name": "Java",
"bytes": "6590034"
},
{
"name": "JavaScript",
"bytes": "1828506"
},
{
"name": "MATLAB",
"bytes": "123"
},
{
"name": "Makefile",
"bytes": "360667"
},
{
"name": "Mustache",
"bytes": "20693"
},
{
"name": "NASL",
"bytes": "285"
},
{
"name": "NSIS",
"bytes": "75538"
},
{
"name": "Objective-C",
"bytes": "5257884"
},
{
"name": "Objective-C++",
"bytes": "479778"
},
{
"name": "Perl",
"bytes": "1710"
},
{
"name": "QML",
"bytes": "29477"
},
{
"name": "QMake",
"bytes": "117073"
},
{
"name": "Rebol",
"bytes": "130"
},
{
"name": "Roff",
"bytes": "328967"
},
{
"name": "Ruby",
"bytes": "17391657"
},
{
"name": "SWIG",
"bytes": "65013"
},
{
"name": "Shell",
"bytes": "39045"
},
{
"name": "SourcePawn",
"bytes": "4786"
},
{
"name": "XSLT",
"bytes": "4315"
}
],
"symlink_target": ""
} |
package android.content;
import com.facebook.infer.builtins.InferBuiltins;
import com.facebook.infer.builtins.InferUndefined;
import android.database.Cursor;
import android.database.sqlite.SQLiteCursor;
import android.net.Uri;
import android.os.CancellationSignal;
import android.os.RemoteException;
public class ContentProviderClient {
private ContentResolver mContentResolver;
private IContentProvider mContentProvider;
private String mPackageName;
private boolean mStable;
ContentProviderClient(
ContentResolver contentResolver, IContentProvider contentProvider, boolean stable) {
mContentResolver = contentResolver;
mContentProvider = contentProvider;
mPackageName = (String)InferUndefined.object_undefined();
mStable = stable;
}
public Cursor query(Uri url, String[] projection, String selection,
String[] selectionArgs, String sortOrder) throws RemoteException {
return query(url, projection, selection, selectionArgs, sortOrder, null);
}
public Cursor query(Uri url, String[] projection, String selection, String[] selectionArgs,
String sortOrder, CancellationSignal cancellationSignal) throws RemoteException {
return new SQLiteCursor(null, null, null);
}
private class NotRespondingRunnable {
}
}
| {
"content_hash": "c8e53f54198976159423b3149b31cbd9",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 105,
"avg_line_length": 31.25,
"alnum_prop": 0.7323636363636363,
"repo_name": "ryoon/infer",
"id": "18e878ffad525e3b4a8d3ea589c4ac5642178ac0",
"size": "1683",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "infer/models/java/src/android/content/ContentProviderClient.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "172593"
},
{
"name": "C++",
"bytes": "19798"
},
{
"name": "CMake",
"bytes": "700"
},
{
"name": "Java",
"bytes": "704286"
},
{
"name": "LLVM",
"bytes": "9227"
},
{
"name": "Makefile",
"bytes": "18803"
},
{
"name": "OCaml",
"bytes": "2649867"
},
{
"name": "Objective-C",
"bytes": "91110"
},
{
"name": "Objective-C++",
"bytes": "430"
},
{
"name": "Perl",
"bytes": "245"
},
{
"name": "Python",
"bytes": "102923"
},
{
"name": "Shell",
"bytes": "23262"
},
{
"name": "Standard ML",
"bytes": "783"
}
],
"symlink_target": ""
} |
FROM balenalib/revpi-connect-fedora:30-build
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
RUN dnf install -y \
python3-pip \
python3-dbus \
&& dnf clean all
# install "virtualenv", since the vast majority of users of this image will want it
RUN pip3 install -U --no-cache-dir --ignore-installed pip setuptools \
&& pip3 install --no-cache-dir virtualenv
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'As of January 1st, 2020, Python 2 was end-of-life, we will change the latest tag for Balenalib Python base image to Python 3.x and drop support for Python 2 soon. So after 1st July, 2020, all the balenalib Python latest tag will point to the latest Python 3 version and no changes, or fixes will be made to balenalib Python 2 base image. If you are using Python 2 for your application, please upgrade to Python 3 before 1st July.' > /.balena/messages/python-deprecation-warning
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \
&& echo "Running test-stack@python" \
&& chmod +x test-stack@python.sh \
&& bash test-stack@python.sh \
&& rm -rf test-stack@python.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Fedora 30 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.9.1, Pip v20.3.1, Setuptools v51.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | {
"content_hash": "f1ee758a7ade44285489fc01c5771f12",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 707,
"avg_line_length": 78.03225806451613,
"alnum_prop": 0.7337742868954114,
"repo_name": "nghiant2710/base-images",
"id": "eac53018e9645ac20137ed102b906d795ebf9442",
"size": "2440",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/python/revpi-connect/fedora/30/3.9.1/build/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "144558581"
},
{
"name": "JavaScript",
"bytes": "16316"
},
{
"name": "Shell",
"bytes": "368690"
}
],
"symlink_target": ""
} |
/**
\file
\brief This file contains the abstraction of the kstat system on Solaris
\date 2007-08-22 11:39:54
*/
/*----------------------------------------------------------------------------*/
#ifndef SCXKSTAT_H
#define SCXKSTAT_H
#if !defined(sun)
#error this file is only meaningful on the SunOS platform
#endif
#include <string>
#include <sstream>
#include <kstat.h>
#include <scxcorelib/scxcmn.h>
#include <scxcorelib/scxexception.h>
#include <scxcorelib/stringaid.h>
#include <scxcorelib/scxhandle.h>
#include <scxcorelib/scxthread.h>
#include <scxcorelib/scxthreadlock.h>
namespace SCXSystemLib
{
/*----------------------------------------------------------------------------*/
/**
This class encapsulates dependencies for the kstat system on solaris.
\date 2008-11-12 13:30
*/
class SCXKstatDependencies
{
public:
SCXKstatDependencies() {
m_lock = SCXCoreLib::ThreadLockHandleGet(L"SCXSystemLib::SCXKstatDependencies");
}
/** Virtual destructor */
virtual ~SCXKstatDependencies() {}
/** Open kstat system.
\returns a kstat_ctl_t pointer.
*/
virtual kstat_ctl_t* Open() {
SCXCoreLib::SCXThreadLock lock(m_lock);
return kstat_open();
}
/** Close the kstat system.
\param pCCS A kstat_ctl_t pointer.
*/
virtual void Close(kstat_ctl_t* pCCS) {
SCXCoreLib::SCXThreadLock lock(m_lock);
kstat_close(pCCS);
}
/** Update the kstat header chain.
\param pCCS A kstat_ctl_t pointer.
\returns Upon successful completion, kstat_chain_update() returns the new
KCID if the kstat chain has changed and 0 if it has not changed.
Otherwise, it returns -1 and sets errno to indicate the error.
*/
virtual kid_t Update(kstat_ctl_t* pCCS) {
SCXCoreLib::SCXThreadLock lock(m_lock);
return kstat_chain_update(pCCS);
}
/** Lookup a kstat instance.
\param pCCS A kstat_ctl_t pointer.
\param m Module.
\param i Instance.
\param n Name.
\returns A kstat_t pointer.
*/
virtual kstat_t* Lookup(kstat_ctl_t* pCCS, char* m, int i, char* n) {
SCXCoreLib::SCXThreadLock lock(m_lock);
return kstat_lookup(pCCS, m, i, n);
}
/** Read a kstat instance.
\param pCCS A kstat_ctl_t pointer.
\param pKS A kstat_t pointer.
\param p A void pointer.
\returns -1 on error.
*/
virtual int Read(kstat_ctl_t* pCCS, kstat_t* pKS, void* p) {
SCXCoreLib::SCXThreadLock lock(m_lock);
return kstat_read(pCCS, pKS, p);
}
/**
Extract named data from a kstat instance.
\param pKS a kstat_t pointer
\param statistic the name of the statistic
\returns a pointer to the data element, or NULL if it doesn't exist.
*/
virtual void* DataLookup(kstat_t* pKS, const std::wstring& statistic) {
SCXCoreLib::SCXThreadLock lock(m_lock);
return kstat_data_lookup(pKS, const_cast<char*>(SCXCoreLib::StrToMultibyte(statistic).c_str()));
}
private:
//! Named lock for this instance to be shared across all threads
SCXCoreLib::SCXThreadLockHandle m_lock;
};
/*----------------------------------------------------------------------------*/
/**
This class represents the file system metrics on Solaris that are available
to both KSTAT_TYPE_NAMED and KSTAT_TYPE_IO.
Prior to Solaris 10, the recommended method for getting FS statistics from
kstat was to lookup the appropriate KSTAT_TYPE_IO structure for the device.
Since Solaris 10, the recommended method is to use VOP statistics and lookup
a KSTAT_TYPE_NAMED structure. These two structures do not map 1-to-1, they
do not even completely cover each other. This class represents a mapping
of the statistics that are common or at least seem to have a reasonable
mapping.
*/
class SCXKstatFSSample
{
private:
scxulong m_numReadOps;
scxulong m_bytesRead;
scxulong m_numWriteOps;
scxulong m_bytesWritten;
public:
SCXKstatFSSample(scxulong numReadOps, scxulong bytesRead, scxulong numWriteOps, scxulong bytesWritten)
: m_numReadOps(numReadOps),
m_bytesRead(bytesRead),
m_numWriteOps(numWriteOps),
m_bytesWritten(bytesWritten)
{
}
SCXKstatFSSample(const SCXKstatFSSample & source)
: m_numReadOps(source.m_numReadOps),
m_bytesRead(source.m_bytesRead),
m_numWriteOps(source.m_numWriteOps),
m_bytesWritten(source.m_bytesWritten)
{
}
SCXKstatFSSample & operator=(const SCXKstatFSSample & source)
{
if (&source != this)
{
m_numReadOps = source.m_numReadOps;
m_bytesRead = source.m_bytesRead;
m_numWriteOps = source.m_numWriteOps;
m_bytesWritten = source.m_bytesWritten;
}
return *this;
}
scxulong GetNumReadOps() const { return m_numReadOps; }
scxulong GetBytesRead() const { return m_bytesRead; }
scxulong GetNumWriteOps() const { return m_numWriteOps; }
scxulong GetBytesWritten() const { return m_bytesWritten; }
};
/*----------------------------------------------------------------------------*/
/**
This class encapsulates the kstat system on Solaris.
\date 2007-08-22 11:41:20
Most uses of the kstat system follows the same pattern. By encapsulating
this pattern in this class, writers of PALs do not have to worry
to much about the inner workings of kstat.
*/
class SCXKstat
{
private:
kstat_ctl_t* m_ChainControlStructure; //!< Pointer to kstat chain.
kstat_t* m_KstatPointer; //!< Pointer to retrieved kstat.
bool TryGetStatisticFromNamed(const std::wstring& statistic, scxulong& value) const;
bool TryGetStatisticFromIO(const std::wstring& statistic, scxulong& value) const;
SCXKstatFSSample GetFSSampleFromNamed() const;
SCXKstatFSSample GetFSSampleFromIO() const;
protected:
/** Test constructor - used during tests for dependency injection
*/
SCXKstat(SCXCoreLib::SCXHandle<SCXKstatDependencies> deps)
: m_ChainControlStructure(0),
m_KstatPointer(0),
m_deps(deps)
{ }
SCXCoreLib::SCXHandle<SCXKstatDependencies> m_deps; //!< Dependency object.
/** Gets pointer to external data. This is a way for a mock-object to
replace a pointer to RAW data with a pointer to a local area
over which it has control.
\returns NULL for the base class. Override in subclasses.
*/
virtual void* GetExternalDataPointer() { return 0; }
/** Initializes the kstat object for given instance.
\throws SCXKstatErrorException if kstat internal error.
\throws SCXKstatNotFoundException if requested kstat is not found in kstat system.
*/
void Init();
public:
SCXKstat();
virtual ~SCXKstat();
virtual void Update();
virtual void Lookup(const std::wstring& module, const std::wstring& name, int instance = -1);
virtual void Lookup(const std::wstring& module, int instance = -1);
virtual void Lookup(const char* module, const char *name, int instance = -1);
virtual scxulong GetValue(const std::wstring& statistic) const;
virtual bool TryGetValue(const std::wstring& statistic, scxulong& value) const;
template<typename T> void GetValueRaw(const T*& dataArea); // Defined below
virtual SCXKstatFSSample GetFSSample() const;
virtual std::wstring DumpString() const;
virtual kstat_t* ResetInternalIterator();
virtual kstat_t* AdvanceInternalIterator();
/** Read string value from the kstat object.
\throws SCXNotSupportedException if named data is of unsupported type.
*/
virtual bool TryGetStringValue(const std::wstring& statistic, std::wstring& value) const;
};
/** Exception for general kstat error */
class SCXKstatException : public SCXCoreLib::SCXException
{
public:
/*----------------------------------------------------------------------------*/
/**
Constructor
\param[in] reason Reason for exception.
\param[in] eno Errno related to the error.
\param[in] module Module name of related kstat object.
\param[in] instance Instance number of related kstat object.
\param[in] name Name of related kstat object.
\param[in] l Source code location.
*/
SCXKstatException(std::wstring reason, int eno,
const std::wstring& module, int instance, const std::wstring name,
const SCXCoreLib::SCXCodeLocation& l)
: SCXException(l),
m_Reason(reason),
m_errno(eno)
{
m_Path = module;
m_Path.append(L":").append(SCXCoreLib::StrFrom(instance)).append(L":").append(name);
};
/*----------------------------------------------------------------------------*/
/**
Constructor
\param[in] reason Reason for exception.
\param[in] eno Errno related to the error.
\param[in] l Source code location.
*/
SCXKstatException(std::wstring reason, int eno, const SCXCoreLib::SCXCodeLocation& l)
: SCXException(l),
m_Reason(reason),
m_errno(eno),
m_Path(L"::")
{ }
std::wstring What() const;
/*----------------------------------------------------------------------------*/
/**
Return errno related to the error.
*/
int GetErrno() const { return m_errno; }
protected:
//! Description of internal error
std::wstring m_Reason;
int m_errno; //!< Errno related to the error.
std::wstring m_Path; //!< Kstat path describing related kstat object.
};
/** Exception for kstat internal error */
class SCXKstatErrorException : public SCXKstatException
{
public:
/*----------------------------------------------------------------------------*/
/**
Constructor
\param[in] reason Reason for exception.
\param[in] eno Errno related to the error.
\param[in] module Module name of related kstat object.
\param[in] instance Instance number of related kstat object.
\param[in] name Name of related kstat object.
\param[in] l Source code location.
*/
SCXKstatErrorException(std::wstring reason, int eno,
const std::wstring& module, int instance, const std::wstring name,
const SCXCoreLib::SCXCodeLocation& l)
: SCXKstatException(reason, eno, module, instance, name, l)
{};
/*----------------------------------------------------------------------------*/
/**
Constructor
\param[in] reason Reason for exception.
\param[in] eno Errno related to the error.
\param[in] l Source code location.
*/
SCXKstatErrorException(std::wstring reason, int eno, const SCXCoreLib::SCXCodeLocation& l)
: SCXKstatException(reason, eno, l)
{};
};
/** Exception for when kstat was not found */
class SCXKstatNotFoundException : public SCXKstatException
{
public:
/*----------------------------------------------------------------------------*/
/**
Constructor
\param[in] reason Reason for exception.
\param[in] eno Errno related to the error.
\param[in] module Module name of related kstat object.
\param[in] instance Instance number of related kstat object.
\param[in] name Name of related kstat object.
\param[in] l Source code location.
*/
SCXKstatNotFoundException(std::wstring reason, int eno,
const std::wstring& module, int instance, const std::wstring name,
const SCXCoreLib::SCXCodeLocation& l)
: SCXKstatException(reason, eno, module, instance, name, l)
{};
/*----------------------------------------------------------------------------*/
/**
Constructor
\param[in] reason Reason for exception.
\param[in] eno Errno related to the error.
\param[in] l Source code location.
*/
SCXKstatNotFoundException(std::wstring reason, int eno,const SCXCoreLib::SCXCodeLocation& l)
: SCXKstatException(reason, eno, l)
{};
};
/** Exception for when a speciffic kstat speciffic was not found */
class SCXKstatStatisticNotFoundException : public SCXKstatException
{
public:
/*----------------------------------------------------------------------------*/
/**
Constructor
\param[in] reason Reason for exception.
\param[in] eno Errno related to the error.
\param[in] module Module name of related kstat object.
\param[in] instance Instance number of related kstat object.
\param[in] name Name of related kstat object.
\param[in] l Source code location.
*/
SCXKstatStatisticNotFoundException(std::wstring reason, int eno,
const std::wstring& module, int instance, const std::wstring name,
const SCXCoreLib::SCXCodeLocation& l)
: SCXKstatException(reason, eno, module, instance, name, l)
{};
/*----------------------------------------------------------------------------*/
/**
Constructor
\param[in] reason Reason for exception.
\param[in] eno Errno related to the error.
\param[in] l Source code location.
*/
SCXKstatStatisticNotFoundException(std::wstring reason, int eno,
const SCXCoreLib::SCXCodeLocation& l)
: SCXKstatException(reason, eno, l)
{};
};
/**
Retrieves raw data from the kstat interface. Raw data from Kstat is expected
to map directly to a "known" datatype, represented by T in this template. This
method will return a pointer to such raw data. The user is not expected to
allocate a data area, but will instead receive a pointer directly onto the Kstat data.
\param[out] dataArea Will receive a pointer to raw data from kstat
\throws SCXNotSupportedException if trying to extract non-raw data, or
if size of data area doesn't match size of retrieved data.
*/
template<typename T> inline void SCXKstat::GetValueRaw(const T*& dataArea)
{
SCXASSERT(KSTAT_TYPE_RAW == m_KstatPointer->ks_type);
SCXASSERT(sizeof(T) == m_KstatPointer->ks_data_size);
if (KSTAT_TYPE_RAW != m_KstatPointer->ks_type) {
throw SCXCoreLib::SCXNotSupportedException(L"kstat type must be \"raw\"",
SCXSRCLOCATION);
}
if (sizeof(T) != m_KstatPointer->ks_data_size) {
std::ostringstream errmsg;
errmsg << "Size of data for kstat module " << m_KstatPointer->ks_module
<< " doesn't match datatype \"" << typeid(T).name() << "\":";
throw SCXCoreLib::SCXNotSupportedException(SCXCoreLib::StrFromMultibyte(
errmsg.str()), SCXSRCLOCATION);
}
// Get mock data area, or real data area.
if (0 == (dataArea = static_cast<T*>(GetExternalDataPointer()))) {
dataArea = static_cast<T*>(m_KstatPointer->ks_data);
}
}
}
#endif /* SCXKSTAT_H */
/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/
| {
"content_hash": "e248c28ed0b04d98fb5b1460de75fb01",
"timestamp": "",
"source": "github",
"line_count": 436,
"max_line_length": 110,
"avg_line_length": 38.07339449541284,
"alnum_prop": 0.5521686746987952,
"repo_name": "MSFTOSSMgmt/SCVMMLinuxGuestAgent",
"id": "56edb0f8f31902ee4fd800bd015cfa0c0f8afdc0",
"size": "17306",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "pal/source/code/include/scxsystemlib/scxkstat.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "2517"
},
{
"name": "C",
"bytes": "4366"
},
{
"name": "C++",
"bytes": "3307131"
},
{
"name": "Makefile",
"bytes": "83773"
},
{
"name": "Shell",
"bytes": "124832"
}
],
"symlink_target": ""
} |
package org.apache.hyracks.storage.am.lsm.common;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.io.FileReference;
import org.apache.hyracks.storage.am.common.api.ITreeIndex;
import org.apache.hyracks.storage.am.common.api.IndexException;
import org.apache.hyracks.storage.am.lsm.common.impls.AbstractLSMIndexFileManager;
import org.apache.hyracks.storage.am.lsm.common.impls.TreeIndexFactory;
import org.apache.hyracks.storage.common.file.IFileMapProvider;
public class DummyLSMIndexFileManager extends AbstractLSMIndexFileManager {
public DummyLSMIndexFileManager(IFileMapProvider fileMapProvider, FileReference file,
TreeIndexFactory<? extends ITreeIndex> treeFactory) {
super(fileMapProvider, file, treeFactory);
}
protected void cleanupAndGetValidFilesInternal(FilenameFilter filter,
TreeIndexFactory<? extends ITreeIndex> treeFactory, ArrayList<ComparableFileName> allFiles)
throws HyracksDataException, IndexException {
File dir = new File(baseDir);
String[] files = dir.list(filter);
for (String fileName : files) {
File file = new File(dir.getPath() + File.separator + fileName);
FileReference fileRef = new FileReference(file);
allFiles.add(new ComparableFileName(fileRef));
}
}
}
| {
"content_hash": "e3972793f75609b1b00098e042cfa309",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 103,
"avg_line_length": 41.48571428571429,
"alnum_prop": 0.7534435261707989,
"repo_name": "waans11/incubator-asterixdb-hyracks",
"id": "7716384f4e34c3230f464cc80c319cfc3ff41bc6",
"size": "2259",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "hyracks/hyracks-tests/hyracks-storage-am-lsm-common-test/src/test/java/org/apache/hyracks/storage/am/lsm/common/DummyLSMIndexFileManager.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2606"
},
{
"name": "CSS",
"bytes": "893"
},
{
"name": "HTML",
"bytes": "8762"
},
{
"name": "Java",
"bytes": "8715335"
},
{
"name": "JavaScript",
"bytes": "24904"
},
{
"name": "Shell",
"bytes": "16545"
}
],
"symlink_target": ""
} |
class CoinStats;
class TradingstatsPage;
class QTabWidget;
class QString;
class QToolBar;
class QAction;
class QStackedWidget;
namespace Ui {
class StatisticsPage;
}
class ClientModel;
class StatisticsPage : public QWidget {
Q_OBJECT
public:
explicit StatisticsPage(QWidget *parent = 0);
~StatisticsPage();
void setModel(ClientModel *model);
CoinStats *coinStatsWidget;
TradingstatsPage *tradingStatsWidget;
private:
Ui::StatisticsPage *ui;
ClientModel *model;
};
#endif // STATISTICSPAGE_H
| {
"content_hash": "32b4a57f84d410c2dff1041cd0e96e4a",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 49,
"avg_line_length": 16.242424242424242,
"alnum_prop": 0.7350746268656716,
"repo_name": "EuropecoinEUORG/EuropecoinV2",
"id": "98e1902f19ef56fbdb7be53ee622bfa7a8e8c1b4",
"size": "955",
"binary": false,
"copies": "1",
"ref": "refs/heads/DEV",
"path": "src/qt/statisticspage.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "51312"
},
{
"name": "C",
"bytes": "706252"
},
{
"name": "C++",
"bytes": "3558422"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "HTML",
"bytes": "50620"
},
{
"name": "Makefile",
"bytes": "11467"
},
{
"name": "NSIS",
"bytes": "5972"
},
{
"name": "Objective-C",
"bytes": "858"
},
{
"name": "Objective-C++",
"bytes": "3537"
},
{
"name": "Python",
"bytes": "2819"
},
{
"name": "QMake",
"bytes": "15040"
},
{
"name": "Shell",
"bytes": "8517"
}
],
"symlink_target": ""
} |
#include "tensorflow/core/common_runtime/direct_session.h"
#include <atomic>
#include <string>
#include <vector>
#include "tensorflow/core/common_runtime/constant_folding.h"
#include "tensorflow/core/common_runtime/debugger_state_interface.h"
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/common_runtime/executor.h"
#include "tensorflow/core/common_runtime/function.h"
#include "tensorflow/core/common_runtime/graph_optimizer.h"
#include "tensorflow/core/common_runtime/memory_types.h"
#include "tensorflow/core/common_runtime/optimization_registry.h"
#include "tensorflow/core/common_runtime/step_stats_collector.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/graph.pb_text.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/graph_def_util.h"
#include "tensorflow/core/framework/log_memory.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/versions.pb.h"
#include "tensorflow/core/graph/algorithm.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/graph/graph_constructor.h"
#include "tensorflow/core/graph/graph_partition.h"
#include "tensorflow/core/graph/subgraph.h"
#include "tensorflow/core/graph/tensor_id.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/notification.h"
#include "tensorflow/core/lib/core/refcount.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
#include "tensorflow/core/lib/gtl/stl_util.h"
#include "tensorflow/core/lib/monitoring/counter.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/cpu_info.h"
#include "tensorflow/core/platform/device_tracer.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/device_name_utils.h"
#include "tensorflow/core/util/env_var.h"
namespace tensorflow {
namespace {
auto* direct_session_runs = monitoring::Counter<0>::New(
"/tensorflow/core/direct_session_runs",
"The number of times DirectSession::Run() has been called.");
int32 NumInterOpThreadsFromSessionOptions(const SessionOptions& options) {
const int32 t = options.config.inter_op_parallelism_threads();
if (t != 0) return t;
// Default to using the number of cores available in the process.
return port::NumSchedulableCPUs();
}
thread::ThreadPool* NewThreadPoolFromSessionOptions(
const SessionOptions& options) {
const int32 num_threads = NumInterOpThreadsFromSessionOptions(options);
VLOG(1) << "Direct session inter op parallelism threads: " << num_threads;
return new thread::ThreadPool(options.env, "Compute", num_threads);
}
Status NewThreadPoolFromThreadPoolOptions(
const SessionOptions& options,
const ThreadPoolOptionProto& thread_pool_options, int pool_number,
thread::ThreadPool** pool, bool* owned) {
int32 num_threads = thread_pool_options.num_threads();
if (num_threads == 0) {
num_threads = NumInterOpThreadsFromSessionOptions(options);
}
const string& name = thread_pool_options.global_name();
if (name.empty()) {
// Session-local threadpool.
VLOG(1) << "Direct session inter op parallelism threads for pool "
<< pool_number << ": " << num_threads;
*pool = new thread::ThreadPool(
options.env, strings::StrCat("Compute", pool_number), num_threads);
*owned = true;
return Status::OK();
}
// Global, named threadpool.
typedef std::pair<int32, thread::ThreadPool*> MapValue;
static std::map<string, MapValue>* global_pool_map =
new std::map<string, MapValue>;
static mutex* mu = new mutex();
mutex_lock l(*mu);
MapValue* mvalue = &(*global_pool_map)[name];
if (mvalue->second == nullptr) {
mvalue->first = thread_pool_options.num_threads();
mvalue->second = new thread::ThreadPool(
options.env, strings::StrCat("Compute", pool_number), num_threads);
} else {
if (mvalue->first != thread_pool_options.num_threads()) {
return errors::InvalidArgument(
"Pool ", name,
" configured previously with num_threads=", mvalue->first,
"; cannot re-configure with num_threads=",
thread_pool_options.num_threads());
}
}
*owned = false;
*pool = mvalue->second;
return Status::OK();
}
thread::ThreadPool* GlobalThreadPool(const SessionOptions& options) {
static thread::ThreadPool* const thread_pool =
NewThreadPoolFromSessionOptions(options);
return thread_pool;
}
// TODO(vrv): Figure out how to unify the many different functions
// that generate RendezvousKey, since many of them have to be
// consistent with each other.
string GetRendezvousKey(const string& tensor_name,
const DeviceAttributes& device_info,
const FrameAndIter& frame_iter) {
return strings::StrCat(device_info.name(), ";",
strings::FpToString(device_info.incarnation()), ";",
device_info.name(), ";", tensor_name, ";",
frame_iter.frame_id, ":", frame_iter.iter_id);
}
} // namespace
class DirectSessionFactory : public SessionFactory {
public:
DirectSessionFactory() {}
bool AcceptsOptions(const SessionOptions& options) override {
return options.target.empty();
}
Session* NewSession(const SessionOptions& options) override {
// Must do this before the CPU allocator is created.
if (options.config.graph_options().build_cost_model() > 0) {
EnableCPUAllocatorFullStats(true);
}
std::vector<Device*> devices;
const Status s = DeviceFactory::AddDevices(
options, "/job:localhost/replica:0/task:0", &devices);
if (!s.ok()) {
LOG(ERROR) << s;
return nullptr;
}
DirectSession* session =
new DirectSession(options, new DeviceMgr(devices), this);
{
mutex_lock l(sessions_lock_);
sessions_.push_back(session);
}
return session;
}
Status Reset(const SessionOptions& options,
const std::vector<string>& containers) override {
std::vector<DirectSession*> sessions_to_reset;
{
mutex_lock l(sessions_lock_);
// We create a copy to ensure that we don't have a deadlock when
// session->Close calls the DirectSessionFactory.Deregister, which
// acquires sessions_lock_.
std::swap(sessions_to_reset, sessions_);
}
Status s;
for (auto session : sessions_to_reset) {
s.Update(session->Reset(containers));
}
// TODO(suharshs): Change the Reset behavior of all SessionFactories so that
// it doesn't close the sessions?
for (auto session : sessions_to_reset) {
s.Update(session->Close());
}
return s;
}
void Deregister(const DirectSession* session) {
mutex_lock l(sessions_lock_);
sessions_.erase(std::remove(sessions_.begin(), sessions_.end(), session),
sessions_.end());
}
private:
mutex sessions_lock_;
std::vector<DirectSession*> sessions_ GUARDED_BY(sessions_lock_);
};
class DirectSessionRegistrar {
public:
DirectSessionRegistrar() {
SessionFactory::Register("DIRECT_SESSION", new DirectSessionFactory());
}
};
static DirectSessionRegistrar registrar;
std::atomic_int_fast64_t DirectSession::step_id_counter_(1);
// NOTE: On Android with a single device, there is never
// a risk of an OpKernel blocking indefinitely:
//
// 1) No operations do I/O that depends on other simultaneous kernels,
//
// 2) Recv nodes always complete immediately: The inputs are sent into
// the local rendezvous before we start the executor, so the
// corresponding recvs will not block.
//
// Based on these assumptions, we can use the same thread pool for
// both "non-blocking" and "blocking" OpKernels on Android.
//
// This may change down the road when we add support for multiple
// devices that run concurrently, in which case we will need to
// revisit this decision.
void DirectSession::SchedClosure(thread::ThreadPool* pool,
std::function<void()> c) {
// TODO(sanjay): Get rid of __ANDROID__ path
#ifdef __ANDROID__
// On Android, there is no implementation of ThreadPool that takes
// std::function, only Closure, which we cannot easily convert.
//
// Instead, we just run the function in-line, which is currently
// safe given the reasoning above.
c();
#else
pool->Schedule(std::move(c));
#endif // __ANDROID__
}
DirectSession::DirectSession(const SessionOptions& options,
const DeviceMgr* device_mgr,
DirectSessionFactory* const factory)
: options_(options),
device_mgr_(device_mgr),
factory_(factory),
cancellation_manager_(new CancellationManager()),
operation_timeout_in_ms_(options_.config.operation_timeout_in_ms()) {
if (options_.config.session_inter_op_thread_pool_size() > 0) {
for (int i = 0; i < options_.config.session_inter_op_thread_pool_size();
++i) {
thread::ThreadPool* pool = nullptr;
bool owned = false;
init_error_.Update(NewThreadPoolFromThreadPoolOptions(
options_, options_.config.session_inter_op_thread_pool(i), i, &pool,
&owned));
thread_pools_.emplace_back(pool, owned);
}
} else if (options_.config.use_per_session_threads()) {
thread_pools_.emplace_back(NewThreadPoolFromSessionOptions(options_),
true /* owned */);
} else {
thread_pools_.emplace_back(GlobalThreadPool(options), false /* owned */);
}
// The default value of sync_on_finish will be flipped soon and this
// environment variable will be removed as well.
const Status status =
ReadBoolFromEnvVar("TF_SYNC_ON_FINISH", true, &sync_on_finish_);
if (!status.ok()) {
LOG(ERROR) << status.error_message();
}
// NOTE(mrry): We do not need to use a unique string for the session
// handle, because DirectSession owns its devices. This may change
// in future versions.
session_handle_ = "direct";
int devices_added = 0;
if (options.config.log_device_placement()) {
const string mapping_str = device_mgr_->DeviceMappingString();
if (mapping_str.empty()) {
printf("Device mapping: no known devices.\n");
} else {
printf("Device mapping:\n%s", mapping_str.c_str());
}
LOG(INFO) << "Device mapping:\n" << mapping_str;
}
for (auto d : device_mgr_->ListDevices()) {
devices_.push_back(d);
device_set_.AddDevice(d);
d->op_segment()->AddHold(session_handle_);
// The first device added is special: it is the 'client device' (a
// CPU device) from which we feed and fetch Tensors.
if (devices_added == 0) {
device_set_.set_client_device(d);
}
++devices_added;
}
}
DirectSession::~DirectSession() {
if (!closed_) Close().IgnoreError();
for (auto& it : partial_runs_) {
it.second.reset(nullptr);
}
for (auto& it : executors_) {
it.second.reset();
}
for (auto d : device_mgr_->ListDevices()) {
d->op_segment()->RemoveHold(session_handle_);
}
delete cancellation_manager_;
for (const auto& p_and_owned : thread_pools_) {
if (p_and_owned.second) delete p_and_owned.first;
}
execution_state_.reset(nullptr);
flib_def_.reset(nullptr);
}
Status DirectSession::MaybeInitializeExecutionState(
const GraphDef& graph, bool* out_already_initialized) {
// If already initialized, do nothing.
if (flib_def_ && execution_state_) {
*out_already_initialized = true;
return Status::OK();
}
// Set up the per-session execution state.
// NOTE(mrry): The function library created here will be used for
// all subsequent extensions of the graph.
flib_def_.reset(
new FunctionLibraryDefinition(OpRegistry::Global(), graph.library()));
GraphExecutionStateOptions options;
options.device_set = &device_set_;
options.session_options = &options_;
// TODO(mrry,suharshs): We explicitly copy `graph` so that
// `MakeForBaseGraph()` can take ownership of its
// contents. Previously this happened implicitly in calls to the
// `GraphExecutionState`. Other sessions call
// `MakeForBaseGraph` in such a way that we can destructively read
// the passed-in `GraphDef`. In principle we could do the same here,
// with a wider refactoring; we might revise the direct session so
// that it copies the graph fewer times.
GraphDef temp(graph);
TF_RETURN_IF_ERROR(
GraphExecutionState::MakeForBaseGraph(&temp, options, &execution_state_));
graph_created_ = true;
*out_already_initialized = false;
return Status::OK();
}
Status DirectSession::Create(const GraphDef& graph) {
TF_RETURN_IF_ERROR(init_error_);
if (graph.node_size() > 0) {
mutex_lock l(graph_def_lock_);
if (graph_created_) {
return errors::AlreadyExists(
"A Graph has already been created for this session.");
}
return ExtendLocked(graph);
}
return Status::OK();
}
Status DirectSession::Extend(const GraphDef& graph) {
TF_RETURN_IF_ERROR(CheckNotClosed());
mutex_lock l(graph_def_lock_);
return ExtendLocked(graph);
}
Status DirectSession::ExtendLocked(const GraphDef& graph) {
bool already_initialized;
// If this is the first call, we can initialize the execution state
// with `graph` and do not need to call `Extend()`.
TF_RETURN_IF_ERROR(
MaybeInitializeExecutionState(graph, &already_initialized));
if (already_initialized) {
TF_RETURN_IF_ERROR(flib_def_->AddLibrary(graph.library()));
std::unique_ptr<GraphExecutionState> state;
TF_RETURN_IF_ERROR(execution_state_->Extend(graph, &state));
execution_state_.swap(state);
}
return Status::OK();
}
Status DirectSession::Run(const NamedTensorList& inputs,
const std::vector<string>& output_names,
const std::vector<string>& target_nodes,
std::vector<Tensor>* outputs) {
RunMetadata run_metadata;
return Run(RunOptions(), inputs, output_names, target_nodes, outputs,
&run_metadata);
}
Status DirectSession::CreateDebuggerState(
const DebugOptions& debug_options, int64 session_run_index,
int64 executor_step_index, const std::vector<string>& input_names,
const std::vector<string>& output_names,
const std::vector<string>& target_names,
std::unique_ptr<DebuggerStateInterface>* debugger_state) {
TF_RETURN_IF_ERROR(
DebuggerStateRegistry::CreateState(debug_options, debugger_state));
TF_RETURN_IF_ERROR(debugger_state->get()->PublishDebugMetadata(
debug_options.global_step(), session_run_index, executor_step_index,
input_names, output_names, target_names));
return Status::OK();
}
Status DirectSession::DecorateAndPublishGraphForDebug(
const DebugOptions& debug_options, Graph* graph, Device* device) {
std::unique_ptr<DebugGraphDecoratorInterface> decorator;
TF_RETURN_IF_ERROR(
DebugGraphDecoratorRegistry::CreateDecorator(debug_options, &decorator));
TF_RETURN_IF_ERROR(decorator->DecorateGraph(graph, device));
TF_RETURN_IF_ERROR(decorator->PublishGraph(*graph, device->name()));
return Status::OK();
}
Status DirectSession::Run(const RunOptions& run_options,
const NamedTensorList& inputs,
const std::vector<string>& output_names,
const std::vector<string>& target_nodes,
std::vector<Tensor>* outputs,
RunMetadata* run_metadata) {
TF_RETURN_IF_ERROR(CheckNotClosed());
direct_session_runs->GetCell()->IncrementBy(1);
{
mutex_lock l(graph_def_lock_);
if (!graph_created_) {
return errors::InvalidArgument(
"Session was not created with a graph before Run()!");
}
}
// Extract the inputs names for this run of the session.
std::vector<string> input_tensor_names;
input_tensor_names.reserve(inputs.size());
for (const auto& it : inputs) {
input_tensor_names.push_back(it.first);
}
if (run_options.inter_op_thread_pool() < 0 ||
run_options.inter_op_thread_pool() >= thread_pools_.size()) {
return errors::InvalidArgument("Invalid inter_op_thread_pool: ",
run_options.inter_op_thread_pool());
}
thread::ThreadPool* pool =
thread_pools_[run_options.inter_op_thread_pool()].first;
// Check if we already have an executor for these arguments.
ExecutorsAndKeys* executors_and_keys;
RunStateArgs run_state_args(run_options.debug_options());
Executor::Args args;
args.step_id = step_id_counter_.fetch_add(1);
TF_RETURN_IF_ERROR(
GetOrCreateExecutors(input_tensor_names, output_names, target_nodes,
&executors_and_keys, &run_state_args));
const int64 executor_step_count = executors_and_keys->step_count.fetch_add(1);
std::unique_ptr<DebuggerStateInterface> debugger_state;
if (!run_options.debug_options().debug_tensor_watch_opts().empty()) {
TF_RETURN_IF_ERROR(CreateDebuggerState(
run_options.debug_options(), args.step_id, executor_step_count,
input_tensor_names, output_names, target_nodes, &debugger_state));
}
// Configure a call frame for the step, which we use to feed and
// fetch values to and from the executors.
FunctionCallFrame call_frame(executors_and_keys->input_types,
executors_and_keys->output_types);
gtl::InlinedVector<Tensor, 4> feed_args(inputs.size());
for (const auto& it : inputs) {
if (it.second.dtype() == DT_RESOURCE) {
Tensor tensor_from_handle;
TF_RETURN_IF_ERROR(
ResourceHandleToInputTensor(it.second, &tensor_from_handle));
feed_args[executors_and_keys->input_name_to_index[it.first]] =
tensor_from_handle;
} else {
feed_args[executors_and_keys->input_name_to_index[it.first]] = it.second;
}
}
const Status s = call_frame.SetArgs(feed_args);
if (errors::IsInternal(s)) {
return errors::InvalidArgument(s.error_message());
} else if (!s.ok()) {
return s;
}
// Create a run state and start execution.
RunState run_state(args.step_id, &devices_);
run_state.rendez = new IntraProcessRendezvous(device_mgr_.get());
CancellationManager step_cancellation_manager;
args.call_frame = &call_frame;
// Start parallel Executors.
const size_t num_executors = executors_and_keys->items.size();
ExecutorBarrier* barrier = new ExecutorBarrier(
num_executors, run_state.rendez, [&run_state](const Status& ret) {
{
mutex_lock l(run_state.mu_);
run_state.status.Update(ret);
}
run_state.executors_done.Notify();
});
args.rendezvous = run_state.rendez;
args.cancellation_manager = &step_cancellation_manager;
args.session_state = &session_state_;
args.tensor_store = &run_state.tensor_store;
args.step_container = &run_state.step_container;
if (LogMemory::IsEnabled()) {
LogMemory::RecordStep(args.step_id, run_state_args.handle);
}
args.sync_on_finish = sync_on_finish_;
const bool do_trace = (run_options.trace_level() > RunOptions::NO_TRACE);
bool update_cost_model = false;
if (options_.config.graph_options().build_cost_model() > 0) {
const int64 build_cost_model_every =
options_.config.graph_options().build_cost_model();
const int64 build_cost_model_after =
options_.config.graph_options().build_cost_model_after();
int64 measure_step_count = executor_step_count - build_cost_model_after;
if (measure_step_count >= 0) {
update_cost_model =
((measure_step_count + 1) % build_cost_model_every == 0);
}
}
if (do_trace || update_cost_model ||
run_options.report_tensor_allocations_upon_oom()) {
run_state.collector.reset(
new StepStatsCollector(run_metadata->mutable_step_stats()));
args.stats_collector = run_state.collector.get();
}
std::unique_ptr<DeviceTracer> tracer;
if (run_options.trace_level() >= RunOptions::HARDWARE_TRACE) {
tracer = CreateDeviceTracer();
// tracer may be NULL on platforms without accelerators.
if (tracer) {
Status s = tracer->Start();
if (!s.ok()) {
run_state.executors_done.Notify();
delete barrier;
return s;
}
}
}
// Register this step with session's cancellation manager, so that
// `Session::Close()` will cancel the step.
const CancellationToken cancellation_token =
cancellation_manager_->get_cancellation_token();
const bool already_cancelled = !cancellation_manager_->RegisterCallback(
cancellation_token, [&step_cancellation_manager]() {
step_cancellation_manager.StartCancel();
});
if (already_cancelled) {
// NOTE(mrry): If we don't explicitly notify
// `run_state.executors_done`, the RunState destructor would
// block on this notification.
run_state.executors_done.Notify();
delete barrier;
return errors::Cancelled("Run call was cancelled");
}
Executor::Args::Runner default_runner = [this,
pool](Executor::Args::Closure c) {
SchedClosure(pool, std::move(c));
};
for (const auto& item : executors_and_keys->items) {
// TODO(zhengxq): support partial run.
// TODO(zhengxq): if the device picks its own threadpool, we need to assign
// less threads to the main compute pool by default.
thread::ThreadPool* device_thread_pool =
item.device->tensorflow_device_thread_pool();
if (!device_thread_pool) {
args.runner = default_runner;
} else {
args.runner = [this, device_thread_pool](Executor::Args::Closure c) {
SchedClosure(device_thread_pool, std::move(c));
};
}
item.executor->RunAsync(args, barrier->Get());
}
WaitForNotification(&run_state, &step_cancellation_manager,
run_options.timeout_in_ms() > 0
? run_options.timeout_in_ms()
: operation_timeout_in_ms_);
if (!cancellation_manager_->DeregisterCallback(cancellation_token)) {
// The step has been cancelled: make sure we don't attempt to receive the
// outputs as this would make it block forever.
mutex_lock l(run_state.mu_);
run_state.status.Update(errors::Cancelled("Run call was cancelled"));
}
if (tracer) {
TF_RETURN_IF_ERROR(tracer->Stop());
TF_RETURN_IF_ERROR(tracer->Collect(args.stats_collector));
}
{
mutex_lock l(run_state.mu_);
TF_RETURN_IF_ERROR(run_state.status);
}
// Receive outputs.
if (outputs) {
std::vector<Tensor> sorted_outputs;
const Status s = call_frame.ConsumeRetvals(&sorted_outputs);
if (errors::IsInternal(s)) {
return errors::InvalidArgument(s.error_message());
} else if (!s.ok()) {
return s;
}
const bool unique_outputs =
output_names.size() == executors_and_keys->output_name_to_index.size();
// first_indices[i] = j implies that j is the smallest value for which
// output_names[i] == output_names[j].
std::vector<int> first_indices;
if (!unique_outputs) {
first_indices.resize(output_names.size());
for (int i = 0; i < output_names.size(); ++i) {
for (int j = 0; j <= i; ++j) {
if (output_names[i] == output_names[j]) {
first_indices[i] = j;
break;
}
}
}
}
outputs->clear();
outputs->reserve(sorted_outputs.size());
for (int i = 0; i < output_names.size(); ++i) {
const string& output_name = output_names[i];
if (first_indices.empty() || first_indices[i] == i) {
outputs->emplace_back(
std::move(sorted_outputs[executors_and_keys
->output_name_to_index[output_name]]));
} else {
outputs->push_back((*outputs)[first_indices[i]]);
}
}
}
// Save the output tensors of this run we choose to keep.
TF_RETURN_IF_ERROR(
run_state.tensor_store.SaveTensors(output_names, &session_state_));
if (args.stats_collector) {
args.stats_collector->Finalize();
}
// Build and return the cost model as instructed.
mutex_lock l(executor_lock_);
if (update_cost_model) {
// Build the cost model
std::unordered_map<string, const Graph*> device_to_graph;
for (const PerPartitionExecutorsAndLib& partition :
executors_and_keys->items) {
const Graph* graph = partition.graph;
const string device = partition.flib->device()->name();
device_to_graph[device] = graph;
}
args.stats_collector->BuildCostModel(&cost_model_manager_, device_to_graph);
// annotate stats onto cost graph.
CostGraphDef* cost_graph = run_metadata->mutable_cost_graph();
for (const auto& item : executors_and_keys->items) {
TF_RETURN_IF_ERROR(
cost_model_manager_.AddToCostGraphDef(item.graph, cost_graph));
}
}
// If requested via RunOptions, output the partition graphs.
if (run_options.output_partition_graphs()) {
protobuf::RepeatedPtrField<GraphDef>* partition_graph_defs =
run_metadata->mutable_partition_graphs();
for (const PerPartitionExecutorsAndLib& exec_and_lib :
executors_and_keys->items) {
GraphDef* partition_graph_def = partition_graph_defs->Add();
exec_and_lib.graph->ToGraphDef(partition_graph_def);
}
}
return Status::OK();
}
Status DirectSession::PRunSetup(const std::vector<string>& input_names,
const std::vector<string>& output_names,
const std::vector<string>& target_nodes,
string* handle) {
TF_RETURN_IF_ERROR(CheckNotClosed());
{
mutex_lock l(graph_def_lock_);
if (!graph_created_) {
return errors::InvalidArgument(
"Session was not created with a graph before PRunSetup()!");
}
}
// RunOptions is not available in PRunSetup, so use thread pool 0.
thread::ThreadPool* pool = thread_pools_[0].first;
// Check if we already have an executor for these arguments.
ExecutorsAndKeys* executors_and_keys;
// TODO(cais): TFDBG support for partial runs.
DebugOptions debug_options;
RunStateArgs run_state_args(debug_options);
run_state_args.is_partial_run = true;
TF_RETURN_IF_ERROR(GetOrCreateExecutors(input_names, output_names,
target_nodes, &executors_and_keys,
&run_state_args));
// Create the run state and save it for future PRun calls.
Executor::Args args;
args.step_id = step_id_counter_.fetch_add(1);
RunState* run_state =
new RunState(input_names, output_names, args.step_id, &devices_);
run_state->rendez = new IntraProcessRendezvous(device_mgr_.get());
{
mutex_lock l(executor_lock_);
if (!partial_runs_
.emplace(run_state_args.handle,
std::unique_ptr<RunState>(run_state))
.second) {
return errors::Internal("The handle '", run_state_args.handle,
"' created for this partial run is not unique.");
}
}
// Start parallel Executors.
const size_t num_executors = executors_and_keys->items.size();
ExecutorBarrier* barrier = new ExecutorBarrier(
num_executors, run_state->rendez, [run_state](const Status& ret) {
if (!ret.ok()) {
mutex_lock l(run_state->mu_);
run_state->status.Update(ret);
}
run_state->executors_done.Notify();
});
args.rendezvous = run_state->rendez;
args.cancellation_manager = cancellation_manager_;
args.runner = [this, pool](Executor::Args::Closure c) {
SchedClosure(pool, std::move(c));
};
args.session_state = &session_state_;
args.tensor_store = &run_state->tensor_store;
args.step_container = &run_state->step_container;
if (LogMemory::IsEnabled()) {
LogMemory::RecordStep(args.step_id, run_state_args.handle);
}
args.sync_on_finish = sync_on_finish_;
if (options_.config.graph_options().build_cost_model()) {
run_state->collector.reset(new StepStatsCollector(nullptr));
args.stats_collector = run_state->collector.get();
}
for (auto& item : executors_and_keys->items) {
item.executor->RunAsync(args, barrier->Get());
}
*handle = run_state_args.handle;
return Status::OK();
}
Status DirectSession::PRun(const string& handle, const NamedTensorList& inputs,
const std::vector<string>& output_names,
std::vector<Tensor>* outputs) {
TF_RETURN_IF_ERROR(CheckNotClosed());
std::vector<string> parts = str_util::Split(handle, ';');
const string& key = parts[0];
// Get the executors for this partial run.
ExecutorsAndKeys* executors_and_keys;
RunState* run_state;
{
mutex_lock l(executor_lock_); // could use reader lock
auto exc_it = executors_.find(key);
if (exc_it == executors_.end()) {
return errors::InvalidArgument(
"Must run 'setup' before performing partial runs!");
}
executors_and_keys = exc_it->second.get();
auto prun_it = partial_runs_.find(handle);
if (prun_it == partial_runs_.end()) {
return errors::InvalidArgument(
"Must run 'setup' before performing partial runs!");
}
run_state = prun_it->second.get();
// Make sure that this is a new set of feeds that are still pending.
for (const auto& input : inputs) {
auto it = run_state->pending_inputs.find(input.first);
if (it == run_state->pending_inputs.end()) {
return errors::InvalidArgument(
"The feed ", input.first,
" was not specified in partial_run_setup.");
} else if (it->second) {
return errors::InvalidArgument("The feed ", input.first,
" has already been fed.");
}
}
// Check that this is a new set of fetches that are still pending.
for (const auto& output : output_names) {
auto it = run_state->pending_outputs.find(output);
if (it == run_state->pending_outputs.end()) {
return errors::InvalidArgument(
"The fetch ", output, " was not specified in partial_run_setup.");
} else if (it->second) {
return errors::InvalidArgument("The fetch ", output,
" has already been fetched.");
}
}
}
// Check that this new set of fetches can be computed from all the
// feeds we have supplied.
TF_RETURN_IF_ERROR(
CheckFetch(inputs, output_names, executors_and_keys, run_state));
// Send inputs.
Status s = SendPRunInputs(inputs, executors_and_keys, run_state->rendez);
// Receive outputs.
if (s.ok()) {
s = RecvPRunOutputs(output_names, executors_and_keys, run_state, outputs);
}
// Save the output tensors of this run we choose to keep.
if (s.ok()) {
s = run_state->tensor_store.SaveTensors(output_names, &session_state_);
}
{
mutex_lock l(executor_lock_);
// Delete the run state if there is an error or all fetches are done.
bool done = true;
if (s.ok()) {
{
mutex_lock l(run_state->mu_);
if (!run_state->status.ok()) {
LOG(WARNING) << "An error unrelated to this prun has been detected. "
<< run_state->status;
}
}
for (const auto& input : inputs) {
auto it = run_state->pending_inputs.find(input.first);
it->second = true;
}
for (const auto& name : output_names) {
auto it = run_state->pending_outputs.find(name);
it->second = true;
}
done = run_state->PendingDone();
}
if (done) {
WaitForNotification(run_state, cancellation_manager_,
operation_timeout_in_ms_);
partial_runs_.erase(handle);
}
}
return s;
}
Status DirectSession::ResourceHandleToInputTensor(const Tensor& resource_tensor,
Tensor* retrieved_tensor) {
if (resource_tensor.dtype() != DT_RESOURCE) {
return errors::InvalidArgument(strings::StrCat(
"ResourceHandleToInputTensor() received non-DT_RESOURCE Tensor: ",
resource_tensor.dtype()));
}
const ResourceHandle& resource_handle =
resource_tensor.scalar<ResourceHandle>()();
if (resource_handle.container() ==
SessionState::kTensorHandleResourceTypeName) {
return session_state_.GetTensor(resource_handle.name(), retrieved_tensor);
} else {
return errors::InvalidArgument(strings::StrCat(
"Invalid resource type hash code: ", resource_handle.hash_code(),
"(name: ", resource_handle.name(),
" type: ", resource_handle.maybe_type_name(),
"). Perhaps a resource tensor was being provided as a feed? That is "
"not currently allowed. Please file an issue at "
"https://github.com/tensorflow/tensorflow/issues/new, ideally with a "
"short code snippet that leads to this error message."));
}
}
Status DirectSession::SendPRunInputs(const NamedTensorList& inputs,
const ExecutorsAndKeys* executors_and_keys,
IntraProcessRendezvous* rendez) {
Status s;
Rendezvous::ParsedKey parsed;
// Insert the input tensors into the local rendezvous by their
// rendezvous key.
for (const auto& input : inputs) {
auto it =
executors_and_keys->input_name_to_rendezvous_key.find(input.first);
if (it == executors_and_keys->input_name_to_rendezvous_key.end()) {
return errors::Internal("'", input.first, "' is not a pre-defined feed.");
}
const string& input_key = it->second;
s = Rendezvous::ParseKey(input_key, &parsed);
if (!s.ok()) {
rendez->StartAbort(s);
return s;
}
if (input.second.dtype() == DT_RESOURCE) {
Tensor tensor_from_handle;
s = ResourceHandleToInputTensor(input.second, &tensor_from_handle);
if (s.ok()) {
s = rendez->Send(parsed, Rendezvous::Args(), tensor_from_handle, false);
}
} else {
s = rendez->Send(parsed, Rendezvous::Args(), input.second, false);
}
if (!s.ok()) {
rendez->StartAbort(s);
return s;
}
}
return Status::OK();
}
Status DirectSession::RecvPRunOutputs(
const std::vector<string>& output_names,
const ExecutorsAndKeys* executors_and_keys, RunState* run_state,
std::vector<Tensor>* outputs) {
Status s;
if (!output_names.empty()) {
outputs->resize(output_names.size());
}
Rendezvous::ParsedKey parsed;
// Get the outputs from the rendezvous
for (size_t output_offset = 0; output_offset < output_names.size();
++output_offset) {
const string& output_name = output_names[output_offset];
auto it =
executors_and_keys->output_name_to_rendezvous_key.find(output_name);
if (it == executors_and_keys->output_name_to_rendezvous_key.end()) {
return errors::Internal("'", output_name,
"' is not a pre-defined fetch.");
}
const string& output_key = it->second;
Tensor output_tensor;
bool is_dead;
IntraProcessRendezvous* rendez = run_state->rendez;
s = Rendezvous::ParseKey(output_key, &parsed);
if (s.ok()) {
// Fetch data from the Rendezvous.
s = rendez->Recv(parsed, Rendezvous::Args(), &output_tensor, &is_dead,
operation_timeout_in_ms_);
if (is_dead && s.ok()) {
s = errors::InvalidArgument("The tensor returned for ", output_name,
" was not valid.");
}
}
if (!s.ok()) {
rendez->StartAbort(s);
outputs->clear();
return s;
}
(*outputs)[output_offset] = output_tensor;
}
return Status::OK();
}
Status DirectSession::CheckFetch(const NamedTensorList& feeds,
const std::vector<string>& fetches,
const ExecutorsAndKeys* executors_and_keys,
const RunState* run_state) {
const Graph* graph = executors_and_keys->graph.get();
const NameNodeMap* name_to_node = &executors_and_keys->name_to_node;
// Build the set of pending feeds that we haven't seen.
std::unordered_set<TensorId, TensorId::Hasher> pending_feeds;
{
mutex_lock l(executor_lock_);
for (const auto& input : run_state->pending_inputs) {
// Skip if the feed has already been fed.
if (input.second) continue;
TensorId id(ParseTensorName(input.first));
auto it = name_to_node->find(id.first);
if (it == name_to_node->end()) {
return errors::NotFound("Feed ", input.first, ": not found");
}
pending_feeds.insert(id);
}
}
for (const auto& it : feeds) {
TensorId id(ParseTensorName(it.first));
pending_feeds.erase(id);
}
// Initialize the stack with the fetch nodes.
std::vector<const Node*> stack;
for (const string& fetch : fetches) {
TensorId id(ParseTensorName(fetch));
auto it = name_to_node->find(id.first);
if (it == name_to_node->end()) {
return errors::NotFound("Fetch ", fetch, ": not found");
}
stack.push_back(it->second);
}
// Any tensor needed for fetches can't be in pending_feeds.
std::vector<bool> visited(graph->num_node_ids(), false);
while (!stack.empty()) {
const Node* n = stack.back();
stack.pop_back();
for (const Edge* in_edge : n->in_edges()) {
const Node* in_node = in_edge->src();
if (pending_feeds.count({in_node->name(), in_edge->src_output()}) > 0) {
return errors::InvalidArgument("Fetch ", in_node->name(), ":",
in_edge->src_output(),
" can't be computed from the feeds"
" that have been fed so far.");
}
if (!visited[in_node->id()]) {
visited[in_node->id()] = true;
stack.push_back(in_node);
}
}
}
return Status::OK();
}
Status DirectSession::GetOrCreateExecutors(
gtl::ArraySlice<string> inputs, gtl::ArraySlice<string> outputs,
gtl::ArraySlice<string> target_nodes, ExecutorsAndKeys** executors_and_keys,
RunStateArgs* run_state_args) {
int64 handle_name_counter_value = -1;
if (LogMemory::IsEnabled() || run_state_args->is_partial_run) {
handle_name_counter_value = handle_name_counter_.fetch_add(1);
}
string debug_tensor_watches_summary;
if (!run_state_args->debug_options.debug_tensor_watch_opts().empty()) {
debug_tensor_watches_summary = SummarizeDebugTensorWatches(
run_state_args->debug_options.debug_tensor_watch_opts());
}
// Fast lookup path, no sorting.
const string key = strings::StrCat(
str_util::Join(inputs, ","), "->", str_util::Join(outputs, ","), "/",
str_util::Join(target_nodes, ","), "/", run_state_args->is_partial_run,
"/", debug_tensor_watches_summary);
// Set the handle, if it's needed to log memory or for partial run.
if (handle_name_counter_value >= 0) {
run_state_args->handle =
strings::StrCat(key, ";", handle_name_counter_value);
}
// See if we already have the executors for this run.
{
mutex_lock l(executor_lock_); // could use reader lock
auto it = executors_.find(key);
if (it != executors_.end()) {
*executors_and_keys = it->second.get();
return Status::OK();
}
}
// Slow lookup path, the unsorted key missed the cache.
// Sort the inputs and outputs, and look up with the sorted key in case an
// earlier call used a different order of inputs and outputs.
//
// We could consider some other signature instead of sorting that
// preserves the same property to avoid the sort in the future.
std::vector<string> inputs_sorted(inputs.begin(), inputs.end());
std::sort(inputs_sorted.begin(), inputs_sorted.end());
std::vector<string> outputs_sorted(outputs.begin(), outputs.end());
std::sort(outputs_sorted.begin(), outputs_sorted.end());
std::vector<string> tn_sorted(target_nodes.begin(), target_nodes.end());
std::sort(tn_sorted.begin(), tn_sorted.end());
const string sorted_key = strings::StrCat(
str_util::Join(inputs_sorted, ","), "->",
str_util::Join(outputs_sorted, ","), "/", str_util::Join(tn_sorted, ","),
"/", run_state_args->is_partial_run, "/", debug_tensor_watches_summary);
// Set the handle, if its needed to log memory or for partial run.
if (handle_name_counter_value >= 0) {
run_state_args->handle =
strings::StrCat(sorted_key, ";", handle_name_counter_value);
}
// See if we already have the executors for this run.
{
mutex_lock l(executor_lock_);
auto it = executors_.find(sorted_key);
if (it != executors_.end()) {
*executors_and_keys = it->second.get();
// Insert this under the original key.
executors_.emplace(key, it->second);
return Status::OK();
}
}
// Nothing found, so create the executors and store in the cache.
BuildGraphOptions options;
options.feed_endpoints = inputs_sorted;
options.fetch_endpoints = outputs_sorted;
options.target_nodes = tn_sorted;
options.use_function_convention = !run_state_args->is_partial_run;
if (!run_state_args->debug_options.debug_tensor_watch_opts().empty()) {
options.debug_options = run_state_args->debug_options;
}
std::shared_ptr<ExecutorsAndKeys> ek(new ExecutorsAndKeys);
// The executor_lock_ is intentionally released while executor is
// being created.
std::unordered_map<string, std::unique_ptr<Graph>> graphs;
TF_RETURN_IF_ERROR(CreateGraphs(options, &graphs, &ek->flib_def,
run_state_args, &ek->input_types,
&ek->output_types));
if (run_state_args->is_partial_run) {
ek->graph = std::move(run_state_args->graph);
std::unordered_set<StringPiece, StringPieceHasher> names;
for (const string& input : inputs) {
TensorId id(ParseTensorName(input));
names.emplace(id.first);
}
for (const string& output : outputs) {
TensorId id(ParseTensorName(output));
names.emplace(id.first);
}
for (Node* n : ek->graph->nodes()) {
if (names.count(n->name()) > 0) {
ek->name_to_node.insert({n->name(), n});
}
}
}
ek->items.reserve(graphs.size());
const auto& optimizer_opts =
options_.config.graph_options().optimizer_options();
int graph_def_version;
{
mutex_lock l(graph_def_lock_);
graph_def_version =
execution_state_->original_graph_def().versions().producer();
}
ek->proc_flr.reset(new ProcessFunctionLibraryRuntime(
device_mgr_.get(), options_.env, graph_def_version, ek->flib_def.get(),
optimizer_opts));
GraphOptimizer optimizer(optimizer_opts);
for (auto iter = graphs.begin(); iter != graphs.end(); ++iter) {
const string& partition_name = iter->first;
std::unique_ptr<Graph>& partition_graph = iter->second;
Device* device;
TF_RETURN_IF_ERROR(device_mgr_->LookupDevice(partition_name, &device));
ek->items.resize(ek->items.size() + 1);
auto* item = &(ek->items.back());
auto lib = ek->proc_flr->GetFLR(partition_name);
if (lib == nullptr) {
return errors::Internal("Could not find device: ", partition_name);
}
item->flib = lib;
LocalExecutorParams params;
params.device = device;
params.function_library = lib;
auto opseg = device->op_segment();
params.create_kernel = [this, lib, opseg](const NodeDef& ndef,
OpKernel** kernel) {
// We do not share the kernel via the OpSegment if the node is
// stateless, or a function.
// NOTE(mrry): We must not share function kernels (implemented
// using `CallOp`) between subgraphs, because `CallOp::handle_`
// is tied to a particular subgraph. Even if the function itself
// is stateful, the `CallOp` that invokes it is not.
if (!lib->IsStateful(ndef.op()) ||
lib->GetFunctionLibraryDefinition()->Find(ndef.op()) != nullptr) {
return lib->CreateKernel(ndef, kernel);
}
auto create_fn = [lib, &ndef](OpKernel** kernel) {
return lib->CreateKernel(ndef, kernel);
};
// Kernels created for subgraph nodes need to be cached. On
// cache miss, create_fn() is invoked to create a kernel based
// on the function library here + global op registry.
return opseg->FindOrCreate(session_handle_, ndef.name(), kernel,
create_fn);
};
params.delete_kernel = [lib](OpKernel* kernel) {
// If the node is stateful, opseg owns it. Otherwise, delete it.
if (kernel && !lib->IsStateful(kernel->type_string())) {
delete kernel;
}
};
params.node_outputs_cb = node_outputs_callback_;
optimizer.Optimize(lib, options_.env, device, &iter->second,
/*shape_map=*/nullptr);
// EXPERIMENTAL: tfdbg inserts debug nodes in the graph.
if (!options.debug_options.debug_tensor_watch_opts().empty()) {
TF_RETURN_IF_ERROR(DecorateAndPublishGraphForDebug(
options.debug_options, partition_graph.get(), params.device));
}
TF_RETURN_IF_ERROR(EnsureMemoryTypes(DeviceType(device->device_type()),
device->name(),
partition_graph.get()));
// NewLocalExecutor takes ownership of partition_graph.
item->graph = partition_graph.get();
item->executor = nullptr;
item->device = device;
Executor* executor;
TF_RETURN_IF_ERROR(
NewLocalExecutor(params, partition_graph.release(), &executor));
item->executor.reset(executor);
}
// Cache the mapping from input/output names to graph elements to
// avoid recomputing it every time.
if (!run_state_args->is_partial_run) {
// For regular `Run()`, we use the function calling convention, and so
// maintain a mapping from input/output names to
// argument/return-value ordinal index.
for (size_t i = 0; i < inputs_sorted.size(); ++i) {
const string& input = inputs_sorted[i];
ek->input_name_to_index[input] = i;
}
for (size_t i = 0; i < outputs_sorted.size(); ++i) {
const string& output = outputs_sorted[i];
ek->output_name_to_index[output] = i;
}
} else {
// For `PRun()`, we use the rendezvous calling convention, and so
// maintain a mapping from input/output names to rendezvous keys.
//
// We always use the first device as the device name portion of the
// key, even if we're feeding another graph.
for (size_t i = 0; i < inputs_sorted.size(); ++i) {
const string& input = inputs_sorted[i];
ek->input_name_to_rendezvous_key[input] = GetRendezvousKey(
input, device_set_.client_device()->attributes(), FrameAndIter(0, 0));
}
for (size_t i = 0; i < outputs_sorted.size(); ++i) {
const string& output = outputs_sorted[i];
ek->output_name_to_rendezvous_key[output] =
GetRendezvousKey(output, device_set_.client_device()->attributes(),
FrameAndIter(0, 0));
}
}
// Reacquire the lock, try to insert into the map.
mutex_lock l(executor_lock_);
// Another thread may have created the entry before us, in which case we will
// reuse the already created one.
auto insert_result = executors_.emplace(sorted_key, ek);
// Insert the value under the original key, so the fast path lookup will work
// if the user uses the same order of inputs, outputs, and targets again.
executors_.emplace(key, insert_result.first->second);
*executors_and_keys = insert_result.first->second.get();
return Status::OK();
}
Status DirectSession::CreateGraphs(
const BuildGraphOptions& subgraph_options,
std::unordered_map<string, std::unique_ptr<Graph>>* outputs,
std::unique_ptr<FunctionLibraryDefinition>* flib_def,
RunStateArgs* run_state_args, DataTypeVector* input_types,
DataTypeVector* output_types) {
mutex_lock l(graph_def_lock_);
std::unique_ptr<ClientGraph> client_graph;
std::unique_ptr<GraphExecutionState> temp_exec_state_holder;
GraphExecutionState* execution_state = nullptr;
if (options_.config.graph_options().place_pruned_graph()) {
// Because we are placing pruned graphs, we need to create a
// new GraphExecutionState for every new unseen graph,
// and then place it.
GraphExecutionStateOptions prune_options;
prune_options.device_set = &device_set_;
prune_options.session_options = &options_;
prune_options.stateful_placements = stateful_placements_;
TF_RETURN_IF_ERROR(GraphExecutionState::MakeForPrunedGraph(
execution_state_->original_graph_def().library(), prune_options,
execution_state_->original_graph_def(), subgraph_options,
&temp_exec_state_holder, &client_graph));
execution_state = temp_exec_state_holder.get();
} else {
execution_state = execution_state_.get();
TF_RETURN_IF_ERROR(
execution_state->BuildGraph(subgraph_options, &client_graph));
}
if (subgraph_options.feed_endpoints.size() !=
client_graph->feed_types.size()) {
return errors::Internal(
"Graph pruning failed: requested number of feed endpoints = ",
subgraph_options.feed_endpoints.size(),
" versus number of pruned feed endpoints = ",
client_graph->feed_types.size());
}
if (subgraph_options.fetch_endpoints.size() !=
client_graph->fetch_types.size()) {
return errors::Internal(
"Graph pruning failed: requested number of fetch endpoints = ",
subgraph_options.fetch_endpoints.size(),
" versus number of pruned fetch endpoints = ",
client_graph->fetch_types.size());
}
auto current_stateful_placements = execution_state->GetStatefulPlacements();
// Update our current state based on the execution_state's
// placements. If there are any mismatches for a node,
// we should fail, as this should never happen.
for (auto placement_pair : current_stateful_placements) {
const string& node_name = placement_pair.first;
const string& placement = placement_pair.second;
auto iter = stateful_placements_.find(node_name);
if (iter == stateful_placements_.end()) {
stateful_placements_.insert(std::make_pair(node_name, placement));
} else if (iter->second != placement) {
return errors::Internal(
"Stateful placement mismatch. "
"Current assignment of ",
node_name, " to ", iter->second, " does not match ", placement);
}
}
stateful_placements_ = execution_state->GetStatefulPlacements();
// Remember the graph in run state if this is a partial run.
if (run_state_args->is_partial_run) {
run_state_args->graph.reset(new Graph(flib_def_.get()));
CopyGraph(*execution_state->full_graph(), run_state_args->graph.get());
}
// Partition the graph across devices.
PartitionOptions popts;
popts.node_to_loc = [](const Node* node) {
return node->assigned_device_name();
};
popts.new_name = [this](const string& prefix) {
return strings::StrCat(prefix, "/_", edge_name_counter_.fetch_add(1));
};
popts.get_incarnation = [](const string& name) {
// The direct session does not have changing incarnation numbers.
// Just return '1'.
return 1;
};
popts.flib_def = &client_graph->graph.flib_def();
popts.control_flow_added = false;
std::unordered_map<string, GraphDef> partitions;
TF_RETURN_IF_ERROR(Partition(popts, &client_graph->graph, &partitions));
std::vector<string> device_names;
for (auto device : devices_) {
// Extract the LocalName from the device.
device_names.push_back(DeviceNameUtils::LocalName(device->name()));
}
// Check for valid partitions.
for (const auto& partition : partitions) {
const string local_partition_name =
DeviceNameUtils::LocalName(partition.first);
if (std::count(device_names.begin(), device_names.end(),
local_partition_name) == 0) {
return errors::InvalidArgument(
"Creating a partition for ", local_partition_name,
" which doesn't exist in the list of available devices. Available "
"devices: ",
str_util::Join(device_names, ","));
}
}
for (const auto& partition : partitions) {
std::unique_ptr<Graph> device_graph(
new Graph(client_graph->flib_def.get()));
GraphConstructorOptions device_opts;
// There are internal operations (e.g., send/recv) that we now allow.
device_opts.allow_internal_ops = true;
device_opts.expect_device_spec = true;
TF_RETURN_IF_ERROR(ConvertGraphDefToGraph(device_opts, partition.second,
device_graph.get()));
outputs->emplace(partition.first, std::move(device_graph));
}
GraphOptimizationPassOptions optimization_options;
optimization_options.session_options = &options_;
optimization_options.flib_def = client_graph->flib_def.get();
optimization_options.partition_graphs = outputs;
TF_RETURN_IF_ERROR(OptimizationPassRegistry::Global()->RunGrouping(
OptimizationPassRegistry::POST_PARTITIONING, optimization_options));
Status s;
for (auto& partition : *outputs) {
const string& partition_name = partition.first;
std::unique_ptr<Graph>* graph = &partition.second;
VLOG(2) << "Created " << DebugString(graph->get()) << " for "
<< partition_name;
// Give the device an opportunity to rewrite its subgraph.
Device* d;
s = device_mgr_->LookupDevice(partition_name, &d);
if (!s.ok()) break;
s = d->MaybeRewriteGraph(graph);
if (!s.ok()) {
break;
}
}
*flib_def = std::move(client_graph->flib_def);
std::swap(*input_types, client_graph->feed_types);
std::swap(*output_types, client_graph->fetch_types);
return s;
}
::tensorflow::Status DirectSession::ListDevices(
std::vector<DeviceAttributes>* response) {
response->clear();
response->reserve(devices_.size());
for (Device* d : devices_) {
const DeviceAttributes& attrs = d->attributes();
response->emplace_back(attrs);
}
return ::tensorflow::Status::OK();
}
::tensorflow::Status DirectSession::Reset(
const std::vector<string>& containers) {
device_mgr_->ClearContainers(containers);
return ::tensorflow::Status::OK();
}
::tensorflow::Status DirectSession::Close() {
cancellation_manager_->StartCancel();
{
mutex_lock l(closed_lock_);
if (closed_) return ::tensorflow::Status::OK();
closed_ = true;
}
if (factory_ != nullptr) factory_->Deregister(this);
return ::tensorflow::Status::OK();
}
DirectSession::RunState::RunState(
const std::vector<string>& pending_input_names,
const std::vector<string>& pending_output_names, int64 step_id,
const std::vector<Device*>* devices)
: step_container(step_id, [devices](const string& name) {
for (auto d : *devices) {
if (!d->resource_manager()->Cleanup(name).ok()) {
// Do nothing...
}
}
}) {
// Initially all the feeds and fetches are pending.
for (auto& name : pending_input_names) {
pending_inputs[name] = false;
}
for (auto& name : pending_output_names) {
pending_outputs[name] = false;
}
}
DirectSession::RunState::RunState(int64 step_id,
const std::vector<Device*>* devices)
: RunState({}, {}, step_id, devices) {}
DirectSession::RunState::~RunState() {
if (rendez != nullptr) {
if (!executors_done.HasBeenNotified()) {
rendez->StartAbort(errors::Cancelled("PRun cancellation"));
executors_done.WaitForNotification();
}
rendez->Unref();
}
}
bool DirectSession::RunState::PendingDone() const {
for (const auto& it : pending_inputs) {
if (!it.second) return false;
}
for (const auto& it : pending_outputs) {
if (!it.second) return false;
}
return true;
}
void DirectSession::WaitForNotification(RunState* run_state,
CancellationManager* cm,
int64 timeout_in_ms) {
const Status status =
WaitForNotification(&run_state->executors_done, timeout_in_ms);
if (!status.ok()) {
{
mutex_lock l(run_state->mu_);
run_state->status.Update(status);
}
cm->StartCancel();
// We must wait for the executors to complete, because they have borrowed
// references to `cm` and other per-step state. After this notification, it
// is safe to clean up the step.
run_state->executors_done.WaitForNotification();
}
}
::tensorflow::Status DirectSession::WaitForNotification(
Notification* notification, int64 timeout_in_ms) {
if (timeout_in_ms > 0) {
const int64 timeout_in_us = timeout_in_ms * 1000;
const bool notified =
WaitForNotificationWithTimeout(notification, timeout_in_us);
if (!notified) {
return Status(error::DEADLINE_EXCEEDED,
"Timed out waiting for notification");
}
} else {
notification->WaitForNotification();
}
return Status::OK();
}
} // namespace tensorflow
| {
"content_hash": "ad16c1dcb69fadc2ff9ff72a9a1bc287",
"timestamp": "",
"source": "github",
"line_count": 1546,
"max_line_length": 80,
"avg_line_length": 37.216688227684344,
"alnum_prop": 0.6448546152910302,
"repo_name": "hsaputra/tensorflow",
"id": "6e243c4b7c31ceb1b3c21b40981fde96a9c173b1",
"size": "58205",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tensorflow/core/common_runtime/direct_session.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "8913"
},
{
"name": "C",
"bytes": "320101"
},
{
"name": "C++",
"bytes": "35737831"
},
{
"name": "CMake",
"bytes": "188490"
},
{
"name": "Go",
"bytes": "1055853"
},
{
"name": "Java",
"bytes": "541818"
},
{
"name": "Jupyter Notebook",
"bytes": "1940884"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "Makefile",
"bytes": "44805"
},
{
"name": "Objective-C",
"bytes": "12456"
},
{
"name": "Objective-C++",
"bytes": "94716"
},
{
"name": "PHP",
"bytes": "1429"
},
{
"name": "Perl",
"bytes": "6179"
},
{
"name": "Perl 6",
"bytes": "1357"
},
{
"name": "PureBasic",
"bytes": "24932"
},
{
"name": "Python",
"bytes": "31102235"
},
{
"name": "Ruby",
"bytes": "547"
},
{
"name": "Shell",
"bytes": "402584"
}
],
"symlink_target": ""
} |
var checkScript = require('./checki18n');
checkScript.check(); | {
"content_hash": "04158eaf51ac2ad8f2a0ddc71761b4ee",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 41,
"avg_line_length": 31.5,
"alnum_prop": 0.7301587301587301,
"repo_name": "nickperez1285/truck-hunt-hackathon",
"id": "a3a0cd948fdc7250848468e780d37f7ca46dfae2",
"size": "63",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "client/stemapp/buildScripts/startchecki18n.js",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "292692"
},
{
"name": "HTML",
"bytes": "319830"
},
{
"name": "JavaScript",
"bytes": "5595621"
},
{
"name": "Shell",
"bytes": "5126"
}
],
"symlink_target": ""
} |
module Happstack.Server.SURI.ParseURI(parseURIRef) where
import qualified Data.ByteString as BB
import qualified Data.ByteString.Internal as BB
import qualified Data.ByteString.Unsafe as BB
import Data.ByteString.Char8 as BC
import Prelude hiding(break,length,null,drop,splitAt)
import Network.URI
-- import Happstack.Util.ByteStringCompat
parseURIRef :: ByteString -> URI
parseURIRef fs =
case break (\c -> ':' == c || '/' == c || '?' == c || '#' == c) fs of
(initial,rest) ->
let ui = unpack initial
in case uncons rest of
Nothing ->
if null initial then nullURI -- empty uri
else -- uri not containing either ':' or '/'
nullURI { uriPath = ui }
Just (c, rrest) ->
case c of
':' -> pabsuri rrest $ URI (unpack initial)
'/' -> puriref fs $ URI "" Nothing
'?' -> pquery rrest $ URI "" Nothing ui
'#' -> pfragment rrest $ URI "" Nothing ui ""
_ -> error "parseURIRef: Can't happen"
pabsuri :: ByteString
-> (Maybe URIAuth -> String -> String -> String -> b)
-> b
pabsuri fs cont =
if length fs >= 2 && unsafeHead fs == '/' && unsafeIndex fs 1 == '/'
then pauthority (drop 2 fs) cont
else puriref fs $ cont Nothing
pauthority :: ByteString
-> (Maybe URIAuth -> String -> String -> String -> b)
-> b
pauthority fs cont =
let (auth,rest) = breakChar '/' fs
in puriref rest $! cont (Just $! pauthinner auth)
pauthinner :: ByteString -> URIAuth
pauthinner fs =
case breakChar '@' fs of
(a,b) -> pauthport b $ URIAuth (unpack a)
pauthport :: ByteString -> (String -> String -> t) -> t
pauthport fs cont =
let spl idx = splitAt (idx+1) fs
in case unsafeHead fs of
_ | null fs -> cont "" ""
'[' -> case fmap spl (elemIndexEnd ']' fs) of
Just (a,b) | null b -> cont (unpack a) ""
| unsafeHead b == ':' -> cont (unpack a) (unpack $ unsafeTail b)
x -> error ("Parsing uri failed (pauthport):"++show x)
_ -> case breakCharEnd ':' fs of
(a,b) -> cont (unpack a) (unpack b)
puriref :: ByteString -> (String -> String -> String -> b) -> b
puriref fs cont =
let (u,r) = break (\c -> '#' == c || '?' == c) fs
in case unsafeHead r of
_ | null r -> cont (unpack u) "" ""
'?' -> pquery (unsafeTail r) $ cont (unpack u)
'#' -> pfragment (unsafeTail r) $ cont (unpack u) ""
_ -> error "unexpected match"
pquery :: ByteString -> (String -> String -> t) -> t
pquery fs cont =
case breakChar '#' fs of
(a,b) -> cont ('?':unpack a) (unpack b)
pfragment :: ByteString -> (String -> b) -> b
pfragment fs cont =
cont $ unpack fs
unsafeTail :: ByteString -> ByteString
unsafeTail = BB.unsafeTail
unsafeHead :: ByteString -> Char
unsafeHead = BB.w2c . BB.unsafeHead
unsafeIndex :: ByteString -> Int -> Char
unsafeIndex s = BB.w2c . BB.unsafeIndex s
-- | Semantically equivalent to break on strings
{-# INLINE breakChar #-}
breakChar :: Char -> ByteString -> (ByteString, ByteString)
breakChar ch = BB.break ((==) x) where x = BB.c2w ch
-- | 'breakCharEnd' behaves like breakChar, but from the end of the
-- ByteString.
--
-- > breakCharEnd ('b') (pack "aabbcc") == ("aab","cc")
--
-- and the following are equivalent:
--
-- > breakCharEnd 'c' "abcdef"
-- > let (x,y) = break (=='c') (reverse "abcdef")
-- > in (reverse (drop 1 y), reverse x)
--
{-# INLINE breakCharEnd #-}
breakCharEnd :: Char -> ByteString -> (ByteString, ByteString)
breakCharEnd c p = BB.breakEnd ((==) x) p where x = BB.c2w c
| {
"content_hash": "0693f9ceeffd918ef596ed9697d73c1a",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 108,
"avg_line_length": 37.693069306930695,
"alnum_prop": 0.5558182295770948,
"repo_name": "erantapaa/happstack-server",
"id": "1e6ce9b132603e8464059bdd54884757b3c2227b",
"size": "3807",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/Happstack/Server/SURI/ParseURI.hs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "1328"
},
{
"name": "HTML",
"bytes": "2878"
},
{
"name": "Haskell",
"bytes": "354979"
},
{
"name": "JavaScript",
"bytes": "4416"
},
{
"name": "Makefile",
"bytes": "338"
},
{
"name": "Nix",
"bytes": "1074"
},
{
"name": "XSLT",
"bytes": "15276"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct template result<This(T &)></title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../_byref.html#id2877301" title="Description">
<link rel="prev" href="../_byref.html" title="Struct _byref">
<link rel="next" href="result_This_T__id1536892.html" title="Struct template result<This(T)>">
</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="../_byref.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../_byref.html#id2877301"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="result_This_T__id1536892.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.proto._byref.result_This(T_&)_id1536856"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct template result<This(T &)></span></h2>
<p>boost::proto::_byref::result<This(T &)></p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../../proto/reference.html#header.boost.proto.transform.arg_hpp" title="Header <boost/proto/transform/arg.hpp>">boost/proto/transform/arg.hpp</a>>
</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> This<span class="special">,</span> <span class="keyword">typename</span> T<span class="special">></span>
<span class="keyword">struct</span> <a class="link" href="result_This_T____id1536856.html" title="Struct template result<This(T &)>">result</a><span class="special"><</span><span class="identifier">This</span><span class="special">(</span><span class="identifier">T</span> <span class="special">&</span><span class="special">)</span><span class="special">></span> <span class="special">{</span>
<span class="comment">// types</span>
<span class="keyword">typedef</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">reference_wrapper</span><span class="special"><</span> <span class="identifier">T</span> <span class="special">></span> <span class="keyword">const</span> <a name="boost.proto._byref.result_This(T_&)_id1536856.type"></a><span class="identifier">type</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span></pre></div>
</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 © 2008 Eric Niebler<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="../_byref.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../_byref.html#id2877301"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="result_This_T__id1536892.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "236c584814477ca89ac365ad797466ec",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 442,
"avg_line_length": 86.14814814814815,
"alnum_prop": 0.6502579535683577,
"repo_name": "djsedulous/namecoind",
"id": "cdbe03bf5fe0e5bf510d3ccc78b44d1fa0eb20e3",
"size": "4652",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "libs/boost_1_50_0/doc/html/boost/proto/_byref/result_This_T____id1536856.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "843598"
},
{
"name": "Awk",
"bytes": "90447"
},
{
"name": "C",
"bytes": "19896147"
},
{
"name": "C#",
"bytes": "121901"
},
{
"name": "C++",
"bytes": "132199970"
},
{
"name": "CSS",
"bytes": "336528"
},
{
"name": "Emacs Lisp",
"bytes": "1639"
},
{
"name": "IDL",
"bytes": "11976"
},
{
"name": "Java",
"bytes": "3955488"
},
{
"name": "JavaScript",
"bytes": "22346"
},
{
"name": "Max",
"bytes": "36857"
},
{
"name": "Objective-C",
"bytes": "23505"
},
{
"name": "Objective-C++",
"bytes": "2450"
},
{
"name": "PHP",
"bytes": "55712"
},
{
"name": "Perl",
"bytes": "4194947"
},
{
"name": "Python",
"bytes": "761429"
},
{
"name": "R",
"bytes": "4009"
},
{
"name": "Rebol",
"bytes": "354"
},
{
"name": "Scheme",
"bytes": "6073"
},
{
"name": "Shell",
"bytes": "550004"
},
{
"name": "Tcl",
"bytes": "2268735"
},
{
"name": "TeX",
"bytes": "13404"
},
{
"name": "TypeScript",
"bytes": "5318296"
},
{
"name": "XSLT",
"bytes": "757548"
},
{
"name": "eC",
"bytes": "5079"
}
],
"symlink_target": ""
} |
package org.qi4j.library.struts2.codebehind.bootstrap;
import org.qi4j.bootstrap.Assembler;
import org.qi4j.bootstrap.AssemblyException;
import org.qi4j.bootstrap.ModuleAssembly;
import org.qi4j.library.struts2.codebehind.Qi4jCodebehindPackageProvider;
public class CodebehindAssembler
implements Assembler
{
@Override
public void assemble( ModuleAssembly aModule )
throws AssemblyException
{
aModule.objects( Qi4jCodebehindPackageProvider.class );
}
}
| {
"content_hash": "9a61d261d0bc914ed9563b216f6cd428",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 73,
"avg_line_length": 27.333333333333332,
"alnum_prop": 0.7845528455284553,
"repo_name": "ramtej/Qi4j.Repo.4.Sync",
"id": "2d18c73db71915a242981b1b60294d574e2425d5",
"size": "492",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop",
"path": "libraries/struts2-codebehind/src/main/java/org/qi4j/library/struts2/codebehind/bootstrap/CodebehindAssembler.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "44634"
},
{
"name": "Groovy",
"bytes": "14940"
},
{
"name": "HTML",
"bytes": "73839"
},
{
"name": "Java",
"bytes": "6871146"
},
{
"name": "JavaScript",
"bytes": "17052"
},
{
"name": "Python",
"bytes": "4879"
},
{
"name": "Ruby",
"bytes": "81"
},
{
"name": "Scala",
"bytes": "2917"
},
{
"name": "Shell",
"bytes": "4516"
},
{
"name": "XSLT",
"bytes": "53394"
}
],
"symlink_target": ""
} |
//
// ConstantHeader.h
// peisongduan
//
// Created by 莫大宝 on 16/6/15.
// Copyright © 2016年 dabao. All rights reserved.
//
#ifndef ConstantHeader_h
#define ConstantHeader_h
#define kScreenWidth [UIScreen mainScreen].bounds.size.width// 屏幕宽度
#define kScreenHeight [UIScreen mainScreen].bounds.size.height// 屏幕高度
#define kStatusHeight 20// 状态条高度
#define kScaleForText ([UIScreen mainScreen].bounds.size.width / 375.0)// 文字比例
#define kNavigationBarHeight 64// 导航栏高度+状态条的高度
#define KTabBarHeight 44// 标签栏高度
#define kScaleForWidth ([UIScreen mainScreen].bounds.size.width / 375.0)// 当前屏幕宽度与iPhone6屏幕宽度的比例
#define kScaleForHeight ([UIScreen mainScreen].bounds.size.height / 667.0)// 当前屏幕高度与iPhone6屏幕高度的比例
#define kHeartWidth 24// 爱心图片的宽度
#define kHeartHeight 18// 爱心图片的高度
#define REQUESTURL @"http://api.tzouyi.com/"
//#define REQUESTURL @"http://121.41.37.126/" //测试链接
#endif /* ConstantHeader_h */
| {
"content_hash": "e4f077e16b0f607476065ee41466e898",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 98,
"avg_line_length": 28.375,
"alnum_prop": 0.7522026431718062,
"repo_name": "MoDaBao/Courier",
"id": "30d6e8b3b3f8b087db60393543376fa27d1a495b",
"size": "1075",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Courier/Courier/tool/ConstantHeader.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "3250"
},
{
"name": "Objective-C",
"bytes": "1967413"
},
{
"name": "Shell",
"bytes": "7953"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execvp_53c.c
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-53c.tmpl.c
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: listen_socket Read data using a listen socket (server side)
* GoodSource: Fixed string
* Sink: w32_execvp
* BadSink : execute command with wexecvp
* Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT L"cmd.exe"
#define COMMAND_ARG1 L"/c"
#define COMMAND_ARG2 L"dir"
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH L"/bin/sh"
#define COMMAND_INT L"sh"
#define COMMAND_ARG1 L"ls"
#define COMMAND_ARG2 L"-la"
#define COMMAND_ARG3 data
#endif
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define LISTEN_BACKLOG 5
#include <process.h>
#define EXECVP _wexecvp
/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */
#ifndef OMITBAD
/* bad function declaration */
void CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execvp_53d_badSink(wchar_t * data);
void CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execvp_53c_badSink(wchar_t * data)
{
CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execvp_53d_badSink(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declaration */
void CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execvp_53d_goodG2BSink(wchar_t * data);
/* goodG2B uses the GoodSource with the BadSink */
void CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execvp_53c_goodG2BSink(wchar_t * data)
{
CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execvp_53d_goodG2BSink(data);
}
#endif /* OMITGOOD */
| {
"content_hash": "cedf90e335e83941638a5ee6ac8bdfd7",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 156,
"avg_line_length": 29.25,
"alnum_prop": 0.7163207163207164,
"repo_name": "maurer/tiamat",
"id": "19f58023871d34e3ebd848fc7577f4819b22deb0",
"size": "2457",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/Juliet/testcases/CWE78_OS_Command_Injection/s08/CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execvp_53c.c",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package org.uberfire.ext.properties.editor.model.validators;
import org.jboss.errai.common.client.api.annotations.Portable;
@Portable
public class LongValidator implements PropertyFieldValidator {
@Override
public boolean validate( Object value ) {
try {
Long.parseLong( value.toString() );
return true;
} catch ( Exception e ) {
return false;
}
}
@Override
public String getValidatorErrorMessage() {
return "Value must be a number.";
}
}
| {
"content_hash": "90a6510ace905cfd1a4e996efeb0a7c1",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 62,
"avg_line_length": 22.375,
"alnum_prop": 0.6368715083798883,
"repo_name": "pefernan/uberfire-extensions",
"id": "53fe18c1cc21880bcd2c6157b72f9f5480f462f5",
"size": "1144",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "uberfire-widgets/uberfire-widgets-properties-editor/uberfire-widgets-properties-editor-api/src/main/java/org/uberfire/ext/properties/editor/model/validators/LongValidator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "19856"
},
{
"name": "HTML",
"bytes": "8871"
},
{
"name": "Java",
"bytes": "3691057"
},
{
"name": "JavaScript",
"bytes": "19560"
}
],
"symlink_target": ""
} |
package org.powlab.jeye.tests
import org.powlab.jeye.tests.call._
import org.powlab.jeye.decompile._
package call {
//TODO FAIL: проблемы с определением типа
@org.junit.Ignore
class CallTest1Test extends DecompileTestClass(classOf[CallTest1]) {}
class CalTest01Test extends DecompileTestClass(classOf[CalTest01], true) {}
} | {
"content_hash": "cf319c2d16f0e159dc7afc51757a1219",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 77,
"avg_line_length": 24,
"alnum_prop": 0.7767857142857143,
"repo_name": "powlab/jeye",
"id": "1e09562a8fe74a11bef5de35c9cf38402635dd2d",
"size": "361",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/scala/org/powlab/jeye/tests/CallTests.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "374095"
},
{
"name": "Scala",
"bytes": "903884"
}
],
"symlink_target": ""
} |
const test = require('tape')
const ipret = require('../src/ipret')
const strings = {
'Current password': 'Şimdiki şifre',
'New password': 'Yeni şifre',
'Change Password': 'Şifreyi Değiştir',
'Updated {0}': '{0} güncellendi',
'password': 'şifre'
}
test('setLanguage throws language not defined error', t => {
t.plan(1)
t.throws(() => {
ipret.setLanguage('tr')
}, /Error/, 'Language should be defined before set')
})
test('setStrings is there and sets default language', t => {
t.plan(3)
t.equal(typeof ipret.setStrings, 'function', 'setStrings function should be defined')
ipret.setStrings('tr', strings)
t.equal(typeof ipret.getLanguage, 'function', 'getLanguage function should be defined')
t.equal(ipret.getLanguage(), 'tr', 'Default language is set for first setStrings call')
})
test('getLanguages', t => {
t.plan(2)
t.equal(typeof ipret.getLanguages, 'function', 'getLanguages function should be defined')
t.equal(ipret.getLanguages()[0], 'tr', 'Returns all languages')
})
test('translate', t => {
t.plan(2)
t.equal(typeof ipret.translate, 'function', 'translate function should be defined')
t.equal(ipret.translate('Updated {0}', 'password'), 'şifre güncellendi', 'Translation with string format should be supported')
}) | {
"content_hash": "8ac51f43f2a34652c80dff5523fc8a97",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 128,
"avg_line_length": 34.4054054054054,
"alnum_prop": 0.6904948939512962,
"repo_name": "dbtek/ipret",
"id": "3ca752a0fb188493c3cb8208d9778b10606f5056",
"size": "1283",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "3443"
}
],
"symlink_target": ""
} |
<div class="signup">
<div class="signupForm">
<h1 class="getEggs">fresh eggs are waiting</h1>
<form ng-submit="addUser(newUser)" method="post">
<div class="form-group">
<label class="sr-only" for="signup.name">Full Name</label>
<input type="name" class="form-control" name="name" placeholder="name" ng-model="newUser.name">
</div>
<div class="form-group">
<label class="sr-only" for="signup.email">Email address</label>
<input type="email" class="form-control" name="email" placeholder="email" ng-model="newUser.email">
</div>
<div class="form-group">
<label class="sr-only" for="signup.password">Password</label>
<input type="password" class="form-control" name="password" placeholder="password" ng-model="newUser.password">
</div>
<button type="submit" class="btn btn-default btn-lg btn-block">sign up</button>
</form>
</div>
</div> | {
"content_hash": "a539e4cf29815661e6b123d452156e7a",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 118,
"avg_line_length": 39.791666666666664,
"alnum_prop": 0.625130890052356,
"repo_name": "toyblox/coop-per-pro",
"id": "1a43fa9900fea96ffe3ef3c945a95cac74105c40",
"size": "955",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/templates/signup-user.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3467"
},
{
"name": "HTML",
"bytes": "12846"
},
{
"name": "JavaScript",
"bytes": "18177"
}
],
"symlink_target": ""
} |
package org.consec.oauth2.authzserver.jpa.entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
@Entity
@Table(name = "authz_code", uniqueConstraints = {
@UniqueConstraint(columnNames = {"code"})})
@NamedQueries({
@NamedQuery(name = "AuthzCode.findAll", query = "SELECT a FROM AuthzCode a"),
@NamedQuery(name = "AuthzCode.findById", query = "SELECT a FROM AuthzCode a WHERE a.id = :id"),
@NamedQuery(name = "AuthzCode.findByCode", query = "SELECT a FROM AuthzCode a WHERE a.code = :code")})
public class AuthzCode implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(nullable = false)
private Integer id;
@Basic(optional = false)
@Column(nullable = false, length = 256)
private String code;
@Basic(optional = false)
@Column(name = "redirect_uri", nullable = false, length = 256)
private String redirectUri;
@Basic(optional = false)
@Column(name = "expire_time", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date expireTime;
@Column(length = 1000)
private String scope;
@JoinColumn(name = "owner_id", referencedColumnName = "id", nullable = false)
@ManyToOne(optional = false)
private Owner owner;
@JoinColumn(name = "client_id", referencedColumnName = "id", nullable = false)
@ManyToOne(optional = false)
private Client client;
public AuthzCode() {
}
public AuthzCode(Integer id) {
this.id = id;
}
public AuthzCode(Integer id, String code, String redirectUri, Date expireTime) {
this.id = id;
this.code = code;
this.redirectUri = redirectUri;
this.expireTime = expireTime;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getRedirectUri() {
return redirectUri;
}
public void setRedirectUri(String redirectUri) {
this.redirectUri = redirectUri;
}
public Date getExpireTime() {
return expireTime;
}
public void setExpireTime(Date expireTime) {
this.expireTime = expireTime;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public Owner getOwner() {
return owner;
}
public void setOwner(Owner owner) {
this.owner = owner;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof AuthzCode)) {
return false;
}
AuthzCode other = (AuthzCode) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "org.consec.oauth2.authzserver.jpa.entities.AuthzCode[ id=" + id + " ]";
}
}
| {
"content_hash": "5f9ef4f947bd85f6d15f92bc4534db67",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 106,
"avg_line_length": 27.175675675675677,
"alnum_prop": 0.6437095972153157,
"repo_name": "consec/ConSec",
"id": "63849fd07df3e4acaf785a306c807910826bb9bc",
"size": "4022",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "oauth2/oauth2-authz-server/src/main/java/org/consec/oauth2/authzserver/jpa/entities/AuthzCode.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "5112"
},
{
"name": "CSS",
"bytes": "262571"
},
{
"name": "Cucumber",
"bytes": "15685"
},
{
"name": "HTML",
"bytes": "76686"
},
{
"name": "Java",
"bytes": "1268727"
},
{
"name": "JavaScript",
"bytes": "1158778"
},
{
"name": "Makefile",
"bytes": "6919"
},
{
"name": "PHP",
"bytes": "2878790"
},
{
"name": "Perl",
"bytes": "48337"
},
{
"name": "Python",
"bytes": "298646"
},
{
"name": "Ruby",
"bytes": "7994"
},
{
"name": "Shell",
"bytes": "22042"
}
],
"symlink_target": ""
} |
<?php
class Template_user {
protected $_ci;
function __construct()
{
$this->_ci=&get_instance();
}
function display($template_user,$data=NULL)
{
$data['_content']=$this->_ci->load->view($template_user,$data, TRUE);
$data['_header']=$this->_ci->load->view('template_user/header',$data, TRUE);
$data['_side']=$this->_ci->load->view('template_user/side',$data, TRUE);
$data['_menu']=$this->_ci->load->view('template_user/menu',$data, TRUE);
$data['_footer']=$this->_ci->load->view('template_user/footer',$data, TRUE);
$this->_ci->load->view('template_user.php',$data);
}
}
/* End of file template_user.php */
/* Location: ./application/libraries/template_user.php */
| {
"content_hash": "8f3f3c94c059b4bd666bba5f8fa55ffb",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 84,
"avg_line_length": 32.69565217391305,
"alnum_prop": 0.5811170212765957,
"repo_name": "Ikaw/Sistem-ABS-Tugas-Akhir-",
"id": "f9d0ae15a862fd4fa0b47526b7ead67be8f1ae70",
"size": "752",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/libraries/template_user.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "240"
},
{
"name": "CSS",
"bytes": "14680"
},
{
"name": "HTML",
"bytes": "8227632"
},
{
"name": "JavaScript",
"bytes": "56182"
},
{
"name": "PHP",
"bytes": "1958708"
},
{
"name": "PLpgSQL",
"bytes": "19445"
}
],
"symlink_target": ""
} |
using System;
using Com.Aspose.Barcode.Api;
using Com.Aspose.Barcode.Model;
using Com.Aspose.Storage.Api;
namespace CSharp.GeneratingSaving.CloudStorage
{
class SetBarcodeImageMargin
{
public static void Run()
{
// ExStart:1
// Instantiate Aspose Storage Cloud API SDK
StorageApi storageApi = new StorageApi(Common.APP_KEY, Common.APP_SID, Common.BASEPATH);
// Instantiate Aspose BarCode Cloud API SDK
BarcodeApi barcodeApi = new BarcodeApi(Common.APP_KEY, Common.APP_SID, Common.BASEPATH);
// Set the barcode file name created on server.
String name = "sample-barcode";
// Set Text to encode inside barcode.
String text = "AsposeBarCode";
// Set Barcode Symbology
String type = "Code128";
// Set Generated Barcode Image Format
String format = "png";
// Set Resolution along X and Y in dpi.
float? resolutionX = 0.0f;
float? resolutionY = 0.0f;
// Set Width and Height of barcode unit
float? dimensionX = 0.0f;
float? dimensionY = 0.0f;
// Set Location, Measurement of the code
String codeLocation = "Above";
String grUnit = "mm";
// Sets if barcode's size will be updated automatically
String autoSize = "true";
// Height of the bar.
float? barHeight = null;
// Set height, Width and quality of the image.
float? imageHeight = 1.0f;
float? imageWidth = 1.0f;
String imageQuality = "default";
// Set Angle of barcode orientation
float? rotAngle = null;
// Set Margin of image border
float? topMargin = 2.0f;
float? bottomMargin = 2.0f;
float? leftMargin = 2.0f;
float? rightMargin = 2.0f;
// Sets if checksum will be added to barcode image.
String enableChecksum = "Yes";
// Set 3rd party cloud storage server (if any)
String storage = "";
String folder = "";
// Set local file (if any)
byte[] file = null;
try
{
// Invoke Aspose.BarCode Cloud SDK API to generate image with specific image margins
SaaSposeResponse apiResponse = barcodeApi.PutBarcodeGenerateFile(name, text, type, format, resolutionX, resolutionY, dimensionX, dimensionY, codeLocation, grUnit, autoSize, barHeight, imageHeight, imageWidth, imageQuality, rotAngle, topMargin, bottomMargin, leftMargin, rightMargin, enableChecksum, storage, folder, file);
// SaaSposeResponse apiResponse = barcodeApi.PutBarcodeGenerateFile(name, text, type, format, resolutionX, resolutionY, dimensionX, dimensionY, codeLocation, grUnit, autoSize, barHeight, imageHeight, imageWidth, imageQuality, rotAngle, topMargin, bottomMargin, leftMargin, rightMargin, enableChecksum, storage, folder, file);
if (apiResponse != null)
{
// Download generated barcode from cloud storage
Com.Aspose.Storage.Model.ResponseMessage storageRes = storageApi.GetDownload(name, null, null);
// Save response stream to a file
System.IO.File.WriteAllBytes(Common.OUTFOLDER + name + "." + format, storageRes.ResponseStream);
Console.WriteLine("Set Barcode Image Margin, Done!");
}
}
catch (Exception ex)
{
Console.WriteLine("error:" + ex.Message + "\n" + ex.StackTrace);
}
// ExEnd:1
}
}
}
| {
"content_hash": "cbbdc3985d7fbdaf3a35ac2cd302a0c8",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 341,
"avg_line_length": 39.552083333333336,
"alnum_prop": 0.5830919146694759,
"repo_name": "asposebarcode/Aspose_BarCode_Cloud",
"id": "b5226a11060c8c39ab6b7d3bcf063845039e0752",
"size": "3797",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Examples/DotNET/CSharp/GeneratingSaving/CloudStorage/SetBarcodeImageMargin.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "207"
},
{
"name": "C#",
"bytes": "96633"
},
{
"name": "Java",
"bytes": "56179"
},
{
"name": "JavaScript",
"bytes": "46992"
},
{
"name": "Objective-C",
"bytes": "72063"
},
{
"name": "PHP",
"bytes": "49676"
},
{
"name": "Python",
"bytes": "60095"
},
{
"name": "Ruby",
"bytes": "63237"
}
],
"symlink_target": ""
} |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **
'use strict';
function main(agent) {
// [START dialogflow_v2beta1_generated_Agents_SetAgent_async]
/**
* 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.
* TODO(developer): Uncomment these variables before running the sample.
*/
/**
* Required. The agent to update.
*/
// const agent = {}
/**
* Optional. The mask to control which fields get updated.
*/
// const updateMask = {}
// Imports the Dialogflow library
const {AgentsClient} = require('@google-cloud/dialogflow').v2beta1;
// Instantiates a client
const dialogflowClient = new AgentsClient();
async function callSetAgent() {
// Construct request
const request = {
agent,
};
// Run request
const response = await dialogflowClient.setAgent(request);
console.log(response);
}
callSetAgent();
// [END dialogflow_v2beta1_generated_Agents_SetAgent_async]
}
process.on('unhandledRejection', err => {
console.error(err.message);
process.exitCode = 1;
});
main(...process.argv.slice(2));
| {
"content_hash": "eebd80e02e167aa7a4e4c9ad6cb449f4",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 98,
"avg_line_length": 30.476923076923075,
"alnum_prop": 0.7031802120141343,
"repo_name": "googleapis/nodejs-dialogflow",
"id": "09788da9aa9fd473b05f40ca86fcf24e475a2a9c",
"size": "1981",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "samples/generated/v2beta1/agents.set_agent.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "3161"
},
{
"name": "Python",
"bytes": "666"
}
],
"symlink_target": ""
} |
var path = require('path');
// The source is split into multiple files (setup.js, cloud.js, etc.) and this file is the one
// that hooks all of the pieces together.
// The setup module handles things like parsing the command line and dealing with the settings file.
// It also keeps track of all of the different modules the code is split into. Most of the modules
// require the setup module.
var setup = require('./lib/setup.js');
setup.settingsDir = path.join(__dirname, 'settings');
// The cloud module interacts with the Particle cloud. The devices
// manager uses the cloud to make the initial connection and locate the server.
// The device module registers with the cloud module below because it needs to receive Particle
// publish calls.
var cloud = require('./lib/cloud.js');
setup.addModule(cloud);
// The devices module keeps track of the devices that are using this server. It uses the cloud
// module to find out when a device comes online and is ready to connect and then calls a function
// on the device to let it know the server IP address, port, and nonce (one-time-use authentication
// token).
var devices = require('./lib/devices.js');
setup.addModule(devices);
cloud.addEventHandler('devices', devices);
// The server module implements the HTTP server. It's used to serve static files in the public
// directory (the index.html, main.js, and main.css) as well as handle SSE (Server Sent Events) and
// sending data from the Photon to this server.
var server = require('./lib/server.js');
server.publicDir = path.join(__dirname, 'liveimu/public');
server.serverPort = 8070;
server.serverAddr = "auto";
setup.addModule(server);
devices.server = server;
// The SSE (Server Sent Events) module implements SSE. We currently have only one channel
// corresponding to the one Photon we allow to connect at a time, but in theory you could have
// multiple channels of SSE
var sse = require('./lib/sse.js');
setup.addModule(sse);
// Hook the SSE channel into the /data URL. Requesting this URL returns the SSE data channel.
var sseChannel = sse.createChannel();
server.addUrlHandler('/data', sseChannel);
// Register the /devices URL with the HTTP server. This is the URL the Photon uses a POST request
// to to upload its data, which is then broadcast to web pages using SSE.
server.addUrlHandler('/devices', devices);
// This is how the device manager knows which channel to broadcast its events to.
devices.addDataHandler(sseChannel);
// Prepare/load the settings file
// This call is asynchronous.
// Eventually, run() will be called for all modules to begun running
setup.init();
| {
"content_hash": "0c15026c590238eaeeeb007d4cb70157",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 100,
"avg_line_length": 42.24193548387097,
"alnum_prop": 0.7487590683466973,
"repo_name": "anttir/rclogger",
"id": "5884245b8d2f2582f3e48e9b202a352b9a58073c",
"size": "3005",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "liveimu.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Arduino",
"bytes": "11266"
},
{
"name": "CSS",
"bytes": "492"
},
{
"name": "HTML",
"bytes": "32298"
},
{
"name": "JavaScript",
"bytes": "44572"
}
],
"symlink_target": ""
} |
class TestRhsaCveNames(object):
def test_cve_names(self, monkeypatch, mock_post, mock_put, rhsa):
"""Verify that we have CVE names in our advisory (not None)"""
expected = 'CVE-2018-14649'
assert rhsa.cve_names == expected
| {
"content_hash": "55dbb0463335c3d80e49936445ab6024",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 70,
"avg_line_length": 42,
"alnum_prop": 0.6587301587301587,
"repo_name": "red-hat-storage/errata-tool",
"id": "00d942293f49a5168fca148099a4e095f83aa66d",
"size": "252",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "errata_tool/tests/test_rhsa_cve_list.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "723"
},
{
"name": "Python",
"bytes": "167318"
},
{
"name": "Shell",
"bytes": "663"
}
],
"symlink_target": ""
} |
<!--
Description: item content:encoded contains onsubmit
Expect: not bozo and entries[0]['description'] == '<img src="http://www.ragingplatypus.com/i/cam-full.jpg" />'
-->
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
<channel>
<item>
<content:encoded><img src="http://www.ragingplatypus.com/i/cam-full.jpg" onsubmit="location.href='http://www.ragingplatypus.com/';" /></content:encoded>
</item>
</channel>
</rss> | {
"content_hash": "08f4c0b092bf050897b8c09590493ee8",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 155,
"avg_line_length": 41.09090909090909,
"alnum_prop": 0.6969026548672567,
"repo_name": "simplepie/simplepie-ng",
"id": "30bbc4b56a16d50d0608794593b1aa29e099634f",
"size": "452",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tests/__unsorted__/feedparser.py/wellformed/sanitize/item_content_encoded_onsubmit.xml",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "22404"
},
{
"name": "Makefile",
"bytes": "8026"
},
{
"name": "PHP",
"bytes": "505427"
},
{
"name": "Python",
"bytes": "10399"
},
{
"name": "Roff",
"bytes": "2170"
},
{
"name": "Shell",
"bytes": "271"
},
{
"name": "XSLT",
"bytes": "734"
}
],
"symlink_target": ""
} |
<?php
namespace app\modules\file\actions;
use app\modules\file\models\Image;
use yii\base\Action;
use yii\helpers\Json;
/**
* Class ImageDeleteAction
* @package app\modules\file\actions
*/
class ImageDeleteAction extends Action
{
/**
* @param $id
* @return string
*/
public function run($id)
{
/** @var Image $file */
$file = Image::findOne(['id' => $id]);
$deleted = $file->delete();
return $this->getResponse($file, $deleted);
}
/**
* @param $file
* @param $deleted
* @return string
*/
protected function getResponse($file, $deleted)
{
return Json::encode([
'files' => [
[
$file->original_name => $deleted
]
]
]);
}
} | {
"content_hash": "9d141352e0f4850293f98fc728b4581d",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 52,
"avg_line_length": 19.902439024390244,
"alnum_prop": 0.5073529411764706,
"repo_name": "vetoni/toko",
"id": "0f717bb004f9c7dc771dc5fb3569af308db5a7c9",
"size": "816",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/file/actions/ImageDeleteAction.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "258"
},
{
"name": "Batchfile",
"bytes": "515"
},
{
"name": "CSS",
"bytes": "30150"
},
{
"name": "JavaScript",
"bytes": "6393"
},
{
"name": "PHP",
"bytes": "373159"
}
],
"symlink_target": ""
} |
/*
Papa Parse
v2.1.3
https://github.com/mholt/jquery.parse
*/
(function($)
{
"use strict";
$.fn.parse = function(options)
{
var config = options.config || {};
var queue = [];
this.each(function(idx)
{
var supported = $(this).prop('tagName').toUpperCase() == "INPUT"
&& $(this).attr('type') == "file"
&& window.FileReader;
if (!supported)
return true; // continue to next input element
var instanceConfig = $.extend({}, config); // This copy is very important
if (!this.files || this.files.length == 0)
{
error("NoFileError", undefined, this);
return true; // continue to next input element
}
for (var i = 0; i < this.files.length; i++)
queue.push({
file: this.files[i],
inputElem: this,
instanceConfig: instanceConfig
});
if (queue.length > 0)
parseFile(queue[0]);
});
return this;
function parseFile(f)
{
var completeFunc = complete, errorFunc;
if (isFunction(options.error))
errorFunc = function() { options.error(reader.error, f.file, f.inputElem); };
if (isFunction(options.complete))
completeFunc = function(results, file, inputElem, event) { options.complete(results, file, inputElem, event); complete(); };
if (isFunction(options.before))
{
var returned = options.before(f.file, f.inputElem);
if (typeof returned === 'object')
f.instanceConfig = $.extend(f.instanceConfig, returned);
else if (returned === "skip")
return complete(); // Proceeds to next file
else if (returned === false)
{
error("AbortError", f.file, f.inputElem);
return; // Aborts all queued files immediately
}
}
if (f.instanceConfig.step)
{
var streamer = new Streamer(f.file, {
inputElem: f.inputElem,
config: $.extend({}, f.instanceConfig) // This copy is very important
});
streamer.stream(completeFunc, errorFunc);
}
else
{
var reader = new FileReader();
reader.onerror = errorFunc;
reader.onload = function(event)
{
var text = event.target.result;
var results = $.parse(text, f.instanceConfig);
completeFunc(results, f.file, f.inputElem, event);
};
reader.readAsText(f.file, f.instanceConfig.encoding);
}
}
function error(name, file, elem)
{
if (isFunction(options.error))
options.error({name: name}, file, elem);
}
function complete()
{
queue.splice(0, 1);
if (queue.length > 0)
parseFile(queue[0]);
}
};
$.parse = function(input, options)
{
var parser = new Parser(options);
return parser.parse(input);
};
function isFunction(func) { return typeof func === 'function'; }
// Streamer is a wrapper over Parser to handle chunking the input file
function Streamer(file, settings)
{
if (!settings)
settings = {};
if (!settings.chunkSize)
settings.chunkSize = 1024 * 1024 * 5; // 5 MB
if (settings.config.step) // it had better be there...!
{
var userStep = settings.config.step;
settings.config.step = function(data) { return userStep(data, file, settings.inputElem); };
}
var start = 0;
var partialLine = "";
var parser = new Parser(settings.config);
var reader = new FileReader();
reader.onload = blobLoaded;
reader.onerror = blobError;
this.stream = function(completeCallback, fileErrorCallback)
{
settings.onComplete = completeCallback;
settings.onFileError = fileErrorCallback;
nextChunk();
};
function blobLoaded(event)
{
var text = partialLine + event.target.result;
partialLine = "";
// If we're maxing out the chunk size, we probably cut a line
// in half. However: doing these operations if the whole file
// fits in one chunk will leave off the last line, which is bad.
if (text.length >= settings.chunkSize)
{
var lastLineEnd = text.lastIndexOf("\n");
if (lastLineEnd < 0)
lastLineEnd = text.lastIndexOf("\r");
if (lastLineEnd > -1)
{
partialLine = text.substring(lastLineEnd + 1); // skip the line ending character
text = text.substring(0, lastLineEnd);
}
}
var results = parser.parse(text);
if (start >= file.size)
return done(event);
else if (results.errors.abort)
return;
else
nextChunk();
}
function done(event)
{
if (typeof settings.onComplete === 'function')
settings.onComplete(undefined, file, settings.inputElem, event);
}
function blobError()
{
if (typeof settings.onFileError === 'function')
settings.onFileError(reader.error, file, settings.inputElem);
}
function nextChunk()
{
if (start < file.size)
{
reader.readAsText(file.slice(start, Math.min(start + settings.chunkSize, file.size)), settings.config.encoding);
start += settings.chunkSize;
}
};
}
// Parser is the actual parsing component.
// It is under test and does not depend on jQuery.
// You could rip this entire function out of the plugin
// and use it independently (with attribution).
function Parser(config)
{
var self = this;
var _invocations = 0;
var _input = "";
var _chunkOffset = 0;
var _abort = false;
var _config = {};
var _state = freshState();
var _defaultConfig = {
delimiter: "",
header: true,
dynamicTyping: true,
preview: 0
};
var _regex = {
floats: /^\s*-?(\d*\.?\d+|\d+\.?\d*)(e[-+]?\d+)?\s*$/i,
empty: /^\s*$/
};
config = validConfig(config);
_config = {
delimiter: config.delimiter,
header: config.header,
dynamicTyping: config.dynamicTyping,
preview: config.preview,
step: config.step
};
this.parse = function(input)
{
if (typeof input !== 'string')
return returnable();
reset(input);
if (!_config.delimiter && !guessDelimiter(input))
{
addError("Delimiter", "UndetectableDelimiter", "Unable to auto-detect delimiting character; defaulted to comma", "config");
_config.delimiter = ",";
}
for (_state.i = 0; _state.i < _input.length; _state.i++)
{
if (_abort || (_config.preview > 0 && _state.lineNum > _config.preview))
break;
_state.ch = _input[_state.i];
_state.line += _state.ch;
if (_state.ch == '"')
handleQuote();
else if (_state.inQuotes)
inQuotes();
else
notInQuotes();
}
if (_abort)
addError("Abort", "ParseAbort", "Parsing was aborted by the user's step function", "abort");
else
{
endRow(); // End of input is also end of the last row
if (_state.inQuotes)
addError("Quotes", "MissingQuotes", "Unescaped or mismatched quotes");
}
return returnable();
};
this.getOptions = function()
{
return {
delimiter: _config.delimiter,
header: _config.header,
dynamicTyping: _config.dynamicTyping,
preview: _config.preview,
step: _config.step
};
};
function validConfig(config)
{
if (typeof config !== 'object')
config = {};
if (typeof config.delimiter !== 'string'
|| config.delimiter.length != 1)
config.delimiter = _defaultConfig.delimiter;
if (config.delimiter == '"' || config.delimiter == "\n")
config.delimiter = _defaultConfig.delimiter;
if (typeof config.header !== 'boolean')
config.header = _defaultConfig.header;
if (typeof config.dynamicTyping !== 'boolean')
config.dynamicTyping = _defaultConfig.dynamicTyping;
if (typeof config.preview !== 'number')
config.preview = _defaultConfig.preview;
if (typeof config.step !== 'function')
config.step = _defaultConfig.step;
return config;
}
function guessDelimiter(input)
{
var recordSep = String.fromCharCode(30);
var unitSep = String.fromCharCode(31);
var delimiters = [",", "\t", "|", ";", recordSep, unitSep];
var bestDelim, bestDelta, fieldCountPrevRow;
for (var i = 0; i < delimiters.length; i++)
{
var delim = delimiters[i];
var delta = 0, avgFieldCount = 0;
var preview = new Parser({
delimiter: delim,
header: false,
dynamicTyping: false,
preview: 10
}).parse(input);
for (var j = 0; j < preview.results.length; j++)
{
var fieldCount = preview.results[j].length;
avgFieldCount += fieldCount;
if (typeof fieldCountPrevRow === 'undefined')
{
fieldCountPrevRow = fieldCount;
continue;
}
else if (fieldCount > 1)
{
delta += Math.abs(fieldCount - fieldCountPrevRow);
fieldCountPrevRow = fieldCount;
}
}
avgFieldCount /= preview.results.length;
if ((typeof bestDelta === 'undefined' || delta < bestDelta)
&& avgFieldCount > 1.99)
{
bestDelta = delta;
bestDelim = delim;
}
}
_config.delimiter = bestDelim;
return !!bestDelim;
}
function handleQuote()
{
var delimBefore = (_state.i > 0 && isBoundary(_state.i-1))
|| _state.i == 0;
var delimAfter = (_state.i < _input.length - 1 && isBoundary(_state.i+1))
|| _state.i == _input.length - 1;
var escaped = _state.i < _input.length - 1
&& _input[_state.i+1] == '"';
if (_state.inQuotes && escaped)
{
_state.fieldVal += '"';
_state.i++;
}
else if (delimBefore || delimAfter)
_state.inQuotes = !_state.inQuotes;
else
addError("Quotes", "UnexpectedQuotes", "Unexpected quotes");
}
function inQuotes()
{
appendCharToField();
}
function appendCharToField()
{
_state.fieldVal += _state.ch;
}
function notInQuotes()
{
if (_state.ch == _config.delimiter)
saveValue();
else if ((_state.ch == "\r" && _state.i < _input.length - 1
&& _input[_state.i+1] == "\n")
|| (_state.ch == "\n" && _state.i < _input.length - 1
&& _input[_state.i+1] == "\r"))
{
newRow();
_state.i++;
}
else if (_state.ch == "\r" || _state.ch == "\n")
newRow();
else
appendCharToField();
}
function isBoundary(i)
{
return _input[i] == _config.delimiter
|| _input[i] == "\n"
|| _input[i] == "\r";
}
function saveValue()
{
if (_config.header)
{
if (_state.lineNum == 1 && _invocations == 1)
_state.parsed.fields.push(_state.fieldVal);
else
{
var currentRow = _state.parsed.rows[_state.parsed.rows.length - 1];
var fieldName = _state.parsed.fields[_state.field];
if (fieldName)
{
if (_config.dynamicTyping)
_state.fieldVal = tryParseFloat(_state.fieldVal);
currentRow[fieldName] = _state.fieldVal;
}
else
{
if (typeof currentRow.__parsed_extra === 'undefined')
currentRow.__parsed_extra = [];
currentRow.__parsed_extra.push(_state.fieldVal);
}
}
}
else
{
if (_config.dynamicTyping)
_state.fieldVal = tryParseFloat(_state.fieldVal);
_state.parsed[_state.parsed.length - 1].push(_state.fieldVal);
}
_state.fieldVal = "";
_state.field ++;
}
function newRow()
{
endRow();
if (streaming())
{
_state.errors = {};
_state.errors.length = 0;
}
if (_config.header)
{
if (_state.lineNum > 0)
{
if (streaming())
_state.parsed.rows = [ {} ];
else
_state.parsed.rows.push({});
}
}
else
{
if (streaming())
_state.parsed = [ [] ];
else if (!_config.header)
_state.parsed.push([]);
}
_state.lineNum++;
_state.line = "";
_state.field = 0;
}
function endRow()
{
if (_abort)
return;
saveValue();
var emptyLine = trimEmptyLine();
if (!emptyLine && _config.header)
inspectFieldCount();
if (streaming() && (!_config.header ||
(_config.header && _state.parsed.rows.length > 0)))
{
var keepGoing = _config.step(returnable());
if (keepGoing === false)
_abort = true;
}
}
function streaming()
{
return typeof _config.step === 'function';
}
function tryParseFloat(num)
{
var isNumber = _regex.floats.test(num);
return isNumber ? parseFloat(num) : num;
}
function trimEmptyLine()
{
if (_regex.empty.test(_state.line))
{
if (_config.header)
{
if (_state.lineNum == 1)
{
_state.parsed.fields = [];
_state.lineNum--;
}
else
_state.parsed.rows.splice(_state.parsed.rows.length - 1, 1);
}
else
_state.parsed.splice(_state.parsed.length - 1, 1);
return true;
}
return false;
}
function inspectFieldCount()
{
if (!_config.header)
return true;
if (_state.parsed.rows.length == 0)
return true;
var expected = _state.parsed.fields.length;
// Actual field count tabulated manually because IE<9 doesn't support Object.keys
var actual = 0;
var lastRow = _state.parsed.rows[_state.parsed.rows.length - 1];
for (var prop in lastRow)
if (lastRow.hasOwnProperty(prop))
actual++;
if (actual < expected)
return addError("FieldMismatch", "TooFewFields", "Too few fields: expected " + expected + " fields but parsed " + actual);
else if (actual > expected)
return addError("FieldMismatch", "TooManyFields", "Too many fields: expected " + expected + " fields but parsed " + actual);
return true;
}
function addError(type, code, msg, errKey)
{
var row = _config.header
? (_state.parsed.rows.length ? _state.parsed.rows.length - 1 : undefined)
: _state.parsed.length - 1;
var key = errKey || row;
if (typeof _state.errors[key] === 'undefined')
_state.errors[key] = [];
_state.errors[key].push({
type: type,
code: code,
message: msg,
line: _state.lineNum,
row: row,
index: _state.i + _chunkOffset
});
_state.errors.length ++;
return false;
}
function returnable()
{
return {
results: _state.parsed,
errors: _state.errors,
meta: {
delimiter: _config.delimiter
}
};
}
function reset(input)
{
_invocations++;
if (_invocations > 1 && streaming())
_chunkOffset += input.length;
_state = freshState();
_input = input;
}
function freshState()
{
// If streaming, and thus parsing the input in chunks, this
// is careful to preserve what we've already got, when necessary.
var parsed;
if (_config.header)
{
parsed = {
fields: streaming() ? _state.parsed.fields || [] : [],
rows: streaming() && _invocations > 1 ? [ {} ] : []
};
}
else
parsed = [ [] ];
return {
i: 0,
lineNum: streaming() ? _state.lineNum : 1,
field: 0,
fieldVal: "",
line: "",
ch: "",
inQuotes: false,
parsed: parsed,
errors: { length: 0 }
};
}
}
})(jQuery);
| {
"content_hash": "27b61d1c10d61494e645da98a58a62e0",
"timestamp": "",
"source": "github",
"line_count": 636,
"max_line_length": 128,
"avg_line_length": 22.78301886792453,
"alnum_prop": 0.6011732229123533,
"repo_name": "malev/csvToHtml",
"id": "f04b230a0555b41cbb7d4b8f73c2b420698b8398",
"size": "14490",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/assets/bower/papa-parse/jquery.parse.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2944"
},
{
"name": "JavaScript",
"bytes": "4302"
},
{
"name": "Ruby",
"bytes": "1507"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
"-//Puppy Crawl//DTD Suppressions 1.2//EN"
"http://checkstyle.sourceforge.net/dtds/suppressions_1_2.dtd">
<suppressions>
<suppress files="src/main/java/org/openkilda/server42/control/messaging/flowrtt/Control.java"
checks=".*"/>
</suppressions>
| {
"content_hash": "06641368c7a4f673721386a3a8849e43",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 97,
"avg_line_length": 36.888888888888886,
"alnum_prop": 0.6716867469879518,
"repo_name": "jonvestal/open-kilda",
"id": "8c3009759759664493282434deaf9beb8e2a96f8",
"size": "332",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src-java/server42/server42-messaging/src/checkstyle/checkstyle-suppressions.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "65404"
},
{
"name": "Dockerfile",
"bytes": "22398"
},
{
"name": "Gherkin",
"bytes": "88336"
},
{
"name": "Groovy",
"bytes": "70766"
},
{
"name": "HTML",
"bytes": "161798"
},
{
"name": "Java",
"bytes": "3580119"
},
{
"name": "JavaScript",
"bytes": "332794"
},
{
"name": "Makefile",
"bytes": "21113"
},
{
"name": "Python",
"bytes": "425871"
},
{
"name": "Shell",
"bytes": "39572"
}
],
"symlink_target": ""
} |
package inf.unibz.ontop.sesame.tests.general;
import java.util.List;
import junit.framework.TestCase;
import org.openrdf.model.Statement;
import org.openrdf.query.BindingSet;
import org.openrdf.query.GraphQuery;
import org.openrdf.query.GraphQueryResult;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.TupleQuery;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.query.TupleQueryResultHandler;
import org.openrdf.query.resultio.sparqlxml.SPARQLResultsXMLWriter;
import org.openrdf.query.resultio.text.tsv.SPARQLResultsTSVWriter;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import sesameWrapper.SesameVirtualRepo;
//import org.openrdf.query.resultio.sparqlkml.stSPARQLResultsKMLWriter;
public class SesameVirtualTest extends TestCase {
public void test() throws Exception
{
//create a sesame repository
RepositoryConnection con = null;
Repository repo = null;
try {
//String owlfile = "/home/constant/books.owl";
String obdafile = "/home/constant/npd.obda";
//"/home/timi/ontologies/helloworld/helloworld.owl";
//repo = new SesameVirtualRepo("my_name", obdafile, false, "TreeWitness");
repo.initialize();
con = repo.getConnection();
String prefixes = "ex: <http://meraka/moss/exampleBooks.owl#>";
///query repo
try {
String spatialQuery = "select distinct ?x1 ?g1 where {" +
"?x1 ex:hasSerialization ?g1 . " +
" ?x2 ex:hasSerialization ?g2 . " +
"FILTER(SpatialOverlap(?g1,?g2))" +
// "FILTER(!sameTerm(?g1,?g2))" +
"} limit 10";
String spatialConstantQuery = "select distinct ?x1 ?g1 where {" +
"?x1 <http://meraka/moss/exampleBooks.owl#hasSerialization> ?g1 . " +
"FILTER(SpatialOverlap(\"POINT(2.497514 56.847728)\",?g1))" +
// "FILTER(!sameTerm(?g1,?g2))" +
"} limit 10";
String geosparqlProjectionQuery = "" +
//"prefix geo: <http://www.opengis.net/ont/geosparql#> \n" +
"select distinct ?x ?y ?z where {" +
"?x ?y ?z " +
"} limit 10";
String spatialProjectionQuery = "select distinct ?g1 where {" +
"?x1 <http://meraka/moss/exampleBooks.owl#hasSerialization> ?g1 . " +
"} limit 10";
String wellboresInFields = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
"PREFIX : <http://meraka/moss/exampleBooks.owl#>" +
"SELECT distinct ?x1 " +
"WHERE {" +
"?x1 :hasWKTGeometry ?g1 . " +
"?x1 rdf:type :fieldArea ." +
"?x2 :hasWKTGeometry ?g2 . " +
"?x2 rdf:type :wellborePoint ." +
"FILTER(SpatialOverlap(?g2,?g1))" +
"} limit 10";
String qualitativeSpatialQuery = "select distinct ?x1 where {" +
"?x1 <http://meraka/moss/exampleBooks.owl#overlaps> ?x2 . " +
"} limit 10";
String NonSpatialQuery = "select distinct ?x1 where {" +
"?x1 <http://meraka/moss/exampleBooks.owl#hasSerialization> ?g1 . " +
"?x2 <http://meraka/moss/exampleBooks.owl#hasSerialization> ?g2 . " +
// "FILTER(SpatialOverlap(?g1,?g2))" +
"FILTER(!sameTerm(?x1,?x2))" +
"} limit 10";
String queryString =
"select distinct ?x ?o where {?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?o ." +
"?x <http://meraka/moss/exampleBooks.owl#writtenBy> ?a . " +
"?x2 <http://meraka/moss/exampleBooks.owl#writtenBy> ?a2. " +
// "FILTER(SpatialOverlap(?a,?a2)) }" ;
"FILTER(!sameTerm(?a,?a2)) }" ;
// "?x2 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?o2." +
//"FILTER(sameTerm(?x,?x2))} " ;
String query2 = "select distinct ?s where { ?s <http://meraka/moss/exampleBooks.owl#writtenBy> ?o}";
//"FILTER (isURI(?o)) }" ;
//"?x2 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://meraka/moss/exampleBooks.owl#Book> ." +
//"FILTER(isURI(?x1)) }";
//"<http://www.semanticweb.org/tibagosi/ontologies/2012/11/Ontology1355819752067.owl#Book>}";
TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SPARQL, wellboresInFields);
TupleQueryResultHandler handler = new SPARQLResultsTSVWriter(System.out);
// TupleQueryResultHandler spatialHandler = new stSPARQLResultsKMLWriter(System.out);
// tupleQuery.evaluate(handler);
/* queryString = "CONSTRUCT {?s ?p ?o} WHERE {?s ?p ?o}";
GraphQuery graphQuery = con.prepareGraphQuery(QueryLanguage.SPARQL, queryString);
GraphQueryResult gresult = graphQuery.evaluate();
while(gresult.hasNext())
{
Statement s = gresult.next();
System.out.println(s.toString());
}
*/
System.out.println("Closing...");
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("Done.");
}
}
| {
"content_hash": "c804826130b762be7eb14a63e59a76b8",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 115,
"avg_line_length": 35.04109589041096,
"alnum_prop": 0.6104378420641126,
"repo_name": "ConstantB/ontop-spatial",
"id": "afdfae4b0741223bc1bad2d9d6eb343c928b7287",
"size": "5790",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "quest-sesame/src/test/java/inf/unibz/ontop/sesame/tests/general/SesameVirtualTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "725"
},
{
"name": "CSS",
"bytes": "2676"
},
{
"name": "GAP",
"bytes": "43623"
},
{
"name": "HTML",
"bytes": "2860560"
},
{
"name": "Java",
"bytes": "6929671"
},
{
"name": "PLpgSQL",
"bytes": "75540766"
},
{
"name": "Ruby",
"bytes": "52622"
},
{
"name": "Shell",
"bytes": "18315"
},
{
"name": "TeX",
"bytes": "10376"
},
{
"name": "Web Ontology Language",
"bytes": "52563785"
}
],
"symlink_target": ""
} |
package integrationTests.data;
public class ClassWithFields
{
private static int static1;
private static String static2 = "B2";
private static long static3;
// Instance fields:
// (coverage accounts for each owner instance)
private boolean instance1 = true;
private Boolean instance2;
private double instance3;
public static int getStatic1()
{
return static1;
}
public static void setStatic1(int static1)
{
ClassWithFields.static1 = static1;
}
public static void setStatic2(String static2)
{
ClassWithFields.static2 = static2;
}
public static long getStatic3()
{
return static3;
}
public static void setStatic3(long static3)
{
ClassWithFields.static3 = static3;
}
/**
* Indicates whether {@link #instance1} is {@code true} or {@code false}.
*/
public boolean isInstance1()
{
return instance1;
}
public void setInstance1(boolean instance1)
{
this.instance1 = instance1;
}
public void setInstance2(Boolean instance2)
{
this.instance2 = instance2;
}
public double getInstance3()
{
return instance3;
}
public void setInstance3(double instance3)
{
this.instance3 = instance3;
}
}
| {
"content_hash": "7d7e6690b1cf704a4be32dae84982f47",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 76,
"avg_line_length": 19.720588235294116,
"alnum_prop": 0.6211782252050708,
"repo_name": "royosherove/javatdddemo",
"id": "f380ae93e27c2705e7a27d90d883d41b8d6d74df",
"size": "1472",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "libs/jmockit/coverage/src/integrationTests/data/ClassWithFields.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "22995"
},
{
"name": "Java",
"bytes": "3164211"
},
{
"name": "JavaScript",
"bytes": "7998"
}
],
"symlink_target": ""
} |
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using Vernacular.Tool;
using Vernacular.Potato;
namespace Vernacular.Parsers
{
public sealed class PoParser : Parser
{
public static readonly Dictionary<string, LanguageGender> GenderContexts = new Dictionary<string, LanguageGender> {
{ "masculine form", LanguageGender.Masculine },
{ "feminine form", LanguageGender.Feminine },
{ "gender-masculine", LanguageGender.Masculine },
{ "gender-feminine", LanguageGender.Feminine }
};
private List<string> po_paths = new List<string> ();
public override IEnumerable<string> SupportedFileExtensions {
get {
yield return ".po";
yield return ".pot";
}
}
public override void Add (string path)
{
po_paths.Add (path);
}
public override void Add (Stream stream, string path)
{
throw new NotSupportedException ();
}
private ILocalizationUnit Parse (IDocumentPart part)
{
var headers = part as HeaderCollection;
var unit = part as Unit;
if (headers != null) {
var metadata = new LocalizationMetadata ();
foreach (var header in headers) {
metadata.Add (header.Name, header.Value);
}
return metadata;
} else if (unit != null) {
return ParsePoMessageUnit (unit);
} else {
return null;
}
}
private LocalizedString ParsePoMessageUnit (Unit unit)
{
var developer_comments_builder = new StringBuilder ();
var translator_comments_builder = new StringBuilder ();
var references_builder = new StringBuilder ();
var flags_builder = new StringBuilder ();
var translated_values = new List<string> ();
string untranslated_singular_value = null;
string untranslated_plural_value = null;
string context = null;
foreach (var message in unit.Messages) {
switch (message.Type) {
case MessageType.SingularIdentifier:
untranslated_singular_value = message.Value;
break;
case MessageType.PluralIdentifier:
untranslated_plural_value = message.Value;
break;
case MessageType.SingularString:
case MessageType.PluralString:
translated_values.Insert (message.PluralOrder, message.Value);
break;
case MessageType.Context:
context = message.Value.Trim ();
break;
}
}
foreach (var comment in unit.Comments) {
switch (comment.Type) {
case CommentType.Extracted:
developer_comments_builder.Append (comment.Value.Trim ());
developer_comments_builder.Append ('\n');
break;
case CommentType.Translator:
translator_comments_builder.Append (comment.Value.Trim ());
translator_comments_builder.Append ('\n');
break;
case CommentType.Reference:
references_builder.Append (comment.Value.Trim ());
references_builder.Append (' ');
break;
case CommentType.Flag:
flags_builder.Append (comment.Value.Trim ());
flags_builder.Append (',');
break;
}
}
var developer_comments = developer_comments_builder.ToString ().Trim ();
var translator_comments = translator_comments_builder.ToString ().Trim ();
var references = references_builder.ToString ().Trim ();
var flags = flags_builder.ToString ().Trim ();
var localized_string = new LocalizedString ();
if (!String.IsNullOrWhiteSpace (developer_comments)) {
localized_string.DeveloperComments = developer_comments;
}
if (!String.IsNullOrWhiteSpace (translator_comments)) {
localized_string.TranslatorComments = translator_comments;
}
if (!String.IsNullOrWhiteSpace (references)) {
localized_string.References = references.Split (' ');
}
if (!String.IsNullOrWhiteSpace (flags)) {
foreach (var flag in flags.Split (',')) {
if (flag.EndsWith ("-format")) {
localized_string.StringFormatHint = flag;
}
}
}
if (context != null) {
var context_lower = context.ToLower ();
foreach (var gender_context in GenderContexts) {
if (context_lower == gender_context.Key) {
localized_string.Gender = gender_context.Value;
context = null;
break;
} else if (context.Contains (gender_context.Key)) {
localized_string.Gender = gender_context.Value;
break;
}
}
}
localized_string.Context = context;
localized_string.UntranslatedSingularValue = untranslated_singular_value;
localized_string.UntranslatedPluralValue = untranslated_plural_value;
if (translated_values.Count > 0) {
localized_string.TranslatedValues = translated_values.ToArray ();
}
return localized_string;
}
public override IEnumerable<ILocalizationUnit> Parse ()
{
foreach (var path in po_paths) {
var parser = new Vernacular.Potato.Internal.Parser ();
foreach (var part in parser.Parse (path)) {
var unit = Parse (part);
if (unit is LocalizationMetadata && Path.GetExtension (path) == ".pot") {
continue;
} else if (unit != null) {
yield return unit;
}
}
}
}
}
}
| {
"content_hash": "9b0c40f30660b1a009c7b02f418be4a3",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 123,
"avg_line_length": 38.201149425287355,
"alnum_prop": 0.5063938618925832,
"repo_name": "rdio/vernacular",
"id": "1178eb8b6696eae72e71b65b1fc1991de6462f73",
"size": "7821",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "Vernacular.Tool/Vernacular.Parsers/PoParser.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "324288"
},
{
"name": "Makefile",
"bytes": "1005"
},
{
"name": "Shell",
"bytes": "443"
}
],
"symlink_target": ""
} |
(function() {
angular
.module('docsApp')
.directive('h4', MdAnchorDirective)
.directive('h3', MdAnchorDirective)
.directive('h2', MdAnchorDirective)
.directive('h1', MdAnchorDirective);
function MdAnchorDirective($mdUtil, $compile) {
/** @const @type {RegExp} */
var unsafeCharRegex = /[&\s+$,:;=?@"#{}|^~[`%!'\]./()*\\]/g;
return {
restrict: 'E',
scope: {},
require: '^?mdContent',
link: postLink
};
function postLink(scope, element, attr, ctrl) {
// Only create anchors when being inside of a md-content.
if (!ctrl) {
return;
}
var anchorEl = $compile('<a class="docs-anchor" ng-href="#{{ name }}" name="{{ name }}"></a>')(scope);
// Wrap contents inside of the anchor element.
anchorEl.append(element.contents());
// Append the anchor element to the directive element.
element.append(anchorEl);
// Delay the URL creation, because the inner text might be not interpolated yet.
$mdUtil.nextTick(createContentURL);
/**
* Creates URL from the text content of the element and writes it into the scope.
*/
function createContentURL() {
scope.name = element.text()
.trim() // Trim text due to browsers extra whitespace.
.replace(/'/g, '') // Transform apostrophes words to a single one.
.replace(unsafeCharRegex, '-') // Replace unsafe chars with a dash symbol.
.replace(/-{2,}/g, '-') // Remove repeating dash symbols.
.replace(/^-|-$/g, '') // Remove preceding or ending dashes.
.toLowerCase(); // Link should be lower-case for accessible URL.
}
}
}
// Manually specify $inject because Strict DI is enabled.
MdAnchorDirective.$inject = ['$mdUtil', '$compile'];
})(); | {
"content_hash": "e1550e07a9fa267b233ee56a9c8b8834",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 108,
"avg_line_length": 34.40350877192982,
"alnum_prop": 0.5512493625701173,
"repo_name": "crisbeto/material",
"id": "9f5b8dae1f09205d104faaf61a4b8a749ffff978",
"size": "1961",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "docs/app/js/anchor.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "260927"
},
{
"name": "HTML",
"bytes": "195578"
},
{
"name": "JavaScript",
"bytes": "2390575"
},
{
"name": "PHP",
"bytes": "7211"
},
{
"name": "Shell",
"bytes": "12906"
}
],
"symlink_target": ""
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml;
using NUnit.Framework;
using Microsoft.Build.BuildEngine;
using Microsoft.Build.BuildEngine.Shared;
namespace Microsoft.Build.UnitTests
{
[TestFixture]
public class ToolsetState_Tests
{
[Test]
public void DefaultTasksAreFoundInToolsPath()
{
//Note Engine's BinPath is distinct from the ToolsVersion's ToolsPath
Engine e = new Engine();
ToolsetState t = new ToolsetState(e, new Toolset("toolsversionname", "c:\\directory1\\directory2"), new GetFiles(this.getFiles), new LoadXmlFromPath(this.loadXmlFromPath));
TaskRegistry taskRegistry = (TaskRegistry) t.GetTaskRegistry(null);
string[] expectedRegisteredTasks = { "a1", "a2", "a3", "a4", "b1", "e1", "g1", "g2", "g3" };
string[] unexpectedRegisteredTasks = { "c1", "d1", "f1", "11", "12", "13", "21" };
foreach (string expectedRegisteredTask in expectedRegisteredTasks)
{
Hashtable registeredTasks;
Assert.IsTrue(taskRegistry.FindRegisteredTasks(expectedRegisteredTask, true, out registeredTasks),
String.Format("Expected task '{0}' registered!", expectedRegisteredTask));
}
foreach (string unexpectedRegisteredTask in unexpectedRegisteredTasks)
{
Hashtable registeredTasks;
Assert.IsFalse(taskRegistry.FindRegisteredTasks(unexpectedRegisteredTask, true, out registeredTasks),
String.Format("Unexpected task '{0}' registered!", unexpectedRegisteredTask));
}
}
[Test]
public void WarningLoggedIfNoDefaultTasksFound()
{
//Note Engine's BinPath is distinct from the ToolsVersion's ToolsPath
Engine e = new Engine();
MockLogger mockLogger = new MockLogger();
e.RegisterLogger(mockLogger);
ToolsetState t = new ToolsetState(e, new Toolset("toolsversionname", "c:\\directory1\\directory2\\doesntexist"), new GetFiles(this.getFiles), new LoadXmlFromPath(this.loadXmlFromPath));
TaskRegistry taskRegistry = (TaskRegistry) t.GetTaskRegistry(null);
string[] unexpectedRegisteredTasks = { "a1", "a2", "a3", "a4", "b1", "c1", "d1", "e1", "f1", "g1", "g2", "g3", "11", "12", "13", "21" };
Assert.AreEqual(1, mockLogger.WarningCount, "Expected 1 warning logged!");
foreach (string unexpectedRegisteredTask in unexpectedRegisteredTasks)
{
Hashtable registeredTasks;
Assert.IsFalse(taskRegistry.FindRegisteredTasks(unexpectedRegisteredTask, true, out registeredTasks),
String.Format("Unexpected task '{0}' registered!", unexpectedRegisteredTask));
}
}
[Test]
public void InvalidToolPath()
{
//Note Engine's BinPath is distinct from the ToolsVersion's ToolsPath
Engine e = new Engine();
MockLogger mockLogger = new MockLogger();
e.RegisterLogger(mockLogger);
ToolsetState t = new ToolsetState(e, new Toolset("toolsversionname", "invalid||path"), new GetFiles(this.getFiles), new LoadXmlFromPath(this.loadXmlFromPath));
TaskRegistry taskRegistry = (TaskRegistry) t.GetTaskRegistry(null);
Console.WriteLine(mockLogger.FullLog);
Assert.AreEqual(1, mockLogger.WarningCount, "Expected a warning for invalid character in toolpath");
}
public ToolsetState_Tests()
{
defaultTasksFileMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (DefaultTasksFile defaultTasksFileCandidate in defaultTasksFileCandidates)
{
defaultTasksFileMap.Add(defaultTasksFileCandidate.Path, defaultTasksFileCandidate.XmlContents);
}
}
private string[] getFiles(string path, string pattern)
{
// Cause an exception if the path is invalid
Path.GetFileName(path);
string pathWithoutTrailingSlash = path.EndsWith("\\") ? path.Substring(0, path.Length - 1) : path;
//NOTE: the Replace calls below are a very minimal attempt to convert a basic, cmd.exe-style wildcard
//into something Regex.IsMatch will know how to use.
string finalPattern = "^" + pattern.Replace(".", "\\.").Replace("*", "[\\w\\W]*") + "$";
List<string> matches = new List<string>(defaultTasksFileMap.Keys);
matches.RemoveAll(
delegate(string candidate)
{
bool sameFolder = (0 == String.Compare(Path.GetDirectoryName(candidate),
pathWithoutTrailingSlash,
StringComparison.OrdinalIgnoreCase));
return !sameFolder || !Regex.IsMatch(Path.GetFileName(candidate), finalPattern);
});
return matches.ToArray();
}
private XmlDocument loadXmlFromPath(string path)
{
string xmlContents = defaultTasksFileMap[path];
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xmlContents);
return xmlDocument;
}
private readonly Dictionary<string, string> defaultTasksFileMap;
private DefaultTasksFile[] defaultTasksFileCandidates =
{ new DefaultTasksFile(
"c:\\directory1\\directory2\\a.tasks",
@"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<UsingTask TaskName='a1' AssemblyName='a' />
<UsingTask TaskName='a2' AssemblyName='a' />
<UsingTask TaskName='a3' AssemblyName='a' />
<UsingTask TaskName='a4' AssemblyName='a' />
</Project>"),
new DefaultTasksFile("c:\\directory1\\directory2\\b.tasks",
@"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<UsingTask TaskName='b1' AssemblyName='b' />
</Project>"),
new DefaultTasksFile("c:\\directory1\\directory2\\c.tasksfile",
@"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<UsingTask TaskName='c1' AssemblyName='c' />
</Project>"),
new DefaultTasksFile("c:\\directory1\\directory2\\directory3\\d.tasks",
@"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<UsingTask TaskName='d1' AssemblyName='d' />
</Project>"),
new DefaultTasksFile("c:\\directory1\\directory2\\e.tasks",
@"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<UsingTask TaskName='e1' AssemblyName='e' />
</Project>"),
new DefaultTasksFile("d:\\directory1\\directory2\\f.tasks",
@"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<UsingTask TaskName='f1' AssemblyName='f' />
</Project>"),
new DefaultTasksFile("c:\\directory1\\directory2\\g.custom.tasks",
@"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<UsingTask TaskName='g1' AssemblyName='g' />
<UsingTask TaskName='g2' AssemblyName='g' />
<UsingTask TaskName='g3' AssemblyName='g' />
</Project>"),
new DefaultTasksFile("c:\\somepath\\1.tasks",
@"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<UsingTask TaskName='11' AssemblyName='1' />
<UsingTask TaskName='12' AssemblyName='1' />
<UsingTask TaskName='13' AssemblyName='1' />
</Project>"),
new DefaultTasksFile("c:\\somepath\\2.tasks",
@"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<UsingTask TaskName='21' AssemblyName='2' />
</Project>") };
public struct DefaultTasksFile
{
public string Path;
public string XmlContents;
public DefaultTasksFile(string path, string xmlContents)
{
this.Path = path;
this.XmlContents = xmlContents;
}
}
}
}
| {
"content_hash": "d118076534364849fb061507bb945855",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 197,
"avg_line_length": 50.39664804469274,
"alnum_prop": 0.5688948010198426,
"repo_name": "cdmihai/msbuild",
"id": "a1e2cce919874d29869885801823dea765d109f7",
"size": "9173",
"binary": false,
"copies": "14",
"ref": "refs/heads/master",
"path": "src/Deprecated/Engine.UnitTests/ToolsVersion_Tests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "5937"
},
{
"name": "C",
"bytes": "21"
},
{
"name": "C#",
"bytes": "29206849"
},
{
"name": "C++",
"bytes": "6"
},
{
"name": "Groovy",
"bytes": "3193"
},
{
"name": "PowerShell",
"bytes": "33189"
},
{
"name": "Scilab",
"bytes": "8"
},
{
"name": "Shell",
"bytes": "3959"
},
{
"name": "XML",
"bytes": "498609"
},
{
"name": "XSLT",
"bytes": "69632"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace VoteApp.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View();
}
}
}
| {
"content_hash": "56b72badfdbad7b32fe2fc3c957650ea",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 71,
"avg_line_length": 19.8,
"alnum_prop": 0.5512265512265512,
"repo_name": "GOlssn/VoteApp",
"id": "b0abf2022bfe830f8d03f7cb3ddc6820cb329b7e",
"size": "695",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Controllers/HomeController.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "112820"
},
{
"name": "CSS",
"bytes": "978"
},
{
"name": "JavaScript",
"bytes": "364"
}
],
"symlink_target": ""
} |
package com.infinityworks.webapp.security;
import com.infinityworks.webapp.config.AppProperties;
import com.infinityworks.webapp.domain.PasswordResetToken;
import com.infinityworks.webapp.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.math.BigInteger;
import java.security.SecureRandom;
import static java.time.LocalDateTime.now;
@Component
public class PasswordResetTokenGenerator {
private final SecureRandom random = new SecureRandom();
private final int tokenExpiryMins;
@Autowired
public PasswordResetTokenGenerator(AppProperties appProperties) {
tokenExpiryMins = appProperties.getPasswordResetExpirationMins();
}
public PasswordResetToken generateToken(User user) {
PasswordResetToken resetToken = new PasswordResetToken();
resetToken.setUser(user);
resetToken.setToken(randToken());
resetToken.setExpires(now().plusMinutes(tokenExpiryMins));
return resetToken;
}
private String randToken() {
return new BigInteger(120, random).toString(32);
}
}
| {
"content_hash": "1d2785ede59fa2f1b3ac480acb1fd3a6",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 73,
"avg_line_length": 32.628571428571426,
"alnum_prop": 0.7679509632224168,
"repo_name": "celestial-winter/vics",
"id": "c03848aca05186bf4bfdc91a559d5ace9c0bd5a1",
"size": "1142",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web-server/src/main/java/com/infinityworks/webapp/security/PasswordResetTokenGenerator.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "227367"
},
{
"name": "HTML",
"bytes": "157752"
},
{
"name": "Java",
"bytes": "521491"
},
{
"name": "JavaScript",
"bytes": "155026"
},
{
"name": "Shell",
"bytes": "3641"
}
],
"symlink_target": ""
} |
var browserSync = require("../../../");
var assert = require("chai").assert;
describe("Plugins: Retrieving user plugins when given inline", function() {
var instance;
var PLUGIN_REQUIRE = "bs-snippet-injector";
var PLUGIN_NAME = "Snippet Injector";
before(function(done) {
browserSync.reset();
var config = {
logLevel: "silent",
plugins: [PLUGIN_REQUIRE]
};
instance = browserSync(config, done).instance;
});
after(function() {
instance.cleanup();
});
it("Should access to only the user-specified plugins (1)", function(done) {
assert.equal(instance.getUserPlugins().length, 1);
done();
});
it("Should access to only the user-specified plugins (2)", function(done) {
var plugin = instance.getUserPlugins()[0];
assert.equal(plugin.name, PLUGIN_NAME);
done();
});
});
| {
"content_hash": "ae3fd56276b3169fb46c1c8932b298df",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 79,
"avg_line_length": 28.71875,
"alnum_prop": 0.5908596300326442,
"repo_name": "BrowserSync/browser-sync",
"id": "97f6a4559f0e404dd7d43d7115c0b2b5b7ffb39a",
"size": "919",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/browser-sync/test/specs/plugins/user.plugins.inline.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "19612"
},
{
"name": "HTML",
"bytes": "62568"
},
{
"name": "Handlebars",
"bytes": "41698"
},
{
"name": "JavaScript",
"bytes": "993349"
},
{
"name": "SCSS",
"bytes": "41362"
},
{
"name": "Shell",
"bytes": "1355"
},
{
"name": "TypeScript",
"bytes": "107044"
}
],
"symlink_target": ""
} |
import { Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { WineryTableColumn } from '../wineryTableModule/wineryTable.component';
import { InterfaceParameter } from '../wineryInterfaces/parameters';
import { WineryValidatorObject } from '../wineryValidators/wineryDuplicateValidator.directive';
import { YesNoEnum } from '../wineryInterfaces/enums';
import { WineryNotificationService } from '../wineryNotificationModule/wineryNotification.service';
/**
* This component provides two tables for adding and removing input and output parameters as they are used for example
* in the {@link InterfacesComponent}. Therefore you need to specify the arrays containing the input/output parameters
* as an {@link InterfaceParameter} array. Additionally, there are some events which fire upon adding/removing elements.
*
* <label>Inputs</label>
* <ul>
* <li><code>inputParameters</code> the array for the input parameters. It must be of type {@link InterfaceParameter}.
* </li>
* <li><code>outputParameters</code> the array for the output parameters. It must be of type {@link InterfaceParameter}.
* </li>
* </ul>
*
* <label>Outputs</label>
* <ul>
* <li><code>inputParameterAdded</code> fires upon adding a input parameter to the table. It also contains the
* added element which is of type {@link InterfaceParameter}..
* </li>
* <li><code>outputParameterAdded</code> fires upon adding a output parameter to the table. It also contains the
* added element which is of type {@link InterfaceParameter}..
* </li>
* <li><code>inputParameterRemoved</code> fires upon removing a input parameter from the table. It also contains the
* removed element which is of type {@link InterfaceParameter}.
* </li>
* <li><code>outputParameterRemoved</code> fires upon removing a output parameter from the table. It also contains the
* removed element which is of type {@link InterfaceParameter}.
* </li>
* </ul>
*
* @example <caption>Minimalistic example:</caption>
* ```
* <winery-io-parameter [inputParameters]="newPlan.inputParameters.inputParameter"
* [outputParameters]="newPlan.outputParameters.outputParameter">
* </winery-io-parameter>
* ```
*/
@Component({
selector: 'winery-io-parameter',
templateUrl: './wineryIoParameter.component.html'
})
export class WineryIoParameterComponent {
@Input() inputParameters: InterfaceParameter[];
@Input() outputParameters: InterfaceParameter[];
@Output() inputParameterAdded = new EventEmitter<InterfaceParameter>();
@Output() outputParameterAdded = new EventEmitter<InterfaceParameter>();
@Output() inputParameterRemoved = new EventEmitter<InterfaceParameter>();
@Output() outputParameterRemoved = new EventEmitter<InterfaceParameter>();
@ViewChild('addIntParametersModal') addParametersModal: any;
@ViewChild('removeElementModal') removeElementModal: any;
@ViewChild('parameterForm') parameterForm: any;
selectedInputParameter: InterfaceParameter;
selectedOutputParameter: InterfaceParameter;
columns: Array<WineryTableColumn> = [
{title: 'Name', name: 'name', sort: true},
{title: 'Type', name: 'type', sort: true},
{title: 'Required', name: 'required', sort: false}
];
modalTitle: string;
elementToRemove: string;
validatorObject: WineryValidatorObject;
constructor(private notify: WineryNotificationService) {
}
// region ########## Input Parameters ##########
addInputParam() {
this.modalTitle = 'Input Parameter';
this.validatorObject = new WineryValidatorObject(this.inputParameters, 'name');
this.parameterForm.reset();
this.addParametersModal.show();
}
onAddInputParam(name: string, type: string, required: boolean) {
const item = new InterfaceParameter(name, type, required ? YesNoEnum.YES : YesNoEnum.NO);
this.inputParameters.push(item);
this.inputParameterAdded.emit(item);
}
onInputParameterSelected(selectedInput: InterfaceParameter) {
this.selectedInputParameter = selectedInput;
}
removeInputParameter() {
this.modalTitle = 'Remove Input Parameter';
this.elementToRemove = this.selectedInputParameter.name;
this.removeElementModal.show();
}
onRemoveInputParameter() {
this.inputParameters.splice(this.inputParameters.indexOf(this.selectedInputParameter));
this.inputParameterRemoved.emit(this.selectedInputParameter);
this.selectedInputParameter = null;
}
// endregion
// region ########## Output Parameters ##########
addOutputParam() {
this.modalTitle = 'Output Parameter';
this.validatorObject = new WineryValidatorObject(this.outputParameters, 'name');
this.parameterForm.reset();
this.addParametersModal.show();
}
onAddOutputParam(name: string, type: string, required: boolean) {
const item = new InterfaceParameter(name, type, required ? YesNoEnum.YES : YesNoEnum.NO);
this.outputParameters.push(item);
this.outputParameterAdded.emit(item);
}
onOutputParameterSelected(selectedOutput: InterfaceParameter) {
this.selectedOutputParameter = selectedOutput;
}
removeOutputParameter() {
this.modalTitle = 'Remove Output Parameter';
this.elementToRemove = this.selectedOutputParameter.name;
this.removeElementModal.show();
}
onRemoveOutputParameter() {
this.outputParameters.splice(this.outputParameters.indexOf(this.selectedOutputParameter));
this.outputParameterRemoved.emit(this.selectedOutputParameter);
this.selectedOutputParameter = null;
}
// endregion
onRemoveElement() {
switch (this.modalTitle) {
case 'Remove Input Parameter':
this.onRemoveInputParameter();
break;
case 'Remove Output Parameter':
this.onRemoveOutputParameter();
break;
default:
this.notify.error('Couldn\'t remove element!');
}
}
}
| {
"content_hash": "1db0efd9ef41fd88d34b6223164c7cf9",
"timestamp": "",
"source": "github",
"line_count": 156,
"max_line_length": 124,
"avg_line_length": 39.66025641025641,
"alnum_prop": 0.6896718926781962,
"repo_name": "YannicSowoidnich/winery",
"id": "860bce1c56f143afcfaff2a2abfdc13b2dba4627",
"size": "6646",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "org.eclipse.winery.repository.ui/src/app/wineryIoParameter/wineryIoParameter.component.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "770"
},
{
"name": "CSS",
"bytes": "96676"
},
{
"name": "HTML",
"bytes": "273259"
},
{
"name": "Java",
"bytes": "1743710"
},
{
"name": "JavaScript",
"bytes": "85796"
},
{
"name": "Shell",
"bytes": "1174"
},
{
"name": "TypeScript",
"bytes": "458830"
}
],
"symlink_target": ""
} |
package org.apache.cordova;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.widget.FrameLayout;
import org.apache.cordova.engine.SystemWebViewEngine;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Main class for interacting with a Cordova webview. Manages plugins, events, and a CordovaWebViewEngine.
* Class uses two-phase initialization. You must call init() before calling any other methods.
*/
public class CordovaWebViewImpl implements CordovaWebView {
public static final String TAG = "CordovaWebViewImpl";
// Public for backwards-compatibility :(
public PluginManager pluginManager;
protected final CordovaWebViewEngine engine;
private CordovaInterface cordova;
// Flag to track that a loadUrl timeout occurred
private int loadUrlTimeout = 0;
private CordovaResourceApi resourceApi;
private CordovaPreferences preferences;
private CoreAndroid appPlugin;
private NativeToJsMessageQueue nativeToJsMessageQueue;
private EngineClient engineClient = new EngineClient();
private Context context;
// The URL passed to loadUrl(), not necessarily the URL of the current page.
String loadedUrl;
/** custom view created by the browser (a video player for example) */
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
private Set<Integer> boundKeyCodes = new HashSet<Integer>();
public static CordovaWebViewEngine createEngine(Context context, CordovaPreferences preferences) {
String className = preferences.getString("webview", SystemWebViewEngine.class.getCanonicalName());
try {
Class<?> webViewClass = Class.forName(className);
Constructor<?> constructor = webViewClass.getConstructor(Context.class, CordovaPreferences.class);
return (CordovaWebViewEngine) constructor.newInstance(context, preferences);
} catch (Exception e) {
throw new RuntimeException("Failed to create webview. ", e);
}
}
public CordovaWebViewImpl(Context context, CordovaWebViewEngine cordovaWebViewEngine) {
this.context = context;
this.engine = cordovaWebViewEngine;
}
// Convenience method for when creating programmatically (not from Config.xml).
public void init(CordovaInterface cordova) {
init(cordova, new ArrayList<PluginEntry>(), new CordovaPreferences());
}
@Override
public void init(CordovaInterface cordova, List<PluginEntry> pluginEntries, CordovaPreferences preferences) {
if (this.cordova != null) {
throw new IllegalStateException();
}
this.cordova = cordova;
this.preferences = preferences;
pluginManager = new PluginManager(this, this.cordova, pluginEntries);
resourceApi = new CordovaResourceApi(engine.getView().getContext(), pluginManager);
nativeToJsMessageQueue = new NativeToJsMessageQueue();
nativeToJsMessageQueue.addBridgeMode(new NativeToJsMessageQueue.NoOpBridgeMode());
nativeToJsMessageQueue.addBridgeMode(new NativeToJsMessageQueue.LoadUrlBridgeMode(engine, cordova));
if (preferences.getBoolean("DisallowOverscroll", false)) {
engine.getView().setOverScrollMode(View.OVER_SCROLL_NEVER);
}
engine.init(this, cordova, engineClient, resourceApi, pluginManager, nativeToJsMessageQueue);
// This isn't enforced by the compiler, so assert here.
assert engine.getView() instanceof CordovaWebViewEngine.EngineView;
pluginManager.addService(CoreAndroid.PLUGIN_NAME, "org.apache.cordova.CoreAndroid");
pluginManager.init();
}
@Override
public boolean isInitialized() {
return cordova != null;
}
@Override
public void loadUrlIntoView(final String url, boolean recreatePlugins) {
LOG.d(TAG, ">>> loadUrl(" + url + ")");
if (url.equals("about:blank") || url.startsWith("javascript:")) {
engine.loadUrl(url, false);
return;
}
recreatePlugins = recreatePlugins || (loadedUrl == null);
if (recreatePlugins) {
// Don't re-initialize on first load.
if (loadedUrl != null) {
pluginManager.init();
}
loadedUrl = url;
}
// Create a timeout timer for loadUrl
final int currentLoadUrlTimeout = loadUrlTimeout;
final int loadUrlTimeoutValue = preferences.getInteger("LoadUrlTimeoutValue", 20000);
// Timeout error method
final Runnable loadError = new Runnable() {
public void run() {
stopLoading();
LOG.e(TAG, "CordovaWebView: TIMEOUT ERROR!");
// Handle other errors by passing them to the webview in JS
JSONObject data = new JSONObject();
try {
data.put("errorCode", -6);
data.put("description", "The connection to the server was unsuccessful.");
data.put("url", url);
} catch (JSONException e) {
// Will never happen.
}
pluginManager.postMessage("onReceivedError", data);
}
};
// Timeout timer method
final Runnable timeoutCheck = new Runnable() {
public void run() {
try {
synchronized (this) {
wait(loadUrlTimeoutValue);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
// If timeout, then stop loading and handle error
if (loadUrlTimeout == currentLoadUrlTimeout) {
cordova.getActivity().runOnUiThread(loadError);
}
}
};
final boolean _recreatePlugins = recreatePlugins;
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
if (loadUrlTimeoutValue > 0) {
cordova.getThreadPool().execute(timeoutCheck);
}
engine.loadUrl(url, _recreatePlugins);
}
});
}
@Override
public void loadUrl(String url) {
loadUrlIntoView(url, true);
}
@Override
public void showWebPage(String url, boolean openExternal, boolean clearHistory, Map<String, Object> params) {
LOG.d(TAG, "showWebPage(%s, %b, %b, HashMap)", url, openExternal, clearHistory);
// If clearing history
if (clearHistory) {
engine.clearHistory();
}
// If loading into our webview
if (!openExternal) {
// Make sure url is in whitelist
if (pluginManager.shouldAllowNavigation(url)) {
// TODO: What about params?
// Load new URL
loadUrlIntoView(url, true);
} else {
LOG.w(TAG, "showWebPage: Refusing to load URL into webview since it is not in the <allow-navigation> whitelist. URL=" + url);
}
}
if (!pluginManager.shouldOpenExternalUrl(url)) {
LOG.w(TAG, "showWebPage: Refusing to send intent for URL since it is not in the <allow-intent> whitelist. URL=" + url);
return;
}
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
// To send an intent without CATEGORY_BROWSER, a custom plugin should be used.
intent.addCategory(Intent.CATEGORY_BROWSABLE);
Uri uri = Uri.parse(url);
// Omitting the MIME type for file: URLs causes "No Activity found to handle Intent".
// Adding the MIME type to http: URLs causes them to not be handled by the downloader.
if ("file".equals(uri.getScheme())) {
intent.setDataAndType(uri, resourceApi.getMimeType(uri));
} else {
intent.setData(uri);
}
cordova.getActivity().startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error loading url " + url, e);
}
}
@Override
@Deprecated
public void showCustomView(View view, WebChromeClient.CustomViewCallback callback) {
// This code is adapted from the original Android Browser code, licensed under the Apache License, Version 2.0
Log.d(TAG, "showing Custom View");
// if a view already exists then immediately terminate the new one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
// Store the view and its callback for later (to kill it properly)
mCustomView = view;
mCustomViewCallback = callback;
// Add the custom view to its container.
ViewGroup parent = (ViewGroup) engine.getView().getParent();
parent.addView(view, new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
Gravity.CENTER));
// Hide the content view.
engine.getView().setVisibility(View.GONE);
// Finally show the custom view container.
parent.setVisibility(View.VISIBLE);
parent.bringToFront();
}
@Override
@Deprecated
public void hideCustomView() {
// This code is adapted from the original Android Browser code, licensed under the Apache License, Version 2.0
if (mCustomView == null) return;
Log.d(TAG, "Hiding Custom View");
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
ViewGroup parent = (ViewGroup) engine.getView().getParent();
parent.removeView(mCustomView);
mCustomView = null;
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
engine.getView().setVisibility(View.VISIBLE);
}
@Override
@Deprecated
public boolean isCustomViewShowing() {
return mCustomView != null;
}
@Override
@Deprecated
public void sendJavascript(String statement) {
nativeToJsMessageQueue.addJavaScript(statement);
}
@Override
public void sendPluginResult(PluginResult cr, String callbackId) {
nativeToJsMessageQueue.addPluginResult(cr, callbackId);
}
@Override
public PluginManager getPluginManager() {
return pluginManager;
}
@Override
public CordovaPreferences getPreferences() {
return preferences;
}
@Override
public ICordovaCookieManager getCookieManager() {
return engine.getCookieManager();
}
@Override
public CordovaResourceApi getResourceApi() {
return resourceApi;
}
@Override
public CordovaWebViewEngine getEngine() {
return engine;
}
@Override
public View getView() {
return engine.getView();
}
@Override
public Context getContext() {
return engine.getView().getContext();
}
private void sendJavascriptEvent(String event) {
if (appPlugin == null) {
appPlugin = (CoreAndroid)pluginManager.getPlugin(CoreAndroid.PLUGIN_NAME);
}
if (appPlugin == null) {
LOG.w(TAG, "Unable to fire event without existing plugin");
return;
}
appPlugin.fireJavascriptEvent(event);
}
@Override
public void setButtonPlumbedToJs(int keyCode, boolean override) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_BACK:
// TODO: Why are search and menu buttons handled separately?
if (override) {
boundKeyCodes.add(keyCode);
} else {
boundKeyCodes.remove(keyCode);
}
return;
default:
throw new IllegalArgumentException("Unsupported keycode: " + keyCode);
}
}
@Override
public boolean isButtonPlumbedToJs(int keyCode) {
return boundKeyCodes.contains(keyCode);
}
@Override
public Object postMessage(String id, Object data) {
return pluginManager.postMessage(id, data);
}
// Engine method proxies:
@Override
public String getUrl() {
return engine.getUrl();
}
@Override
public void stopLoading() {
// Clear timeout flag
loadUrlTimeout++;
}
@Override
public boolean canGoBack() {
return engine.canGoBack();
}
@Override
public void clearCache() {
engine.clearCache();
}
@Override
@Deprecated
public void clearCache(boolean b) {
engine.clearCache();
}
@Override
public void clearHistory() {
engine.clearHistory();
}
@Override
public boolean backHistory() {
return engine.goBack();
}
/////// LifeCycle methods ///////
@Override
public void onNewIntent(Intent intent) {
if (this.pluginManager != null) {
this.pluginManager.onNewIntent(intent);
}
}
@Override
public void handlePause(boolean keepRunning) {
if (!isInitialized()) {
return;
}
LOG.d(TAG, "Handle the pause");
sendJavascriptEvent("pause");
pluginManager.onPause(keepRunning);
// If app doesn't want to run in background
if (!keepRunning) {
// Pause JavaScript timers. This affects all webviews within the app!
engine.setPaused(true);
}
}
@Override
public void handleResume(boolean keepRunning) {
if (!isInitialized()) {
return;
}
// Resume JavaScript timers. This affects all webviews within the app!
engine.setPaused(false);
sendJavascriptEvent("resume");
this.pluginManager.onResume(keepRunning);
}
@Override
public void handleDestroy() {
if (!isInitialized()) {
return;
}
// Cancel pending timeout timer.
loadUrlTimeout++;
// Forward to plugins
this.pluginManager.onDestroy();
// Load blank page so that JavaScript onunload is called
this.loadUrl("about:blank");
// TODO: Should not destroy webview until after about:blank is done loading.
engine.destroy();
hideCustomView();
}
protected class EngineClient implements CordovaWebViewEngine.Client {
@Override
public void clearLoadTimeoutTimer() {
loadUrlTimeout++;
}
@Override
public void onPageStarted(String newUrl) {
LOG.d(TAG, "onPageDidNavigate(" + newUrl + ")");
boundKeyCodes.clear();
pluginManager.onReset();
pluginManager.postMessage("onPageStarted", newUrl);
}
@Override
public void onReceivedError(int errorCode, String description, String failingUrl) {
clearLoadTimeoutTimer();
JSONObject data = new JSONObject();
try {
data.put("errorCode", errorCode);
data.put("description", description);
data.put("url", failingUrl);
} catch (JSONException e) {
e.printStackTrace();
}
pluginManager.postMessage("onReceivedError", data);
}
@Override
public void onPageFinishedLoading(String url) {
LOG.d(TAG, "onPageFinished(" + url + ")");
clearLoadTimeoutTimer();
// Broadcast message that page has loaded
pluginManager.postMessage("onPageFinished", url);
// Make app visible after 2 sec in case there was a JS error and Cordova JS never initialized correctly
if (engine.getView().getVisibility() != View.VISIBLE) {
Thread t = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(2000);
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
pluginManager.postMessage("spinner", "stop");
}
});
} catch (InterruptedException e) {
}
}
});
t.start();
}
// Shutdown if blank loaded
if (url.equals("about:blank")) {
pluginManager.postMessage("exit", null);
}
}
@Override
public Boolean onDispatchKeyEvent(KeyEvent event) {
int keyCode = event.getKeyCode();
boolean isBackButton = keyCode == KeyEvent.KEYCODE_BACK;
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (isBackButton && mCustomView != null) {
return true;
} else if (boundKeyCodes.contains(keyCode)) {
return true;
} else if (isBackButton) {
return engine.canGoBack();
}
} else if (event.getAction() == KeyEvent.ACTION_UP) {
if (isBackButton && mCustomView != null) {
hideCustomView();
return true;
} else if (boundKeyCodes.contains(keyCode)) {
String eventName = null;
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
eventName = "volumedownbutton";
break;
case KeyEvent.KEYCODE_VOLUME_UP:
eventName = "volumeupbutton";
break;
case KeyEvent.KEYCODE_SEARCH:
eventName = "searchbutton";
break;
case KeyEvent.KEYCODE_MENU:
eventName = "menubutton";
break;
case KeyEvent.KEYCODE_BACK:
eventName = "backbutton";
break;
}
if (eventName != null) {
sendJavascriptEvent(eventName);
return true;
}
} else if (isBackButton) {
return engine.goBack();
}
}
return null;
}
@Override
public void onScrollChanged(int l, int t, int oldl, int oldt) {
// TODO: scrolling is perf-sensitive, so we'd probably be better to no use postMessage
// here, and also not to create any new objects.
ScrollEvent myEvent = new ScrollEvent(l, t, oldl, oldt, getView());
pluginManager.postMessage("onScrollChanged", myEvent);
}
@Override
public boolean onNavigationAttempt(String url) {
// Give plugins the chance to handle the url
if (pluginManager.onOverrideUrlLoading(url)) {
return true;
} else if (pluginManager.shouldAllowNavigation(url)) {
return false;
} else if (pluginManager.shouldOpenExternalUrl(url)) {
showWebPage(url, true, false, null);
return true;
}
LOG.w(TAG, "Blocked (possibly sub-frame) navigation to non-allowed URL: " + url);
return true;
}
}
}
| {
"content_hash": "0b22a9871ca01c1f07e0747218e99b23",
"timestamp": "",
"source": "github",
"line_count": 583,
"max_line_length": 141,
"avg_line_length": 34.64493996569468,
"alnum_prop": 0.5810971383305278,
"repo_name": "walkingriver/mdcl",
"id": "ed9d9da14cbe8b66d9a1d99ef7a1a4086b972350",
"size": "21056",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "engine/cordova-android-c0.6.1/framework/src/org/apache/cordova/CordovaWebViewImpl.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11015"
},
{
"name": "HTML",
"bytes": "60262"
},
{
"name": "Java",
"bytes": "332494"
},
{
"name": "JavaScript",
"bytes": "152852"
},
{
"name": "Shell",
"bytes": "15366"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("disk-usage-test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Hyder Consulting Ltd")]
[assembly: AssemblyProduct("disk-usage-test")]
[assembly: AssemblyCopyright("Copyright © Hyder Consulting Ltd 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b9e7a81b-147d-44e1-8bad-48e48e3e66e8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "d36802416adc726568de28cd67e7ac04",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 84,
"avg_line_length": 40.114285714285714,
"alnum_prop": 0.7443019943019943,
"repo_name": "factorydefault/disk-usage",
"id": "7dfaffe0c0f0db6635b637f09a23c1afda816a9f",
"size": "1407",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "disk-usage-test/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "98062"
}
],
"symlink_target": ""
} |
var Promise = require("promise");
var path = require("path");
var packageInfo = require(path.join(__dirname, "package.json"));
var spawn = require("child_process").spawn;
// Use major.minor.patch from version string - e.g. "1.2.3" from "1.2.3-alpha"
var elmVersion = packageInfo.version.replace(/^(\d+\.\d+\.\d+).*$/, "$1");
var platformDir = path.join(__dirname, "Elm-Platform", elmVersion);
var distDir = path.join(platformDir, ".cabal-sandbox", "bin");
var shareDir = path.join(platformDir, "share");
var shareReactorDir = path.join(shareDir, "reactor");
var executables = Object.keys(packageInfo.bin);
var binaryExtension = process.platform === "win32" ? ".exe" : "";
var executablePaths = {};
executables.forEach(function(executable) {
executablePaths[executable] = path.join(distDir, executable + binaryExtension);
});
module.exports = {
packageInfo: packageInfo,
elmVersion: elmVersion,
distDir: distDir,
shareDir: shareDir,
shareReactorDir: shareReactorDir,
executablePaths: executablePaths,
executables: executables
};
| {
"content_hash": "118a93ed413ec0cd20c5fc5ff033271c",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 81,
"avg_line_length": 37.392857142857146,
"alnum_prop": 0.7163323782234957,
"repo_name": "jvoigtlaender/elm-platform",
"id": "c84281fe70b8472c812a9ad08f84c44961681d3b",
"size": "1047",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "installers/npm/platform.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "584"
},
{
"name": "Haskell",
"bytes": "5636"
},
{
"name": "JavaScript",
"bytes": "8263"
},
{
"name": "NSIS",
"bytes": "8212"
},
{
"name": "Shell",
"bytes": "3728"
},
{
"name": "Visual Basic",
"bytes": "1096"
}
],
"symlink_target": ""
} |
package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_4973 {
}
| {
"content_hash": "0ab2782f83f00b196e138fc8a01482c2",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 52,
"avg_line_length": 21.571428571428573,
"alnum_prop": 0.8079470198675497,
"repo_name": "lesaint/experimenting-annotation-processing",
"id": "04c1d8a3000382d4d950a08bb197aa8607fec8be",
"size": "151",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_4973.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1909421"
},
{
"name": "Shell",
"bytes": "1605"
}
],
"symlink_target": ""
} |
<html>
<head>
<style>
.box {
position: relative;
left: 0;
height: 100px;
width: 100px;
margin: 10px;
background-color: blue;
transition-property: width, left, background-color, height, top;
transition-duration: 0.06s;
}
.box1 {
left: 50px;
}
.box2 {
background-color: red;
}
.box3 {
width: 150px;
transition-duration: 0.1s;
}
</style>
<script src="transition-end-event-helpers.js"></script>
<script type="text/javascript">
var expectedEndEvents = [
// [property-name, element-id, elapsed-time, listen]
["background-color", "box2", 0.06, false],
["left", "box1", 0.06, false],
["width", "box3", 0.1, false],
];
function handleEndEvent3(event)
{
recordTransitionEndEvent(event);
}
function handleEndEvent2(event)
{
recordTransitionEndEvent(event);
var box = document.getElementById("box3");
box.addEventListener("transitionend", handleEndEvent3, false);
box.className = "box box3";
}
function handleEndEvent1(event)
{
recordTransitionEndEvent(event);
var box = document.getElementById("box2");
box.addEventListener("transitionend", handleEndEvent2, false);
box.className = "box box2";
}
function setupTest()
{
var box = document.getElementById("box1");
box.addEventListener("transitionend", handleEndEvent1, false);
box.className = "box box1";
}
runTransitionTest(expectedEndEvents, setupTest);
</script>
</head>
<body>
<p>Initiating transitions on various properties of all boxes.</p>
<div id="container">
<div id="box1" class="box"></div>
<div id="box2" class="box"></div>
<div id="box3" class="box"></div>
</div>
<div id="result"></div>
</body>
</html> | {
"content_hash": "a21cd36aa99d6e9237d9ff5d944e98f1",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 70,
"avg_line_length": 22.105882352941176,
"alnum_prop": 0.5971261309207025,
"repo_name": "nwjs/chromium.src",
"id": "0c708100a9c01e91561e98eaf0de3ccf8adcfbb0",
"size": "1879",
"binary": false,
"copies": "12",
"ref": "refs/heads/nw70",
"path": "third_party/blink/web_tests/transitions/transition-end-event-nested.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package flash.swf.types;
/**
* Defines the common API for all filters.
*/
public abstract class Filter
{
public abstract int getID();
}
| {
"content_hash": "1bc2686eae510c10ca4d6d7f7e122bf9",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 42,
"avg_line_length": 13.181818181818182,
"alnum_prop": 0.6827586206896552,
"repo_name": "shyamalschandra/flex-sdk",
"id": "9893df27168ec8f3c3dab566a72c90876292e376",
"size": "964",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "modules/swfutils/src/java/flash/swf/types/Filter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AGS Script",
"bytes": "478"
},
{
"name": "ASP",
"bytes": "6381"
},
{
"name": "ActionScript",
"bytes": "34905828"
},
{
"name": "Awk",
"bytes": "1958"
},
{
"name": "Batchfile",
"bytes": "40336"
},
{
"name": "C",
"bytes": "4601"
},
{
"name": "C++",
"bytes": "10259"
},
{
"name": "CSS",
"bytes": "508448"
},
{
"name": "Groff",
"bytes": "59633"
},
{
"name": "HTML",
"bytes": "84174"
},
{
"name": "Java",
"bytes": "15072097"
},
{
"name": "JavaScript",
"bytes": "110516"
},
{
"name": "PureBasic",
"bytes": "362"
},
{
"name": "Shell",
"bytes": "306431"
},
{
"name": "Visual Basic",
"bytes": "4498"
},
{
"name": "XSLT",
"bytes": "757371"
}
],
"symlink_target": ""
} |
PEGASUS_USING_PEGASUS;
PEGASUS_USING_STD;
#include "UNIX_SupportAccessProvider.h"
extern "C"
PEGASUS_EXPORT CIMProvider* PegasusCreateProvider(const String& providerName)
{
if (String::equalNoCase(providerName, CIMHelper::EmptyString)) return NULL;
else if (String::equalNoCase(providerName, "UNIX_SupportAccessProvider")) return new UNIX_SupportAccessProvider();
return NULL;
}
| {
"content_hash": "0bee34509f9473410e4de3dbb665c470",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 115,
"avg_line_length": 24.25,
"alnum_prop": 0.7912371134020618,
"repo_name": "brunolauze/openpegasus-providers-old",
"id": "7705868238cc6799ed62a41c418d20722354a9a5",
"size": "2192",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Providers/UNIXProviders/SupportAccess/UNIX_SupportAccessMain.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2631164"
},
{
"name": "C++",
"bytes": "120884401"
},
{
"name": "Objective-C",
"bytes": "64"
},
{
"name": "Shell",
"bytes": "17094"
}
],
"symlink_target": ""
} |
from datetime import timedelta as td
import time
from unittest.mock import patch
from django.core import signing
from django.utils.timezone import now
from hc.test import BaseTestCase
class UnsubscribeReportsTestCase(BaseTestCase):
def test_it_unsubscribes(self):
self.profile.next_report_date = now()
self.profile.nag_period = td(hours=1)
self.profile.next_nag_date = now()
self.profile.save()
sig = signing.TimestampSigner(salt="reports").sign("alice")
url = "/accounts/unsubscribe_reports/%s/" % sig
r = self.client.post(url)
self.assertContains(r, "Unsubscribed")
self.profile.refresh_from_db()
self.assertEqual(self.profile.reports, "off")
self.assertIsNone(self.profile.next_report_date)
self.assertEqual(self.profile.nag_period.total_seconds(), 0)
self.assertIsNone(self.profile.next_nag_date)
def test_bad_signature_gets_rejected(self):
url = "/accounts/unsubscribe_reports/invalid/"
r = self.client.get(url)
self.assertContains(r, "Incorrect Link")
def test_it_serves_confirmation_form(self):
sig = signing.TimestampSigner(salt="reports").sign("alice")
url = "/accounts/unsubscribe_reports/%s/" % sig
r = self.client.get(url)
self.assertContains(r, "Please press the button below")
self.assertNotContains(r, "submit()")
def test_aged_signature_autosubmits(self):
with patch("django.core.signing.time") as mock_time:
mock_time.time.return_value = time.time() - 301
signer = signing.TimestampSigner(salt="reports")
sig = signer.sign("alice")
url = "/accounts/unsubscribe_reports/%s/" % sig
r = self.client.get(url)
self.assertContains(r, "Please press the button below")
self.assertContains(r, "submit()")
def test_it_handles_missing_user(self):
self.alice.delete()
sig = signing.TimestampSigner(salt="reports").sign("alice")
url = "/accounts/unsubscribe_reports/%s/" % sig
r = self.client.post(url)
self.assertContains(r, "Unsubscribed")
| {
"content_hash": "093d4939a975be7119d0f62be8416364",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 68,
"avg_line_length": 34.935483870967744,
"alnum_prop": 0.6523545706371191,
"repo_name": "iphoting/healthchecks",
"id": "f4cdb2fec6f4b1bd3b74ba91a0681163e2ceec95",
"size": "2166",
"binary": false,
"copies": "1",
"ref": "refs/heads/heroku",
"path": "hc/accounts/tests/test_unsubscribe_reports.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "64145"
},
{
"name": "Dockerfile",
"bytes": "939"
},
{
"name": "HTML",
"bytes": "595497"
},
{
"name": "JavaScript",
"bytes": "55883"
},
{
"name": "Less",
"bytes": "14135"
},
{
"name": "Python",
"bytes": "894208"
},
{
"name": "Shell",
"bytes": "4382"
}
],
"symlink_target": ""
} |
package de.codecentric.centerdevice.util;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class MenuBarUtils {
public static MenuBar createMenuBar(List<Menu> menus) {
MenuBar bar = new MenuBar();
bar.setUseSystemMenuBar(true);
bar.getMenus().addAll(menus);
return bar;
}
public static void removeExistingMenuBar(ObservableList<Node> children) {
children.removeAll(children.stream().filter(node -> node instanceof MenuBar).collect(Collectors.toList()));
}
public static void setMenuBar(Stage stage, MenuBar menuBar) {
Scene scene = stage.getScene();
if (scene != null) {
ObservableList<Node> children = getChildren(scene.getRoot());
if (children != null) {
setMenuBar(children, menuBar);
}
}
}
private static ObservableList<Node> getChildren(Parent parent) {
if (parent instanceof Pane) {
return ((Pane) parent).getChildren();
} else if (parent instanceof Group) {
return ((Group) parent).getChildren();
}
return null;
}
public static void setMenuBar(Pane pane, MenuBar menuBar) {
setMenuBar(pane.getChildren(), menuBar);
}
private static void setMenuBar(ObservableList<Node> children, MenuBar menuBar) {
replaceMenuBar(children, createMenuBar(extractSubMenus(menuBar)));
}
private static void replaceMenuBar(ObservableList<Node> children, MenuBar createMenuBar) {
removeExistingMenuBar(children);
children.add(createMenuBar);
}
private static List<Menu> extractSubMenus(MenuBar bar) {
if (bar.getMenus().size() <= 1) {
return new ArrayList<>();
}
return bar.getMenus().subList(1, bar.getMenus().size());
}
}
| {
"content_hash": "5a01727cec53aab0228297b448ef590e",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 109,
"avg_line_length": 28.264705882352942,
"alnum_prop": 0.7434963579604579,
"repo_name": "codecentric/NSMenuFX",
"id": "81af44879b1e27dff16b755ea67fea3ca88eb981",
"size": "1922",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/de/codecentric/centerdevice/util/MenuBarUtils.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "405"
},
{
"name": "Java",
"bytes": "41790"
}
],
"symlink_target": ""
} |
package com.mzy.mzy.coolweather.gson;
import com.google.gson.annotations.SerializedName;
/**
* Created by MZY on 2017/7/31.
*/
public class Forecast {
public String date;
@SerializedName("tmp")
public Temperature temperature;
@SerializedName("cond")
public More more;
public class Temperature{
public String max;
public String min;
}
public class More{
@SerializedName("txt_d")
public String info;
}
}
| {
"content_hash": "09372bf5a210d339a1f9d53ed261fad3",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 50,
"avg_line_length": 17.74074074074074,
"alnum_prop": 0.6450939457202505,
"repo_name": "miaozhenyu/coolweather",
"id": "542930e5d95c90a6daeb4091b6fc5268e779deef",
"size": "479",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/mzy/mzy/coolweather/gson/Forecast.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "32691"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ECharts.Entities.series
{
public class EventDetail
{
public string link { get; set; }
public string text { get; set; }
public string img { get; set; }
public EventDetail Link(string link)
{
this.link = link;
return this;
}
public EventDetail Text(string text)
{
this.text = text;
return this;
}
public EventDetail Img(string img)
{
this.img = img;
return this;
}
}
}
| {
"content_hash": "74e71397ac19fe6cc29299017af8467d",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 44,
"avg_line_length": 18.973684210526315,
"alnum_prop": 0.5090152565880721,
"repo_name": "idoku/EChartsSDK",
"id": "aa7dfd5fea3586194e56b51191f41e3ebdd96305",
"size": "723",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "EChartsSDK/ECharts/Entities/series/event/EventDetail.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "102"
},
{
"name": "C#",
"bytes": "870021"
},
{
"name": "CSS",
"bytes": "61294"
},
{
"name": "HTML",
"bytes": "6467"
},
{
"name": "JavaScript",
"bytes": "11041592"
},
{
"name": "Smalltalk",
"bytes": "5"
}
],
"symlink_target": ""
} |
<!--
@license
Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<link rel="import" href="../lib/bind/accessors.html">
<link rel="import" href="../lib/bind/effects.html">
<script>
/**
* Support for property side effects.
*
* Key for effect objects:
*
* property | ann | anCmp | cmp | obs | cplxOb | description
* ---------|-----|-------|-----|-----|--------|----------------------------------------
* method | | X | X | X | X | function name to call on instance
* args | | X | X | | X | list of all arg descriptors for fn
* arg | | X | X | | X | arg descriptor for effect
* property | | | X | X | | property for effect to set or get
* name | X | | | | | annotation value (text inside {{...}})
* kind | X | X | | | | binding type (property or attribute)
* index | X | X | | | | node index to set
*
*/
Polymer.Base._addFeature({
_addPropertyEffect: function(property, kind, effect) {
Polymer.Bind.addPropertyEffect(this, property, kind, effect);
},
// prototyping
_prepEffects: function() {
Polymer.Bind.prepareModel(this);
this._addAnnotationEffects(this._notes);
},
_prepBindings: function() {
Polymer.Bind.createBindings(this);
},
_addPropertyEffects: function(properties) {
if (properties) {
for (var p in properties) {
var prop = properties[p];
if (prop.observer) {
this._addObserverEffect(p, prop.observer);
}
if (prop.computed) {
this._addComputedEffect(p, prop.computed);
}
if (prop.notify) {
this._addPropertyEffect(p, 'notify');
}
if (prop.reflectToAttribute) {
this._addPropertyEffect(p, 'reflect');
}
if (prop.readOnly) {
// Ensure accessor is created
Polymer.Bind.ensurePropertyEffects(this, p);
}
}
}
},
_parseMethod: function(expression) {
var m = expression.match(/(\w*)\((.*)\)/);
if (m) {
return {
method: m[1],
args: m[2].split(/[^\w.*]+/).map(this._parseArg, this)
};
}
},
_parseArg: function(arg) {
var a = {
name: arg,
model: this._modelForPath(arg)
};
a.structured = arg.indexOf('.') > 0;
if (a.structured) {
a.wildcard = (arg.slice(-2) == '.*');
if (a.wildcard) {
a.name = arg.slice(0, -2);
}
}
return a;
},
_addComputedEffect: function(name, expression) {
var sig = this._parseMethod(expression);
sig.args.forEach(function(arg) {
this._addPropertyEffect(arg.model, 'compute', {
method: sig.method,
args: sig.args,
arg: arg,
property: name
});
}, this);
},
_addObserverEffect: function(property, observer) {
this._addPropertyEffect(property, 'observer', {
method: observer,
property: property
});
},
_addComplexObserverEffects: function(observers) {
if (observers) {
observers.forEach(function(observer) {
this._addComplexObserverEffect(observer);
}, this);
}
},
_addComplexObserverEffect: function(observer) {
var sig = this._parseMethod(observer);
sig.args.forEach(function(arg) {
this._addPropertyEffect(arg.model, 'complexObserver', {
method: sig.method,
args: sig.args,
arg: arg
});
}, this);
},
_addAnnotationEffects: function(notes) {
// create a virtual annotation list, must be concretized at instance time
this._nodes = [];
// process annotations that have been parsed from template
notes.forEach(function(note) {
// where to find the node in the concretized list
var index = this._nodes.push(note) - 1;
note.bindings.forEach(function(binding) {
this._addAnnotationEffect(binding, index);
}, this);
}, this);
},
_addAnnotationEffect: function(note, index) {
// TODO(sjmiles): annotations have 'effects' proper and 'listener'
if (Polymer.Bind._shouldAddListener(note)) {
// <node>.on.<dash-case-property>-changed: <path> = e.detail.value
Polymer.Bind._addAnnotatedListener(this, index,
note.name, note.value, note.event);
}
if (note.signature) {
this._addAnnotatedComputationEffect(note, index);
} else {
// capture the node index
note.index = index;
// add 'annotation' binding effect for property 'model'
this._addPropertyEffect(note.model, 'annotation', note);
}
},
_addAnnotatedComputationEffect: function(note, index) {
var sig = note.signature;
sig.args.forEach(function(arg) {
this._addPropertyEffect(arg.model, 'annotatedComputation', {
kind: note.kind,
method: sig.method,
args: sig.args,
arg: arg,
property: note.name,
index: index,
negate: note.negate
});
}, this);
},
// instancing
_marshalInstanceEffects: function() {
Polymer.Bind.prepareInstance(this);
Polymer.Bind.setupBindListeners(this);
},
_applyEffectValue: function(value, info) {
var node = this._nodes[info.index];
// TODO(sorvell): ideally, the info object is normalized for easy
// lookup here.
var property = info.property || info.name || 'textContent';
// special processing for 'class' and 'className'; 'class' handled
// when attr is serialized.
if (info.kind == 'attribute') {
this.serializeValueToAttribute(value, property, node);
} else {
// TODO(sorvell): consider pre-processing this step so we don't need
// this lookup.
if (property === 'className') {
value = this._scopeElementClass(node, value);
}
return node[property] = value;
}
}
});
</script>
| {
"content_hash": "513a9af6c3f69ef38a81c0e078641cc8",
"timestamp": "",
"source": "github",
"line_count": 210,
"max_line_length": 100,
"avg_line_length": 32.70952380952381,
"alnum_prop": 0.5412723831707672,
"repo_name": "degranda/Polymer-0.9",
"id": "639f9f7fc2691582799629a787c5d3637e96bff4",
"size": "6869",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/standard/effects.html",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "433"
},
{
"name": "HTML",
"bytes": "744391"
},
{
"name": "JavaScript",
"bytes": "36999"
}
],
"symlink_target": ""
} |
use borrowck::*;
use rustc::middle::expr_use_visitor as euv;
use rustc::middle::mem_categorization as mc;
use rustc::middle::mem_categorization::Categorization;
use rustc::middle::region;
use rustc::ty;
use syntax::ast;
use syntax_pos::Span;
type R = Result<(),()>;
pub fn guarantee_lifetime<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>,
item_scope: region::Scope,
span: Span,
cause: euv::LoanCause,
cmt: &'a mc::cmt_<'tcx>,
loan_region: ty::Region<'tcx>)
-> Result<(),()> {
//! Reports error if `loan_region` is larger than S
//! where S is `item_scope` if `cmt` is an upvar,
//! and is scope of `cmt` otherwise.
debug!("guarantee_lifetime(cmt={:?}, loan_region={:?})",
cmt, loan_region);
let ctxt = GuaranteeLifetimeContext {bccx: bccx,
item_scope,
span,
cause,
loan_region,
cmt_original: cmt};
ctxt.check(cmt, None)
}
///////////////////////////////////////////////////////////////////////////
// Private
struct GuaranteeLifetimeContext<'a, 'tcx: 'a> {
bccx: &'a BorrowckCtxt<'a, 'tcx>,
// the scope of the function body for the enclosing item
item_scope: region::Scope,
span: Span,
cause: euv::LoanCause,
loan_region: ty::Region<'tcx>,
cmt_original: &'a mc::cmt_<'tcx>
}
impl<'a, 'tcx> GuaranteeLifetimeContext<'a, 'tcx> {
fn check(&self, cmt: &mc::cmt_<'tcx>, discr_scope: Option<ast::NodeId>) -> R {
//! Main routine. Walks down `cmt` until we find the
//! "guarantor". Reports an error if `self.loan_region` is
//! larger than scope of `cmt`.
debug!("guarantee_lifetime.check(cmt={:?}, loan_region={:?})",
cmt,
self.loan_region);
match cmt.cat {
Categorization::Rvalue(..) |
Categorization::ThreadLocal(..) |
Categorization::Local(..) | // L-Local
Categorization::Upvar(..) |
Categorization::Deref(_, mc::BorrowedPtr(..)) | // L-Deref-Borrowed
Categorization::Deref(_, mc::UnsafePtr(..)) => {
self.check_scope(self.scope(cmt))
}
Categorization::StaticItem => {
Ok(())
}
Categorization::Downcast(ref base, _) |
Categorization::Deref(ref base, mc::Unique) | // L-Deref-Send
Categorization::Interior(ref base, _) => { // L-Field
self.check(base, discr_scope)
}
}
}
fn check_scope(&self, max_scope: ty::Region<'tcx>) -> R {
//! Reports an error if `loan_region` is larger than `max_scope`
if !self.bccx.is_subregion_of(self.loan_region, max_scope) {
Err(self.report_error(err_out_of_scope(max_scope, self.loan_region, self.cause)))
} else {
Ok(())
}
}
fn scope(&self, cmt: &mc::cmt_<'tcx>) -> ty::Region<'tcx> {
//! Returns the maximal region scope for the which the
//! place `cmt` is guaranteed to be valid without any
//! rooting etc, and presuming `cmt` is not mutated.
match cmt.cat {
Categorization::ThreadLocal(temp_scope) |
Categorization::Rvalue(temp_scope) => {
temp_scope
}
Categorization::Upvar(..) => {
self.bccx.tcx.mk_region(ty::ReScope(self.item_scope))
}
Categorization::Local(local_id) => {
let hir_id = self.bccx.tcx.hir().node_to_hir_id(local_id);
self.bccx.tcx.mk_region(ty::ReScope(
self.bccx.region_scope_tree.var_scope(hir_id.local_id)))
}
Categorization::StaticItem |
Categorization::Deref(_, mc::UnsafePtr(..)) => {
self.bccx.tcx.types.re_static
}
Categorization::Deref(_, mc::BorrowedPtr(_, r)) => {
r
}
Categorization::Downcast(ref cmt, _) |
Categorization::Deref(ref cmt, mc::Unique) |
Categorization::Interior(ref cmt, _) => {
self.scope(cmt)
}
}
}
fn report_error(&self, code: bckerr_code<'tcx>) {
self.bccx.report(BckError { cmt: self.cmt_original,
span: self.span,
cause: BorrowViolation(self.cause),
code: code });
}
}
| {
"content_hash": "15718da516a09664f1c7da7ff9af7a4e",
"timestamp": "",
"source": "github",
"line_count": 129,
"max_line_length": 93,
"avg_line_length": 37.434108527131784,
"alnum_prop": 0.47898115551874093,
"repo_name": "GBGamer/rust",
"id": "ccc091a6a1ce6e68860bc9432a98c535b62dc097",
"size": "5426",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/librustc_borrowck/borrowck/gather_loans/lifetime.rs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "27014"
},
{
"name": "Awk",
"bytes": "271"
},
{
"name": "C",
"bytes": "391581"
},
{
"name": "C++",
"bytes": "64107"
},
{
"name": "CSS",
"bytes": "27753"
},
{
"name": "HTML",
"bytes": "496"
},
{
"name": "JavaScript",
"bytes": "45051"
},
{
"name": "Lex",
"bytes": "9270"
},
{
"name": "Makefile",
"bytes": "306032"
},
{
"name": "PHP",
"bytes": "265"
},
{
"name": "Pascal",
"bytes": "13456"
},
{
"name": "Puppet",
"bytes": "3296"
},
{
"name": "Python",
"bytes": "197397"
},
{
"name": "Rust",
"bytes": "21265061"
},
{
"name": "Shell",
"bytes": "270571"
},
{
"name": "Yacc",
"bytes": "81068"
}
],
"symlink_target": ""
} |
<?php
namespace NyroDev\NyroCmsBundle\Controller;
use NyroDev\NyroCmsBundle\Services\UserService;
use NyroDev\UtilityBundle\Controller\AbstractController as NyroDevAbstractController;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class AdminController extends NyroDevAbstractController
{
use Traits\SubscribedServiceTrait;
public function loginAction(Request $request, AuthenticationUtils $authenticationUtils)
{
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('@NyroDevNyroCms/Admin/login.html.php', [
// last username entered by the user
'last_username' => $lastUsername,
'error' => $error,
]);
}
public function indexAction()
{
return $this->redirectToRoute('nyrocms_admin_data_content_tree');
}
public function forgotAction(Request $request, $id = null, $key = null, $welcome = false)
{
return $this->render('@NyroDevNyroCms/Admin/forgot.html.php', $this->get(UserService::class)->handleForgot('admin', $request, $id, $key, $welcome));
}
public function accountAction(Request $request)
{
return $this->render('@NyroDevNyroCms/Admin/account.html.php', $this->get(UserService::class)->handleAccount('admin', $request));
}
public function ccAction()
{
$fs = new Filesystem();
$cacheDir = $this->get(KernelInterface::class)->getCacheDir();
$ret = 'Nothing to remove';
try {
if ($fs->exists($cacheDir)) {
$fs->remove($cacheDir);
$ret = 'removed';
}
} catch (\Exception $e) {
$ret = $e->getMessage();
}
return new Response($ret);
}
}
| {
"content_hash": "92280ea94d9710863ab32bf45833b91a",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 156,
"avg_line_length": 32.646153846153844,
"alnum_prop": 0.6573986804901036,
"repo_name": "nyroDev/NyroCmsBundle",
"id": "583c337c09d2015fa68fe6f08c36803d0eb1cb36",
"size": "2122",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Controller/AdminController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "74557"
},
{
"name": "Hack",
"bytes": "20"
},
{
"name": "JavaScript",
"bytes": "162421"
},
{
"name": "PHP",
"bytes": "449258"
}
],
"symlink_target": ""
} |
workers Integer(ENV.fetch('WEB_CONCURRENCY') { 1 })
threads_count = Integer(ENV.fetch('RAILS_MAX_THREADS') { 4 })
threads 2, threads_count
preload_app!
rackup DefaultRackup
port Integer(ENV.fetch('PORT') { 3000 })
environment ENV.fetch('RACK_ENV') { 'development' }
# stdout_redirect '/dev/stdout', '/dev/stderr', true
on_worker_boot do
# Worker specific setup for Rails 4.1+
# See: https://devcenter.heroku.com/articles/deploying-rails-applications-with-the-puma-web-server#on-worker-boot
ActiveRecord::Base.establish_connection
end
| {
"content_hash": "bb40180fd6a0eec776c4958e29179420",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 115,
"avg_line_length": 32.705882352941174,
"alnum_prop": 0.7230215827338129,
"repo_name": "NNRUG/it52-rails",
"id": "3dbf2ecc46df043fb0711eb0b827546c566e7ca4",
"size": "587",
"binary": false,
"copies": "1",
"ref": "refs/heads/it52",
"path": "config/puma.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "662"
},
{
"name": "Dockerfile",
"bytes": "1988"
},
{
"name": "HTML",
"bytes": "3419"
},
{
"name": "JavaScript",
"bytes": "2887"
},
{
"name": "Makefile",
"bytes": "793"
},
{
"name": "Ruby",
"bytes": "250407"
},
{
"name": "Sass",
"bytes": "50446"
},
{
"name": "Shell",
"bytes": "673"
},
{
"name": "Slim",
"bytes": "54408"
},
{
"name": "TypeScript",
"bytes": "7779"
}
],
"symlink_target": ""
} |
'use strict'
const {Emitter} = require('atom')
const Identifiable = require('./mixins/identifiable')
const widthConfig = 'tablr.tableEditor.columnWidth'
class DisplayColumn {
static initClass () {
Identifiable.includeInto(this)
return this
}
get name () { return this.options.name }
set name (newName) {
const oldName = this.name
this.setOption('name', newName)
this.emitter.emit('did-change-name', {oldName, newName, column: this})
}
get width () { return this.options.width || atom.config.get(widthConfig) }
set width (newWidth) { this.setOption('width', newWidth) }
get align () { return this.options.align || 'left' }
set align (newAlign) { this.setOption('align', newAlign) }
get cellRender () { return this.options.cellRender }
set cellRender (newCellRender) { this.setOption('cellRender', newCellRender) }
get grammarScope () {
return this.options.grammarScope || 'text.plain.null-grammar'
}
set grammarScope (newGrammarScope) {
this.setOption('grammarScope', newGrammarScope)
}
constructor (options = {}) {
this.options = options
this.initID()
this.emitter = new Emitter()
}
onDidChangeName (callback) {
return this.emitter.on('did-change-name', callback)
}
onDidChangeOption (callback) {
return this.emitter.on('did-change-option', callback)
}
setOptions (options = {}) {
return (() => {
let result = []
for (let name in options) {
let value = options[name]
if (name !== 'name') {
result.push(this[name] = value)
}
}
return result
})()
}
setOption (name, newValue, batch = false) {
let oldValue = this[name]
this.options[name] = newValue
if (!batch) {
return this.emitter.emit('did-change-option', {
option: name,
column: this,
oldValue,
newValue
})
}
}
}
module.exports = DisplayColumn.initClass()
| {
"content_hash": "1d9bad9e843c22aced33970b1ef488cf",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 80,
"avg_line_length": 24.645569620253166,
"alnum_prop": 0.632768361581921,
"repo_name": "alorlov/elitecsv",
"id": "7ff461c3179b695daa081f0a12c8c5dce64b4e50",
"size": "1947",
"binary": false,
"copies": "3",
"ref": "refs/heads/prepare",
"path": "lib/tablr/display-column.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "26888"
},
{
"name": "CoffeeScript",
"bytes": "38984"
},
{
"name": "JavaScript",
"bytes": "376024"
}
],
"symlink_target": ""
} |
<?php
namespace RK\HelperModule\Helper\Base;
/**
* Helper base class for dynamic feature enablement methods.
*/
abstract class AbstractFeatureActivationHelper
{
/**
* Translation feature
*/
const TRANSLATIONS = 'translations';
/**
* This method checks whether a certain feature is enabled for a given entity type or not.
*
* @param string $feature Name of requested feature
* @param string $objectType Currently treated entity type
*
* @return boolean True if the feature is enabled, false otherwise
*/
public function isEnabled($feature, $objectType)
{
if ($feature == self::TRANSLATIONS) {
$method = 'hasTranslations';
if (method_exists($this, $method)) {
return $this->$method($objectType);
}
return in_array($objectType, ['info']);
}
return false;
}
}
| {
"content_hash": "3a8afed693c59a9cae18ef869f847aaa",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 94,
"avg_line_length": 25.35135135135135,
"alnum_prop": 0.5970149253731343,
"repo_name": "rallek/helper",
"id": "afbce92e512076e4297c58fe61940cbed612d9fd",
"size": "1241",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/modules/RK/HelperModule/Helper/Base/AbstractFeatureActivationHelper.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8598"
},
{
"name": "HTML",
"bytes": "225495"
},
{
"name": "JavaScript",
"bytes": "33947"
},
{
"name": "PHP",
"bytes": "1298983"
},
{
"name": "PowerShell",
"bytes": "2939"
},
{
"name": "Smarty",
"bytes": "21980"
}
],
"symlink_target": ""
} |
//-*-c++-*-
/*****************************************************************************/
/**
** @file predicates.h
** @brief Routines for Arbitrary Precision Floating-point Arithmetic
** and Fast Robust Geometric Predicates
*/
// These functions are added as members of the class Predicates; should
// ideally be a namespace, but some compilers, including Sun's, do not
// support namespaces yet.
// Presently, these functions are called from some member functions of
// tGrid to check for line segment intersection because inexact arithmetic
// can lead to the wrong answer.
// Note that the group of functions in class Predicates is a subset of
// the original "predicates" package, except that I've added two new
// functions, DifferenceOfProductsOfDifferences(...) and
// AdaptDiffOfProdsOfDiffs(...) to do segment intersection detection.
// --Stephen Lancaster, 1/99
// $Id: predicates.h,v 1.9 2003/07/18 17:49:55 childcvs Exp $
/*****************************************************************************/
/* */
/* Routines for Arbitrary Precision Floating-point Arithmetic */
/* and Fast Robust Geometric Predicates */
/* (predicates.c) */
/* */
/* May 18, 1996 */
/* */
/* Placed in the public domain by */
/* Jonathan Richard Shewchuk */
/* School of Computer Science */
/* Carnegie Mellon University */
/* 5000 Forbes Avenue */
/* Pittsburgh, Pennsylvania 15213-3891 */
/* jrs@cs.cmu.edu */
/* */
/* This file contains C implementation of algorithms for exact addition */
/* and multiplication of floating-point numbers, and predicates for */
/* robustly performing the orientation and incircle tests used in */
/* computational geometry. The algorithms and underlying theory are */
/* described in Jonathan Richard Shewchuk. "Adaptive Precision Floating- */
/* Point Arithmetic and Fast Robust Geometric Predicates." Technical */
/* Report CMU-CS-96-140, School of Computer Science, Carnegie Mellon */
/* University, Pittsburgh, Pennsylvania, May 1996. (Submitted to */
/* Discrete & Computational Geometry.) */
/* */
/* This file, the paper listed above, and other information are available */
/* from the Web page http://www.cs.cmu.edu/~quake/robust.html . */
/* */
/*****************************************************************************/
/*****************************************************************************/
/* */
/* Using this code: */
/* */
/* First, read the short or long version of the paper (from the Web page */
/* above). */
/* */
/* Be sure to call exactinit() once, before calling any of the arithmetic */
/* functions or geometric predicates. Also be sure to turn on the */
/* optimizer when compiling this file. */
/* */
/* */
/* Several geometric predicates are defined. Their parameters are all */
/* points. Each point is an array of two or three floating-point */
/* numbers. The geometric predicates, described in the papers, are */
/* */
/* orient2d(pa, pb, pc) */
/* orient2dfast(pa, pb, pc) */
/* orient3d(pa, pb, pc, pd) */
/* orient3dfast(pa, pb, pc, pd) */
/* incircle(pa, pb, pc, pd) */
/* incirclefast(pa, pb, pc, pd) */
/* insphere(pa, pb, pc, pd, pe) */
/* inspherefast(pa, pb, pc, pd, pe) */
/* */
/* Those with suffix "fast" are approximate, non-robust versions. Those */
/* without the suffix are adaptive precision, robust versions. There */
/* are also versions with the suffices "exact" and "slow", which are */
/* non-adaptive, exact arithmetic versions, which I use only for timings */
/* in my arithmetic papers. */
/* */
/* */
/* An expansion is represented by an array of floating-point numbers, */
/* sorted from smallest to largest magnitude (possibly with interspersed */
/* zeros). The length of each expansion is stored as a separate integer, */
/* and each arithmetic function returns an integer which is the length */
/* of the expansion it created. */
/* */
/* Several arithmetic functions are defined. Their parameters are */
/* */
/* e, f Input expansions */
/* elen, flen Lengths of input expansions (must be >= 1) */
/* h Output expansion */
/* b Input scalar */
/* */
/* The arithmetic functions are */
/* */
/* grow_expansion(elen, e, b, h) */
/* grow_expansion_zeroelim(elen, e, b, h) */
/* expansion_sum(elen, e, flen, f, h) */
/* expansion_sum_zeroelim1(elen, e, flen, f, h) */
/* expansion_sum_zeroelim2(elen, e, flen, f, h) */
/* fast_expansion_sum(elen, e, flen, f, h) */
/* fast_expansion_sum_zeroelim(elen, e, flen, f, h) */
/* linear_expansion_sum(elen, e, flen, f, h) */
/* linear_expansion_sum_zeroelim(elen, e, flen, f, h) */
/* scale_expansion(elen, e, b, h) */
/* scale_expansion_zeroelim(elen, e, b, h) */
/* compress(elen, e, h) */
/* */
/* All of these are described in the long version of the paper; some are */
/* described in the short version. All return an integer that is the */
/* length of h. Those with suffix _zeroelim perform zero elimination, */
/* and are recommended over their counterparts. The procedure */
/* fast_expansion_sum_zeroelim() (or linear_expansion_sum_zeroelim() on */
/* processors that do not use the round-to-even tiebreaking rule) is */
/* recommended over expansion_sum_zeroelim(). Each procedure has a */
/* little note next to it (in the code below) that tells you whether or */
/* not the output expansion may be the same array as one of the input */
/* expansions. */
/* */
/* */
/* If you look around below, you'll also find macros for a bunch of */
/* simple unrolled arithmetic operations, and procedures for printing */
/* expansions (commented out because they don't work with all C */
/* compilers) and for generating random floating-point numbers whose */
/* significand bits are all random. Most of the macros have undocumented */
/* requirements that certain of their parameters should not be the same */
/* variable; for safety, better to make sure all the parameters are */
/* distinct variables. Feel free to send email to jrs@cs.cmu.edu if you */
/* have questions. */
/* */
/*****************************************************************************/
#ifndef PREDICATES_H
#define PREDICATES_H
#include <stdio.h>
#include <math.h>
/* On some machines, the exact arithmetic routines might be defeated by the */
/* use of internal extended precision floating-point registers. Sometimes */
/* this problem can be fixed by defining certain values to be volatile, */
/* thus forcing them to be stored to memory and rounded off. This isn't */
/* a great solution, though, as it slows the arithmetic down. */
/* */
/* To try this out, write "#define INEXACT volatile" below. Normally, */
/* however, INEXACT should be defined to be nothing. ("#define INEXACT".) */
#define INEXACT /* Nothing */
/* #define INEXACT volatile */
#define REAL double /* float or double */
/* Which of the following two methods of finding the absolute values is */
/* fastest is compiler-dependent. A few compilers can inline and optimize */
/* the fabs() call; but most will incur the overhead of a function call, */
/* which is disastrously slow. A faster way on IEEE machines might be to */
/* mask the appropriate bit, but that's difficult to do in C. */
#define Absolute(a) ((a) >= 0.0 ? (a) : -(a))
/* #define Absolute(a) fabs(a) */
//#define Absolute(a) abs(a) // defined in <macros.h>
/* Many of the operations are broken up into two pieces, a main part that */
/* performs an approximate operation, and a "tail" that computes the */
/* roundoff error of that operation. */
/* */
/* The operations Fast_Two_Sum(), Fast_Two_Diff(), Two_Sum(), Two_Diff(), */
/* Split(), and Two_Product() are all implemented as described in the */
/* reference. Each of these macros requires certain variables to be */
/* defined in the calling routine. The variables `bvirt', `c', `abig', */
/* `_i', `_j', `_k', `_l', `_m', and `_n' are declared `INEXACT' because */
/* they store the result of an operation that may incur roundoff error. */
/* The input parameter `x' (or the highest numbered `x_' parameter) must */
/* also be declared `INEXACT'. */
#define Fast_Two_Sum_Tail(a, b, x, y) bvirt = x - a; y = b - bvirt
#define Fast_Two_Sum(a, b, x, y) x = static_cast<REAL>(a + b); Fast_Two_Sum_Tail(a, b, x, y)
#define Two_Sum_Tail(a, b, x, y) bvirt = static_cast<REAL>(x - a); avirt = x - bvirt; bround = b - bvirt; around = a - avirt; y = around + bround
#define Two_Sum(a, b, x, y) x = static_cast<REAL>(a + b); Two_Sum_Tail(a, b, x, y)
#define Two_Diff_Tail(a, b, x, y) bvirt = static_cast<REAL>(a - x); avirt = x + bvirt; bround = bvirt - b; around = a - avirt; y = around + bround
#define Two_Diff(a, b, x, y) x = static_cast<REAL>(a - b); Two_Diff_Tail(a, b, x, y)
#define Split(a, ahi, alo) c = static_cast<REAL>(splitter * a); abig = static_cast<REAL>(c - a); ahi = c - abig; alo = a - ahi
#define Two_Product_Tail(a, b, x, y) Split(a, ahi, alo); Split(b, bhi, blo); err1 = x - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); y = (alo * blo) - err3
#define Two_Product(a, b, x, y) x = static_cast<REAL>(a * b); Two_Product_Tail(a, b, x, y)
/* Two_Product_Presplit() is Two_Product() where one of the inputs has */
/* already been split. Avoids redundant splitting. */
#define Two_Product_Presplit(a, b, bhi, blo, x, y) x = static_cast<REAL>(a * b); Split(a, ahi, alo); err1 = x - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); y = (alo * blo) - err3
/* Square() can be done more quickly than Two_Product(). */
#define Square_Tail(a, x, y) Split(a, ahi, alo); err1 = x - (ahi * ahi); err3 = err1 - ((ahi + ahi) * alo); y = (alo * alo) - err3
#define Square(a, x, y) x = static_cast<REAL>(a * a); Square_Tail(a, x, y)
/* Macros for summing expansions of various fixed lengths. These are all */
/* unrolled versions of Expansion_Sum(). */
#define Two_One_Sum(a1, a0, b, x2, x1, x0) Two_Sum(a0, b , _i, x0); Two_Sum(a1, _i, x2, x1)
#define Two_One_Diff(a1, a0, b, x2, x1, x0) Two_Diff(a0, b , _i, x0); Two_Sum( a1, _i, x2, x1)
#define Two_Two_Sum(a1, a0, b1, b0, x3, x2, x1, x0) Two_One_Sum(a1, a0, b0, _j, _0, x0); Two_One_Sum(_j, _0, b1, x3, x2, x1)
#define Two_Two_Diff(a1, a0, b1, b0, x3, x2, x1, x0) Two_One_Diff(a1, a0, b0, _j, _0, x0); Two_One_Diff(_j, _0, b1, x3, x2, x1)
//namespace Predicates
// wanted to make this a namespace, but Sun's compiler was last updated
// in Nov., 1996 (4.2), and pre-dates the introduction of namespaces;
// probably waiting for the final version of the standard to come out
// with a new version compiler; what a pain.
class Predicates
{
public:
Predicates(); // just calls exactinit()
~Predicates() {} // doesn't do anything
private:
// basically the constructor:
void exactinit();
// basic "exact" arithmetic:
int grow_expansion(int elen, const REAL* e, REAL b, REAL* h);
int grow_expansion_zeroelim(int elen, const REAL* e, REAL b, REAL* h);
int expansion_sum(int elen, const REAL* e, int flen, const REAL* f, REAL* h);
int expansion_sum_zeroelim1(int elen, const REAL* e, int flen, const REAL* f,
REAL* h);
int expansion_sum_zeroelim2(int elen, const REAL* e, int flen, const REAL* f,
REAL* h);
int fast_expansion_sum(int elen, const REAL* e, int flen, const REAL* f, REAL* h);
int fast_expansion_sum_zeroelim(int elen, const REAL* e, int flen, const REAL* f,
REAL* h);
int linear_expansion_sum(int elen, const REAL* e, int flen, const REAL* f, REAL* h);
int linear_expansion_sum_zeroelim(int elen, const REAL* e, int flen, const REAL* f,
REAL* h);
int scale_expansion(int elen, const REAL* e, REAL b, REAL* h);
int scale_expansion_zeroelim(int elen, const REAL* e, REAL b, REAL* h);
int compress(int elen, const REAL* e, REAL* h);
REAL estimate( int elen, const REAL* e );
public:
// two functions added by SL, 10/98, to deal with line
// segment intersection; modeled after orient2d() and
// orient2dadapt(), which do cross-products and tell you
// whether the result is positive, negative, or zero:
double DifferenceOfProductsOfDifferences( double a, double b,
double c, double d,
double e, double f,
double g, double h );
private:
double AdaptDiffOfProdsOfDiffs( double a, double b,
double c, double d,
double e, double f,
double g, double h,
double sum );
public:
// orient...() and in...() functions; the ...adapt()
// functions should not be called directly--they are called
// by ...()'s (no suffix), e.g., orient2d(); the latter are
// generally the ones to use; for CHILD purposes, only need
// orient2d(), orient2dadapt(), and, potentially, incircle()
// and incircleadapt():
REAL orient2dfast(const REAL *pa, const REAL *pb, const REAL *pc);
REAL orient2dadapt(const REAL *pa, const REAL *pb, const REAL *pc, REAL detsum);
REAL orient2d(const REAL *pa, const REAL *pb, const REAL *pc);
REAL incirclefast(const REAL *pa, const REAL *pb, const REAL *pc, const REAL *pd);
REAL incircleadapt(const REAL *pa, const REAL *pb, const REAL *pc, const REAL *pd,
REAL permanent);
REAL incircle(const REAL *pa, const REAL *pb, const REAL *pc, const REAL *pd);
private:
REAL splitter; /* = 2^ceiling(p / 2) + 1. Used to split floats in half. */
REAL epsilon; /* = 2^(-p). Used to estimate roundoff errors. */
/* A set of coefficients used to calculate maximum roundoff errors. */
REAL resulterrbound;
REAL ccwerrboundA, ccwerrboundB, ccwerrboundC;
REAL o3derrboundA, o3derrboundB, o3derrboundC;
REAL iccerrboundA, iccerrboundB, iccerrboundC;
REAL isperrboundA, isperrboundB, isperrboundC;
};
#endif
| {
"content_hash": "b2d106db0ccbea393c225c910ab92105",
"timestamp": "",
"source": "github",
"line_count": 298,
"max_line_length": 202,
"avg_line_length": 62.53020134228188,
"alnum_prop": 0.4740796393688956,
"repo_name": "childmodel/child",
"id": "fdcc56f7f91c5ccfa243a3f07a359677a1b225ff",
"size": "18634",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Child/Releases/r081211/Code/Predicates/predicates.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Awk",
"bytes": "75"
},
{
"name": "C",
"bytes": "9197"
},
{
"name": "C++",
"bytes": "4669338"
},
{
"name": "CMake",
"bytes": "7771"
},
{
"name": "Fortran",
"bytes": "48455"
},
{
"name": "HTML",
"bytes": "240865"
},
{
"name": "HiveQL",
"bytes": "201986"
},
{
"name": "Limbo",
"bytes": "151049"
},
{
"name": "MATLAB",
"bytes": "209157"
},
{
"name": "Makefile",
"bytes": "88944"
},
{
"name": "Python",
"bytes": "22963"
},
{
"name": "Shell",
"bytes": "272"
},
{
"name": "TeX",
"bytes": "291172"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<!--
| Generated by Apache Maven Doxia at 2014-04-11
| Rendered using Apache Maven Fluido Skin 1.3.1
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="Date-Revision-yyyymmdd" content="20140411" />
<meta http-equiv="Content-Language" content="en" />
<title>Play! 2.x - Project Plugin Management</title>
<link rel="stylesheet" href="./css/apache-maven-fluido-1.3.1.min.css" />
<link rel="stylesheet" href="./css/site.css" />
<link rel="stylesheet" href="./css/print.css" media="print" />
<script type="text/javascript" src="./js/apache-maven-fluido-1.3.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="./css/site.css"/>
</head>
<body class="topBarDisabled">
<div class="container-fluid">
<div id="banner">
<div class="pull-left">
<div id="bannerLeft">
<h2>Play! 2.x</h2>
</div>
</div>
<div class="pull-right"> </div>
<div class="clear"><hr/></div>
</div>
<div id="breadcrumbs">
<ul class="breadcrumb">
<li id="publishDate">Last Published: 2014-04-11
<span class="divider">|</span>
</li>
<li id="projectVersion">Version: 1.0.0-alpha6
</li>
</ul>
</div>
<div class="row-fluid">
<div id="leftColumn" class="span3">
<div class="well sidebar-nav">
<ul class="nav nav-list">
<li class="nav-header">Modules</li>
<li>
<a href="play2-provider-api/index.html" title="Play! 2.x Provider API">
<i class="none"></i>
Play! 2.x Provider API</a>
</li>
<li>
<a href="play2-maven-plugin/index.html" title="Play! 2.x Maven Plugin">
<i class="none"></i>
Play! 2.x Maven Plugin</a>
</li>
<li>
<a href="play2-providers/index.html" title="Play! 2.x Providers">
<i class="none"></i>
Play! 2.x Providers</a>
</li>
<li class="nav-header">Project Documentation</li>
<li>
<a href="project-info.html" title="Project Information">
<i class="icon-chevron-down"></i>
Project Information</a>
<ul class="nav nav-list">
<li>
<a href="index.html" title="About">
<i class="none"></i>
About</a>
</li>
<li class="active">
<a href="#"><i class="none"></i>Plugin Management</a>
</li>
<li>
<a href="distribution-management.html" title="Distribution Management">
<i class="none"></i>
Distribution Management</a>
</li>
<li>
<a href="dependency-info.html" title="Dependency Information">
<i class="none"></i>
Dependency Information</a>
</li>
<li>
<a href="dependency-convergence.html" title="Dependency Convergence">
<i class="none"></i>
Dependency Convergence</a>
</li>
<li>
<a href="source-repository.html" title="Source Repository">
<i class="none"></i>
Source Repository</a>
</li>
<li>
<a href="mail-lists.html" title="Mailing Lists">
<i class="none"></i>
Mailing Lists</a>
</li>
<li>
<a href="issue-tracking.html" title="Issue Tracking">
<i class="none"></i>
Issue Tracking</a>
</li>
<li>
<a href="integration.html" title="Continuous Integration">
<i class="none"></i>
Continuous Integration</a>
</li>
<li>
<a href="plugins.html" title="Project Plugins">
<i class="none"></i>
Project Plugins</a>
</li>
<li>
<a href="license.html" title="Project License">
<i class="none"></i>
Project License</a>
</li>
<li>
<a href="modules.html" title="Project Modules">
<i class="none"></i>
Project Modules</a>
</li>
<li>
<a href="team-list.html" title="Project Team">
<i class="none"></i>
Project Team</a>
</li>
<li>
<a href="project-summary.html" title="Project Summary">
<i class="none"></i>
Project Summary</a>
</li>
<li>
<a href="dependencies.html" title="Dependencies">
<i class="none"></i>
Dependencies</a>
</li>
</ul>
</li>
</ul>
<hr />
<div id="poweredBy">
<div class="clear"></div>
<div class="clear"></div>
<div class="clear"></div>
<div class="clear"></div>
<a href="http://maven.apache.org/" title="Built by Maven" class="poweredBy">
<img class="builtBy" alt="Built by Maven" src="./images/logos/maven-feather.png" />
</a>
</div>
</div>
</div>
<div id="bodyColumn" class="span9" >
<div class="section">
<h2>Project Plugin Management<a name="Project_Plugin_Management"></a></h2><a name="Project_Plugin_Management"></a>
<table border="0" class="table table-striped">
<tr class="a">
<th>GroupId</th>
<th>ArtifactId</th>
<th>Version</th></tr>
<tr class="b">
<td>com.google.code.maven-scm-provider-svnjava</td>
<td><a class="externalLink" href="http://code.google.com/p/maven-scm-provider-svnjava/">maven-scm-provider-svnjava</a></td>
<td>1.15</td></tr>
<tr class="a">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/plugins/maven-antrun-plugin/">maven-antrun-plugin</a></td>
<td>1.3</td></tr>
<tr class="b">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/plugins/maven-assembly-plugin/">maven-assembly-plugin</a></td>
<td>2.4</td></tr>
<tr class="a">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/plugins/maven-checkstyle-plugin/">maven-checkstyle-plugin</a></td>
<td>2.12</td></tr>
<tr class="b">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/plugins/maven-clean-plugin/">maven-clean-plugin</a></td>
<td>2.5</td></tr>
<tr class="a">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/plugins/maven-compiler-plugin/">maven-compiler-plugin</a></td>
<td>3.1</td></tr>
<tr class="b">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/plugins/maven-dependency-plugin/">maven-dependency-plugin</a></td>
<td>2.8</td></tr>
<tr class="a">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/plugins/maven-deploy-plugin/">maven-deploy-plugin</a></td>
<td>2.8.1</td></tr>
<tr class="b">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/enforcer/maven-enforcer-plugin">maven-enforcer-plugin</a></td>
<td>1.3.1</td></tr>
<tr class="a">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/plugins/maven-help-plugin/">maven-help-plugin</a></td>
<td>2.2</td></tr>
<tr class="b">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/plugins/maven-install-plugin/">maven-install-plugin</a></td>
<td>2.5.1</td></tr>
<tr class="a">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/plugins/maven-invoker-plugin/">maven-invoker-plugin</a></td>
<td>1.8</td></tr>
<tr class="b">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/plugins/maven-jar-plugin/">maven-jar-plugin</a></td>
<td>2.4</td></tr>
<tr class="a">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/plugins/maven-jarsigner-plugin/">maven-jarsigner-plugin</a></td>
<td>1.3.1</td></tr>
<tr class="b">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/plugins/maven-javadoc-plugin/">maven-javadoc-plugin</a></td>
<td>2.9.1</td></tr>
<tr class="a">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/jxr/maven-jxr-plugin/">maven-jxr-plugin</a></td>
<td>2.4</td></tr>
<tr class="b">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/plugins/maven-pmd-plugin/">maven-pmd-plugin</a></td>
<td>3.1</td></tr>
<tr class="a">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/plugins/maven-project-info-reports-plugin/">maven-project-info-reports-plugin</a></td>
<td>2.7</td></tr>
<tr class="b">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/maven-release/maven-release-plugin/">maven-release-plugin</a></td>
<td>2.4.2</td></tr>
<tr class="a">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/plugins/maven-resources-plugin/">maven-resources-plugin</a></td>
<td>2.6</td></tr>
<tr class="b">
<td>org.apache.maven.plugins</td>
<td>scp://people.apache.org/www/maven.apache.org/scm/maven-scm-plugin</td>
<td>1.6</td></tr>
<tr class="a">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/plugins/maven-site-plugin/">maven-site-plugin</a></td>
<td>3.3</td></tr>
<tr class="b">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/plugins/maven-source-plugin/">maven-source-plugin</a></td>
<td>2.2.1</td></tr>
<tr class="a">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/surefire/maven-surefire-plugin">maven-surefire-plugin</a></td>
<td>2.17</td></tr>
<tr class="b">
<td>org.apache.maven.plugins</td>
<td><a class="externalLink" href="http://maven.apache.org/surefire/maven-surefire-report-plugin">maven-surefire-report-plugin</a></td>
<td>2.17</td></tr>
<tr class="a">
<td>org.codehaus.mojo</td>
<td><a class="externalLink" href="http://mojo.codehaus.org/animal-sniffer-parent/animal-sniffer-maven-plugin">animal-sniffer-maven-plugin</a></td>
<td>1.9</td></tr>
<tr class="b">
<td>org.codehaus.mojo</td>
<td><a class="externalLink" href="http://mojo.codehaus.org/clirr-maven-plugin">clirr-maven-plugin</a></td>
<td>2.6</td></tr>
<tr class="a">
<td>org.codehaus.mojo</td>
<td><a class="externalLink" href="http://mojo.codehaus.org/cobertura-maven-plugin/">cobertura-maven-plugin</a></td>
<td>2.6</td></tr>
<tr class="b">
<td>org.codehaus.mojo</td>
<td><a class="externalLink" href="http://mojo.codehaus.org/findbugs-maven-plugin">findbugs-maven-plugin</a></td>
<td>2.5.3</td></tr>
<tr class="a">
<td>org.codehaus.mojo</td>
<td><a class="externalLink" href="http://mojo.codehaus.org/javancss-maven-plugin">javancss-maven-plugin</a></td>
<td>2.0</td></tr>
<tr class="b">
<td>org.codehaus.mojo</td>
<td><a class="externalLink" href="http://mojo.codehaus.org/taglist-maven-plugin">taglist-maven-plugin</a></td>
<td>2.4</td></tr>
<tr class="a">
<td>org.codehaus.mojo</td>
<td><a class="externalLink" href="http://mojo.codehaus.org/versions-maven-plugin">versions-maven-plugin</a></td>
<td>2.1</td></tr>
<tr class="b">
<td>org.eclipse.m2e</td>
<td>lifecycle-mapping</td>
<td>1.0.0</td></tr></table></div>
</div>
</div>
</div>
<hr/>
<footer>
<div class="container-fluid">
<div class="row-fluid">
<p >Copyright © 2013–2014.
All rights reserved.
</p>
</div>
</div>
</footer>
</body>
</html>
| {
"content_hash": "40969cb4fa3ca07797775b79c465329b",
"timestamp": "",
"source": "github",
"line_count": 379,
"max_line_length": 342,
"avg_line_length": 35.992084432717675,
"alnum_prop": 0.5184370647313247,
"repo_name": "play2-maven-plugin/play2-maven-plugin.github.io",
"id": "055ae0d864f4c032e3b04235191e363e73ff7ae9",
"size": "13641",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "play2-maven-plugin/1.0.0-alpha6/plugin-management.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2793124"
},
{
"name": "HTML",
"bytes": "178221432"
},
{
"name": "JavaScript",
"bytes": "120742"
}
],
"symlink_target": ""
} |
{-# LANGUAGE TemplateHaskell #-}
module Lol.Build where
import Prelude
import Data.Lens.Template
import Lol.Champs
import Lol.Items
import Lol.Stats
type BuildItems = (Item, Item, Item, Item, Item, Item)
data Build = Build { _bChamp :: Champ
, _bLevel :: Level
, _bItems :: BuildItems
, _bChampStats :: ChampStats }
deriving (Show)
$( makeLens ''Build )
-- | Pack build items into a tuple for Build usage.
packBuildItems :: [Item] -> BuildItems
packBuildItems ([a,b,c,d,e,f]) = (a,b,c,d,e,f)
packBuildItems _ =
error "Implementation error: packBuildItems called with /= 6 items"
makeBuild :: Champ -> Level -> [Item] -> Build
makeBuild c l is =
let stats = makeChampStats c l is
in Build c l (packBuildItems is) stats
| {
"content_hash": "24ab46ca64da1431dfa01722eff60ce3",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 71,
"avg_line_length": 25,
"alnum_prop": 0.64,
"repo_name": "MostAwesomeDude/lollerskates",
"id": "d91a1bae99e6eef991269f6c040c21e4ae23a2c2",
"size": "800",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Lol/Build.hs",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Haskell",
"bytes": "88094"
},
{
"name": "Perl",
"bytes": "55421"
},
{
"name": "Prolog",
"bytes": "1039"
},
{
"name": "Python",
"bytes": "3690"
}
],
"symlink_target": ""
} |
<!--[metadata]>
+++
title = "volume create"
description = "The volume create command description and usage"
keywords = ["volume, create"]
[menu.main]
parent = "smn_cli"
+++
<![end-metadata]-->
# volume create
Usage: docker volume create [OPTIONS]
Create a volume
-d, --driver=local Specify volume driver name
--help Print usage
--name= Specify volume name
-o, --opt=map[] Set driver specific options
Creates a new volume that containers can consume and store data in. If a name is not specified, Docker generates a random name. You create a volume and then configure the container to use it, for example:
$ docker volume create --name hello
hello
$ docker run -d -v hello:/world busybox ls /world
The mount is created inside the container's `/world` directory. Docker does not support relative paths for mount points inside the container.
Multiple containers can use the same volume in the same time period. This is useful if two containers need access to shared data. For example, if one container writes and the other reads the data.
Volume names must be unique among drivers. This means you cannot use the same volume name with two different drivers. If you attempt this `docker` returns an error:
```
A volume named "hello" already exists with the "some-other" driver. Choose a different volume name.
```
If you specify a volume name already in use on the current driver, Docker assumes you want to re-use the existing volume and does not return an error.
## Driver specific options
Some volume drivers may take options to customize the volume creation. Use the `-o` or `--opt` flags to pass driver options:
$ docker volume create --driver fake --opt tardis=blue --opt timey=wimey
These options are passed directly to the volume driver. Options for
different volume drivers may do different things (or nothing at all).
*Note*: The built-in `local` volume driver does not currently accept any options.
## Related information
* [volume inspect](volume_inspect.md)
* [volume ls](volume_ls.md)
* [volume rm](volume_rm.md)
* [Understand Data Volumes](../../userguide/containers/dockervolumes.md) | {
"content_hash": "f5c5310ea16286de6fb84e568e37ef89",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 204,
"avg_line_length": 38.70175438596491,
"alnum_prop": 0.7248413417951043,
"repo_name": "vijaykilari/docker",
"id": "79e794698f8b08cb8ebfa100b579325135656d7a",
"size": "2206",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "docs/reference/commandline/volume_create.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "3652"
},
{
"name": "Go",
"bytes": "4424717"
},
{
"name": "Makefile",
"bytes": "5742"
},
{
"name": "PowerShell",
"bytes": "5978"
},
{
"name": "Shell",
"bytes": "324740"
},
{
"name": "VimL",
"bytes": "1332"
}
],
"symlink_target": ""
} |
package com.demo.boot.vo.in;
import org.hibernate.validator.constraints.NotBlank;
public class TestVo {
@NotBlank(message="name不能为空")
private String name;
@NotBlank(message="age不能为空")
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
| {
"content_hash": "5008c9ea0e63099fc497a3556b2fb4ba",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 52,
"avg_line_length": 14.586206896551724,
"alnum_prop": 0.6926713947990544,
"repo_name": "organ-dayefenbu/boot-demo",
"id": "5c4dfc4755b969b507409063604da764dbd06cac",
"size": "439",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/demo/boot/vo/in/TestVo.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "22727"
}
],
"symlink_target": ""
} |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/deploy/v1/cloud_deploy.proto
package com.google.cloud.deploy.v1;
public interface ListTargetsRequestOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.deploy.v1.ListTargetsRequest)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Required. The parent, which owns this collection of targets. Format must be
* projects/{project_id}/locations/{location_name}.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
java.lang.String getParent();
/**
*
*
* <pre>
* Required. The parent, which owns this collection of targets. Format must be
* projects/{project_id}/locations/{location_name}.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
com.google.protobuf.ByteString getParentBytes();
/**
*
*
* <pre>
* Optional. The maximum number of `Target` objects to return. The service may return
* fewer than this value. If unspecified, at most 50 `Target` objects will be
* returned. The maximum value is 1000; values above 1000 will be set to 1000.
* </pre>
*
* <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageSize.
*/
int getPageSize();
/**
*
*
* <pre>
* Optional. A page token, received from a previous `ListTargets` call.
* Provide this to retrieve the subsequent page.
* When paginating, all other provided parameters match
* the call that provided the page token.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageToken.
*/
java.lang.String getPageToken();
/**
*
*
* <pre>
* Optional. A page token, received from a previous `ListTargets` call.
* Provide this to retrieve the subsequent page.
* When paginating, all other provided parameters match
* the call that provided the page token.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for pageToken.
*/
com.google.protobuf.ByteString getPageTokenBytes();
/**
*
*
* <pre>
* Optional. Filter targets to be returned. See https://google.aip.dev/160 for more
* details.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The filter.
*/
java.lang.String getFilter();
/**
*
*
* <pre>
* Optional. Filter targets to be returned. See https://google.aip.dev/160 for more
* details.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for filter.
*/
com.google.protobuf.ByteString getFilterBytes();
/**
*
*
* <pre>
* Optional. Field to sort by. See https://google.aip.dev/132#ordering for more details.
* </pre>
*
* <code>string order_by = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The orderBy.
*/
java.lang.String getOrderBy();
/**
*
*
* <pre>
* Optional. Field to sort by. See https://google.aip.dev/132#ordering for more details.
* </pre>
*
* <code>string order_by = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for orderBy.
*/
com.google.protobuf.ByteString getOrderByBytes();
}
| {
"content_hash": "6b49d750097da438aac3171dc80aa96b",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 107,
"avg_line_length": 26.22142857142857,
"alnum_prop": 0.6232634159629529,
"repo_name": "googleapis/google-cloud-java",
"id": "b18437a420200774b9f69ce767717127328c1d51",
"size": "4265",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "java-deploy/proto-google-cloud-deploy-v1/src/main/java/com/google/cloud/deploy/v1/ListTargetsRequestOrBuilder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2614"
},
{
"name": "HCL",
"bytes": "28592"
},
{
"name": "Java",
"bytes": "826434232"
},
{
"name": "Jinja",
"bytes": "2292"
},
{
"name": "Python",
"bytes": "200408"
},
{
"name": "Shell",
"bytes": "97954"
}
],
"symlink_target": ""
} |
#include "OgreGLFrameBufferObject.h"
#include "OgreGLPixelFormat.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreRoot.h"
#include "OgreGLHardwarePixelBuffer.h"
#include "OgreGLFBORenderTexture.h"
#include "OgreGLDepthBuffer.h"
namespace Ogre {
//-----------------------------------------------------------------------------
GLFrameBufferObject::GLFrameBufferObject(GLFBOManager *manager, uint fsaa):
mManager(manager), mNumSamples(fsaa)
{
// Generate framebuffer object
glGenFramebuffersEXT(1, &mFB);
// check multisampling
if (GLEW_EXT_framebuffer_blit && GLEW_EXT_framebuffer_multisample)
{
// check samples supported
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFB);
GLint maxSamples;
glGetIntegerv(GL_MAX_SAMPLES_EXT, &maxSamples);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
mNumSamples = std::min(mNumSamples, (GLsizei)maxSamples);
}
else
{
mNumSamples = 0;
}
// will we need a second FBO to do multisampling?
if (mNumSamples)
{
glGenFramebuffersEXT(1, &mMultisampleFB);
}
else
{
mMultisampleFB = 0;
}
// Initialise state
mDepth.buffer=0;
mStencil.buffer=0;
for(size_t x=0; x<OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x)
{
mColour[x].buffer=0;
}
}
GLFrameBufferObject::~GLFrameBufferObject()
{
mManager->releaseRenderBuffer(mDepth);
mManager->releaseRenderBuffer(mStencil);
mManager->releaseRenderBuffer(mMultisampleColourBuffer);
// Delete framebuffer object
glDeleteFramebuffersEXT(1, &mFB);
if (mMultisampleFB)
glDeleteFramebuffersEXT(1, &mMultisampleFB);
}
void GLFrameBufferObject::bindSurface(size_t attachment, const GLSurfaceDesc &target)
{
assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS);
mColour[attachment] = target;
// Re-initialise
if(mColour[0].buffer)
initialise();
}
void GLFrameBufferObject::unbindSurface(size_t attachment)
{
assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS);
mColour[attachment].buffer = 0;
// Re-initialise if buffer 0 still bound
if(mColour[0].buffer)
{
initialise();
}
}
void GLFrameBufferObject::initialise()
{
// Release depth and stencil, if they were bound
mManager->releaseRenderBuffer(mDepth);
mManager->releaseRenderBuffer(mStencil);
mManager->releaseRenderBuffer(mMultisampleColourBuffer);
// First buffer must be bound
if(!mColour[0].buffer)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Attachment 0 must have surface attached",
"GLFrameBufferObject::initialise");
}
// If we're doing multisampling, then we need another FBO which contains a
// renderbuffer which is set up to multisample, and we'll blit it to the final
// FBO afterwards to perform the multisample resolve. In that case, the
// mMultisampleFB is bound during rendering and is the one with a depth/stencil
// Store basic stats
size_t width = mColour[0].buffer->getWidth();
size_t height = mColour[0].buffer->getHeight();
GLuint format = mColour[0].buffer->getGLFormat();
ushort maxSupportedMRTs = Root::getSingleton().getRenderSystem()->getCapabilities()->getNumMultiRenderTargets();
// Bind simple buffer to add colour attachments
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFB);
// Bind all attachment points to frame buffer
for(size_t x=0; x<maxSupportedMRTs; ++x)
{
if(mColour[x].buffer)
{
if(mColour[x].buffer->getWidth() != width || mColour[x].buffer->getHeight() != height)
{
StringStream ss;
ss << "Attachment " << x << " has incompatible size ";
ss << mColour[x].buffer->getWidth() << "x" << mColour[x].buffer->getHeight();
ss << ". It must be of the same as the size of surface 0, ";
ss << width << "x" << height;
ss << ".";
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLFrameBufferObject::initialise");
}
if(mColour[x].buffer->getGLFormat() != format)
{
StringStream ss;
ss << "Attachment " << x << " has incompatible format.";
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLFrameBufferObject::initialise");
}
mColour[x].buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0_EXT+x, mColour[x].zoffset);
}
else
{
// Detach
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT+x,
GL_RENDERBUFFER_EXT, 0);
}
}
// Now deal with depth / stencil
if (mMultisampleFB)
{
// Bind multisample buffer
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mMultisampleFB);
// Create AA render buffer (colour)
// note, this can be shared too because we blit it to the final FBO
// right after the render is finished
mMultisampleColourBuffer = mManager->requestRenderBuffer(format, width, height, mNumSamples);
// Attach it, because we won't be attaching below and non-multisample has
// actually been attached to other FBO
mMultisampleColourBuffer.buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0_EXT,
mMultisampleColourBuffer.zoffset);
// depth & stencil will be dealt with below
}
// Depth buffer is not handled here anymore.
// See GLFrameBufferObject::attachDepthBuffer() & RenderSystem::setDepthBufferFor()
// Do glDrawBuffer calls
GLenum bufs[OGRE_MAX_MULTIPLE_RENDER_TARGETS];
GLsizei n=0;
for(size_t x=0; x<OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x)
{
// Fill attached colour buffers
if(mColour[x].buffer)
{
bufs[x] = GL_COLOR_ATTACHMENT0_EXT + x;
// Keep highest used buffer + 1
n = x+1;
}
else
{
bufs[x] = GL_NONE;
}
}
if(glDrawBuffers)
{
// Drawbuffer extension supported, use it
glDrawBuffers(n, bufs);
}
else
{
// In this case, the capabilities will not show more than 1 simultaneaous render target.
glDrawBuffer(bufs[0]);
}
if (mMultisampleFB)
{
// we need a read buffer because we'll be blitting to mFB
glReadBuffer(bufs[0]);
}
else
{
// No read buffer, by default, if we want to read anyway we must not forget to set this.
glReadBuffer(GL_NONE);
}
// Check status
GLuint status;
status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
// Bind main buffer
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
switch(status)
{
case GL_FRAMEBUFFER_COMPLETE_EXT:
// All is good
break;
case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"All framebuffer formats with this texture internal format unsupported",
"GLFrameBufferObject::initialise");
default:
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Framebuffer incomplete or other FBO status error",
"GLFrameBufferObject::initialise");
}
}
void GLFrameBufferObject::bind()
{
// Bind it to FBO
const GLuint fb = mMultisampleFB ? mMultisampleFB : mFB;
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb);
}
void GLFrameBufferObject::swapBuffers()
{
if (mMultisampleFB)
{
GLint oldfb = 0;
glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT, &oldfb);
// Blit from multisample buffer to final buffer, triggers resolve
size_t width = mColour[0].buffer->getWidth();
size_t height = mColour[0].buffer->getHeight();
glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, mMultisampleFB);
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, mFB);
glBlitFramebufferEXT(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
// Unbind
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, oldfb);
}
}
void GLFrameBufferObject::attachDepthBuffer( DepthBuffer *depthBuffer )
{
GLDepthBuffer *glDepthBuffer = static_cast<GLDepthBuffer*>(depthBuffer);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mMultisampleFB ? mMultisampleFB : mFB );
if( glDepthBuffer )
{
GLRenderBuffer *depthBuf = glDepthBuffer->getDepthBuffer();
GLRenderBuffer *stencilBuf = glDepthBuffer->getStencilBuffer();
// Attach depth buffer, if it has one.
if( depthBuf )
depthBuf->bindToFramebuffer( GL_DEPTH_ATTACHMENT_EXT, 0 );
// Attach stencil buffer, if it has one.
if( stencilBuf )
stencilBuf->bindToFramebuffer( GL_STENCIL_ATTACHMENT_EXT, 0 );
}
else
{
glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
GL_RENDERBUFFER_EXT, 0);
glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT,
GL_RENDERBUFFER_EXT, 0);
}
}
//-----------------------------------------------------------------------------
void GLFrameBufferObject::detachDepthBuffer()
{
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mMultisampleFB ? mMultisampleFB : mFB );
glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0 );
glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT,
GL_RENDERBUFFER_EXT, 0 );
}
size_t GLFrameBufferObject::getWidth()
{
assert(mColour[0].buffer);
return mColour[0].buffer->getWidth();
}
size_t GLFrameBufferObject::getHeight()
{
assert(mColour[0].buffer);
return mColour[0].buffer->getHeight();
}
PixelFormat GLFrameBufferObject::getFormat()
{
assert(mColour[0].buffer);
return mColour[0].buffer->getFormat();
}
GLsizei GLFrameBufferObject::getFSAA()
{
return mNumSamples;
}
//-----------------------------------------------------------------------------
}
| {
"content_hash": "595fc1a4352ed52bd124927388aae0c0",
"timestamp": "",
"source": "github",
"line_count": 305,
"max_line_length": 120,
"avg_line_length": 33.114754098360656,
"alnum_prop": 0.6292079207920792,
"repo_name": "jakzale/ogre",
"id": "662f1bba3db5e53d191b6b8f002f3a23874fec3e",
"size": "11463",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "RenderSystems/GL/src/OgreGLFrameBufferObject.cpp",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "4588107"
},
{
"name": "C++",
"bytes": "20466233"
},
{
"name": "Java",
"bytes": "5855"
},
{
"name": "Objective-C",
"bytes": "562324"
},
{
"name": "Python",
"bytes": "479296"
},
{
"name": "Shell",
"bytes": "19333"
},
{
"name": "Visual Basic",
"bytes": "1095"
}
],
"symlink_target": ""
} |
Continuous Deployment is the process of checking into master, running all the
tests and if everything goes green it is automatically pushed to production.
A good case for Continuous Deployment is when using Octopus deploy, as you
cannot publish the same version of a package into the same feed.
For this mode we follow the logic in [this blog post by Xavier Decoster][blog]
on the issues of incrementing automatically.
As such we force a pre-release tag on all branches, this is fine for
applications but can cause problems for libraries. As such this mode may or may
not work for you, which leads us into a new mode in v4 of GitVersion:
[Mainline Development](mainline-development.md).
### Usage
By default GitVersion is set up to do Continuous Deployment versioning on the
`develop` branch, but for all other branches,
[Continuous Delivery](continuous-delivery.md) is the default mode. From version
3 of GitVersion this behavior is [configurable](../configuration.md).
The default behavior for v3 and how v1 & 2 worked was that the version only
incremented after a tag, which signified a release. In v3 you can simply switch
the default mode in the [configuration](../configuration.md) from
`ContinuousDelivery` to `ContinuousDeployment` and the version will then
increment each commit, giving you the features of GitVersion with continuous
deployment:
```yaml
mode: ContinuousDeployment
```
[blog]: http://www.xavierdecoster.com/semantic-versioning-auto-incremented-nuget-package-versions | {
"content_hash": "a141daefa07392aaf3763834c88346da",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 97,
"avg_line_length": 46.8125,
"alnum_prop": 0.7977303070761015,
"repo_name": "dpurge/GitVersion",
"id": "ff8bd8800f9207508352f80adfbb946e2aba087b",
"size": "1522",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "docs/reference/continuous-deployment.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "735625"
},
{
"name": "F#",
"bytes": "508"
},
{
"name": "PowerShell",
"bytes": "10810"
},
{
"name": "Roff",
"bytes": "812"
},
{
"name": "Ruby",
"bytes": "7612"
},
{
"name": "Shell",
"bytes": "2310"
},
{
"name": "TypeScript",
"bytes": "2383"
},
{
"name": "Visual Basic",
"bytes": "502"
}
],
"symlink_target": ""
} |
package com.google.gerrit.server.account;
import com.google.gerrit.extensions.registration.DynamicMap;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.ChildCollection;
import com.google.gerrit.extensions.restapi.IdString;
import com.google.gerrit.extensions.restapi.ResourceNotFoundException;
import com.google.gerrit.extensions.restapi.RestView;
import com.google.gerrit.reviewdb.client.AccountSshKey;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.permissions.GlobalPermission;
import com.google.gerrit.server.permissions.PermissionBackend;
import com.google.gerrit.server.permissions.PermissionBackendException;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
@Singleton
public class SshKeys implements ChildCollection<AccountResource, AccountResource.SshKey> {
private final DynamicMap<RestView<AccountResource.SshKey>> views;
private final GetSshKeys list;
private final Provider<CurrentUser> self;
private final PermissionBackend permissionBackend;
private final VersionedAuthorizedKeys.Accessor authorizedKeys;
@Inject
SshKeys(
DynamicMap<RestView<AccountResource.SshKey>> views,
GetSshKeys list,
Provider<CurrentUser> self,
PermissionBackend permissionBackend,
VersionedAuthorizedKeys.Accessor authorizedKeys) {
this.views = views;
this.list = list;
this.self = self;
this.permissionBackend = permissionBackend;
this.authorizedKeys = authorizedKeys;
}
@Override
public RestView<AccountResource> list() {
return list;
}
@Override
public AccountResource.SshKey parse(AccountResource rsrc, IdString id)
throws ResourceNotFoundException, OrmException, IOException, ConfigInvalidException,
PermissionBackendException {
if (self.get() != rsrc.getUser()) {
try {
permissionBackend.user(self).check(GlobalPermission.MODIFY_ACCOUNT);
} catch (AuthException e) {
// If lacking MODIFY_ACCOUNT claim the resource does not exist.
throw new ResourceNotFoundException();
}
}
return parse(rsrc.getUser(), id);
}
public AccountResource.SshKey parse(IdentifiedUser user, IdString id)
throws ResourceNotFoundException, IOException, ConfigInvalidException {
try {
int seq = Integer.parseInt(id.get(), 10);
AccountSshKey sshKey = authorizedKeys.getKey(user.getAccountId(), seq);
if (sshKey == null) {
throw new ResourceNotFoundException(id);
}
return new AccountResource.SshKey(user, sshKey);
} catch (NumberFormatException e) {
throw new ResourceNotFoundException(id);
}
}
@Override
public DynamicMap<RestView<AccountResource.SshKey>> views() {
return views;
}
}
| {
"content_hash": "57a8d191d8cea6b649cedf5210392e67",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 90,
"avg_line_length": 36.63414634146341,
"alnum_prop": 0.7633155792276964,
"repo_name": "gerrit-review/gerrit",
"id": "70c02a15261ea02849072d36a97eba5ce7f0677e",
"size": "3613",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java/com/google/gerrit/server/account/SshKeys.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "47547"
},
{
"name": "GAP",
"bytes": "4124"
},
{
"name": "Go",
"bytes": "8041"
},
{
"name": "HTML",
"bytes": "1695553"
},
{
"name": "Java",
"bytes": "14114142"
},
{
"name": "JavaScript",
"bytes": "821208"
},
{
"name": "PLpgSQL",
"bytes": "2616"
},
{
"name": "Perl",
"bytes": "9943"
},
{
"name": "Prolog",
"bytes": "18454"
},
{
"name": "Python",
"bytes": "187604"
},
{
"name": "Roff",
"bytes": "32749"
},
{
"name": "Shell",
"bytes": "58865"
}
],
"symlink_target": ""
} |
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[string]
$SharePointCmdletModule = (Join-Path -Path $PSScriptRoot `
-ChildPath "..\Stubs\SharePoint\15.0.4805.1000\Microsoft.SharePoint.PowerShell.psm1" `
-Resolve)
)
Import-Module -Name (Join-Path -Path $PSScriptRoot `
-ChildPath "..\SharePointDsc.TestHarness.psm1" `
-Resolve)
$Global:SPDscHelper = New-SPDscUnitTestHelper -SharePointStubModule $SharePointCmdletModule `
-DscResource "SPRemoteFarmTrust"
Describe -Name $Global:SPDscHelper.DescribeHeader -Fixture {
InModuleScope -ModuleName $Global:SPDscHelper.ModuleName -ScriptBlock {
Invoke-Command -ScriptBlock $Global:SPDscHelper.InitializeScript -NoNewScope
# Mocks for all contexts
Mock -CommandName Get-SPSite -MockWith {
return @{
Url = $Identity
}
}
Mock -CommandName Get-SPServiceContext {
return @{
Site = $Site
}
}
Mock -CommandName Get-SPAuthenticationRealm {
return "14757a87-4d74-4323-83b9-fb1e77e8f22f"
}
Mock -CommandName Get-SPAppPrincipal {
return @{
Site = $Site
}
}
Mock -CommandName Set-SPAuthenticationRealm {}
Mock -CommandName Set-SPAppPrincipalPermission {}
Mock -CommandName Remove-SPAppPrincipalPermission {}
Mock -CommandName Remove-SPTrustedRootAuthority {}
Mock -CommandName Remove-SPTrustedSecurityTokenIssuer {}
Mock -CommandName New-SPTrustedSecurityTokenIssuer {
return @{
NameId = "f5a433c7-69f9-48ef-916b-dde8b5fa6fdb@14757a87-4d74-4323-83b9-fb1e77e8f22f"
}
}
Mock -CommandName New-SPTrustedRootAuthority {
return @{
NameId = "f5a433c7-69f9-48ef-916b-dde8b5fa6fdb@14757a87-4d74-4323-83b9-fb1e77e8f22f"
}
}
# Test contexts
Context -Name "A remote farm trust doesn't exist, but should" -Fixture {
$testParams = @{
Name = "SendingFarm"
LocalWebAppUrl = "https://sharepoint.adventureworks.com"
RemoteWebAppUrl = "https://sharepoint.contoso.com"
Ensure = "Present"
}
Mock -CommandName Get-SPTrustedSecurityTokenIssuer -MockWith {
return $null
}
Mock -CommandName Get-SPTrustedRootAuthority -MockWith {
return $null
}
It "Should return absent from the get method" {
(Get-TargetResource @testParams).Ensure | Should Be "Absent"
}
It "Should return false from the test method" {
Test-TargetResource @testParams | Should Be $false
}
It "Should add the trust in the set method" {
Set-TargetResource @testParams
Assert-MockCalled -CommandName New-SPTrustedSecurityTokenIssuer
Assert-MockCalled -CommandName New-SPTrustedRootAuthority
}
}
Context -Name "A remote farm trust exists and should" -Fixture {
$testParams = @{
Name = "SendingFarm"
LocalWebAppUrl = "https://sharepoint.adventureworks.com"
RemoteWebAppUrl = "https://sharepoint.contoso.com"
Ensure = "Present"
}
Mock -CommandName Get-SPTrustedSecurityTokenIssuer -MockWith {
return @(
@{
NameId = "f5a433c7-69f9-48ef-916b-dde8b5fa6fdb@14757a87-4d74-4323-83b9-fb1e77e8f22f"
}
)
}
Mock -CommandName Get-SPTrustedRootAuthority -MockWith {
return @{
NameId = "f5a433c7-69f9-48ef-916b-dde8b5fa6fdb@14757a87-4d74-4323-83b9-fb1e77e8f22f"
}
}
It "Should return present from the get method" {
(Get-TargetResource @testParams).Ensure | Should Be "Present"
}
It "Should return true from the test method" {
Test-TargetResource @testParams | Should Be $true
}
}
Context -Name "A remote farm trust exists and shouldn't" -Fixture {
$testParams = @{
Name = "SendingFarm"
LocalWebAppUrl = "https://sharepoint.adventureworks.com"
RemoteWebAppUrl = "https://sharepoint.contoso.com"
Ensure = "Absent"
}
Mock -CommandName Get-SPTrustedSecurityTokenIssuer -MockWith {
return @(
@{
NameId = "f5a433c7-69f9-48ef-916b-dde8b5fa6fdb@14757a87-4d74-4323-83b9-fb1e77e8f22f"
}
)
}
Mock -CommandName Get-SPTrustedRootAuthority -MockWith {
return @{
NameId = "f5a433c7-69f9-48ef-916b-dde8b5fa6fdb@14757a87-4d74-4323-83b9-fb1e77e8f22f"
}
}
It "Should return present from the get method" {
(Get-TargetResource @testParams).Ensure | Should Be "Present"
}
It "Should return false from the test method" {
Test-TargetResource @testParams | Should Be $false
}
It "Should remove the trust in the set method" {
Set-TargetResource @testParams
Assert-MockCalled -CommandName Remove-SPTrustedSecurityTokenIssuer
Assert-MockCalled -CommandName Remove-SPTrustedRootAuthority
}
}
Context -Name "A remote farm trust doesn't exist and shouldn't" -Fixture {
$testParams = @{
Name = "SendingFarm"
LocalWebAppUrl = "https://sharepoint.adventureworks.com"
RemoteWebAppUrl = "https://sharepoint.contoso.com"
Ensure = "Absent"
}
Mock -CommandName Get-SPTrustedSecurityTokenIssuer -MockWith {
return $null
}
Mock -CommandName Get-SPTrustedRootAuthority -MockWith {
return $null
}
It "Should return absent from the get method" {
(Get-TargetResource @testParams).Ensure | Should Be "Absent"
}
It "Should return true from the test method" {
Test-TargetResource @testParams | Should Be $true
}
}
}
}
Invoke-Command -ScriptBlock $Global:SPDscHelper.CleanupScript -NoNewScope
| {
"content_hash": "dad72b8c404f857f967c83bce6d46276",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 127,
"avg_line_length": 38.26815642458101,
"alnum_prop": 0.5481751824817518,
"repo_name": "mrpullen/xSharePoint",
"id": "505fddba91419f1623878ff95402afdd9efb2bd1",
"size": "6850",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Tests/Unit/SharePointDsc/SharePointDsc.SPRemoteFarmTrust.Tests.ps1",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1357"
},
{
"name": "JavaScript",
"bytes": "789"
},
{
"name": "PowerShell",
"bytes": "3096791"
}
],
"symlink_target": ""
} |
title: Edit or Delete Gitter Messages
---
> Editing or Deleting a previous message within 10 mins. of posting
 | {
"content_hash": "ae781cd40392d475d39715eb5350a0b6",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 125,
"avg_line_length": 47.2,
"alnum_prop": 0.8050847457627118,
"repo_name": "pahosler/freecodecamp",
"id": "599a7d49e5ee6fdfa2ea5accbfadda7bca828c89",
"size": "240",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "guide/english/miscellaneous/edit-or-delete-gitter-messages/index.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "35491"
},
{
"name": "HTML",
"bytes": "17600"
},
{
"name": "JavaScript",
"bytes": "777274"
}
],
"symlink_target": ""
} |
package ezbake.deployer.publishers.local;
public class LocalDeployment {
public final String artifactFile;
public final Process process;
public final String configPath;
public LocalDeployment(Process process, String artifactFile, String configPath) {
this.artifactFile = artifactFile;
this.process = process;
this.configPath = configPath;
}
}
| {
"content_hash": "d69cc806c255040923293b4015b72c8d",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 85,
"avg_line_length": 26.066666666666666,
"alnum_prop": 0.7212276214833759,
"repo_name": "ezbake/ezbake-deployer",
"id": "e50ced3525f9f1db23f555834a469eba45a02df4",
"size": "1010",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "deployer-service/src/main/java/ezbake/deployer/publishers/local/LocalDeployment.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1373722"
},
{
"name": "Ruby",
"bytes": "1889"
},
{
"name": "Shell",
"bytes": "12999"
},
{
"name": "Thrift",
"bytes": "10621"
}
],
"symlink_target": ""
} |
using UnityEngine;
using System.Collections;
public class PowerSwitch : MonoBehaviour {
public GameObject go;
void OnSelect()
{
if(go.activeSelf)
{
go.SetActive(false);
}
else
{
go.SetActive(true);
}
}
}
| {
"content_hash": "65d64ef63ff4dbaf0d5fb420ea01fdbb",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 42,
"avg_line_length": 13.565217391304348,
"alnum_prop": 0.48717948717948717,
"repo_name": "reillydonovan/MurmurG",
"id": "6a986266c244f0f93f73386f100220ec64f83877",
"size": "314",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Assets/Scripts/PowerSwitch.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "5936263"
},
{
"name": "C++",
"bytes": "10585"
},
{
"name": "GLSL",
"bytes": "113815"
},
{
"name": "HLSL",
"bytes": "40863"
},
{
"name": "Objective-C",
"bytes": "271"
},
{
"name": "PowerShell",
"bytes": "170390"
},
{
"name": "ShaderLab",
"bytes": "567239"
},
{
"name": "Smalltalk",
"bytes": "16"
}
],
"symlink_target": ""
} |
package com.touchpo.android.dotykacka_meetup;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | {
"content_hash": "8785ea7c58fda7c5d534f312287406a5",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 93,
"avg_line_length": 28.23076923076923,
"alnum_prop": 0.7547683923705722,
"repo_name": "Dotykacka/dotykacka-meetup",
"id": "70a32a8a61a344ee85b0161719a6d8d0a5ad7813",
"size": "367",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/androidTest/java/com/touchpo/android/dotykacka_meetup/ApplicationTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "4945"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
namespace OpenIDConnect.Host.InMemoryService
{
public class InMemoryScope
{
public InMemoryScope()
{
ScopeClaims = new List<InMemoryScopeClaim>();
}
public int Id { get; set; }
public string Name { get; set; }
public string ClaimsRule { get; set; }
public string Description { get; set; }
public string DisplayName { get; set; }
public bool Emphasize { get; set; }
public bool Enabled { get; set; }
public bool IncludeAllClaimsForUser { get; set; }
public bool Required { get; set; }
public ICollection<InMemoryScopeClaim> ScopeClaims { get; set; }
public bool ShowInDiscoveryDocument { get; set; }
public int Type { get; set; }
}
public class InMemoryScopeClaim
{
public bool AlwaysIncludeInIdToken { get; set; }
public string Description { get; set; }
public int Id { get; set; }
public string Name { get; set; }
}
} | {
"content_hash": "921e88232e2242ee6da71f48a280e70c",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 72,
"avg_line_length": 30.764705882352942,
"alnum_prop": 0.6022944550669216,
"repo_name": "JDawes-ScottLogic/openidconnect",
"id": "2930ef5d2adb322b2ad4e238d568f9e03717e8d2",
"size": "1669",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "OpenIDConnect.IdentityAdmin/InMemoryService/InMemoryScope.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "564631"
},
{
"name": "CSS",
"bytes": "7241"
},
{
"name": "HTML",
"bytes": "90886"
},
{
"name": "JavaScript",
"bytes": "92247"
}
],
"symlink_target": ""
} |
<?php
class Admin_Form_ResetPassword extends Ext_Form
{
public function init()
{
$this->setMethod('post');
$this->addElement('password', 'password', array(
'label' => 'password',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
'Alnum'
)
));
$this->addElement('password', 'confirm', array(
'label' => 'confirm_password',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array (
new Zend_Validate_Identical('password')
)
));
$this->addElement('submit', 'save', array(
'label' => 'save',
'class' => 'ui-state-default ui-corner-all'
));
}
} | {
"content_hash": "d5e3fee4a57e30cf4447923b33c9856e",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 58,
"avg_line_length": 26.875,
"alnum_prop": 0.44651162790697674,
"repo_name": "pierrealbert/checkit",
"id": "609ab72d601606ce99a9d64afdee94c57efcf662",
"size": "860",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/modules/admin/forms/ResetPassword.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "364359"
},
{
"name": "Go",
"bytes": "6808"
},
{
"name": "JavaScript",
"bytes": "3646135"
},
{
"name": "PHP",
"bytes": "19484960"
},
{
"name": "PowerShell",
"bytes": "1028"
},
{
"name": "Python",
"bytes": "5596"
},
{
"name": "Ruby",
"bytes": "3291"
},
{
"name": "Shell",
"bytes": "6066"
}
],
"symlink_target": ""
} |
'use strict';
Connector.playerSelector = '#radio';
Connector.remainingTimeSelector = '#clock';
Connector.getArtistTrack = () => {
const marquee = Util.getTextFromSelectors('#marquee');
const artistTrack = marquee.split(' :: ')[0];
const track = Util.getTextFromSelectors('#slots > .live h4');
const artist = artistTrack.substring(`${track} by `.length);
return { track, artist };
};
Connector.getOriginUrl = () => {
return location.origin;
};
Connector.isPlaying = () => {
return Util.hasElementClass(Connector.playerSelector, 'playing');
};
Connector.isScrobblingAllowed = () => {
return Util.hasElementClass('#slots > .live', 'music');
};
| {
"content_hash": "4afdb95da704fc5ab89ea4d2d95fd6fc",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 66,
"avg_line_length": 26.2,
"alnum_prop": 0.6931297709923664,
"repo_name": "inverse/web-scrobbler",
"id": "58c8a42360cfa8e0ccc7eee6b064ca59040df491",
"size": "655",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/connectors/refnet.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4548"
},
{
"name": "HTML",
"bytes": "22008"
},
{
"name": "JavaScript",
"bytes": "555468"
}
],
"symlink_target": ""
} |
<?php namespace Fungku\NetSuite\Classes;
class ResourceAllocationAllocationUnit {
static $paramtypesmap = array(
);
const _hours = "_hours";
const _percentOfTime = "_percentOfTime";
}
| {
"content_hash": "c9beb59546af34520b347a197c8cd56d",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 41,
"avg_line_length": 21.11111111111111,
"alnum_prop": 0.7368421052631579,
"repo_name": "Arkitecht/netsuite-php",
"id": "f241599027f9934277f4aa7bcc4d6993660c6865",
"size": "190",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Classes/ResourceAllocationAllocationUnit.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "1541401"
}
],
"symlink_target": ""
} |
using System.IO.Compression;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Xml.Linq;
using Microsoft.AspNetCore.Testing;
using Newtonsoft.Json.Linq;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore;
public class SharedFxTests
{
private readonly string _expectedTfm;
private readonly string _expectedRid;
private readonly string _sharedFxRoot;
private readonly ITestOutputHelper _output;
public SharedFxTests(ITestOutputHelper output)
{
_output = output;
_expectedTfm = TestData.GetDefaultNetCoreTargetFramework();
_expectedRid = TestData.GetSharedFxRuntimeIdentifier();
_sharedFxRoot = Path.Combine(
Environment.GetEnvironmentVariable("DOTNET_ROOT"),
"shared",
"Microsoft.AspNetCore.App",
TestData.GetSharedFxVersion());
}
[Fact]
public void SharedFrameworkContainsListedAssemblies()
{
var actualAssemblies = Directory.GetFiles(_sharedFxRoot, "*.dll")
.Select(Path.GetFileNameWithoutExtension)
.ToHashSet();
_output.WriteLine("==== actual assemblies ====");
_output.WriteLine(string.Join('\n', actualAssemblies.OrderBy(i => i)));
_output.WriteLine("==== expected assemblies ====");
_output.WriteLine(string.Join('\n', TestData.ListedSharedFxAssemblies.OrderBy(i => i)));
var missing = TestData.ListedSharedFxAssemblies.Except(actualAssemblies);
var unexpected = actualAssemblies.Except(TestData.ListedSharedFxAssemblies);
_output.WriteLine("==== missing assemblies from the framework ====");
_output.WriteLine(string.Join('\n', missing));
_output.WriteLine("==== unexpected assemblies in the framework ====");
_output.WriteLine(string.Join('\n', unexpected));
Assert.Empty(missing);
Assert.Empty(unexpected);
}
[Fact]
public void SharedFrameworkContainsExpectedFiles()
{
var actualAssemblies = Directory.GetFiles(_sharedFxRoot, "*.dll")
.Select(Path.GetFileNameWithoutExtension)
.ToHashSet();
var expectedAssemblies = TestData.GetSharedFxDependencies()
.Split(';', StringSplitOptions.RemoveEmptyEntries)
.ToHashSet();
_output.WriteLine("==== actual assemblies ====");
_output.WriteLine(string.Join('\n', actualAssemblies.OrderBy(i => i)));
_output.WriteLine("==== expected assemblies ====");
_output.WriteLine(string.Join('\n', expectedAssemblies.OrderBy(i => i)));
var missing = expectedAssemblies.Except(actualAssemblies);
var unexpected = actualAssemblies.Except(expectedAssemblies);
_output.WriteLine("==== missing assemblies from the framework ====");
_output.WriteLine(string.Join('\n', missing));
_output.WriteLine("==== unexpected assemblies in the framework ====");
_output.WriteLine(string.Join('\n', unexpected));
Assert.Empty(missing);
Assert.Empty(unexpected);
}
[Fact]
public void SharedFrameworkContainsValidRuntimeConfigFile()
{
var runtimeConfigFilePath = Path.Combine(_sharedFxRoot, "Microsoft.AspNetCore.App.runtimeconfig.json");
AssertEx.FileExists(runtimeConfigFilePath);
AssertEx.FileDoesNotExists(Path.Combine(_sharedFxRoot, "Microsoft.AspNetCore.App.runtimeconfig.dev.json"));
var runtimeConfig = JObject.Parse(File.ReadAllText(runtimeConfigFilePath));
Assert.Equal("Microsoft.NETCore.App", (string)runtimeConfig["runtimeOptions"]["framework"]["name"]);
Assert.Equal(_expectedTfm, (string)runtimeConfig["runtimeOptions"]["tfm"]);
Assert.Equal("LatestPatch", (string)runtimeConfig["runtimeOptions"]["rollForward"]);
Assert.Equal(TestData.GetMicrosoftNETCoreAppPackageVersion(), (string)runtimeConfig["runtimeOptions"]["framework"]["version"]);
}
[Fact]
public void SharedFrameworkContainsValidDepsJson()
{
var depsFilePath = Path.Combine(_sharedFxRoot, "Microsoft.AspNetCore.App.deps.json");
var target = $".NETCoreApp,Version=v{_expectedTfm.Substring(3)}/{_expectedRid}";
var ridPackageId = $"Microsoft.AspNetCore.App.Runtime.{_expectedRid}";
var libraryId = $"{ridPackageId}/{TestData.GetSharedFxVersion()}";
AssertEx.FileExists(depsFilePath);
var depsFile = JObject.Parse(File.ReadAllText(depsFilePath));
Assert.Equal(target, (string)depsFile["runtimeTarget"]["name"]);
Assert.NotNull(depsFile["compilationOptions"]);
Assert.Empty(depsFile["compilationOptions"]);
Assert.All(depsFile["libraries"], item =>
{
var prop = Assert.IsType<JProperty>(item);
var lib = Assert.IsType<JObject>(prop.Value);
Assert.Equal("package", lib["type"].Value<string>());
Assert.Empty(lib["sha512"].Value<string>());
});
Assert.NotNull(depsFile["libraries"][libraryId]);
Assert.Single(depsFile["libraries"].Values());
var targetLibraries = depsFile["targets"][target];
Assert.Single(targetLibraries.Values());
var runtimeLibrary = targetLibraries[libraryId];
Assert.Null(runtimeLibrary["dependencies"]);
Assert.All(runtimeLibrary["runtime"], item =>
{
var obj = Assert.IsType<JProperty>(item);
var assemblyVersion = obj.Value["assemblyVersion"].Value<string>();
Assert.NotEmpty(assemblyVersion);
Assert.True(Version.TryParse(assemblyVersion, out _), $"{assemblyVersion} should deserialize to System.Version");
var fileVersion = obj.Value["fileVersion"].Value<string>();
Assert.NotEmpty(fileVersion);
Assert.True(Version.TryParse(fileVersion, out _), $"{fileVersion} should deserialize to System.Version");
});
if (_expectedRid.StartsWith("win", StringComparison.Ordinal) && !_expectedRid.Contains("arm"))
{
Assert.All(runtimeLibrary["native"], item =>
{
var obj = Assert.IsType<JProperty>(item);
var fileVersion = obj.Value["fileVersion"].Value<string>();
Assert.NotEmpty(fileVersion);
Assert.True(Version.TryParse(fileVersion, out _), $"{fileVersion} should deserialize to System.Version");
});
}
else
{
Assert.Null(runtimeLibrary["native"]);
}
}
[Fact]
public void SharedFrameworkAssembliesHaveExpectedAssemblyVersions()
{
// Assemblies from this repo and dotnet/runtime don't always have identical assembly versions.
var repoAssemblies = TestData.GetSharedFrameworkBinariesFromRepo()
.Split(';', StringSplitOptions.RemoveEmptyEntries)
.ToHashSet();
var versionStringWithoutPrereleaseTag = TestData.GetMicrosoftNETCoreAppPackageVersion().Split('-', 2)[0];
var version = Version.Parse(versionStringWithoutPrereleaseTag);
var aspnetcoreVersionString = TestData.GetSharedFxVersion().Split('-', 2)[0];
var aspnetcoreVersion = Version.Parse(aspnetcoreVersionString);
var dlls = Directory.GetFiles(_sharedFxRoot, "*.dll", SearchOption.AllDirectories);
Assert.NotEmpty(dlls);
Assert.All(dlls, path =>
{
var name = Path.GetFileNameWithoutExtension(path);
if (string.Equals(name, "aspnetcorev2_inprocess", StringComparison.Ordinal))
{
// Skip our native assembly.
return;
}
var expectedVersion = repoAssemblies.Contains(name) ? aspnetcoreVersion : version;
using var fileStream = File.OpenRead(path);
using var peReader = new PEReader(fileStream, PEStreamOptions.Default);
var reader = peReader.GetMetadataReader(MetadataReaderOptions.Default);
var assemblyDefinition = reader.GetAssemblyDefinition();
// Assembly versions should all match Major.Minor.0.0
if (repoAssemblies.Contains(name))
{
// We always align major.minor in assemblies and packages.
Assert.Equal(expectedVersion.Major, assemblyDefinition.Version.Major);
}
else
{
// ... but dotnet/runtime has a window between package version and (then) assembly version updates.
Assert.True(expectedVersion.Major == assemblyDefinition.Version.Major ||
expectedVersion.Major - 1 == assemblyDefinition.Version.Major,
$"Unexpected Major assembly version '{assemblyDefinition.Version.Major}' is neither " +
$"{expectedVersion.Major - 1}' nor '{expectedVersion.Major}'.");
}
Assert.Equal(expectedVersion.Minor, assemblyDefinition.Version.Minor);
Assert.Equal(0, assemblyDefinition.Version.Build);
Assert.Equal(0, assemblyDefinition.Version.Revision);
});
}
// ASP.NET Core shared Fx assemblies should reference only ASP.NET Core assemblies with Revsion == 0.
[Fact]
public void SharedFrameworkAssemblyReferencesHaveExpectedAssemblyVersions()
{
// Only test managed assemblies from dotnet/aspnetcore.
var repoAssemblies = TestData.GetSharedFrameworkBinariesFromRepo()
.Split(';', StringSplitOptions.RemoveEmptyEntries)
.ToHashSet();
IEnumerable<string> dlls = Directory.GetFiles(_sharedFxRoot, "*.dll", SearchOption.AllDirectories);
Assert.NotEmpty(dlls);
Assert.All(dlls, path =>
{
// Unlike dotnet/aspnetcore, dotnet/runtime varies the assembly version while in servicing.
// dotnet/aspnetcore assemblies build against RTM targeting pack from dotnet/runtime.
if (!repoAssemblies.Contains(Path.GetFileNameWithoutExtension(path)))
{
return;
}
using var fileStream = File.OpenRead(path);
using var peReader = new PEReader(fileStream, PEStreamOptions.Default);
var reader = peReader.GetMetadataReader(MetadataReaderOptions.Default);
Assert.All(reader.AssemblyReferences, handle =>
{
var reference = reader.GetAssemblyReference(handle);
Assert.Equal(0, reference.Version.Build);
Assert.Equal(0, reference.Version.Revision);
});
});
}
[Fact]
public void ItContainsVersionFile()
{
var versionFile = Path.Combine(_sharedFxRoot, ".version");
AssertEx.FileExists(versionFile);
var lines = File.ReadAllLines(versionFile);
Assert.Equal(2, lines.Length);
Assert.Equal(TestData.GetRepositoryCommit(), lines[0]);
Assert.Equal(TestData.GetSharedFxVersion(), lines[1]);
}
[Fact]
public void RuntimeListContainsCorrectEntries()
{
var expectedAssemblies = TestData.GetSharedFxDependencies()
.Split(';', StringSplitOptions.RemoveEmptyEntries)
.ToHashSet();
var runtimeListPath = "RuntimeList.xml";
AssertEx.FileExists(runtimeListPath);
var runtimeListDoc = XDocument.Load(runtimeListPath);
var runtimeListEntries = runtimeListDoc.Root.Descendants();
_output.WriteLine("==== file contents ====");
_output.WriteLine(string.Join('\n', runtimeListEntries.Select(i => i.Attribute("Path").Value).OrderBy(i => i)));
_output.WriteLine("==== expected assemblies ====");
_output.WriteLine(string.Join('\n', expectedAssemblies.OrderBy(i => i)));
var actualAssemblies = runtimeListEntries
.Select(i =>
{
var filePath = i.Attribute("Path").Value;
var fileParts = filePath.Split('/');
var fileName = fileParts[fileParts.Length - 1];
return fileName.EndsWith(".dll", StringComparison.Ordinal)
? fileName.Substring(0, fileName.Length - 4)
: fileName;
})
.ToHashSet();
var missing = expectedAssemblies.Except(actualAssemblies);
var unexpected = actualAssemblies.Except(expectedAssemblies);
_output.WriteLine("==== missing assemblies from the runtime list ====");
_output.WriteLine(string.Join('\n', missing));
_output.WriteLine("==== unexpected assemblies in the runtime list ====");
_output.WriteLine(string.Join('\n', unexpected));
Assert.Empty(missing);
Assert.Empty(unexpected);
Assert.All(runtimeListEntries, i =>
{
var assemblyType = i.Attribute("Type").Value;
var assemblyPath = i.Attribute("Path").Value;
var fileVersion = i.Attribute("FileVersion").Value;
if (assemblyType.Equals("Managed"))
{
var assemblyVersion = i.Attribute("AssemblyVersion").Value;
Assert.True(Version.TryParse(assemblyVersion, out _), $"{assemblyPath} has assembly version {assemblyVersion}. Assembly version must be convertable to System.Version");
}
Assert.True(Version.TryParse(fileVersion, out _), $"{assemblyPath} has file version {fileVersion}. File version must be convertable to System.Version");
});
}
[Fact]
public void RuntimeListContainsCorrectPaths()
{
var runtimeListPath = "RuntimeList.xml";
AssertEx.FileExists(runtimeListPath);
var runtimeListDoc = XDocument.Load(runtimeListPath);
var runtimeListEntries = runtimeListDoc.Root.Descendants();
var packageFolder = SkipOnHelixAttribute.OnHelix() ?
Environment.GetEnvironmentVariable("HELIX_WORKITEM_ROOT") :
TestData.GetPackagesFolder();
var sharedFxPath = Path.Combine(
packageFolder,
"Microsoft.AspNetCore.App.Runtime.win-x64." + TestData.GetSharedFxVersion() + ".nupkg");
AssertEx.FileExists(sharedFxPath);
ZipArchive archive = ZipFile.OpenRead(sharedFxPath);
var actualPaths = archive.Entries
.Where(i => i.FullName.EndsWith(".dll", StringComparison.Ordinal))
.Select(i => i.FullName).ToHashSet();
var expectedPaths = runtimeListEntries.Select(i => i.Attribute("Path").Value).ToHashSet();
_output.WriteLine("==== package contents ====");
_output.WriteLine(string.Join('\n', actualPaths.OrderBy(i => i)));
_output.WriteLine("==== expected assemblies ====");
_output.WriteLine(string.Join('\n', expectedPaths.OrderBy(i => i)));
var missing = expectedPaths.Except(actualPaths);
var unexpected = actualPaths.Except(expectedPaths);
_output.WriteLine("==== missing assemblies from the runtime list ====");
_output.WriteLine(string.Join('\n', missing));
_output.WriteLine("==== unexpected assemblies in the runtime list ====");
_output.WriteLine(string.Join('\n', unexpected));
Assert.Empty(missing);
Assert.Empty(unexpected);
}
}
| {
"content_hash": "8fba5ba748b84786d6964db690889079",
"timestamp": "",
"source": "github",
"line_count": 353,
"max_line_length": 184,
"avg_line_length": 43.079320113314445,
"alnum_prop": 0.6404945091076478,
"repo_name": "aspnet/AspNetCore",
"id": "302df8a51e9c89ad968fb4a03b53c65eb76c9ceb",
"size": "15345",
"binary": false,
"copies": "1",
"ref": "refs/heads/darc-main-3ce916a7-9d9b-4849-8f14-6703adcb3cb2",
"path": "src/Framework/test/SharedFxTests.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "109"
},
{
"name": "Batchfile",
"bytes": "19526"
},
{
"name": "C",
"bytes": "213916"
},
{
"name": "C#",
"bytes": "47455169"
},
{
"name": "C++",
"bytes": "1900454"
},
{
"name": "CMake",
"bytes": "7955"
},
{
"name": "CSS",
"bytes": "62326"
},
{
"name": "Dockerfile",
"bytes": "3584"
},
{
"name": "F#",
"bytes": "7982"
},
{
"name": "Groovy",
"bytes": "1529"
},
{
"name": "HTML",
"bytes": "1130653"
},
{
"name": "Java",
"bytes": "297552"
},
{
"name": "JavaScript",
"bytes": "2726829"
},
{
"name": "Lua",
"bytes": "4904"
},
{
"name": "Makefile",
"bytes": "220"
},
{
"name": "Objective-C",
"bytes": "222"
},
{
"name": "PowerShell",
"bytes": "241706"
},
{
"name": "Python",
"bytes": "19476"
},
{
"name": "Roff",
"bytes": "6044"
},
{
"name": "Shell",
"bytes": "142293"
},
{
"name": "Smalltalk",
"bytes": "3"
},
{
"name": "TypeScript",
"bytes": "797435"
}
],
"symlink_target": ""
} |
using System;
using System.Net;
using System.Text;
namespace Dev4s.WebClient
{
public sealed class WebClientWrapper : IWebClientWrapper
{
private readonly System.Net.WebClient _webClient;
public Encoding Encoding
{
get { return _webClient.Encoding; }
set { _webClient.Encoding = value; }
}
public WebClientWrapper()
{
_webClient = new System.Net.WebClient {Encoding = Encoding.UTF8};
//NOTE: This one needs some special checkings...
_webClient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1)");
}
public string DownloadString(Uri uri)
{
return _webClient.DownloadString(uri);
}
}
} | {
"content_hash": "781da318b77b45952d4cb8f57460288a",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 109,
"avg_line_length": 22.433333333333334,
"alnum_prop": 0.7147102526002972,
"repo_name": "dev4s/dev4s-webclient",
"id": "d2dfe9fb087297e2154df28338bd990fb55d394e",
"size": "675",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Dev4s.WebClient/WebClientWrapper.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "82223"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
Bot. Notiser 130(4): 366 (1977)
#### Original name
Anthracoidea douglasii Nannf.
### Remarks
null | {
"content_hash": "3ac47a8fd1c56285b1934bfa975b5425",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 12.384615384615385,
"alnum_prop": 0.7018633540372671,
"repo_name": "mdoering/backbone",
"id": "ad0b692122b0118589df1eaa91f969ef11cab83e",
"size": "214",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Basidiomycota/Ustilaginomycetes/Ustilaginales/Anthracoideaceae/Anthracoidea/Anthracoidea douglasii/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
"""
========
Dispatch
========
Identical to django.dispatch module but adds few more features
"""
import django.dispatch
from celery import shared_task
def async_receiver(signal, sender=None, **kwargs):
"""
Decorator to perform django signal asynchronously using Celery. The function decorated with
this should be recognized by celery. django signal mechanism should be working normally and
no additional changes are required while using in-built signals or custom signals.
"""
def _decorator(func):
# Convert normal function to celery task
func_celery = shared_task(func, **kwargs)
# Connect to a signal
if isinstance(signal, (list, tuple)):
for s in signal:
# Weak is false as func_celery doesn't exists outside the closure scope. So cannot
# be referenced weakly and will be erased by garbage collector
s.connect(func_celery.delay, sender=sender)
else:
signal.connect(func_celery.delay, sender=sender)
# To let celery recognize normal function as celery task
return func_celery
return _decorator
def reducer(self):
return django.dispatch.Signal, (self.providing_args,)
#: Monkey patched Signal class to remove non-pickleable attribute
django.dispatch.Signal.__reduce__ = reducer
class Signal(django.dispatch.Signal):
"""
Base class for all custom signal.
The reason of overriding standard django Signal class is to accept sender in construction and
passing it ``Signal.sends()`` implicitly
"""
def __init__(self, providing_args=None, use_caching=False, sender=None):
self.sender = sender
super(Signal, self).__init__(providing_args=providing_args, use_caching=use_caching)
def send(self, **named):
super(Signal, self).send(sender=self.sender, **named)
| {
"content_hash": "c27cc02866809e47c4c9fe3e387504fe",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 98,
"avg_line_length": 32.44827586206897,
"alnum_prop": 0.6785334750265675,
"repo_name": "inabhi9/drf-ext",
"id": "9220615708b564058e75a55f667e5a264204e25a",
"size": "1882",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "drf_ext/core/dispatch.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "41247"
}
],
"symlink_target": ""
} |
package iso20022
// Choice between a reason or no reason for the corporate action instruction processing pending status.
type PendingStatus44Choice struct {
// Reason not specified.
NoSpecifiedReason *NoReasonCode `xml:"NoSpcfdRsn"`
// Reason for the pending status.
Reason []*PendingStatusReason12 `xml:"Rsn"`
}
func (p *PendingStatus44Choice) SetNoSpecifiedReason(value string) {
p.NoSpecifiedReason = (*NoReasonCode)(&value)
}
func (p *PendingStatus44Choice) AddReason() *PendingStatusReason12 {
newValue := new(PendingStatusReason12)
p.Reason = append(p.Reason, newValue)
return newValue
}
| {
"content_hash": "257210e38ac1f6273cee300e3b828d45",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 103,
"avg_line_length": 28.904761904761905,
"alnum_prop": 0.7759472817133443,
"repo_name": "fgrid/iso20022",
"id": "994977c9660aaa10b7fe9590c2d90ddc3e9d235c",
"size": "607",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PendingStatus44Choice.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "21383920"
}
],
"symlink_target": ""
} |
#include "optionsdialog.h"
#include "ui_optionsdialog.h"
#include "bitcoinunits.h"
#include "monitoreddatamapper.h"
#include "netbase.h"
#include "optionsmodel.h"
#include <QDir>
#include <QIntValidator>
#include <QLocale>
#include <QMessageBox>
OptionsDialog::OptionsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::OptionsDialog),
model(0),
mapper(0),
fRestartWarningDisplayed_Proxy(false),
fRestartWarningDisplayed_Lang(false),
fProxyIpValid(true)
{
ui->setupUi(this);
/* Network elements init */
#ifndef USE_UPNP
ui->mapPortUpnp->setEnabled(false);
#endif
ui->proxyIp->setEnabled(false);
ui->proxyPort->setEnabled(false);
ui->proxyPort->setValidator(new QIntValidator(1, 65535, this));
ui->socksVersion->setEnabled(false);
ui->socksVersion->addItem("5", 5);
ui->socksVersion->addItem("4", 4);
ui->socksVersion->setCurrentIndex(0);
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy()));
ui->proxyIp->installEventFilter(this);
/* Window elements init */
#ifdef Q_OS_MAC
/* remove Window tab on Mac */
ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow));
#endif
/* Display elements init */
QDir translations(":translations");
ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
foreach(const QString &langStr, translations.entryList())
{
QLocale locale(langStr);
/** check if the locale name consists of 2 parts (language_country) */
if(langStr.contains("_"))
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
else
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language (locale name)", e.g. "German (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
}
ui->unit->setModel(new BitcoinUnits(this));
/* Widget-to-option mapper */
mapper = new MonitoredDataMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
mapper->setOrientation(Qt::Vertical);
/* enable apply button when data modified */
connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton()));
/* disable apply button when new data loaded */
connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton()));
/* setup/change UI elements when proxy IP is invalid/valid */
connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool)));
}
OptionsDialog::~OptionsDialog()
{
delete ui;
}
void OptionsDialog::setModel(OptionsModel *model)
{
this->model = model;
if(model)
{
connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
mapper->setModel(model);
setMapper();
mapper->toFirst();
}
/* update the display unit, to not use the default ("BTC") */
updateDisplayUnit();
/* warn only when language selection changes by user action (placed here so init via mapper doesn't trigger this) */
connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning_Lang()));
/* disable apply button after settings are loaded as there is nothing to save */
disableApplyButton();
}
void OptionsDialog::setMapper()
{
/* Main */
mapper->addMapping(ui->transactionFee, OptionsModel::Fee);
mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup);
/* Network */
mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP);
mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse);
mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP);
mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort);
mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion);
/* Window */
#ifndef Q_OS_MAC
mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray);
mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose);
#endif
/* Display */
mapper->addMapping(ui->lang, OptionsModel::Language);
mapper->addMapping(ui->unit, OptionsModel::DisplayUnit);
mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses);
mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures);
}
void OptionsDialog::enableApplyButton()
{
ui->applyButton->setEnabled(true);
}
void OptionsDialog::disableApplyButton()
{
ui->applyButton->setEnabled(false);
}
void OptionsDialog::enableSaveButtons()
{
/* prevent enabling of the save buttons when data modified, if there is an invalid proxy address present */
if(fProxyIpValid)
setSaveButtonState(true);
}
void OptionsDialog::disableSaveButtons()
{
setSaveButtonState(false);
}
void OptionsDialog::setSaveButtonState(bool fState)
{
ui->applyButton->setEnabled(fState);
ui->okButton->setEnabled(fState);
}
void OptionsDialog::on_resetButton_clicked()
{
if(model)
{
// confirmation dialog
QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Confirm options reset"),
tr("Some settings may require a client restart to take effect.") + "<br><br>" + tr("Do you want to proceed?"),
QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
if(btnRetVal == QMessageBox::Cancel)
return;
disableApplyButton();
/* disable restart warning messages display */
fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = true;
/* reset all options and save the default values (QSettings) */
model->Reset();
mapper->toFirst();
mapper->submit();
/* re-enable restart warning messages display */
fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = false;
}
}
void OptionsDialog::on_okButton_clicked()
{
mapper->submit();
accept();
}
void OptionsDialog::on_cancelButton_clicked()
{
reject();
}
void OptionsDialog::on_applyButton_clicked()
{
mapper->submit();
disableApplyButton();
}
void OptionsDialog::showRestartWarning_Proxy()
{
if(!fRestartWarningDisplayed_Proxy)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Teestcoin."), QMessageBox::Ok);
fRestartWarningDisplayed_Proxy = true;
}
}
void OptionsDialog::showRestartWarning_Lang()
{
if(!fRestartWarningDisplayed_Lang)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Teestcoin."), QMessageBox::Ok);
fRestartWarningDisplayed_Lang = true;
}
}
void OptionsDialog::updateDisplayUnit()
{
if(model)
{
/* Update transactionFee with the current unit */
ui->transactionFee->setDisplayUnit(model->getDisplayUnit());
}
}
void OptionsDialog::handleProxyIpValid(QValidatedLineEdit *object, bool fState)
{
// this is used in a check before re-enabling the save buttons
fProxyIpValid = fState;
if(fProxyIpValid)
{
enableSaveButtons();
ui->statusLabel->clear();
}
else
{
disableSaveButtons();
object->setValid(fProxyIpValid);
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
ui->statusLabel->setText(tr("The supplied proxy address is invalid."));
}
}
bool OptionsDialog::eventFilter(QObject *object, QEvent *event)
{
if(event->type() == QEvent::FocusOut)
{
if(object == ui->proxyIp)
{
CService addr;
/* Check proxyIp for a valid IPv4/IPv6 address and emit the proxyIpValid signal */
emit proxyIpValid(ui->proxyIp, LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr));
}
}
return QDialog::eventFilter(object, event);
}
| {
"content_hash": "26194cacde52a9f52dbd9afe8e55a893",
"timestamp": "",
"source": "github",
"line_count": 282,
"max_line_length": 198,
"avg_line_length": 32.05673758865248,
"alnum_prop": 0.6696902654867256,
"repo_name": "teestcoin/teestcoin1",
"id": "bc626dc7d10957ba7dbc7d9b40531f46c8744f81",
"size": "9040",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/qt/optionsdialog.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "103297"
},
{
"name": "C++",
"bytes": "2522848"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "IDL",
"bytes": "14696"
},
{
"name": "Objective-C",
"bytes": "5864"
},
{
"name": "Python",
"bytes": "69714"
},
{
"name": "Shell",
"bytes": "9702"
},
{
"name": "TypeScript",
"bytes": "5236293"
}
],
"symlink_target": ""
} |
<div layout="column" layout-gt-md="row" layout-margin layout-wrap flex>
<md-whiteframe layout="column" class="md-whiteframe-z1 md-padding task-container" flex>
<h3>Task #{{ task.taskData.id }}</h3>
<div class="template-item" ng-repeat="item in task.taskData.task_template.template_items">
<div md-template-compiler="task.buildHtml(item)"></div>
</div>
<div layout="row" class="task-actions" layout-align="end center">
<md-button ng-click="task.submitOrSave(1)">Save</md-button>
<md-button ng-click="task.skip()" class="">Skip</md-button>
<md-button ng-click="task.submitOrSave(2)" class="">Submit</md-button>
</div>
</md-whiteframe>
<md-whiteframe class="md-whiteframe-z1 task-comments md-padding" layout="column" flex>
<div class="input-comment" layout="column">
<form name="task-form" ng-submit="task.saveComment()">
<div layout="column">
<md-input-container layout="column" flex>
<h4>Add Comment</h4>
<label>Enter comment here</label>
<textarea ng-model="task.comment.body" columns="1"></textarea>
</md-input-container>
</div>
<div layout="row">
<md-button type="submit" ng-disabled="!task.comment.body"
aria-label="post-comment"
class="md-no-ink">
Send comment
</md-button>
<md-button type="button" ng-click="task.comment.body=null" aria-label="cancel-comment"
class="md-no-ink">
Cancel
</md-button>
</div>
</form>
</div>
<md-list class="previous-comments" ng-if="task.taskData.comments">
<h4>Feedback on Task Design</h4>
<md-list-item class="md-3-line" layout="column" ng-repeat="item in task.taskData.comments track by $index">
<div class="md-list-item-text">
<h3 class="comment-sender">{{ item.comment.sender_alias }}</h3>
<h4 class="comment-body">{{ item.comment.body }}</h4>
<p class="comment-time">Posted {{ item.comment.posted_time }}</p>
</div>
<md-divider ng-if="!$last"></md-divider>
</md-list-item>
</md-list>
</md-whiteframe>
</div> | {
"content_hash": "351c83d4a8a143e26b29f218989fe22a",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 119,
"avg_line_length": 45.660714285714285,
"alnum_prop": 0.5154477903793508,
"repo_name": "Macbull/crowdsource-platform",
"id": "309604738c421a0e3da05cbba83a118aa166353f",
"size": "2557",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop2",
"path": "static/templates/task/base.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "292511"
},
{
"name": "HTML",
"bytes": "205159"
},
{
"name": "JavaScript",
"bytes": "146059"
},
{
"name": "Python",
"bytes": "258405"
},
{
"name": "Shell",
"bytes": "828"
}
],
"symlink_target": ""
} |
///////////////////////////////////////////////////////////////////////////
// Copyright © 2014 - 2016 Esri. All Rights Reserved.
//
// Licensed under the Apache License Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////
define([
'dojo/_base/declare',
'dijit/_WidgetBase',
'dijit/_TemplatedMixin',
'dijit/_WidgetsInTemplateMixin',
'dojo/text!./templates/DrawBox.html',
'dojo/_base/lang',
'dojo/_base/html',
'dojo/_base/array',
'dojo/on',
'dojo/query',
'dojo/Evented',
'esri/graphic',
'esri/layers/GraphicsLayer',
'esri/toolbars/draw',
'esri/symbols/jsonUtils',
'esri/geometry/Polygon'
],
function(declare, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, template, lang, html,
array, on, query, Evented, Graphic, GraphicsLayer, Draw, jsonUtils, Polygon) {
return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, Evented], {
templateString:template,
baseClass: 'jimu-draw-box',
declaredClass: 'jimu.dijit.DrawBox',
nls:null,
drawLayer:null,
drawLayerId:null,
drawToolBar:null,
_isDisabled: false,
_shiftKey: false,
_ctrlKey: false,
_metaKey: false, //used for Mac
//options:
//note: 'types' is mutually exclusive with 'geoTypes' and the latter has high priority
//available types: ['point','polyline','polygon','text']
types:null,
/*available geoTypes:
["POINT",
"LINE", "POLYLINE", "FREEHAND_POLYLINE",
"TRIANGLE", "EXTENT", "CIRCLE", "ELLIPSE", "POLYGON", "FREEHAND_POLYGON",
"TEXT"]
*/
geoTypes:null,//if 'geoTypes' is set, 'types' is ignored
map:null,
pointSymbol:null,
polylineSymbol:null,
polygonSymbol:null,
textSymbol:null,
showClear:false,//show Clear button or not
keepOneGraphic:false,//only keep one graphic or not
deactivateAfterDrawing: true,//deactivate drawToolbar or not after every drawing
//public methods:
//setMap
//setPointSymbol
//setLineSymbol
//setPolygonSymbol
//setTextSymbol
//addGraphic
//removeGraphic
//reset
//clear
//activate
//deactivate
//enable
//disable
//isEnabled
//events:
//icon-selected
//draw-end
//clear
//user-clear
//draw-activate
//draw-deactivate
//css classes:
//draw-item
//point-icon
//line-icon
//polyline-icon
//freehand-polyline-icon
//triangle-icon
//extent-icon
//circle-icon
//ellipse-icon
//polygon-icon
//freehand-polygon-icon
//text-icon
//drawings-clear
postMixInProperties:function(){
this.nls = window.jimuNls.drawBox;
},
postCreate:function(){
this.inherited(arguments);
var layerArgs = {};
if(this.drawLayerId){
layerArgs.id = this.drawLayerId;
}
this.drawLayer = new GraphicsLayer(layerArgs);
this._initDefaultSymbols();
this._initTypes();
var items = query('.draw-item', this.domNode);
this.own(items.on('click', lang.hitch(this, this._onItemClick)));
this.own(on(this.btnClear, 'click', lang.hitch(this, this._onClickClear)));
//bind key events before draw-end
this.own(on(document.body, 'keydown', lang.hitch(this, function(event){
this._shiftKey = !!event.shiftKey;
this._ctrlKey = !!event.ctrlKey;
this._metaKey = !!event.metaKey;
})));
this.own(on(document.body, 'keyup', lang.hitch(this, function(event){
this._shiftKey = !!event.shiftKey;
this._ctrlKey = !!event.ctrlKey;
this._metaKey = !!event.metaKey;
})));
if(this.map){
this.setMap(this.map);
}
var display = this.showClear === true ? 'block' : 'none';
html.setStyle(this.btnClear, 'display', display);
this.enable();
},
enable: function(){
this._isDisabled = false;
html.addClass(this.domNode, 'enabled');
html.removeClass(this.domNode, 'disabled');
},
disable: function(){
this._isDisabled = true;
html.addClass(this.domNode, 'disabled');
html.removeClass(this.domNode, 'enabled');
this.deactivate();
},
hideLayer: function(){
if(this.drawLayer){
this.drawLayer.hide();
}
},
showLayer: function(){
if(this.drawLayer){
this.drawLayer.show();
}
},
isEnabled: function(){
return !this._isDisabled;
},
isActive: function(){
var items = query('.draw-item.jimu-state-active', this.domNode);
return items && items.length > 0;
},
disableWebMapPopup:function(){
if(this.map){
this.map.setInfoWindowOnClick(false);
}
},
enableWebMapPopup:function(){
if(this.map){
this.map.setInfoWindowOnClick(true);
}
},
destroy:function(){
this.deactivate();
if(this.drawLayer){
if(this.map){
this.map.removeLayer(this.drawLayer);
}
}
this.drawToolBar = null;
this.map = null;
this.drawLayer = null;
this.inherited(arguments);
},
setMap:function(map){
if(map){
this.map = map;
this.map.addLayer(this.drawLayer);
this.drawToolBar = new Draw(this.map);
this.drawToolBar.setMarkerSymbol(this.pointSymbol);
this.drawToolBar.setLineSymbol(this.polylineSymbol);
this.drawToolBar.setFillSymbol(this.polygonSymbol);
this.own(on(this.drawToolBar, 'draw-end', lang.hitch(this, this._onDrawEnd)));
}
},
setPointSymbol:function(symbol){
this.pointSymbol = symbol;
this.drawToolBar.setMarkerSymbol(this.pointSymbol);
},
setLineSymbol:function(symbol){
this.polylineSymbol = symbol;
this.drawToolBar.setLineSymbol(symbol);
},
setPolygonSymbol:function(symbol){
this.polygonSymbol = symbol;
this.drawToolBar.setFillSymbol(symbol);
},
setTextSymbol:function(symbol){
this.textSymbol = symbol;
},
reset: function(){
this.deactivate();
this.clear();
},
clear:function(){
this.drawLayer.clear();
this.onClear();
},
deactivate:function(){
this.enableWebMapPopup();
query('.draw-item', this.domNode).removeClass('jimu-state-active');
if(this.drawToolBar){
this.drawToolBar.deactivate();
this.emit('draw-deactivate');
}
},
activate: function(tool){
//tool available values:
//POINT
//LINE,POLYLINE,FREEHAND_POLYLINE
//TRIANGLE,EXTENT,CIRCLE,ELLIPSE,POLYGON,FREEHAND_POLYGON
//TEXT
var itemIcon = null;
var items = query('.draw-item', this.domNode);
if(tool === 'TEXT'){
tool = 'POINT';
itemIcon = this.textIcon;
}else{
var filterItems = items.filter(function(itemNode){
return itemNode.getAttribute('data-geotype') === tool;
});
if(filterItems.length > 0){
itemIcon = filterItems[0];
}
}
if(itemIcon){
this._activate(itemIcon);
}
},
onIconSelected:function(target, geotype, commontype){
this.emit("icon-selected", target, geotype, commontype);
},
onDrawEnd:function(graphic, geotype, commontype, shiftKey, ctrlKey, metaKey){
this.emit('draw-end', graphic, geotype, commontype, shiftKey, ctrlKey, metaKey);
},
onClear:function(){
this.emit("clear");
},
addGraphic:function(g){
if(this.keepOneGraphic){
this.drawLayer.clear();
}
this.drawLayer.add(g);
},
removeGraphic:function(g){
this.drawLayer.remove(g);
},
getFirstGraphic: function(){
var firstGraphic = null;
if(this.drawLayer && this.drawLayer.graphics.length > 0){
firstGraphic = this.drawLayer.graphics[0];
}
return firstGraphic;
},
show: function(){
html.removeClass(this.domNode, 'hidden');
},
hide: function(){
html.addClass(this.domNode, 'hidden');
},
getDrawItemIcons: function(){
return query('.draw-item', this.domNode);
},
_onClickClear: function(){
if(this._isDisabled){
return;
}
this.clear();
this.emit("user-clear");
},
_initDefaultSymbols:function(){
var pointSys = {
"style": "esriSMSCircle",
"color": [0, 0, 128, 128],
"name": "Circle",
"outline": {
"color": [0, 0, 128, 255],
"width": 1
},
"type": "esriSMS",
"size": 18
};
var lineSys = {
"style": "esriSLSSolid",
"color": [79, 129, 189, 255],
"width": 3,
"name": "Blue 1",
"type": "esriSLS"
};
var polygonSys = {
"style": "esriSFSSolid",
"color": [79, 129, 189, 128],
"type": "esriSFS",
"outline": {
"style": "esriSLSSolid",
"color": [54, 93, 141, 255],
"width": 1.5,
"type": "esriSLS"
}
};
if(!this.pointSymbol){
this.pointSymbol = jsonUtils.fromJson(pointSys);
}
if(!this.polylineSymbol){
this.polylineSymbol = jsonUtils.fromJson(lineSys);
}
if(!this.polygonSymbol){
this.polygonSymbol = jsonUtils.fromJson(polygonSys);
}
},
_initTypes:function(){
if(this.geoTypes && this.geoTypes.length > 0){
//if 'geoTypes' is set, we ignore 'types'
this.types = null;
}else{
this.geoTypes = [];
if(!(this.types && this.types.length > 0)){
this.types = ['point', 'polyline', 'polygon'];
}
if(this.types.indexOf('point') >= 0){
this.geoTypes = this.geoTypes.concat(["POINT"]);
}
if(this.types.indexOf('polyline') >= 0){
this.geoTypes = this.geoTypes.concat(["LINE", "POLYLINE", "FREEHAND_POLYLINE"]);
}
if(this.types.indexOf('polygon') >= 0){
var a = ["TRIANGLE", "EXTENT", "CIRCLE", "ELLIPSE", "POLYGON", "FREEHAND_POLYGON"];
this.geoTypes = this.geoTypes.concat(a);
}
if(this.types.indexOf('text') >= 0){
this.geoTypes = this.geoTypes.concat(["TEXT"]);
}
}
var items = query('.draw-item', this.domNode);
items.style('display', 'none');
array.forEach(items, lang.hitch(this, function(item){
var geoType = item.getAttribute('data-geotype');
var display = array.indexOf(this.geoTypes, geoType) >= 0;
html.setStyle(item, 'display', display ? 'block' : 'none');
}));
},
_onItemClick:function(event){
if(this._isDisabled){
return;
}
var target = event.target || event.srcElement;
if(!html.hasClass(target, 'draw-item')){
return;
}
var isSelected = html.hasClass(target, 'jimu-state-active');
//toggle tools on and off
if(isSelected){
this.deactivate();
}else{
this._activate(target);
}
},
_activate: function(itemIcon){
var items = query('.draw-item', this.domNode);
items.removeClass('jimu-state-active');
html.addClass(itemIcon, 'jimu-state-active');
var geotype = itemIcon.getAttribute('data-geotype');
var commontype = itemIcon.getAttribute('data-commontype');
var tool = Draw[geotype];
if(geotype === 'TEXT'){
tool = Draw.POINT;
}
this.disableWebMapPopup();
this.drawToolBar.activate(tool);
this.emit('draw-activate', tool);
this.onIconSelected(itemIcon, geotype, commontype);
},
_onDrawEnd:function(event){
var selectedItem = query('.draw-item.jimu-state-active', this.domNode)[0];
var geotype = selectedItem.getAttribute('data-geotype');
var commontype = selectedItem.getAttribute('data-commontype');
var geometry = null;
if(event.geometry.type === 'extent'){
//convert extent to polygon because Analysis dijit doesn't support extent
geometry = Polygon.fromExtent(event.geometry);
}else{
geometry = event.geometry;
}
geometry.geoType = geotype;
geometry.commonType = commontype;
var type = geometry.type;
var symbol = null;
if (type === "point" || type === "multipoint") {
if(html.hasClass(this.textIcon, 'jimu-state-active')){
symbol = this.textSymbol;
}
else{
symbol = this.pointSymbol;
}
} else if (type === "line" || type === "polyline") {
symbol = this.polylineSymbol;
} else {
symbol = this.polygonSymbol;
}
var g = new Graphic(geometry, symbol, null, null);
if(this.keepOneGraphic){
this.drawLayer.clear();
}
this.drawLayer.add(g);
if(this.deactivateAfterDrawing){
this.deactivate();
}
this.onDrawEnd(g, geotype, commontype, this._shiftKey, this._ctrlKey, this._metaKey);
}
});
}); | {
"content_hash": "0be4c782e7437c353c689c6ed259a52a",
"timestamp": "",
"source": "github",
"line_count": 487,
"max_line_length": 94,
"avg_line_length": 27.68583162217659,
"alnum_prop": 0.5843654972928873,
"repo_name": "cmccullough2/cmv-wab-widgets",
"id": "efca7781d37c5982b1c88e96ffc2f7535c4037fc",
"size": "13484",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "wab/2.3/jimu.js/dijit/DrawBox.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1198579"
},
{
"name": "HTML",
"bytes": "946692"
},
{
"name": "JavaScript",
"bytes": "22190423"
},
{
"name": "Pascal",
"bytes": "4207"
},
{
"name": "TypeScript",
"bytes": "102918"
}
],
"symlink_target": ""
} |
/*
* Ultrix 4.x Dynamic Loader Library Version 1.0
*
* dl.h
* header file for the Dynamic Loader Library
*/
#ifndef _DL_HEADER_
#define _DL_HEADER_
#include <stdio.h>
#include "filehdr.h"
#include "syms.h"
#include "ldfcn.h"
#include "reloc.h"
#include "scnhdr.h"
typedef long CoreAddr;
typedef struct ScnInfo
{
CoreAddr addr; /* starting address of the section */
SCNHDR hdr; /* section header */
RELOC *relocEntries; /* relocation entries */
} ScnInfo;
typedef enum
{
DL_NEEDRELOC, /* still need relocation */
DL_RELOCATED, /* no relocation necessary */
DL_INPROG /* relocation in progress */
} dlRStatus;
typedef struct JmpTbl
{
char *block; /* the jump table memory block */
struct JmpTbl *next; /* next block */
} JmpTbl;
typedef struct dlFile
{
char *filename; /* file name of the object file */
int textSize; /* used by mprotect */
CoreAddr textAddress; /* start addr of text section */
long textVaddr; /* vaddr of text section in obj file */
CoreAddr rdataAddress; /* start addr of rdata section */
long rdataVaddr; /* vaddr of text section in obj file */
CoreAddr dataAddress; /* start addr of data section */
long dataVaddr; /* vaddr of text section in obj file */
CoreAddr bssAddress; /* start addr of bss section */
long bssVaddr; /* vaddr of text section in obj file */
int nsect; /* number of sections */
ScnInfo *sect; /* details of each section (array) */
int issExtMax; /* size of string space */
char *extss; /* extern sym string space (in core) */
int iextMax; /* maximum number of Symbols */
pEXTR extsyms; /* extern syms */
dlRStatus relocStatus; /* what relocation needed? */
int needReloc;
JmpTbl *jmptable; /* the jump table for R_JMPADDR */
struct dlFile *next; /* next member of the archive */
} dlFile;
typedef struct dlSymbol
{
char *name; /* name of the symbol */
long addr; /* address of the symbol */
dlFile *objFile; /* from which file */
} dlSymbol;
/*
* prototypes for the dl* interface
*/
extern void *dl_open( /* char *filename, int mode */ );
extern void *dl_sym( /* void *handle, char *name */ );
extern void dl_close( /* void *handle */ );
extern char *dl_error( /* void */ );
#define DL_LAZY 0 /* lazy resolution */
#define DL_NOW 1 /* immediate resolution */
/*
* Miscellaneous utility routines:
*/
extern char **dl_undefinedSymbols( /* int *count */ );
extern void dl_printAllSymbols( /* void *handle */ );
extern void dl_setLibraries( /* char *libs */ );
#endif /* _DL_HEADER_ */
| {
"content_hash": "51cbf6da9f00a966310896920bacdaf6",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 59,
"avg_line_length": 26.54639175257732,
"alnum_prop": 0.6532038834951456,
"repo_name": "edespino/gpdb",
"id": "ae92709d6336ac42e9d4a96349d5e9a66836aead",
"size": "3001",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "src/backend/port/dynloader/ultrix4.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "3737"
},
{
"name": "Batchfile",
"bytes": "11369"
},
{
"name": "C",
"bytes": "36580146"
},
{
"name": "C++",
"bytes": "3396346"
},
{
"name": "CMake",
"bytes": "17118"
},
{
"name": "CSS",
"bytes": "7407"
},
{
"name": "Csound Score",
"bytes": "164"
},
{
"name": "DTrace",
"bytes": "3746"
},
{
"name": "Fortran",
"bytes": "14777"
},
{
"name": "GDB",
"bytes": "576"
},
{
"name": "Gherkin",
"bytes": "740582"
},
{
"name": "HTML",
"bytes": "354931"
},
{
"name": "Java",
"bytes": "186576"
},
{
"name": "JavaScript",
"bytes": "23969"
},
{
"name": "Lex",
"bytes": "195794"
},
{
"name": "M4",
"bytes": "97709"
},
{
"name": "Makefile",
"bytes": "440584"
},
{
"name": "Objective-C",
"bytes": "42255"
},
{
"name": "PLSQL",
"bytes": "218116"
},
{
"name": "PLpgSQL",
"bytes": "5424886"
},
{
"name": "Perl",
"bytes": "3911633"
},
{
"name": "Perl 6",
"bytes": "8302"
},
{
"name": "Python",
"bytes": "8130606"
},
{
"name": "Roff",
"bytes": "39530"
},
{
"name": "Ruby",
"bytes": "26862"
},
{
"name": "SQLPL",
"bytes": "3939815"
},
{
"name": "Shell",
"bytes": "571615"
},
{
"name": "XS",
"bytes": "8405"
},
{
"name": "XSLT",
"bytes": "5779"
},
{
"name": "Yacc",
"bytes": "519516"
}
],
"symlink_target": ""
} |
package com.intellij.ide.ui;
import com.intellij.ide.IdeBundle;
import com.intellij.openapi.options.BaseConfigurable;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Dictionary;
import java.util.Hashtable;
/**
* @author Eugene Belyaev
*/
public class AppearanceConfigurable extends BaseConfigurable implements SearchableConfigurable {
private MyComponent myComponent;
public String getDisplayName() {
return IdeBundle.message("title.appearance");
}
public JComponent createComponent() {
myComponent = new MyComponent();
DefaultComboBoxModel aModel = new DefaultComboBoxModel(UIUtil.getValidFontNames(false));
myComponent.myFontCombo.setModel(aModel);
myComponent.myFontSizeCombo.setModel(new DefaultComboBoxModel(UIUtil.getStandardFontSizes()));
myComponent.myFontSizeCombo.setEditable(true);
// myComponent.myLafComboBox=new JComboBox(LafManager.getInstance().getInstalledLookAndFeels());
myComponent.myLafComboBox.setModel(new DefaultComboBoxModel(LafManager.getInstance().getInstalledLookAndFeels()));
myComponent.myLafComboBox.setRenderer(new MyLafComboBoxRenderer());
myComponent.myEnableAlphaModeCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean state = myComponent.myEnableAlphaModeCheckBox.isSelected();
myComponent.myAlphaModeDelayTextField.setEnabled(state);
myComponent.myAlphaModeRatioSlider.setEnabled(state);
}
});
myComponent.myAlphaModeRatioSlider.setSize(100, 50);
Dictionary<Integer, JLabel> dictionary = new Hashtable<Integer, JLabel>();
dictionary.put(new Integer(0), new JLabel("0%"));
dictionary.put(new Integer(50), new JLabel("50%"));
dictionary.put(new Integer(100), new JLabel("100%"));
myComponent.myAlphaModeRatioSlider.setLabelTable(dictionary);
UIUtil.setSliderIsFilled(myComponent.myAlphaModeRatioSlider, Boolean.TRUE);
myComponent.myAlphaModeRatioSlider.setPaintLabels(true);
myComponent.myAlphaModeRatioSlider.setPaintTicks(true);
myComponent.myAlphaModeRatioSlider.setPaintTrack(true);
myComponent.myAlphaModeRatioSlider.setMajorTickSpacing(50);
myComponent.myAlphaModeRatioSlider.setMinorTickSpacing(10);
myComponent.myAlphaModeRatioSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
myComponent.myAlphaModeRatioSlider.setToolTipText(myComponent.myAlphaModeRatioSlider.getValue() + "%");
}
});
myComponent.myTransparencyPanel.setVisible(WindowManagerEx.getInstanceEx().isAlphaModeSupported());
return myComponent.myPanel;
}
public Icon getIcon() {
return IconLoader.getIcon("/general/configurableAppearance.png");
}
public void apply() {
UISettings settings = UISettings.getInstance();
String temp = (String)myComponent.myFontSizeCombo.getEditor().getItem();
int _fontSize = -1;
if (temp != null && temp.trim().length() > 0) {
try {
_fontSize = Integer.parseInt(temp);
}
catch (NumberFormatException ex) {
}
if (_fontSize <= 0) {
_fontSize = settings.FONT_SIZE;
}
}
else {
_fontSize = settings.FONT_SIZE;
}
boolean shouldUpdateUI = false;
String _fontFace = (String)myComponent.myFontCombo.getSelectedItem();
LafManager lafManager = LafManager.getInstance();
if (_fontSize != settings.FONT_SIZE || !settings.FONT_FACE.equals(_fontFace)) {
settings.FONT_SIZE = _fontSize;
settings.FONT_FACE = _fontFace;
shouldUpdateUI = true;
}
settings.ANIMATE_WINDOWS = myComponent.myAnimateWindowsCheckBox.isSelected();
boolean update = settings.SHOW_TOOL_WINDOW_NUMBERS != myComponent.myWindowShortcutsCheckBox.isSelected();
settings.SHOW_TOOL_WINDOW_NUMBERS = myComponent.myWindowShortcutsCheckBox.isSelected();
update |= settings.HIDE_TOOL_STRIPES != !myComponent.myShowToolStripesCheckBox.isSelected();
settings.HIDE_TOOL_STRIPES = !myComponent.myShowToolStripesCheckBox.isSelected();
update |= settings.SHOW_ICONS_IN_MENUS != myComponent.myCbDisplayIconsInMenu.isSelected();
settings.SHOW_ICONS_IN_MENUS = myComponent.myCbDisplayIconsInMenu.isSelected();
update |= settings.SHOW_MEMORY_INDICATOR != myComponent.myShowMemoryIndicatorCheckBox.isSelected();
settings.SHOW_MEMORY_INDICATOR = myComponent.myShowMemoryIndicatorCheckBox.isSelected();
update |= settings.CYCLE_SCROLLING != myComponent.myCycleScrollingCheckBox.isSelected();
settings.CYCLE_SCROLLING = myComponent.myCycleScrollingCheckBox.isSelected();
if (settings.OVERRIDE_NONIDEA_LAF_FONTS != myComponent.myOverrideLAFFonts.isSelected()) {
shouldUpdateUI = true;
}
settings.OVERRIDE_NONIDEA_LAF_FONTS = myComponent.myOverrideLAFFonts.isSelected();
settings.MOVE_MOUSE_ON_DEFAULT_BUTTON = myComponent.myMoveMouseOnDefaultButtonCheckBox.isSelected();
update |= settings.DISABLE_MNEMONICS != myComponent.myDisableMnemonics.isSelected();
settings.DISABLE_MNEMONICS = myComponent.myDisableMnemonics.isSelected();
update |= settings.SHOW_ICONS_IN_QUICK_NAVIGATION != myComponent.myHideIconsInQuickNavigation.isSelected();
settings.SHOW_ICONS_IN_QUICK_NAVIGATION = myComponent.myHideIconsInQuickNavigation.isSelected();
if (!Comparing.equal(myComponent.myLafComboBox.getSelectedItem(), lafManager.getCurrentLookAndFeel())) {
update = shouldUpdateUI = true;
lafManager.setCurrentLookAndFeel((UIManager.LookAndFeelInfo)myComponent.myLafComboBox.getSelectedItem());
}
if (shouldUpdateUI) {
lafManager.updateUI();
}
if (WindowManagerEx.getInstanceEx().isAlphaModeSupported()) {
int delay = -1;
try {
delay = Integer.parseInt(myComponent.myAlphaModeDelayTextField.getText());
}
catch (NumberFormatException ignored) {
}
float ratio = myComponent.myAlphaModeRatioSlider.getValue() / 100f;
if (myComponent.myEnableAlphaModeCheckBox.isSelected() != settings.ENABLE_ALPHA_MODE ||
delay != -1 && delay != settings.ALPHA_MODE_DELAY || ratio != settings.ALPHA_MODE_RATIO) {
update = true;
settings.ENABLE_ALPHA_MODE = myComponent.myEnableAlphaModeCheckBox.isSelected();
settings.ALPHA_MODE_DELAY = delay;
settings.ALPHA_MODE_RATIO = ratio;
}
}
if (update) {
settings.fireUISettingsChanged();
}
myComponent.updateCombo();
}
public void reset() {
UISettings settings = UISettings.getInstance();
myComponent.myFontCombo.setSelectedItem(settings.FONT_FACE);
myComponent.myFontSizeCombo.setSelectedItem(Integer.toString(settings.FONT_SIZE));
myComponent.myAnimateWindowsCheckBox.setSelected(settings.ANIMATE_WINDOWS);
myComponent.myWindowShortcutsCheckBox.setSelected(settings.SHOW_TOOL_WINDOW_NUMBERS);
myComponent.myShowToolStripesCheckBox.setSelected(!settings.HIDE_TOOL_STRIPES);
myComponent.myCbDisplayIconsInMenu.setSelected(settings.SHOW_ICONS_IN_MENUS);
myComponent.myShowMemoryIndicatorCheckBox.setSelected(settings.SHOW_MEMORY_INDICATOR);
myComponent.myCycleScrollingCheckBox.setSelected(settings.CYCLE_SCROLLING);
myComponent.myHideIconsInQuickNavigation.setSelected(settings.SHOW_ICONS_IN_QUICK_NAVIGATION);
myComponent.myMoveMouseOnDefaultButtonCheckBox.setSelected(settings.MOVE_MOUSE_ON_DEFAULT_BUTTON);
myComponent.myLafComboBox.setSelectedItem(LafManager.getInstance().getCurrentLookAndFeel());
myComponent.myOverrideLAFFonts.setSelected(settings.OVERRIDE_NONIDEA_LAF_FONTS);
myComponent.myDisableMnemonics.setSelected(settings.DISABLE_MNEMONICS);
boolean alphaModeEnabled = WindowManagerEx.getInstanceEx().isAlphaModeSupported();
if (alphaModeEnabled) {
myComponent.myEnableAlphaModeCheckBox.setSelected(settings.ENABLE_ALPHA_MODE);
}
else {
myComponent.myEnableAlphaModeCheckBox.setSelected(false);
}
myComponent.myEnableAlphaModeCheckBox.setEnabled(alphaModeEnabled);
myComponent.myAlphaModeDelayTextField.setText(Integer.toString(settings.ALPHA_MODE_DELAY));
myComponent.myAlphaModeDelayTextField.setEnabled(alphaModeEnabled && settings.ENABLE_ALPHA_MODE);
int ratio = (int)(settings.ALPHA_MODE_RATIO * 100f);
myComponent.myAlphaModeRatioSlider.setValue(ratio);
myComponent.myAlphaModeRatioSlider.setToolTipText(ratio + "%");
myComponent.myAlphaModeRatioSlider.setEnabled(alphaModeEnabled && settings.ENABLE_ALPHA_MODE);
myComponent.updateCombo();
}
public boolean isModified() {
UISettings settings = UISettings.getInstance();
boolean isModified = false;
isModified |= !Comparing.equal(myComponent.myFontCombo.getSelectedItem(), settings.FONT_FACE);
isModified |= !Comparing.equal(myComponent.myFontSizeCombo.getEditor().getItem(), Integer.toString(settings.FONT_SIZE));
isModified |= myComponent.myAnimateWindowsCheckBox.isSelected() != settings.ANIMATE_WINDOWS;
isModified |= myComponent.myWindowShortcutsCheckBox.isSelected() != settings.SHOW_TOOL_WINDOW_NUMBERS;
isModified |= myComponent.myShowToolStripesCheckBox.isSelected() == settings.HIDE_TOOL_STRIPES;
isModified |= myComponent.myCbDisplayIconsInMenu.isSelected() != settings.SHOW_ICONS_IN_MENUS;
isModified |= myComponent.myShowMemoryIndicatorCheckBox.isSelected() != settings.SHOW_MEMORY_INDICATOR;
isModified |= myComponent.myCycleScrollingCheckBox.isSelected() != settings.CYCLE_SCROLLING;
isModified |= myComponent.myOverrideLAFFonts.isSelected() != settings.OVERRIDE_NONIDEA_LAF_FONTS;
isModified |= myComponent.myDisableMnemonics.isSelected() != settings.DISABLE_MNEMONICS;
isModified |= myComponent.myHideIconsInQuickNavigation.isSelected() != settings.SHOW_ICONS_IN_QUICK_NAVIGATION;
isModified |= myComponent.myMoveMouseOnDefaultButtonCheckBox.isSelected() != settings.MOVE_MOUSE_ON_DEFAULT_BUTTON;
isModified |= !Comparing.equal(myComponent.myLafComboBox.getSelectedItem(), LafManager.getInstance().getCurrentLookAndFeel());
if (WindowManagerEx.getInstanceEx().isAlphaModeSupported()) {
isModified |= myComponent.myEnableAlphaModeCheckBox.isSelected() != settings.ENABLE_ALPHA_MODE;
int delay = -1;
try {
delay = Integer.parseInt(myComponent.myAlphaModeDelayTextField.getText());
}
catch (NumberFormatException ignored) {
}
if (delay != -1) {
isModified |= delay != settings.ALPHA_MODE_DELAY;
}
float ratio = myComponent.myAlphaModeRatioSlider.getValue() / 100f;
isModified |= ratio != settings.ALPHA_MODE_RATIO;
}
return isModified;
}
private static boolean isModified(JTextField textField, int value) {
try {
int fieldValue = Integer.parseInt(textField.getText().trim());
return fieldValue != value;
}
catch (NumberFormatException e) {
return false;
}
}
private static boolean isModified(JToggleButton checkBox, boolean value) {
return checkBox.isSelected() != value;
}
public void disposeUIResources() {
// if (myComponent == null)
myComponent = null;
}
public String getHelpTopic() {
return "preferences.lookFeel";
}
private static final class MyLafComboBoxRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
UIManager.LookAndFeelInfo laf = (UIManager.LookAndFeelInfo)value;
return super.getListCellRendererComponent(list, laf == null ? null : laf.getName(), index, isSelected, cellHasFocus);
}
}
private static class MyComponent {
JPanel myPanel;
private JComboBox myFontCombo;
private JComboBox myFontSizeCombo;
private JCheckBox myAnimateWindowsCheckBox;
private JCheckBox myWindowShortcutsCheckBox;
private JCheckBox myShowToolStripesCheckBox;
private JCheckBox myShowMemoryIndicatorCheckBox;
private JComboBox myLafComboBox;
private JCheckBox myCycleScrollingCheckBox;
private JCheckBox myMoveMouseOnDefaultButtonCheckBox;
private JCheckBox myEnableAlphaModeCheckBox;
private JTextField myAlphaModeDelayTextField;
private JSlider myAlphaModeRatioSlider;
private JLabel myFontSizeLabel;
private JLabel myFontNameLabel;
private JPanel myTransparencyPanel;
private JCheckBox myOverrideLAFFonts;
private JLabel myIDEALafFont;
private JCheckBox myHideIconsInQuickNavigation;
private JCheckBox myCbDisplayIconsInMenu;
private JCheckBox myDisableMnemonics;
public MyComponent() {
ActionListener updater = new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateCombo();
}
};
myLafComboBox.addActionListener(updater);
myOverrideLAFFonts.addActionListener(updater);
myIDEALafFont.setPreferredSize(new Dimension(myIDEALafFont.getPreferredSize().width, myOverrideLAFFonts.getPreferredSize().height));
myCbDisplayIconsInMenu.setVisible(SystemInfo.isMac);
}
public void updateCombo() {
UIManager.LookAndFeelInfo selectedLAF = (UIManager.LookAndFeelInfo)myLafComboBox.getSelectedItem();
//noinspection HardCodedStringLiteral
boolean isIdeaLAFSelected = selectedLAF != null && selectedLAF.getName().startsWith("IDEA");
myIDEALafFont.setVisible(isIdeaLAFSelected);
myOverrideLAFFonts.setVisible(!isIdeaLAFSelected);
boolean enableChooser = isIdeaLAFSelected || myOverrideLAFFonts.isSelected();
myFontCombo.setEnabled(enableChooser);
myFontSizeCombo.setEnabled(enableChooser);
myFontNameLabel.setEnabled(enableChooser);
myFontSizeLabel.setEnabled(enableChooser);
}
}
public String getId() {
return getHelpTopic();
}
@Nullable
public Runnable enableSearch(String option) {
return null;
}
}
| {
"content_hash": "f13419e1a15dce883870c00fe60f0737",
"timestamp": "",
"source": "github",
"line_count": 334,
"max_line_length": 138,
"avg_line_length": 43.01197604790419,
"alnum_prop": 0.7559515522762077,
"repo_name": "jexp/idea2",
"id": "ca6d6d1d70f583c9946fee47274e82041cdeb166",
"size": "14966",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "platform/platform-impl/src/com/intellij/ide/ui/AppearanceConfigurable.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "6350"
},
{
"name": "C#",
"bytes": "103"
},
{
"name": "C++",
"bytes": "30760"
},
{
"name": "Erlang",
"bytes": "10"
},
{
"name": "Java",
"bytes": "72888555"
},
{
"name": "JavaScript",
"bytes": "910"
},
{
"name": "PHP",
"bytes": "133"
},
{
"name": "Perl",
"bytes": "6523"
},
{
"name": "Shell",
"bytes": "4068"
}
],
"symlink_target": ""
} |
Tests are not included in the package, clone the repository and install dependencies to run the test suite:
```
npm test
```
| {
"content_hash": "6ffa0e2637340c838bcec2e7d379e5ca",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 107,
"avg_line_length": 25.2,
"alnum_prop": 0.753968253968254,
"repo_name": "freeformsystems/cli-command",
"id": "9f4311b188ea1f4254334001fe9b618899bd2c03",
"size": "135",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "doc/readme/test.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "123937"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.