text stringlengths 2 1.04M | meta dict |
|---|---|
<html>
<head>
<title>fork</title>
<body bgcolor=#ffffff>
<h2 align=center>fork</h2>
<h4 align=center>OS/161 Reference Manual</h4>
<h3>Name</h3>
fork - copy the current process
<h3>Library</h3>
Standard C Library (libc, -lc)
<h3>Synopsis</h3>
#include <unistd.h><br>
<br>
pid_t<br>
fork(void);
<h3>Description</h3>
fork duplicates the currently running process. The two copies are
identical, except that one (the "new" one, or "child"), has a new,
unique process id, and in the other (the "parent") the process id is
unchanged.
<p>
The process id must be greater than 0.
<p>
The two processes do not share memory or open file tables; this state
is copied into the new process, and subsequent modification in one
process does not affect the other.
<p>
However, the file handle objects the file tables point to are shared,
so, for instance, calls to lseek in one process can affect the other.
<p>
<h3>Return Values</h3>
On success, fork returns twice, once in the parent process and once in
the child process. In the child process, 0 is returned. In the parent
process, the process id of the new child process is returned.
<p>
On error, no new process is created, fork only returns once, returning
-1, and <A HREF=errno.html>errno</A> is set according to the error
encountered.
<h3>Errors</h3>
The following error codes should be returned under the conditions
given. Other error codes may be returned for other errors not
mentioned here.
<blockquote><table width=90%>
<tr><td width=10%> </td><td> </td></tr>
<tr><td>EAGAIN</td> <td>Too many processes already exist.</td></tr>
<tr><td>ENOMEM</td> <td>Sufficient virtual memory for the new
process was not available.</td></tr>
</table></blockquote>
</body>
</html>
| {
"content_hash": "a155428029b31f80341c966f94644269",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 70,
"avg_line_length": 27.28125,
"alnum_prop": 0.7302405498281787,
"repo_name": "nyanzebra/Operating-Systems",
"id": "0f41987a1a3f592fe80fa48b312de8a083c0240f",
"size": "1746",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "project5/Project 5 Source/src/man/syscall/fork.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "79473"
},
{
"name": "C",
"bytes": "1872769"
},
{
"name": "C++",
"bytes": "15868"
},
{
"name": "Makefile",
"bytes": "212823"
},
{
"name": "Objective-C",
"bytes": "12424"
},
{
"name": "Shell",
"bytes": "80301"
}
],
"symlink_target": ""
} |
package com.google.code.chatterbotapi;
public class ChatterBotThought {
private String[] emotions;
private String text;
public String[] getEmotions() {
return emotions;
}
public void setEmotions(String[] emotions) {
this.emotions = emotions;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
} | {
"content_hash": "710b4985ea87fb4d67ebc53de1f2fd34",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 48,
"avg_line_length": 18.217391304347824,
"alnum_prop": 0.6181384248210023,
"repo_name": "Kitt3120/ViperBot",
"id": "7cd83fadba39591512d379b8575f8381060f81d2",
"size": "1172",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "src/com/google/code/chatterbotapi/ChatterBotThought.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "113730"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/VscoForMuzei.iml" filepath="$PROJECT_DIR$/VscoForMuzei.iml" />
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
</modules>
</component>
</project> | {
"content_hash": "baddba92ab4cecef31ff58579625abf1",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 106,
"avg_line_length": 40.111111111111114,
"alnum_prop": 0.6648199445983379,
"repo_name": "varunoberoi/VscoForMuzei",
"id": "5ec6aee779d687098fd98ea74193f749fa9d23e7",
"size": "361",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/modules.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "27155"
}
],
"symlink_target": ""
} |
using System;
using System.Xml;
namespace fyiReporting.RDL
{
///<summary>
/// A Row in a data set.
///</summary>
internal class Row
{
int _RowNumber; // Original row #
int _Level; // Usually 0; set when row is part of group with ParentGroup (ie recursive hierarchy)
GroupEntry _GroupEntry; // like level;
Rows _R; // Owner of row collection
object[] _Data; // Row of data
internal Row(Rows r, Row rd) // Constructor that uses existing Row data
{
_R = r;
_Data = rd.Data;
_Level = rd.Level;
}
internal Row(Rows r, int columnCount)
{
_R = r;
_Data = new object[columnCount];
_Level=0;
}
internal object[] Data
{
get { return _Data; }
set { _Data = value; }
}
internal Rows R
{
get { return _R; }
set { _R = value; }
}
internal GroupEntry GroupEntry
{
get { return _GroupEntry; }
set { _GroupEntry = value; }
}
internal int Level
{
get { return _Level; }
set { _Level = value; }
}
internal int RowNumber
{
get { return _RowNumber; }
set { _RowNumber = value; }
}
}
}
| {
"content_hash": "56a272d357b21cc4d829a3362999660e",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 101,
"avg_line_length": 17.476190476190474,
"alnum_prop": 0.5831062670299727,
"repo_name": "gregberns/ZipRdlProjectDev410",
"id": "76c58880ee339f9b4bf5e15907e3eaf31055f77b",
"size": "1945",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/RdlEngine/Definition/Row.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "14489"
},
{
"name": "C#",
"bytes": "4799366"
},
{
"name": "JavaScript",
"bytes": "41119"
},
{
"name": "Shell",
"bytes": "1135"
},
{
"name": "Smalltalk",
"bytes": "207560"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<Document>
<Sentence>
<value>Arteries are blood vessels that carry blood from the heart to other places in your body.</value>
<pattern_crowdsource> Arteries are [[blood vessels|C0005847]] that carry [[blood|C0005767]] from the heart to other places in your body. </pattern_crowdsource>
<annotations>
<annotation>
<surface-form>Arteries</surface-form>
<RDF-ID>C0003842</RDF-ID>
</annotation>
<annotation>
<surface-form>blood vessels</surface-form>
<RDF-ID>C0005847</RDF-ID>
</annotation>
<annotation>
<surface-form>blood</surface-form>
<RDF-ID>C0005767</RDF-ID>
</annotation>
<annotation>
<surface-form>heart</surface-form>
<RDF-ID>C0018787</RDF-ID>
</annotation>
<annotation>
<surface-form>places</surface-form>
<RDF-ID>C0442504</RDF-ID>
</annotation>
</annotations>
<triples>
<triple>C0005767 PART_OF C0005847</triple>
</triples>
</Sentence>
<Sentence>
<value>One of the most common causes of arterial insufficiency is atherosclerosis or "hardening of the arteries."</value>
<pattern_crowdsource> One of the most common causes of arterial insufficiency is [[atherosclerosis|C0004153]] or "[[hardening|C0702118]] of the [[arteries|C0003842]]." </pattern_crowdsource>
<annotations>
<annotation>
<surface-form>One</surface-form>
<RDF-ID>C0205447</RDF-ID>
</annotation>
<annotation>
<surface-form>most</surface-form>
<RDF-ID>C0205393</RDF-ID>
</annotation>
<annotation>
<surface-form>common</surface-form>
<RDF-ID>C0205214</RDF-ID>
</annotation>
<annotation>
<surface-form>causes</surface-form>
<RDF-ID>C0015127</RDF-ID>
</annotation>
<annotation>
<surface-form>arterial insufficiency</surface-form>
<RDF-ID>C0003834</RDF-ID>
</annotation>
<annotation>
<surface-form>atherosclerosis</surface-form>
<RDF-ID>C0004153</RDF-ID>
</annotation>
<annotation>
<surface-form>hardening</surface-form>
<RDF-ID>C0702118</RDF-ID>
</annotation>
<annotation>
<surface-form>arteries</surface-form>
<RDF-ID>C0003842</RDF-ID>
</annotation>
</annotations>
<triples>
<triple>C0003842 LOCATION_OF C0702118</triple>
<triple>C0003842 LOCATION_OF C0004153</triple>
</triples>
</Sentence>
<Sentence>
<value>Clots can form on the plaque or travel from another place in the heart or artery (also called embolus).</value>
<pattern_crowdsource> Clots can form on the [[plaque|C0333463]] or travel from another place in the [[heart|C0018787]] or [[artery|C0003842]] (also called embolus). </pattern_crowdsource>
<annotations>
<annotation>
<surface-form>plaque</surface-form>
<RDF-ID>C0333463</RDF-ID>
</annotation>
<annotation>
<surface-form>travel</surface-form>
<RDF-ID>C0040802</RDF-ID>
</annotation>
<annotation>
<surface-form>place</surface-form>
<RDF-ID>C0442504</RDF-ID>
</annotation>
<annotation>
<surface-form>heart</surface-form>
<RDF-ID>C0018787</RDF-ID>
</annotation>
<annotation>
<surface-form>artery</surface-form>
<RDF-ID>C0003842</RDF-ID>
</annotation>
<annotation>
<surface-form>embolus</surface-form>
<RDF-ID>C0013922</RDF-ID>
</annotation>
</annotations>
<triples>
<triple>C0018787 LOCATION_OF C0333463</triple>
<triple>C0003842 LOCATION_OF C0333463</triple>
</triples>
</Sentence>
</Document>
| {
"content_hash": "ba48d299e1ebc3e981eeb31efaf088de",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 193,
"avg_line_length": 30.9009009009009,
"alnum_prop": 0.6819241982507288,
"repo_name": "pvougiou/KB-Text-Alignment",
"id": "d49749e8421d3efe64acd56cdf036513195340df",
"size": "3430",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Data/MedlinePlus/XML/0000314.xml",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "OpenEdge ABL",
"bytes": "611292"
},
{
"name": "Python",
"bytes": "72310"
}
],
"symlink_target": ""
} |
package io.aeron.driver.cmd;
import io.aeron.driver.Sender;
public interface SenderCmd
{
void execute(Sender sender);
}
| {
"content_hash": "9a7eb825ff7f8d5646a0d0a7c26dfce3",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 32,
"avg_line_length": 14.11111111111111,
"alnum_prop": 0.7480314960629921,
"repo_name": "oleksiyp/Aeron",
"id": "3e40fed0d16416770cd4a4e7604da716b0846df0",
"size": "726",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aeron-driver/src/main/java/io/aeron/driver/cmd/SenderCmd.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "570"
},
{
"name": "C++",
"bytes": "491858"
},
{
"name": "CMake",
"bytes": "12769"
},
{
"name": "Java",
"bytes": "1488160"
},
{
"name": "Shell",
"bytes": "314"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="style/style.css" >
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>
<body>
<div>
<nav class="navbar navbar-default">
<div class="container-fluid">
<ul class="nav navbar-link col-xs-12">
<li>
<a href="page-list.html" class="nav navbar-brand">
<span class="glyphicon glyphicon-menu-left"></span>
</a>
</li>
<li>
<a href="" class="nav navbar-brand">
<span>Widget Edit</span>
</a>
</li>
<li class="nav navbar-right">
<a href="widget-chooser.html" class="nav navbar-brand">
<span class="glyphicon glyphicon-plus"></span>
</a>
</li>
</ul>
</div>
<ul class="nav navbar-default navbar-fixed-bottom col-xs-12">
<li>
<a href="" class="nav navbar-brand">
<span class="glyphicon glyphicon-play"></span>
</a>
</li>
<li>
<a href="" class="nav navbar-brand">
<span class="glyphicon glyphicon-eye-open"></span>
</a>
</li>
<li class="nav navbar-right">
<a href="profile.html" class="nav navbar-brand">
<span class="glyphicon glyphicon-user"></span>
</a>
</li>
</ul>
</nav>
<div class="container-fluid">
<div class="col-xs-12">
<div class="list-group">
<div class="list-group-item no-border">
<div class="media">
<div class="media-body">
<span class="overlay-icons">
<a class="glyphicon glyphicon-cog text-primary" href="widget-heading.html"></a>
<span class="glyphicon glyphicon-align-justify"></span>
</span>
<h1 class="media-heading">Gizmodo</h1>
</div>
</div>
</div>
<div class="list-group-item no-border">
<div class="media">
<div class="media-body">
<span class="overlay-icons">
<a href="widget-image.html" class="glyphicon glyphicon-cog text-primary"></a>
<span class="glyphicon glyphicon-align-justify"></span>
</span>
<img
src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/cd/Image_Germania_%28painting%29.jpg/158px-Image_Germania_%28painting%29.jpg"
alt="this is the image of a state" />
</div>
</div>
</div>
<div class="list-group-item no-border">
<div class="media">
<div class="media-body">
<span class="overlay-icons">
<a href="widget-youtube.html" class="glyphicon glyphicon-cog text-primary"></a>
<span class="glyphicon glyphicon-align-justify"></span>
</span>
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/9suqmB9X8Q8"></iframe>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
| {
"content_hash": "c66c4ede937dd1f030f4b5320b6b6302",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 177,
"avg_line_length": 52.66990291262136,
"alnum_prop": 0.40442396313364054,
"repo_name": "krishnavikasm/krishna-minnamareddy-webdev-assignments",
"id": "9a98e87c6f91fbb3de799ff72251fbacc1677722",
"size": "5425",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/assignment/assignment2/widget-list.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "140496"
},
{
"name": "HTML",
"bytes": "193983"
},
{
"name": "JavaScript",
"bytes": "723376"
}
],
"symlink_target": ""
} |
package io.jcoder.tutorials.ch05.inheritance.basics;
/**
* Basic example of a class representing an CommercialAirplane (used for Chapter 5).
*
* <p>
* https://jcoder.io/content/course/java/beginners/ch05/inheritance
* </p>
*
* @author Camilo Gonzalez
*/
public class CommercialAirplane extends Airplane {
private int passengersOnBoard;
public void boardPassenger() {
passengersOnBoard++;
}
public int getPassengersOnBoard() {
return passengersOnBoard;
}
}
| {
"content_hash": "b9261b4034138a33a46ab5204e1cc22b",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 84,
"avg_line_length": 20.96,
"alnum_prop": 0.6717557251908397,
"repo_name": "jcoderltd/tutorial-java-basics",
"id": "f76128187305a787c0d13cf62e8fdf7c217440fa",
"size": "561",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/io/jcoder/tutorials/ch05/inheritance/basics/CommercialAirplane.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "103769"
}
],
"symlink_target": ""
} |
<?php
namespace GuestbookTest\Controller;
use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;
class GuestbookControllerTest extends AbstractHttpControllerTestCase
{
public function setUp()
{
$this->setApplicationConfig(
include '/home/epi/09_buszewicz/public_html/zf/config/application.config.php'
);
parent::setUp();
}
public function testIndexActionCanBeAccessed()
{
$this->dispatch('/guestbook');
$this->assertResponseStatusCode(200);
$this->assertModuleName('Guestbook');
$this->assertControllerName('Guestbook\Controller\Index');
$this->assertControllerClass('IndexController');
$this->assertMatchedRouteName('guestbook');
}
}
| {
"content_hash": "393ffb160f2e7efb130756f12f97efbf",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 89,
"avg_line_length": 29.115384615384617,
"alnum_prop": 0.6882430647291942,
"repo_name": "marziolek/zend-app",
"id": "3abef91aeaa28bdb8b80467dda02a471e760ca04",
"size": "757",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "module/Guestbook/test/GuestbookTest/Controller/GuestbookControllerTest.php",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "371701"
},
{
"name": "JavaScript",
"bytes": "77960"
},
{
"name": "PHP",
"bytes": "114130"
}
],
"symlink_target": ""
} |
package com.google.gerrit.server.args4j;
import static com.google.gerrit.util.cli.Localizable.localizable;
import com.google.gerrit.server.util.SocketUtil;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import java.net.SocketAddress;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.OptionDef;
import org.kohsuke.args4j.spi.OptionHandler;
import org.kohsuke.args4j.spi.Parameters;
import org.kohsuke.args4j.spi.Setter;
public class SocketAddressHandler extends OptionHandler<SocketAddress> {
@Inject
public SocketAddressHandler(
@Assisted final CmdLineParser parser,
@Assisted final OptionDef option,
@Assisted final Setter<SocketAddress> setter) {
super(parser, option, setter);
}
@Override
public final int parseArguments(Parameters params) throws CmdLineException {
final String token = params.getParameter(0);
try {
setter.addValue(SocketUtil.parse(token, 0));
} catch (IllegalArgumentException e) {
throw new CmdLineException(owner, localizable(e.getMessage()));
}
return 1;
}
@Override
public final String getDefaultMetaVariable() {
return "HOST:PORT";
}
}
| {
"content_hash": "d0bdfeff8367d7a57395e68bda82e91e",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 78,
"avg_line_length": 30.317073170731707,
"alnum_prop": 0.7626709573612228,
"repo_name": "qtproject/qtqa-gerrit",
"id": "198cf6722ebb39b9fc54eb90b443706f2b84afce",
"size": "1852",
"binary": false,
"copies": "3",
"ref": "refs/heads/upstream/stable-3.0",
"path": "java/com/google/gerrit/server/args4j/SocketAddressHandler.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "48801"
},
{
"name": "GAP",
"bytes": "4303"
},
{
"name": "Go",
"bytes": "1865"
},
{
"name": "Groff",
"bytes": "28221"
},
{
"name": "HTML",
"bytes": "57863"
},
{
"name": "Java",
"bytes": "8471079"
},
{
"name": "JavaScript",
"bytes": "1590"
},
{
"name": "Makefile",
"bytes": "1313"
},
{
"name": "PLpgSQL",
"bytes": "4462"
},
{
"name": "Perl",
"bytes": "9943"
},
{
"name": "Prolog",
"bytes": "17711"
},
{
"name": "Python",
"bytes": "7074"
},
{
"name": "Shell",
"bytes": "47588"
}
],
"symlink_target": ""
} |
import { monacoTypes } from '@grafana/ui';
import {
multiLineFullQuery,
singleLineFullQuery,
singleLineEmptyQuery,
singleLineTwoQueries,
} from '../../__mocks__/cloudwatch-sql-test-data';
import MonacoMock from '../../__mocks__/monarch/Monaco';
import TextModel from '../../__mocks__/monarch/TextModel';
import { linkedTokenBuilder } from '../../monarch/linkedTokenBuilder';
import { StatementPosition } from '../../monarch/types';
import cloudWatchSqlLanguageDefinition from '../definition';
import { getStatementPosition } from './statementPosition';
import { SQLTokenTypes } from './types';
describe('statementPosition', () => {
function assertPosition(query: string, position: monacoTypes.IPosition, expected: StatementPosition) {
const testModel = TextModel(query);
const current = linkedTokenBuilder(
MonacoMock,
cloudWatchSqlLanguageDefinition,
testModel as monacoTypes.editor.ITextModel,
position,
SQLTokenTypes
);
const statementPosition = getStatementPosition(current);
expect(statementPosition).toBe(expected);
}
test.each([
[singleLineFullQuery.query, { lineNumber: 1, column: 0 }],
[multiLineFullQuery.query, { lineNumber: 1, column: 0 }],
[singleLineEmptyQuery.query, { lineNumber: 1, column: 0 }],
[singleLineTwoQueries.query, { lineNumber: 1, column: 154 }],
])('should be before select keyword', (query: string, position: monacoTypes.IPosition) => {
assertPosition(query, position, StatementPosition.SelectKeyword);
});
test.each([
[singleLineFullQuery.query, { lineNumber: 1, column: 7 }],
[multiLineFullQuery.query, { lineNumber: 1, column: 7 }],
[singleLineTwoQueries.query, { lineNumber: 1, column: 161 }],
])('should be after select keyword', (query: string, position: monacoTypes.IPosition) => {
assertPosition(query, position, StatementPosition.AfterSelectKeyword);
});
test.each([
[singleLineFullQuery.query, { lineNumber: 1, column: 12 }],
[multiLineFullQuery.query, { lineNumber: 1, column: 12 }],
[singleLineTwoQueries.query, { lineNumber: 1, column: 166 }],
])('should be first argument in select statistic function', (query: string, position: monacoTypes.IPosition) => {
assertPosition(query, position, StatementPosition.AfterSelectFuncFirstArgument);
});
test.each([
[singleLineFullQuery.query, { lineNumber: 1, column: 27 }],
[multiLineFullQuery.query, { lineNumber: 2, column: 0 }],
[singleLineTwoQueries.query, { lineNumber: 1, column: 181 }],
])('should be before the FROM keyword', (query: string, position: monacoTypes.IPosition) => {
assertPosition(query, position, StatementPosition.FromKeyword);
});
test.each([
[singleLineFullQuery.query, { lineNumber: 1, column: 32 }],
[multiLineFullQuery.query, { lineNumber: 2, column: 5 }],
[singleLineTwoQueries.query, { lineNumber: 1, column: 186 }],
])('should after the FROM keyword', (query: string, position: monacoTypes.IPosition) => {
assertPosition(query, position, StatementPosition.AfterFromKeyword);
});
test.each([
[singleLineFullQuery.query, { lineNumber: 1, column: 40 }],
[multiLineFullQuery.query, { lineNumber: 2, column: 13 }],
[singleLineTwoQueries.query, { lineNumber: 1, column: 40 }],
])('should be namespace arg in the schema func', (query: string, position: monacoTypes.IPosition) => {
assertPosition(query, position, StatementPosition.SchemaFuncFirstArgument);
});
test.each([
[singleLineFullQuery.query, { lineNumber: 1, column: 50 }],
[multiLineFullQuery.query, { lineNumber: 2, column: 23 }],
[singleLineTwoQueries.query, { lineNumber: 1, column: 50 }],
])('should be label key args within the schema func', (query: string, position: monacoTypes.IPosition) => {
assertPosition(query, position, StatementPosition.SchemaFuncExtraArgument);
});
test.each([
[singleLineFullQuery.query, { lineNumber: 1, column: 63 }],
[multiLineFullQuery.query, { lineNumber: 3, column: 0 }],
[singleLineTwoQueries.query, { lineNumber: 1, column: 63 }],
])('should be after from schema/namespace', (query: string, position: monacoTypes.IPosition) => {
assertPosition(query, position, StatementPosition.AfterFrom);
});
test.each([
[singleLineFullQuery.query, { lineNumber: 1, column: 69 }],
[multiLineFullQuery.query, { lineNumber: 4, column: 6 }],
[singleLineTwoQueries.query, { lineNumber: 1, column: 69 }],
])('should after where keyword and before label key', (query: string, position: monacoTypes.IPosition) => {
assertPosition(query, position, StatementPosition.WhereKey);
});
test.each([
[singleLineFullQuery.query, { lineNumber: 1, column: 79 }],
[multiLineFullQuery.query, { lineNumber: 4, column: 17 }],
[singleLineTwoQueries.query, { lineNumber: 1, column: 79 }],
])('should be before the comparison operator in a where filter', (query: string, position: monacoTypes.IPosition) => {
assertPosition(query, position, StatementPosition.WhereComparisonOperator);
});
test.each([
[singleLineFullQuery.query, { lineNumber: 1, column: 81 }],
[multiLineFullQuery.query, { lineNumber: 4, column: 19 }],
[singleLineTwoQueries.query, { lineNumber: 1, column: 81 }],
])('should be before or in the value in a where filter', (query: string, position: monacoTypes.IPosition) => {
assertPosition(query, position, StatementPosition.WhereValue);
});
test.each([
[singleLineFullQuery.query, { lineNumber: 1, column: 105 }],
[multiLineFullQuery.query, { lineNumber: 5, column: 0 }],
[singleLineTwoQueries.query, { lineNumber: 1, column: 105 }],
])('should be after a where value', (query: string, position: monacoTypes.IPosition) => {
assertPosition(query, position, StatementPosition.AfterWhereValue);
});
test.each([
[singleLineFullQuery.query, { lineNumber: 1, column: 115 }],
[multiLineFullQuery.query, { lineNumber: 5, column: 10 }],
[singleLineTwoQueries.query, { lineNumber: 1, column: 115 }],
])('should be after group by keywords', (query: string, position: monacoTypes.IPosition) => {
assertPosition(query, position, StatementPosition.AfterGroupByKeywords);
});
test.each([
[singleLineFullQuery.query, { lineNumber: 1, column: 123 }],
[multiLineFullQuery.query, { lineNumber: 5, column: 22 }],
[singleLineTwoQueries.query, { lineNumber: 1, column: 123 }],
])('should be after group by labels', (query: string, position: monacoTypes.IPosition) => {
assertPosition(query, position, StatementPosition.AfterGroupBy);
});
test.each([
[singleLineFullQuery.query, { lineNumber: 1, column: 132 }],
[multiLineFullQuery.query, { lineNumber: 5, column: 31 }],
[singleLineTwoQueries.query, { lineNumber: 1, column: 132 }],
])('should be after order by keywords', (query: string, position: monacoTypes.IPosition) => {
assertPosition(query, position, StatementPosition.AfterOrderByKeywords);
});
test.each([
[singleLineFullQuery.query, { lineNumber: 1, column: 138 }],
[multiLineFullQuery.query, { lineNumber: 5, column: 37 }],
[singleLineTwoQueries.query, { lineNumber: 1, column: 138 }],
])('should be after order by function', (query: string, position: monacoTypes.IPosition) => {
assertPosition(query, position, StatementPosition.AfterOrderByFunction);
});
test.each([
[singleLineFullQuery.query, { lineNumber: 1, column: 143 }],
[multiLineFullQuery.query, { lineNumber: 6, column: 0 }],
[singleLineTwoQueries.query, { lineNumber: 1, column: 145 }],
])('should be after order by direction', (query: string, position: monacoTypes.IPosition) => {
assertPosition(query, position, StatementPosition.AfterOrderByDirection);
});
});
| {
"content_hash": "8404afebbba158fd99b92829d841dab3",
"timestamp": "",
"source": "github",
"line_count": 167,
"max_line_length": 120,
"avg_line_length": 46.49101796407186,
"alnum_prop": 0.6983513652756311,
"repo_name": "GridProtectionAlliance/openHistorian",
"id": "40ed83ee21ac6986ea1c46474307048beee66b9b",
"size": "7764",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Source/Applications/openHistorian/openHistorian/Grafana/public/app/plugins/datasource/cloudwatch/cloudwatch-sql/completion/statementPosition.test.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "114"
},
{
"name": "Batchfile",
"bytes": "15193"
},
{
"name": "C#",
"bytes": "5416175"
},
{
"name": "CSS",
"bytes": "34695"
},
{
"name": "CUE",
"bytes": "17648"
},
{
"name": "Go",
"bytes": "1562"
},
{
"name": "HTML",
"bytes": "975678"
},
{
"name": "JavaScript",
"bytes": "1301988"
},
{
"name": "PLSQL",
"bytes": "122550"
},
{
"name": "PowerShell",
"bytes": "1071"
},
{
"name": "Rich Text Format",
"bytes": "37561"
},
{
"name": "SCSS",
"bytes": "227212"
},
{
"name": "Shell",
"bytes": "41513"
},
{
"name": "TSQL",
"bytes": "267652"
},
{
"name": "TypeScript",
"bytes": "12607989"
}
],
"symlink_target": ""
} |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsxs)(React.Fragment, {
children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M14.47 13.5L11 20v-5.5H9l.53-1H7V22h10v-8.5h-2.53z"
}), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
fillOpacity: ".3",
d: "M17 4h-3V2h-4v2H7v9.5h2.53L13 7v5.5h2l-.53 1H17V4z"
})]
}), 'BatteryCharging50Sharp');
exports.default = _default; | {
"content_hash": "66886a12c1f6a3858c40e65c5c884253",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 804,
"avg_line_length": 90.57142857142857,
"alnum_prop": 0.6987381703470031,
"repo_name": "mui-org/material-ui",
"id": "0ddf0d452f7668f32ae02f40d3030a18b76067dc",
"size": "1902",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/mui-icons-material/lib/BatteryCharging50Sharp.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2126"
},
{
"name": "JavaScript",
"bytes": "4120512"
},
{
"name": "TypeScript",
"bytes": "3263233"
}
],
"symlink_target": ""
} |
from google.cloud import monitoring_v3
async def sample_delete_alert_policy():
# Create a client
client = monitoring_v3.AlertPolicyServiceAsyncClient()
# Initialize request argument(s)
request = monitoring_v3.DeleteAlertPolicyRequest(
name="name_value",
)
# Make the request
await client.delete_alert_policy(request=request)
# [END monitoring_v3_generated_AlertPolicyService_DeleteAlertPolicy_async]
| {
"content_hash": "5fec666b196d7566603a081ad5ec7b5d",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 74,
"avg_line_length": 26,
"alnum_prop": 0.7375565610859729,
"repo_name": "googleapis/python-monitoring",
"id": "e1b3565227b20a9fe10d3db8391f3074be7843e3",
"size": "1847",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "samples/generated_samples/monitoring_v3_generated_alert_policy_service_delete_alert_policy_async.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2050"
},
{
"name": "Python",
"bytes": "2375818"
},
{
"name": "Shell",
"bytes": "30672"
}
],
"symlink_target": ""
} |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'certified'}
DOCUMENTATION = '''
---
module: azure_rm_storageblob
short_description: Manage blob containers and blob objects.
version_added: "2.1"
description:
- Create, update and delete blob containers and blob objects. Use to upload a file and store it as a blob object,
or download a blob object to a file.
options:
storage_account_name:
description:
- Name of the storage account to use.
required: true
aliases:
- account_name
- storage_account
blob:
description:
- Name of a blob object within the container.
required: false
default: null
aliases:
- blob_name
container:
description:
- Name of a blob container within the storage account.
required: true
aliases:
- container_name
content_type:
description:
- Set the blob content-type header. For example, 'image/png'.
default: null
required: false
cache_control:
description:
- Set the blob cache-control header.
required: false
default: null
content_disposition:
description:
- Set the blob content-disposition header.
required: false
default: null
content_encoding:
description:
- Set the blob encoding header.
required: false
default: null
content_language:
description:
- Set the blob content-language header.
required: false
default: null
content_md5:
description:
- Set the blob md5 hash value.
required: false
default: null
dest:
description:
- Destination file path. Use with state 'present' to download a blob.
aliases:
- destination
required: false
default: null
force:
description:
- Overwrite existing blob or file when uploading or downloading. Force deletion of a container
that contains blobs.
default: false
required: false
resource_group:
description:
- Name of the resource group to use.
required: true
aliases:
- resource_group_name
src:
description:
- Source file path. Use with state 'present' to upload a blob.
aliases:
- source
required: false
default: null
state:
description:
- Assert the state of a container or blob.
- Use state 'absent' with a container value only to delete a container. Include a blob value to remove
a specific blob. A container will not be deleted, if it contains blobs. Use the force option to override,
deleting the container and all associated blobs.
- Use state 'present' to create or update a container and upload or download a blob. If the container
does not exist, it will be created. If it exists, it will be updated with configuration options. Provide
a blob name and either src or dest to upload or download. Provide a src path to upload and a dest path
to download. If a blob (uploading) or a file (downloading) already exists, it will not be overwritten
unless the force parameter is true.
default: present
required: false
choices:
- absent
- present
public_access:
description:
- Determine a container's level of public access. By default containers are private. Can only be set at
time of container creation.
required: false
default: null
choices:
- container
- blob
extends_documentation_fragment:
- azure
- azure_tags
author:
- "Chris Houseknecht (@chouseknecht)"
- "Matt Davis (@nitzmahone)"
'''
EXAMPLES = '''
- name: Remove container foo
azure_rm_storageblob:
resource_group: testing
storage_account_name: clh0002
container: foo
state: absent
- name: Create container foo and upload a file
azure_rm_storageblob:
resource_group: Testing
storage_account_name: clh0002
container: foo
blob: graylog.png
src: ./files/graylog.png
public_access: container
content_type: 'application/image'
- name: Download the file
azure_rm_storageblob:
resource_group: Testing
storage_account_name: clh0002
container: foo
blob: graylog.png
dest: ~/tmp/images/graylog.png
'''
RETURN = '''
blob:
description: Facts about the current state of the blob.
returned: when a blob is operated on
type: dict
sample: {
"content_length": 136532,
"content_settings": {
"cache_control": null,
"content_disposition": null,
"content_encoding": null,
"content_language": null,
"content_md5": null,
"content_type": "application/image"
},
"last_modified": "09-Mar-2016 22:08:25 +0000",
"name": "graylog.png",
"tags": {},
"type": "BlockBlob"
}
container:
description: Facts about the current state of the selected container.
returned: always
type: dict
sample: {
"last_mdoified": "09-Mar-2016 19:28:26 +0000",
"name": "foo",
"tags": {}
}
'''
import os
try:
from azure.storage.blob.models import ContentSettings
from azure.common import AzureMissingResourceHttpError, AzureHttpError
except ImportError:
# This is handled in azure_rm_common
pass
from ansible.module_utils.azure_rm_common import AzureRMModuleBase
class AzureRMStorageBlob(AzureRMModuleBase):
def __init__(self):
self.module_arg_spec = dict(
storage_account_name=dict(required=True, type='str', aliases=['account_name', 'storage_account']),
blob=dict(type='str', aliases=['blob_name']),
container=dict(required=True, type='str', aliases=['container_name']),
dest=dict(type='str'),
force=dict(type='bool', default=False),
resource_group=dict(required=True, type='str', aliases=['resource_group_name']),
src=dict(type='str'),
state=dict(type='str', default='present', choices=['absent', 'present']),
public_access=dict(type='str', choices=['container', 'blob']),
content_type=dict(type='str'),
content_encoding=dict(type='str'),
content_language=dict(type='str'),
content_disposition=dict(type='str'),
cache_control=dict(type='str'),
content_md5=dict(type='str'),
)
mutually_exclusive = [('src', 'dest')]
self.blob_client = None
self.blob_details = None
self.storage_account_name = None
self.blob = None
self.blob_obj = None
self.container = None
self.container_obj = None
self.dest = None
self.force = None
self.resource_group = None
self.src = None
self.state = None
self.tags = None
self.public_access = None
self.results = dict(
changed=False,
actions=[],
container=dict(),
blob=dict()
)
super(AzureRMStorageBlob, self).__init__(derived_arg_spec=self.module_arg_spec,
supports_check_mode=True,
mutually_exclusive=mutually_exclusive,
supports_tags=True)
def exec_module(self, **kwargs):
for key in list(self.module_arg_spec.keys()) + ['tags']:
setattr(self, key, kwargs[key])
self.results['check_mode'] = self.check_mode
# add file path validation
self.blob_client = self.get_blob_client(self.resource_group, self.storage_account_name)
self.container_obj = self.get_container()
if self.blob is not None:
self.blob_obj = self.get_blob()
if self.state == 'present':
if not self.container_obj:
# create the container
self.create_container()
elif self.container_obj and not self.blob:
# update container attributes
update_tags, self.container_obj['tags'] = self.update_tags(self.container_obj.get('tags'))
if update_tags:
self.update_container_tags(self.container_obj['tags'])
if self.blob:
# create, update or download blob
if self.src and self.src_is_valid():
if self.blob_obj and not self.force:
self.log("Cannot upload to {0}. Blob with that name already exists. "
"Use the force option".format(self.blob))
else:
self.upload_blob()
elif self.dest and self.dest_is_valid():
self.download_blob()
update_tags, self.blob_obj['tags'] = self.update_tags(self.blob_obj.get('tags'))
if update_tags:
self.update_blob_tags(self.blob_obj['tags'])
if self.blob_content_settings_differ():
self.update_blob_content_settings()
elif self.state == 'absent':
if self.container_obj and not self.blob:
# Delete container
if self.container_has_blobs():
if self.force:
self.delete_container()
else:
self.log("Cannot delete container {0}. It contains blobs. Use the force option.".format(
self.container))
else:
self.delete_container()
elif self.container_obj and self.blob_obj:
# Delete blob
self.delete_blob()
# until we sort out how we want to do this globally
del self.results['actions']
return self.results
def get_container(self):
result = dict()
container = None
if self.container:
try:
container = self.blob_client.get_container_properties(self.container)
except AzureMissingResourceHttpError:
pass
if container:
result = dict(
name=container.name,
tags=container.metadata,
last_mdoified=container.properties.last_modified.strftime('%d-%b-%Y %H:%M:%S %z'),
)
return result
def get_blob(self):
result = dict()
blob = None
if self.blob:
try:
blob = self.blob_client.get_blob_properties(self.container, self.blob)
except AzureMissingResourceHttpError:
pass
if blob:
result = dict(
name=blob.name,
tags=blob.metadata,
last_modified=blob.properties.last_modified.strftime('%d-%b-%Y %H:%M:%S %z'),
type=blob.properties.blob_type,
content_length=blob.properties.content_length,
content_settings=dict(
content_type=blob.properties.content_settings.content_type,
content_encoding=blob.properties.content_settings.content_encoding,
content_language=blob.properties.content_settings.content_language,
content_disposition=blob.properties.content_settings.content_disposition,
cache_control=blob.properties.content_settings.cache_control,
content_md5 =blob.properties.content_settings.content_md5
)
)
return result
def create_container(self):
self.log('Create container %s' % self.container)
tags = None
if not self.blob and self.tags:
# when a blob is present, then tags are assigned at the blob level
tags = self.tags
if not self.check_mode:
try:
self.blob_client.create_container(self.container, metadata=tags, public_access=self.public_access)
except AzureHttpError as exc:
self.fail("Error creating container {0} - {1}".format(self.container, str(exc)))
self.container_obj = self.get_container()
self.results['changed'] = True
self.results['actions'].append('created container {0}'.format(self.container))
self.results['container'] = self.container_obj
def upload_blob(self):
content_settings = None
if self.content_type or self.content_encoding or self.content_language or self.content_disposition or \
self.cache_control or self.content_md5:
content_settings = ContentSettings(
content_type=self.content_type,
content_encoding=self.content_encoding,
content_language=self.content_language,
content_disposition=self.content_disposition,
cache_control=self.cache_control,
content_md5=self.content_md5
)
if not self.check_mode:
try:
self.blob_client.create_blob_from_path(self.container, self.blob, self.src,
metadata=self.tags, content_settings=content_settings)
except AzureHttpError as exc:
self.fail("Error creating blob {0} - {1}".format(self.blob, str(exc)))
self.blob_obj = self.get_blob()
self.results['changed'] = True
self.results['actions'].append('created blob {0} from {1}'.format(self.blob, self.src))
self.results['container'] = self.container_obj
self.results['blob'] = self.blob_obj
def download_blob(self):
if not self.check_mode:
try:
self.blob_client.get_blob_to_path(self.container, self.blob, self.dest)
except Exception as exc:
self.fail("Failed to download blob {0}:{1} to {2} - {3}".format(self.container,
self.blob,
self.dest,
exc))
self.results['changed'] = True
self.results['actions'].append('downloaded blob {0}:{1} to {2}'.format(self.container,
self.blob,
self.dest))
self.results['container'] = self.container_obj
self.results['blob'] = self.blob_obj
def src_is_valid(self):
if not os.path.isfile(self.src):
self.fail("The source path must be a file.")
try:
fp = open(self.src, 'r')
fp.close()
except IOError:
self.fail("Failed to access {0}. Make sure the file exists and that you have "
"read access.".format(self.src))
return True
def dest_is_valid(self):
if not self.check_mode:
self.dest = os.path.expanduser(self.dest)
self.dest = os.path.expandvars(self.dest)
if not os.path.basename(self.dest):
# dest is a directory
if os.path.isdir(self.dest):
self.log("Path is dir. Appending blob name.")
self.dest += self.blob
else:
try:
self.log('Attempting to makedirs {0}'.format(self.dest))
os.makddirs(self.dest)
except IOError as exc:
self.fail("Failed to create directory {0} - {1}".format(self.dest, str(exc)))
self.dest += self.blob
else:
# does path exist without basename
file_name = os.path.basename(self.dest)
path = self.dest.replace(file_name, '')
self.log('Checking path {0}'.format(path))
if not os.path.isdir(path):
try:
self.log('Attempting to makedirs {0}'.format(path))
os.makedirs(path)
except IOError as exc:
self.fail("Failed to create directory {0} - {1}".format(path, str(exc)))
self.log('Checking final path {0}'.format(self.dest))
if os.path.isfile(self.dest) and not self.force:
# dest already exists and we're not forcing
self.log("Dest {0} already exists. Cannot download. Use the force option.".format(self.dest))
return False
return True
def delete_container(self):
if not self.check_mode:
try:
self.blob_client.delete_container(self.container)
except AzureHttpError as exc:
self.fail("Error deleting container {0} - {1}".format(self.container, str(exc)))
self.results['changed'] = True
self.results['actions'].append('deleted container {0}'.format(self.container))
def container_has_blobs(self):
try:
list_generator = self.blob_client.list_blobs(self.container)
except AzureHttpError as exc:
self.fail("Error list blobs in {0} - {1}".format(self.container, str(exc)))
if len(list_generator.items) > 0:
return True
return False
def delete_blob(self):
if not self.check_mode:
try:
self.blob_client.delete_blob(self.container, self.blob)
except AzureHttpError as exc:
self.fail("Error deleting blob {0}:{1} - {2}".format(self.container, self.blob, str(exc)))
self.results['changed'] = True
self.results['actions'].append('deleted blob {0}:{1}'.format(self.container, self.blob))
self.results['container'] = self.container_obj
def update_container_tags(self, tags):
if not self.check_mode:
try:
self.blob_client.set_container_metadata(self.container, metadata=tags)
except AzureHttpError as exc:
self.fail("Error updating container tags {0} - {1}".format(self.container, str(exc)))
self.container_obj = self.get_container()
self.results['changed'] = True
self.results['actions'].append("updated container {0} tags.".format(self.container))
self.results['container'] = self.container_obj
def update_blob_tags(self, tags):
if not self.check_mode:
try:
self.blob_client.set_blob_metadata(self.container, self.blob, metadata=tags)
except AzureHttpError as exc:
self.fail("Update blob tags {0}:{1} - {2}".format(self.container, self.blob, str(exc)))
self.blob_obj = self.get_blob()
self.results['changed'] = True
self.results['actions'].append("updated blob {0}:{1} tags.".format(self.container, self.blob))
self.results['container'] = self.container_obj
self.results['blob'] = self.blob_obj
def blob_content_settings_differ(self):
if self.content_type or self.content_encoding or self.content_language or self.content_disposition or \
self.cache_control or self.content_md5:
settings = dict(
content_type=self.content_type,
content_encoding=self.content_encoding,
content_language=self.content_language,
content_disposition=self.content_disposition,
cache_control=self.cache_control,
content_md5=self.content_md5
)
if self.blob_obj['content_settings'] != settings:
return True
return False
def update_blob_content_settings(self):
content_settings = ContentSettings(
content_type=self.content_type,
content_encoding=self.content_encoding,
content_language=self.content_language,
content_disposition=self.content_disposition,
cache_control=self.cache_control,
content_md5=self.content_md5
)
if not self.check_mode:
try:
self.blob_client.set_blob_properties(self.container, self.blob, content_settings=content_settings)
except AzureHttpError as exc:
self.fail("Update blob content settings {0}:{1} - {2}".format(self.container, self.blob, str(exc)))
self.blob_obj = self.get_blob()
self.results['changed'] = True
self.results['actions'].append("updated blob {0}:{1} content settings.".format(self.container, self.blob))
self.results['container'] = self.container_obj
self.results['blob'] = self.blob_obj
def main():
AzureRMStorageBlob()
if __name__ == '__main__':
main()
| {
"content_hash": "fed3041f07f3e13c202ab788fca16d0a",
"timestamp": "",
"source": "github",
"line_count": 555,
"max_line_length": 119,
"avg_line_length": 38.5981981981982,
"alnum_prop": 0.5597983381570348,
"repo_name": "e-gob/plataforma-kioscos-autoatencion",
"id": "c92d9cc708867b77e0bc261a25814fcd41b7eb09",
"size": "21651",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/modules/cloud/azure/azure_rm_storageblob.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "41110"
},
{
"name": "C++",
"bytes": "3804"
},
{
"name": "CSS",
"bytes": "34823"
},
{
"name": "CoffeeScript",
"bytes": "8521"
},
{
"name": "HTML",
"bytes": "61168"
},
{
"name": "JavaScript",
"bytes": "7206"
},
{
"name": "Makefile",
"bytes": "1347"
},
{
"name": "PowerShell",
"bytes": "584344"
},
{
"name": "Python",
"bytes": "25506593"
},
{
"name": "Ruby",
"bytes": "245726"
},
{
"name": "Shell",
"bytes": "5075"
}
],
"symlink_target": ""
} |
'use strict';
var Image = require('Image');
var React = require('React');
var StyleSheet = require('StyleSheet');
var { Text, Heading1, Paragraph } = require('F8Text');
var ProfilePicture = require('../../common/ProfilePicture');
var View = require('View');
var { connect } = require('react-redux');
import type {State as User} from '../../reducers/user';
class SharingSettingsCommon extends React.Component {
props: {
user: User;
style: any;
};
render() {
const {user} = this.props;
const title = user.name && (
<View style={styles.title}>
<ProfilePicture userID={user.id} size={24} />
<Text style={styles.name}>
{user.name.split(' ')[0] + "'"}s Schedule
</Text>
</View>
);
return (
<View style={[styles.container, this.props.style]}>
<Image style={styles.image} source={require('./img/sharing-nux.png')}>
{title}
</Image>
<View style={styles.content}>
<Heading1 style={styles.h1}>
Let friends view your schedule in the F8 app?
</Heading1>
<Paragraph style={styles.p}>
This will not post to Facebook. Only friends using the F8 app will
be able to see your schedule in their My F8 tab.
</Paragraph>
</View>
</View>
);
}
}
var styles = StyleSheet.create({
container: {
alignItems: 'center',
},
image: {
height: 250,
alignSelf: 'center',
alignItems: 'center',
justifyContent: 'center',
},
content: {
padding: 18,
alignItems: 'center',
},
h1: {
textAlign: 'center',
},
p: {
marginTop: 10,
textAlign: 'center',
},
title: {
marginTop: 40,
flexDirection: 'row',
alignItems: 'center',
backgroundColor: 'transparent',
},
name: {
fontSize: 12,
color: 'white',
marginLeft: 10,
fontWeight: 'bold',
},
});
function select(store) {
return {
user: store.user,
};
}
module.exports = connect(select)(SharingSettingsCommon);
| {
"content_hash": "893c96fa680b6a3063af569f2487284d",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 78,
"avg_line_length": 22.384615384615383,
"alnum_prop": 0.5758468335787923,
"repo_name": "josedab/react-native-examples",
"id": "9ee372f7079d3729a9ea9ebe9e73a2d2deec6437",
"size": "3120",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "meetup-information/js/tabs/schedule/SharingSettingsCommon.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "5516"
},
{
"name": "JavaScript",
"bytes": "386970"
},
{
"name": "Objective-C",
"bytes": "14748"
},
{
"name": "Python",
"bytes": "1545"
},
{
"name": "Ruby",
"bytes": "1329"
},
{
"name": "Shell",
"bytes": "2382"
}
],
"symlink_target": ""
} |
package requests
import "errors"
// Add errors here
var (
ErrNotFound = errors.New("Request not found")
)
| {
"content_hash": "d912052f8839824777f536fd5370efa0",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 46,
"avg_line_length": 13.625,
"alnum_prop": 0.7155963302752294,
"repo_name": "Zandrr/heketi",
"id": "43ac2e83f724fc1070b87b722f083f2cc595deb7",
"size": "711",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "_prototype/requets/errors.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "187347"
},
{
"name": "Python",
"bytes": "1605"
},
{
"name": "Shell",
"bytes": "1347"
}
],
"symlink_target": ""
} |
package org.seaborne.delta;
import static org.apache.jena.atlas.lib.ThreadLib.async;
import java.util.concurrent.Semaphore;
import org.apache.jena.atlas.lib.Lib;
import org.apache.jena.sparql.core.DatasetGraph;
import org.apache.jena.system.Txn;
import org.junit.Test;
import org.seaborne.delta.client.*;
import org.seaborne.delta.link.DeltaLink;
public abstract class AbstractTestDeltaLogLock {
abstract protected DeltaLink getDLink();
protected static Id dsRef;
private static boolean VERBOSE = false;
@Test public void testAcquireLock() {
if ( VERBOSE ) {
System.out.println("testAcquireLock");
LogLock.verbose();
LogLockMgr.verbose();
}
DeltaLink dLink = getDLink();
LogLockMgr mgr = new LogLockMgr(dLink);
// Drive the LogLockMgr manually.
// Do not start the background thread.
LogLock lock = new LogLock(dLink, dsRef);
LogLock lock2 = new LogLock(dLink, dsRef);
if ( VERBOSE )
System.out.println("Acquire 1");
lock.acquireLock();
mgr.add(lock); // Check on begin.
async(()->{
if ( VERBOSE )
System.out.println("Pause and refresh");
// Refresh a few times and stop
for ( int i = 0 ; i < 5 ; i++ ) {
Lib.sleep(750);
mgr.refresh();
}
if ( VERBOSE )
System.out.println("Stop refresh");
});
// Start a delayed operation to release the lock.
async(()->{
Lib.sleep(1000);
if ( VERBOSE )
System.out.println("Release");
lock.releaseLock();
if ( VERBOSE )
System.out.println("Remove");
mgr.remove(lock);
});
// Acquire by the other java object.
if ( VERBOSE )
System.out.println("Acquire 2");
boolean b = lock2.acquireLock();
lock2.releaseLock();
if ( VERBOSE )
System.out.println("End - testAcquireLock");
}
@Test public void testContendTxn() {
if ( VERBOSE ) {
System.out.println("testContendTxn");
LogLock.verbose();
//LogLock.testMode();
LogLockMgr.verbose();
}
Zone zone1 = Zone.connectMem();
DeltaClient dClient1 = DeltaClient.create(zone1, getDLink());
Zone zone2 = Zone.connectMem();
DeltaClient dClient2 = DeltaClient.create(zone2, getDLink());
// Two mirrors - same log
DeltaConnection dConn1 = dClient1.register(dsRef, LocalStorageType.MEM,SyncPolicy.TXN_RW);
DeltaConnection dConn2 = dClient2.register(dsRef, LocalStorageType.MEM,SyncPolicy.TXN_RW);
LogLockMgr mgr = new LogLockMgr(getDLink());
mgr.start();
Semaphore sema1 = new Semaphore(0);
Semaphore sema2 = new Semaphore(0);
Runnable r = ()-> {
DatasetGraph dsg1 = dConn1.getDatasetGraph();
Txn.executeWrite(dsg1, ()->{
if ( VERBOSE )
System.out.println("1: In Txn");
sema1.release();
// Long wait.
Lib.sleep(2000);
if ( VERBOSE )
System.out.println("1: Leave Txn");
});
if ( VERBOSE )
System.out.println("1: Left Txn");
sema2.release();
};
try {
async(r);
sema1.acquire();
// LockState state = dLink.readLock(dConn1.getDataSourceId());
// System.out.println(state);
if ( VERBOSE )
System.out.println("2: Enter Txn");
DatasetGraph dsg2 = dConn2.getDatasetGraph();
Txn.executeWrite(dsg2, ()->{
if ( VERBOSE )
System.out.println("2: In Txn");
});
if ( VERBOSE )
System.out.println("2: Left Txn");
sema2.acquire();
if ( VERBOSE )
System.out.println("End - testContendTxn");
}
catch (Exception ex) { ex.printStackTrace(); }
}
}
| {
"content_hash": "8afdfef3658e791dac30680057f46510",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 98,
"avg_line_length": 30.25179856115108,
"alnum_prop": 0.5326991676575505,
"repo_name": "afs/rdf-delta",
"id": "c9d8f352c4cc377b5e42845348731218d5ffa830",
"size": "4891",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "rdf-delta-integration-tests/src/test/java/org/seaborne/delta/AbstractTestDeltaLogLock.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1510869"
},
{
"name": "Shell",
"bytes": "6757"
},
{
"name": "Thrift",
"bytes": "4002"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using PioViewerApi.Plugin;
using PioViewerApi.Server;
namespace PioViewerPlugins.Aggregation
{
public class MultipleFlopsAggregationAnalysisPlugin : IServerPlugin
{
#region Identification
public string Name
{
get { return "Multiple Files runouts aggregated frequencies analysis"; }
}
public string Category
{
get { return "Aggregation"; }
}
public bool IsGUIPlugin
{
get { return false; }
}
#endregion
#region plugin initialization
protected IServerPluginContext Context { get; private set; }
protected IServerPlayer OOP, IP;
public void Initialize(IServerPluginContext context)
{
this.Context = context;
this.OOP = context.ServerUtils.OOP;
this.IP = context.ServerUtils.IP;
}
#endregion
public void Execute(IPluginProgressProvider progress)
{
var node = Context.Controller.SelectedNode;
if (node == null)
{
throw new InvalidOperationException("The aggregated analysis can only be run when action node is selected");
}
progress.UpdateProgress("Started");
AggregationRunner result = new AggregationRunner(node, progress, this.Context);
result.CFRFilePaths = new List<string>();
if (Context.Controller.CurrentFileName == null)
{
throw new InvalidOperationException("Unknown location of current tree.");
}
var dirName = Path.GetDirectoryName(Context.Controller.CurrentFileName);
var files = Directory.GetFiles(dirName, "*.cfr");
var msg = "Perform analysis over " + files.Length + " files in " + dirName + "?" +Environment.NewLine + "Please not that it only makes sense if all trees are identical except for the board.";
var dialogResult = MessageBox.Show(msg, "Confirm aggregation?", MessageBoxButtons.YesNoCancel);
if (dialogResult == DialogResult.Yes)
{
result.CFRFilePaths.AddRange(files);
result.RunReport();
var fileName = Context.Controller.CurrentFileName;
progress.UpdateProgress("Generating intro");
}
}
}
}
| {
"content_hash": "41ce20f0c70ea762789592217b56d1b0",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 203,
"avg_line_length": 32.58974358974359,
"alnum_prop": 0.6129032258064516,
"repo_name": "kuba97531/pioViewerPlugins",
"id": "c7bef53273ad6681c4f12d458fc38846860cefdc",
"size": "2544",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PioViewerPlugins/Aggregation/MultipleFlopsAggregationAnalysisPlugin.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "71200"
}
],
"symlink_target": ""
} |
import static com.google.flatbuffers.Constants.*;
import MyGame.Example.*;
import optional_scalars.ScalarStuff;
import optional_scalars.OptionalByte;
import MyGame.MonsterExtra;
import NamespaceA.*;
import NamespaceA.NamespaceB.*;
import com.google.flatbuffers.ByteBufferUtil;
import com.google.flatbuffers.ByteVector;
import com.google.flatbuffers.FlatBufferBuilder;
import com.google.flatbuffers.FlexBuffers;
import com.google.flatbuffers.FlexBuffersBuilder;
import com.google.flatbuffers.StringVector;
import com.google.flatbuffers.UnionVector;
import com.google.flatbuffers.FlexBuffers.FlexBufferException;
import com.google.flatbuffers.FlexBuffers.Reference;
import com.google.flatbuffers.FlexBuffers.Vector;
import com.google.flatbuffers.ArrayReadWriteBuf;
import com.google.flatbuffers.FlexBuffers.KeyVector;
import java.io.*;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
class JavaTest {
public static void main(String[] args) {
// First, let's test reading a FlatBuffer generated by C++ code:
// This file was generated from monsterdata_test.json
byte[] data = null;
File file = new File("monsterdata_test.mon");
RandomAccessFile f = null;
try {
f = new RandomAccessFile(file, "r");
data = new byte[(int)f.length()];
f.readFully(data);
f.close();
} catch(java.io.IOException e) {
System.out.println("FlatBuffers test: couldn't read file");
return;
}
// Now test it:
ByteBuffer bb = ByteBuffer.wrap(data);
TestBuffer(bb);
// Second, let's create a FlatBuffer from scratch in Java, and test it also.
// We use an initial size of 1 to exercise the reallocation algorithm,
// normally a size larger than the typical FlatBuffer you generate would be
// better for performance.
FlatBufferBuilder fbb = new FlatBufferBuilder(1);
TestBuilderBasics(fbb, true);
TestBuilderBasics(fbb, false);
TestExtendedBuffer(fbb.dataBuffer().asReadOnlyBuffer());
TestNamespaceNesting();
TestNestedFlatBuffer();
TestCreateByteVector();
TestCreateUninitializedVector();
TestByteBufferFactory();
TestSizedInputStream();
TestVectorOfUnions();
TestFixedLengthArrays();
TestFlexBuffers();
TestVectorOfBytes();
TestSharedStringPool();
TestScalarOptional();
TestPackUnpack(bb);
System.out.println("FlatBuffers test: completed successfully");
}
static void TestEnums() {
TestEq(Color.name(Color.Red), "Red");
TestEq(Color.name(Color.Blue), "Blue");
TestEq(Any.name(Any.NONE), "NONE");
TestEq(Any.name(Any.Monster), "Monster");
}
static void TestBuffer(ByteBuffer bb) {
TestEq(Monster.MonsterBufferHasIdentifier(bb), true);
Monster monster = Monster.getRootAsMonster(bb);
TestEq(monster.hp(), (short)80);
TestEq(monster.mana(), (short)150); // default
TestEq(monster.name(), "MyMonster");
// monster.friendly() // can't access, deprecated
Vec3 pos = monster.pos();
TestEq(pos.x(), 1.0f);
TestEq(pos.y(), 2.0f);
TestEq(pos.z(), 3.0f);
TestEq(pos.test1(), 3.0);
// issue: int != byte
TestEq(pos.test2(), (int) Color.Green);
Test t = pos.test3();
TestEq(t.a(), (short)5);
TestEq(t.b(), (byte)6);
TestEq(monster.testType(), (byte)Any.Monster);
Monster monster2 = new Monster();
TestEq(monster.test(monster2) != null, true);
TestEq(monster2.name(), "Fred");
TestEq(monster.inventoryLength(), 5);
int invsum = 0;
for (int i = 0; i < monster.inventoryLength(); i++)
invsum += monster.inventory(i);
TestEq(invsum, 10);
// Method using a vector access object:
ByteVector inventoryVector = monster.inventoryVector();
TestEq(inventoryVector.length(), 5);
invsum = 0;
for (int i = 0; i < inventoryVector.length(); i++)
invsum += inventoryVector.getAsUnsigned(i);
TestEq(invsum, 10);
// Alternative way of accessing a vector:
ByteBuffer ibb = monster.inventoryAsByteBuffer();
invsum = 0;
while (ibb.position() < ibb.limit())
invsum += ibb.get();
TestEq(invsum, 10);
Test test_0 = monster.test4(0);
Test test_1 = monster.test4(1);
TestEq(monster.test4Length(), 2);
TestEq(test_0.a() + test_0.b() + test_1.a() + test_1.b(), 100);
Test.Vector test4Vector = monster.test4Vector();
test_0 = test4Vector.get(0);
test_1 = test4Vector.get(1);
TestEq(test4Vector.length(), 2);
TestEq(test_0.a() + test_0.b() + test_1.a() + test_1.b(), 100);
TestEq(monster.testarrayofstringLength(), 2);
TestEq(monster.testarrayofstring(0),"test1");
TestEq(monster.testarrayofstring(1),"test2");
// Method using a vector access object:
StringVector testarrayofstringVector = monster.testarrayofstringVector();
TestEq(testarrayofstringVector.length(), 2);
TestEq(testarrayofstringVector.get(0),"test1");
TestEq(testarrayofstringVector.get(1),"test2");
TestEq(monster.testbool(), true);
}
// this method checks additional fields not present in the binary buffer read from file
// these new tests are performed on top of the regular tests
static void TestExtendedBuffer(ByteBuffer bb) {
TestBuffer(bb);
Monster monster = Monster.getRootAsMonster(bb);
TestEq(monster.testhashu32Fnv1(), Integer.MAX_VALUE + 1L);
}
static void TestNamespaceNesting() {
// reference / manipulate these to verify compilation
FlatBufferBuilder fbb = new FlatBufferBuilder(1);
TableInNestedNS.startTableInNestedNS(fbb);
TableInNestedNS.addFoo(fbb, 1234);
int nestedTableOff = TableInNestedNS.endTableInNestedNS(fbb);
TableInFirstNS.startTableInFirstNS(fbb);
TableInFirstNS.addFooTable(fbb, nestedTableOff);
int off = TableInFirstNS.endTableInFirstNS(fbb);
}
static void TestNestedFlatBuffer() {
final String nestedMonsterName = "NestedMonsterName";
final short nestedMonsterHp = 600;
final short nestedMonsterMana = 1024;
FlatBufferBuilder fbb1 = new FlatBufferBuilder(16);
int str1 = fbb1.createString(nestedMonsterName);
Monster.startMonster(fbb1);
Monster.addName(fbb1, str1);
Monster.addHp(fbb1, nestedMonsterHp);
Monster.addMana(fbb1, nestedMonsterMana);
int monster1 = Monster.endMonster(fbb1);
Monster.finishMonsterBuffer(fbb1, monster1);
byte[] fbb1Bytes = fbb1.sizedByteArray();
fbb1 = null;
FlatBufferBuilder fbb2 = new FlatBufferBuilder(16);
int str2 = fbb2.createString("My Monster");
int nestedBuffer = Monster.createTestnestedflatbufferVector(fbb2, fbb1Bytes);
Monster.startMonster(fbb2);
Monster.addName(fbb2, str2);
Monster.addHp(fbb2, (short)50);
Monster.addMana(fbb2, (short)32);
Monster.addTestnestedflatbuffer(fbb2, nestedBuffer);
int monster = Monster.endMonster(fbb2);
Monster.finishMonsterBuffer(fbb2, monster);
// Now test the data extracted from the nested buffer
Monster mons = Monster.getRootAsMonster(fbb2.dataBuffer());
Monster nestedMonster = mons.testnestedflatbufferAsMonster();
TestEq(nestedMonsterMana, nestedMonster.mana());
TestEq(nestedMonsterHp, nestedMonster.hp());
TestEq(nestedMonsterName, nestedMonster.name());
}
static void TestCreateByteVector() {
FlatBufferBuilder fbb = new FlatBufferBuilder(16);
int str = fbb.createString("MyMonster");
byte[] inventory = new byte[] { 0, 1, 2, 3, 4 };
int vec = fbb.createByteVector(inventory);
Monster.startMonster(fbb);
Monster.addInventory(fbb, vec);
Monster.addName(fbb, str);
int monster1 = Monster.endMonster(fbb);
Monster.finishMonsterBuffer(fbb, monster1);
Monster monsterObject = Monster.getRootAsMonster(fbb.dataBuffer());
TestEq(monsterObject.inventory(1), (int)inventory[1]);
TestEq(monsterObject.inventoryLength(), inventory.length);
ByteVector inventoryVector = monsterObject.inventoryVector();
TestEq(inventoryVector.getAsUnsigned(1), (int)inventory[1]);
TestEq(inventoryVector.length(), inventory.length);
TestEq(ByteBuffer.wrap(inventory), monsterObject.inventoryAsByteBuffer());
}
static void TestCreateUninitializedVector() {
FlatBufferBuilder fbb = new FlatBufferBuilder(16);
int str = fbb.createString("MyMonster");
byte[] inventory = new byte[] { 0, 1, 2, 3, 4 };
ByteBuffer bb = fbb.createUnintializedVector(1, inventory.length, 1);
for (byte i:inventory) {
bb.put(i);
}
int vec = fbb.endVector();
Monster.startMonster(fbb);
Monster.addInventory(fbb, vec);
Monster.addName(fbb, str);
int monster1 = Monster.endMonster(fbb);
Monster.finishMonsterBuffer(fbb, monster1);
Monster monsterObject = Monster.getRootAsMonster(fbb.dataBuffer());
TestEq(monsterObject.inventory(1), (int)inventory[1]);
TestEq(monsterObject.inventoryLength(), inventory.length);
ByteVector inventoryVector = monsterObject.inventoryVector();
TestEq(inventoryVector.getAsUnsigned(1), (int)inventory[1]);
TestEq(inventoryVector.length(), inventory.length);
TestEq(ByteBuffer.wrap(inventory), monsterObject.inventoryAsByteBuffer());
}
static void TestByteBufferFactory() {
final class MappedByteBufferFactory extends FlatBufferBuilder.ByteBufferFactory {
@Override
public ByteBuffer newByteBuffer(int capacity) {
ByteBuffer bb;
try {
RandomAccessFile f = new RandomAccessFile("javatest.bin", "rw");
bb = f.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, capacity).order(ByteOrder.LITTLE_ENDIAN);
f.close();
} catch(Throwable e) {
System.out.println("FlatBuffers test: couldn't map ByteBuffer to a file");
bb = null;
}
return bb;
}
}
FlatBufferBuilder fbb = new FlatBufferBuilder(1, new MappedByteBufferFactory());
TestBuilderBasics(fbb, false);
}
static void TestSizedInputStream() {
// Test on default FlatBufferBuilder that uses HeapByteBuffer
FlatBufferBuilder fbb = new FlatBufferBuilder(1);
TestBuilderBasics(fbb, false);
InputStream in = fbb.sizedInputStream();
byte[] array = fbb.sizedByteArray();
int count = 0;
int currentVal = 0;
while (currentVal != -1 && count < array.length) {
try {
currentVal = in.read();
} catch(java.io.IOException e) {
System.out.println("FlatBuffers test: couldn't read from InputStream");
return;
}
TestEq((byte)currentVal, array[count]);
count++;
}
TestEq(count, array.length);
}
static void TestBuilderBasics(FlatBufferBuilder fbb, boolean sizePrefix) {
int[] names = {fbb.createString("Frodo"), fbb.createString("Barney"), fbb.createString("Wilma")};
int[] off = new int[3];
Monster.startMonster(fbb);
Monster.addName(fbb, names[0]);
off[0] = Monster.endMonster(fbb);
Monster.startMonster(fbb);
Monster.addName(fbb, names[1]);
off[1] = Monster.endMonster(fbb);
Monster.startMonster(fbb);
Monster.addName(fbb, names[2]);
off[2] = Monster.endMonster(fbb);
int sortMons = fbb.createSortedVectorOfTables(new Monster(), off);
// We set up the same values as monsterdata.json:
int str = fbb.createString("MyMonster");
int inv = Monster.createInventoryVector(fbb, new byte[] { 0, 1, 2, 3, 4 });
int fred = fbb.createString("Fred");
Monster.startMonster(fbb);
Monster.addName(fbb, fred);
int mon2 = Monster.endMonster(fbb);
Monster.startTest4Vector(fbb, 2);
Test.createTest(fbb, (short)10, (byte)20);
Test.createTest(fbb, (short)30, (byte)40);
int test4 = fbb.endVector();
int testArrayOfString = Monster.createTestarrayofstringVector(fbb, new int[] {
fbb.createString("test1"),
fbb.createString("test2")
});
Monster.startMonster(fbb);
Monster.addPos(fbb, Vec3.createVec3(fbb, 1.0f, 2.0f, 3.0f, 3.0,
Color.Green, (short)5, (byte)6));
Monster.addHp(fbb, (short)80);
Monster.addName(fbb, str);
Monster.addInventory(fbb, inv);
Monster.addTestType(fbb, (byte)Any.Monster);
Monster.addTest(fbb, mon2);
Monster.addTest4(fbb, test4);
Monster.addTestarrayofstring(fbb, testArrayOfString);
Monster.addTestbool(fbb, true);
Monster.addTesthashu32Fnv1(fbb, Integer.MAX_VALUE + 1L);
Monster.addTestarrayoftables(fbb, sortMons);
int mon = Monster.endMonster(fbb);
if (sizePrefix) {
Monster.finishSizePrefixedMonsterBuffer(fbb, mon);
} else {
Monster.finishMonsterBuffer(fbb, mon);
}
// Write the result to a file for debugging purposes:
// Note that the binaries are not necessarily identical, since the JSON
// parser may serialize in a slightly different order than the above
// Java code. They are functionally equivalent though.
try {
String filename = "monsterdata_java_wire" + (sizePrefix ? "_sp" : "") + ".mon";
FileChannel fc = new FileOutputStream(filename).getChannel();
fc.write(fbb.dataBuffer().duplicate());
fc.close();
} catch(java.io.IOException e) {
System.out.println("FlatBuffers test: couldn't write file");
return;
}
// Test it:
ByteBuffer dataBuffer = fbb.dataBuffer();
if (sizePrefix) {
TestEq(ByteBufferUtil.getSizePrefix(dataBuffer) + SIZE_PREFIX_LENGTH,
dataBuffer.remaining());
dataBuffer = ByteBufferUtil.removeSizePrefix(dataBuffer);
}
TestExtendedBuffer(dataBuffer);
// Make sure it also works with read only ByteBuffers. This is slower,
// since creating strings incurs an additional copy
// (see Table.__string).
TestExtendedBuffer(dataBuffer.asReadOnlyBuffer());
TestEnums();
//Attempt to mutate Monster fields and check whether the buffer has been mutated properly
// revert to original values after testing
Monster monster = Monster.getRootAsMonster(dataBuffer);
// mana is optional and does not exist in the buffer so the mutation should fail
// the mana field should retain its default value
TestEq(monster.mutateMana((short)10), false);
TestEq(monster.mana(), (short)150);
// Accessing a vector of sorted by the key tables
TestEq(monster.testarrayoftables(0).name(), "Barney");
TestEq(monster.testarrayoftables(1).name(), "Frodo");
TestEq(monster.testarrayoftables(2).name(), "Wilma");
Monster.Vector testarrayoftablesVector = monster.testarrayoftablesVector();
TestEq(testarrayoftablesVector.get(0).name(), "Barney");
TestEq(testarrayoftablesVector.get(1).name(), "Frodo");
TestEq(testarrayoftablesVector.get(2).name(), "Wilma");
// Example of searching for a table by the key
TestEq(monster.testarrayoftablesByKey("Frodo").name(), "Frodo");
TestEq(monster.testarrayoftablesByKey("Barney").name(), "Barney");
TestEq(monster.testarrayoftablesByKey("Wilma").name(), "Wilma");
TestEq(testarrayoftablesVector.getByKey("Frodo").name(), "Frodo");
TestEq(testarrayoftablesVector.getByKey("Barney").name(), "Barney");
TestEq(testarrayoftablesVector.getByKey("Wilma").name(), "Wilma");
// testType is an existing field and mutating it should succeed
TestEq(monster.testType(), (byte)Any.Monster);
//mutate the inventory vector
TestEq(monster.mutateInventory(0, 1), true);
TestEq(monster.mutateInventory(1, 2), true);
TestEq(monster.mutateInventory(2, 3), true);
TestEq(monster.mutateInventory(3, 4), true);
TestEq(monster.mutateInventory(4, 5), true);
for (int i = 0; i < monster.inventoryLength(); i++) {
TestEq(monster.inventory(i), i + 1);
}
ByteVector inventoryVector = monster.inventoryVector();
for (int i = 0; i < inventoryVector.length(); i++) {
TestEq((int)inventoryVector.get(i), i + 1);
}
//reverse mutation
TestEq(monster.mutateInventory(0, 0), true);
TestEq(monster.mutateInventory(1, 1), true);
TestEq(monster.mutateInventory(2, 2), true);
TestEq(monster.mutateInventory(3, 3), true);
TestEq(monster.mutateInventory(4, 4), true);
// get a struct field and edit one of its fields
Vec3 pos = monster.pos();
TestEq(pos.x(), 1.0f);
pos.mutateX(55.0f);
TestEq(pos.x(), 55.0f);
pos.mutateX(1.0f);
TestEq(pos.x(), 1.0f);
}
static void TestVectorOfUnions() {
final FlatBufferBuilder fbb = new FlatBufferBuilder();
final int swordAttackDamage = 1;
final int[] characterVector = new int[] {
Attacker.createAttacker(fbb, swordAttackDamage),
};
final byte[] characterTypeVector = new byte[]{
Character.MuLan,
};
Movie.finishMovieBuffer(
fbb,
Movie.createMovie(
fbb,
(byte)0,
(byte)0,
Movie.createCharactersTypeVector(fbb, characterTypeVector),
Movie.createCharactersVector(fbb, characterVector)
)
);
final Movie movie = Movie.getRootAsMovie(fbb.dataBuffer());
ByteVector charactersTypeByteVector = movie.charactersTypeVector();
UnionVector charactersVector = movie.charactersVector();
TestEq(movie.charactersTypeLength(), characterTypeVector.length);
TestEq(charactersTypeByteVector.length(), characterTypeVector.length);
TestEq(movie.charactersLength(), characterVector.length);
TestEq(charactersVector.length(), characterVector.length);
TestEq(movie.charactersType(0), characterTypeVector[0]);
TestEq(charactersTypeByteVector.get(0), characterTypeVector[0]);
TestEq(((Attacker)movie.characters(new Attacker(), 0)).swordAttackDamage(), swordAttackDamage);
}
static void TestFixedLengthArrays() {
FlatBufferBuilder builder = new FlatBufferBuilder(0);
float a;
int[] b = new int[15];
byte c;
int[][] d_a = new int[2][2];
byte[] d_b = new byte[2];
byte[][] d_c = new byte[2][2];
long[][] d_d = new long[2][2];
int e;
long[] f = new long[2];
a = 0.5f;
for (int i = 0; i < 15; i++) b[i] = i;
c = 1;
d_a[0][0] = 1;
d_a[0][1] = 2;
d_a[1][0] = 3;
d_a[1][1] = 4;
d_b[0] = TestEnum.B;
d_b[1] = TestEnum.C;
d_c[0][0] = TestEnum.A;
d_c[0][1] = TestEnum.B;
d_c[1][0] = TestEnum.C;
d_c[1][1] = TestEnum.B;
d_d[0][0] = -1;
d_d[0][1] = 1;
d_d[1][0] = -2;
d_d[1][1] = 2;
e = 2;
f[0] = -1;
f[1] = 1;
int arrayOffset = ArrayStruct.createArrayStruct(builder,
a, b, c, d_a, d_b, d_c, d_d, e, f);
// Create a table with the ArrayStruct.
ArrayTable.startArrayTable(builder);
ArrayTable.addA(builder, arrayOffset);
int tableOffset = ArrayTable.endArrayTable(builder);
ArrayTable.finishArrayTableBuffer(builder, tableOffset);
ArrayTable table = ArrayTable.getRootAsArrayTable(builder.dataBuffer());
NestedStruct nested = new NestedStruct();
TestEq(table.a().a(), 0.5f);
for (int i = 0; i < 15; i++) TestEq(table.a().b(i), i);
TestEq(table.a().c(), (byte)1);
TestEq(table.a().d(nested, 0).a(0), 1);
TestEq(table.a().d(nested, 0).a(1), 2);
TestEq(table.a().d(nested, 1).a(0), 3);
TestEq(table.a().d(nested, 1).a(1), 4);
TestEq(table.a().d(nested, 0).b(), TestEnum.B);
TestEq(table.a().d(nested, 1).b(), TestEnum.C);
TestEq(table.a().d(nested, 0).c(0), TestEnum.A);
TestEq(table.a().d(nested, 0).c(1), TestEnum.B);
TestEq(table.a().d(nested, 1).c(0), TestEnum.C);
TestEq(table.a().d(nested, 1).c(1), TestEnum.B);
TestEq(table.a().d(nested, 0).d(0), (long)-1);
TestEq(table.a().d(nested, 0).d(1), (long)1);
TestEq(table.a().d(nested, 1).d(0), (long)-2);
TestEq(table.a().d(nested, 1).d(1), (long)2);
TestEq(table.a().e(), 2);
TestEq(table.a().f(0), (long)-1);
TestEq(table.a().f(1), (long)1);
}
public static void testFlexBuffersTest() {
FlexBuffersBuilder builder = new FlexBuffersBuilder(ByteBuffer.allocate(512),
FlexBuffersBuilder.BUILDER_FLAG_SHARE_KEYS_AND_STRINGS);
testFlexBuffersTest(builder);
int bufferLimit1 = ((ArrayReadWriteBuf) builder.getBuffer()).limit();
// Repeat after clearing the builder to ensure the builder is reusable
builder.clear();
testFlexBuffersTest(builder);
int bufferLimit2 = ((ArrayReadWriteBuf) builder.getBuffer()).limit();
TestEq(bufferLimit1, bufferLimit2);
}
public static void testFlexBuffersTest(FlexBuffersBuilder builder) {
// Write the equivalent of:
// { vec: [ -100, "Fred", 4.0, false ], bar: [ 1, 2, 3 ], bar3: [ 1, 2, 3 ],
// foo: 100, bool: true, mymap: { foo: "Fred" } }
// It's possible to do this without std::function support as well.
int map1 = builder.startMap();
int vec1 = builder.startVector();
builder.putInt(-100);
builder.putString("Fred");
builder.putBlob(new byte[]{(byte) 77});
builder.putBoolean(false);
builder.putInt(Long.MAX_VALUE);
int map2 = builder.startMap();
builder.putInt("test", 200);
builder.endMap(null, map2);
builder.putFloat(150.9);
builder.putFloat(150.9999998);
builder.endVector("vec", vec1, false, false);
vec1 = builder.startVector();
builder.putInt(1);
builder.putInt(2);
builder.putInt(3);
builder.endVector("bar", vec1, true, false);
vec1 = builder.startVector();
builder.putBoolean(true);
builder.putBoolean(false);
builder.putBoolean(true);
builder.putBoolean(false);
builder.endVector("bools", vec1, true, false);
builder.putBoolean("bool", true);
builder.putFloat("foo", 100);
map2 = builder.startMap();
builder.putString("bar", "Fred"); // Testing key and string reuse.
builder.putInt("int", -120);
builder.putFloat("float", -123.0f);
builder.putBlob("blob", new byte[]{ 65, 67 });
builder.endMap("mymap", map2);
builder.endMap(null, map1);
builder.finish();
FlexBuffers.Map m = FlexBuffers.getRoot(builder.getBuffer()).asMap();
TestEq(m.size(), 6);
// test empty (an null)
TestEq(m.get("no_key").asString(), ""); // empty if fail
TestEq(m.get("no_key").asMap(), FlexBuffers.Map.empty()); // empty if fail
TestEq(m.get("no_key").asKey(), FlexBuffers.Key.empty()); // empty if fail
TestEq(m.get("no_key").asVector(), FlexBuffers.Vector.empty()); // empty if fail
TestEq(m.get("no_key").asBlob(), FlexBuffers.Blob.empty()); // empty if fail
assert(m.get("no_key").asVector().isEmpty()); // empty if fail
// testing "vec" field
FlexBuffers.Vector vec = m.get("vec").asVector();
TestEq(vec.size(), 8);
TestEq(vec.get(0).asLong(), (long) -100);
TestEq(vec.get(1).asString(), "Fred");
TestEq(vec.get(2).isBlob(), true);
TestEq(vec.get(2).asBlob().size(), 1);
TestEq(vec.get(2).asBlob().data().get(0), (byte) 77);
TestEq(vec.get(3).isBoolean(), true); // Check if type is a bool
TestEq(vec.get(3).asBoolean(), false); // Check if value is false
TestEq(vec.get(4).asLong(), Long.MAX_VALUE);
TestEq(vec.get(5).isMap(), true);
TestEq(vec.get(5).asMap().get("test").asInt(), 200);
TestEq(Float.compare((float)vec.get(6).asFloat(), 150.9f), 0);
TestEq(Double.compare(vec.get(7).asFloat(), 150.9999998), 0);
TestEq((long)0, (long)vec.get(1).asLong()); //conversion fail returns 0 as C++
// bar vector
FlexBuffers.Vector tvec = m.get("bar").asVector();
TestEq(tvec.size(), 3);
TestEq(tvec.get(0).asInt(), 1);
TestEq(tvec.get(1).asInt(), 2);
TestEq(tvec.get(2).asInt(), 3);
TestEq(((FlexBuffers.TypedVector) tvec).getElemType(), FlexBuffers.FBT_INT);
// bools vector
FlexBuffers.Vector bvec = m.get("bools").asVector();
TestEq(bvec.size(), 4);
TestEq(bvec.get(0).asBoolean(), true);
TestEq(bvec.get(1).asBoolean(), false);
TestEq(bvec.get(2).asBoolean(), true);
TestEq(bvec.get(3).asBoolean(), false);
TestEq(((FlexBuffers.TypedVector) bvec).getElemType(), FlexBuffers.FBT_BOOL);
TestEq((float)m.get("foo").asFloat(), (float) 100);
TestEq(m.get("unknown").isNull(), true);
// mymap vector
FlexBuffers.Map mymap = m.get("mymap").asMap();
TestEq(mymap.keys().get(0), m.keys().get(0)); // These should be equal by pointer equality, since key and value are shared.
TestEq(mymap.keys().get(0).toString(), "bar");
TestEq(mymap.values().get(0).asString(), vec.get(1).asString());
TestEq(mymap.get("int").asInt(), -120);
TestEq((float)mymap.get("float").asFloat(), -123.0f);
TestEq(Arrays.equals(mymap.get("blob").asBlob().getBytes(), new byte[]{ 65, 67 }), true);
TestEq(mymap.get("blob").asBlob().toString(), "AC");
TestEq(mymap.get("blob").toString(), "\"AC\"");
}
public static void testFlexBufferVectorStrings() {
FlexBuffersBuilder builder = new FlexBuffersBuilder(ByteBuffer.allocate(10000000));
int size = 3000;
StringBuilder sb = new StringBuilder();
for (int i=0; i< size; i++) {
sb.append("a");
}
String text = sb.toString();
TestEq(text.length(), size);
int pos = builder.startVector();
for (int i=0; i<size; i++) {
builder.putString(text);
}
try {
builder.endVector(null, pos, true, false);
// this should raise an exception as
// typed vector of string was deprecated
assert false;
} catch(FlexBufferException fb) {
// no op
}
// we finish the vector again as non-typed
builder.endVector(null, pos, false, false);
ByteBuffer b = builder.finish();
Vector v = FlexBuffers.getRoot(b).asVector();
TestEq(v.size(), size);
for (int i=0; i<size; i++) {
TestEq(v.get(i).asString().length(), size);
TestEq(v.get(i).asString(), text);
}
}
public static void testDeprecatedTypedVectorString() {
// tests whether we are able to support reading deprecated typed vector string
// data is equivalent to [ "abc", "abc", "abc", "abc"]
byte[] data = new byte[] {0x03, 0x61, 0x62, 0x63, 0x00, 0x03, 0x61, 0x62, 0x63, 0x00,
0x03, 0x61, 0x62, 0x63, 0x00, 0x03, 0x61, 0x62, 0x63, 0x00, 0x04, 0x14, 0x10,
0x0c, 0x08, 0x04, 0x3c, 0x01};
Reference ref = FlexBuffers.getRoot(ByteBuffer.wrap(data));
TestEq(ref.getType(), FlexBuffers.FBT_VECTOR_STRING_DEPRECATED);
TestEq(ref.isTypedVector(), true);
Vector vec = ref.asVector();
for (int i=0; i< vec.size(); i++) {
TestEq("abc", vec.get(i).asString());
}
}
public static void testSingleElementBoolean() {
FlexBuffersBuilder builder = new FlexBuffersBuilder(ByteBuffer.allocate(100));
builder.putBoolean(true);
ByteBuffer b = builder.finish();
assert(FlexBuffers.getRoot(b).asBoolean());
}
public static void testSingleElementByte() {
FlexBuffersBuilder builder = new FlexBuffersBuilder();
builder.putInt(10);
ByteBuffer b = builder.finish();
TestEq(10, FlexBuffers.getRoot(b).asInt());
}
public static void testSingleElementShort() {
FlexBuffersBuilder builder = new FlexBuffersBuilder();
builder.putInt(Short.MAX_VALUE);
ByteBuffer b = builder.finish();
TestEq(Short.MAX_VALUE, (short)FlexBuffers.getRoot(b).asInt());
}
public static void testSingleElementInt() {
FlexBuffersBuilder builder = new FlexBuffersBuilder();
builder.putInt(Integer.MIN_VALUE);
ByteBuffer b = builder.finish();
TestEq(Integer.MIN_VALUE, FlexBuffers.getRoot(b).asInt());
}
public static void testSingleElementLong() {
FlexBuffersBuilder builder = new FlexBuffersBuilder();
builder.putInt(Long.MAX_VALUE);
ByteBuffer b = builder.finish();
TestEq(Long.MAX_VALUE, FlexBuffers.getRoot(b).asLong());
}
public static void testSingleElementFloat() {
FlexBuffersBuilder builder = new FlexBuffersBuilder();
builder.putFloat(Float.MAX_VALUE);
ByteBuffer b = builder.finish();
TestEq(Float.compare(Float.MAX_VALUE, (float) FlexBuffers.getRoot(b).asFloat()), 0);
}
public static void testSingleElementDouble() {
FlexBuffersBuilder builder = new FlexBuffersBuilder();
builder.putFloat(Double.MAX_VALUE);
ByteBuffer b = builder.finish();
TestEq(Double.compare(Double.MAX_VALUE, FlexBuffers.getRoot(b).asFloat()), 0);
}
public static void testSingleElementBigString() {
FlexBuffersBuilder builder = new FlexBuffersBuilder(ByteBuffer.allocate(10000));
StringBuilder sb = new StringBuilder();
for (int i=0; i< 3000; i++) {
sb.append("a");
}
builder.putString(sb.toString());
ByteBuffer b = builder.finish();
FlexBuffers.Reference r = FlexBuffers.getRoot(b);
TestEq(FlexBuffers.FBT_STRING, r.getType());
TestEq(sb.toString(), r.asString());
}
public static void testSingleElementSmallString() {
FlexBuffersBuilder builder = new FlexBuffersBuilder(ByteBuffer.allocate(10000));
builder.putString("aa");
ByteBuffer b = builder.finish();
FlexBuffers.Reference r = FlexBuffers.getRoot(b);
TestEq(FlexBuffers.FBT_STRING, r.getType());
TestEq("aa", r.asString());
}
public static void testSingleElementBlob() {
FlexBuffersBuilder builder = new FlexBuffersBuilder();
builder.putBlob(new byte[]{5, 124, 118, -1});
ByteBuffer b = builder.finish();
FlexBuffers.Reference r = FlexBuffers.getRoot(b);
byte[] result = r.asBlob().getBytes();
TestEq((byte)5, result[0]);
TestEq((byte)124, result[1]);
TestEq((byte)118, result[2]);
TestEq((byte)-1, result[3]);
}
public static void testSingleElementLongBlob() {
// verifies blobs of up to 2^16 in length
for (int i = 2; i <= 1<<16; i = i<<1) {
byte[] input = new byte[i-1];
for (int index = 0; index < input.length; index++) {
input[index] = (byte)(index % 64);
}
FlexBuffersBuilder builder = new FlexBuffersBuilder();
builder.putBlob(input);
ByteBuffer b = builder.finish();
FlexBuffers.Reference r = FlexBuffers.getRoot(b);
byte[] result = r.asBlob().getBytes();
for (int index = 0; index < input.length; index++) {
TestEq((byte)(index % 64), result[index]);
}
}
}
public static void testSingleElementUByte() {
FlexBuffersBuilder builder = new FlexBuffersBuilder();
builder.putUInt(0xFF);
ByteBuffer b = builder.finish();
FlexBuffers.Reference r = FlexBuffers.getRoot(b);
TestEq(255, (int)r.asUInt());
}
public static void testSingleElementUShort() {
FlexBuffersBuilder builder = new FlexBuffersBuilder();
builder.putUInt(0xFFFF);
ByteBuffer b = builder.finish();
FlexBuffers.Reference r = FlexBuffers.getRoot(b);
TestEq(65535, (int)r.asUInt());
}
public static void testSingleElementUInt() {
FlexBuffersBuilder builder = new FlexBuffersBuilder();
builder.putUInt(0xFFFF_FFFFL);
ByteBuffer b = builder.finish();
FlexBuffers.Reference r = FlexBuffers.getRoot(b);
TestEq(4294967295L, r.asUInt());
}
public static void testSingleFixedTypeVector() {
int[] ints = new int[]{5, 124, 118, -1};
float[] floats = new float[]{5.5f, 124.124f, 118.118f, -1.1f};
String[] strings = new String[]{"This", "is", "a", "typed", "array"};
boolean[] booleans = new boolean[]{false, true, true, false};
FlexBuffersBuilder builder = new FlexBuffersBuilder(ByteBuffer.allocate(512),
FlexBuffersBuilder.BUILDER_FLAG_NONE);
int mapPos = builder.startMap();
int vecPos = builder.startVector();
for (final int i : ints) {
builder.putInt(i);
}
builder.endVector("ints", vecPos, true, false);
vecPos = builder.startVector();
for (final float i : floats) {
builder.putFloat(i);
}
builder.endVector("floats", vecPos, true, false);
vecPos = builder.startVector();
for (final boolean i : booleans) {
builder.putBoolean(i);
}
builder.endVector("booleans", vecPos, true, false);
builder.endMap(null, mapPos);
ByteBuffer b = builder.finish();
FlexBuffers.Reference r = FlexBuffers.getRoot(b);
assert(r.asMap().get("ints").isTypedVector());
assert(r.asMap().get("floats").isTypedVector());
assert(r.asMap().get("booleans").isTypedVector());
}
public static void testSingleElementVector() {
FlexBuffersBuilder b = new FlexBuffersBuilder();
int vecPos = b.startVector();
b.putInt(99);
b.putString("wow");
int vecpos2 = b.startVector();
b.putInt(99);
b.putString("wow");
b.endVector(null, vecpos2, false, false);
b.endVector(null, vecPos, false, false);
b.finish();
FlexBuffers.Reference r = FlexBuffers.getRoot(b.getBuffer());
TestEq(FlexBuffers.FBT_VECTOR, r.getType());
FlexBuffers.Vector vec = FlexBuffers.getRoot(b.getBuffer()).asVector();
TestEq(3, vec.size());
TestEq(99, vec.get(0).asInt());
TestEq("wow", vec.get(1).asString());
TestEq("[ 99, \"wow\" ]", vec.get(2).toString());
TestEq("[ 99, \"wow\", [ 99, \"wow\" ] ]", FlexBuffers.getRoot(b.getBuffer()).toString());
}
public static void testSingleElementMap() {
FlexBuffersBuilder b = new FlexBuffersBuilder();
int mapPost = b.startMap();
b.putInt("myInt", 0x7fffffbbbfffffffL);
b.putString("myString", "wow");
b.putString("myString2", "incredible");
int start = b.startVector();
b.putInt(99);
b.putString("wow");
b.endVector("myVec", start, false, false);
b.putFloat("double", 0x1.ffffbbbffffffP+1023);
b.endMap(null, mapPost);
b.finish();
FlexBuffers.Reference r = FlexBuffers.getRoot(b.getBuffer());
TestEq(FlexBuffers.FBT_MAP, r.getType());
FlexBuffers.Map map = FlexBuffers.getRoot(b.getBuffer()).asMap();
TestEq(5, map.size());
TestEq(0x7fffffbbbfffffffL, map.get("myInt").asLong());
TestEq("wow", map.get("myString").asString());
TestEq("incredible", map.get("myString2").asString());
TestEq(99, map.get("myVec").asVector().get(0).asInt());
TestEq("wow", map.get("myVec").asVector().get(1).asString());
TestEq(Double.compare(0x1.ffffbbbffffffP+1023, map.get("double").asFloat()), 0);
TestEq("{ \"double\" : 1.7976894783391937E308, \"myInt\" : 9223371743723257855, \"myString\" : \"wow\", \"myString2\" : \"incredible\", \"myVec\" : [ 99, \"wow\" ] }",
FlexBuffers.getRoot(b.getBuffer()).toString());
}
public static void testFlexBuferEmpty() {
FlexBuffers.Blob blob = FlexBuffers.Blob.empty();
FlexBuffers.Map ary = FlexBuffers.Map.empty();
FlexBuffers.Vector map = FlexBuffers.Vector.empty();
FlexBuffers.TypedVector typedAry = FlexBuffers.TypedVector.empty();
TestEq(blob.size(), 0);
TestEq(map.size(), 0);
TestEq(ary.size(), 0);
TestEq(typedAry.size(), 0);
}
public static void testHashMapToMap() {
int entriesCount = 12;
HashMap<String, String> source = new HashMap<>();
for (int i = 0; i < entriesCount; i++) {
source.put("foo_param_" + i, "foo_value_" + i);
}
FlexBuffersBuilder builder = new FlexBuffersBuilder(1000);
int mapStart = builder.startMap();
for (Map.Entry<String, String> entry : source.entrySet()) {
builder.putString(entry.getKey(), entry.getValue());
}
builder.endMap(null, mapStart);
ByteBuffer bb = builder.finish();
bb.rewind();
FlexBuffers.Reference rootReference = FlexBuffers.getRoot(bb);
TestEq(rootReference.isMap(), true);
FlexBuffers.Map flexMap = rootReference.asMap();
FlexBuffers.KeyVector keys = flexMap.keys();
FlexBuffers.Vector values = flexMap.values();
TestEq(entriesCount, keys.size());
TestEq(entriesCount, values.size());
HashMap<String, String> result = new HashMap<>();
for (int i = 0; i < keys.size(); i++) {
result.put(keys.get(i).toString(), values.get(i).asString());
}
TestEq(source, result);
}
public static void testBuilderGrowth() {
FlexBuffersBuilder builder = new FlexBuffersBuilder();
String someString = "This is a small string";
builder.putString(someString);
ByteBuffer b = builder.finish();
TestEq(someString, FlexBuffers.getRoot(b).asString());
FlexBuffersBuilder failBuilder = new FlexBuffersBuilder(ByteBuffer.allocate(1));
failBuilder.putString(someString);
}
public static void testFlexBuffersUtf8Map() {
FlexBuffersBuilder builder = new FlexBuffersBuilder(ByteBuffer.allocate(512),
FlexBuffersBuilder.BUILDER_FLAG_SHARE_KEYS_AND_STRINGS);
String key0 = "😨 face1";
String key1 = "😩 face2";
String key2 = "😨 face3";
String key3 = "trademark ®";
String key4 = "€ euro";
String utf8keys[] = { "😨 face1", "😩 face2", "😨 face3", "trademark ®", "€ euro"};
int map = builder.startMap();
for (int i=0; i< utf8keys.length; i++) {
builder.putString(utf8keys[i], utf8keys[i]); // Testing key and string reuse.
}
builder.endMap(null, map);
builder.finish();
FlexBuffers.Map m = FlexBuffers.getRoot(builder.getBuffer()).asMap();
TestEq(m.size(), 5);
KeyVector kv = m.keys();
for (int i=0; i< utf8keys.length; i++) {
TestEq(kv.get(i).toString(), m.get(i).asString());
}
TestEq(m.get(key0).asString(), utf8keys[0]);
TestEq(m.get(key1).asString(), utf8keys[1]);
TestEq(m.get(key2).asString(), utf8keys[2]);
TestEq(m.get(key3).asString(), utf8keys[3]);
TestEq(m.get(key4).asString(), utf8keys[4]);
}
public static void TestFlexBuffers() {
testSingleElementByte();
testSingleElementShort();
testSingleElementInt();
testSingleElementLong();
testSingleElementFloat();
testSingleElementDouble();
testSingleElementSmallString();
testSingleElementBigString();
testSingleElementBlob();
testSingleElementLongBlob();
testSingleElementVector();
testSingleFixedTypeVector();
testSingleElementUShort();
testSingleElementUInt();
testSingleElementUByte();
testSingleElementMap();
testFlexBuffersTest();
testHashMapToMap();
testFlexBuferEmpty();
testFlexBufferVectorStrings();
testDeprecatedTypedVectorString();
testBuilderGrowth();
testFlexBuffersUtf8Map();
}
static void TestVectorOfBytes() {
FlatBufferBuilder fbb = new FlatBufferBuilder(16);
int str = fbb.createString("ByteMonster");
byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int offset = Monster.createInventoryVector(fbb, data);
Monster.startMonster(fbb);
Monster.addName(fbb, str);
Monster.addInventory(fbb, offset);
int monster1 = Monster.endMonster(fbb);
Monster.finishMonsterBuffer(fbb, monster1);
Monster monsterObject = Monster.getRootAsMonster(fbb.dataBuffer());
TestEq(monsterObject.inventoryLength(), data.length);
TestEq(monsterObject.inventory(4), (int) data[4]);
TestEq(ByteBuffer.wrap(data), monsterObject.inventoryAsByteBuffer());
fbb.clear();
ByteBuffer bb = ByteBuffer.wrap(data);
offset = fbb.createByteVector(bb);
str = fbb.createString("ByteMonster");
Monster.startMonster(fbb);
Monster.addName(fbb, str);
Monster.addInventory(fbb, offset);
monster1 = Monster.endMonster(fbb);
Monster.finishMonsterBuffer(fbb, monster1);
Monster monsterObject2 = Monster.getRootAsMonster(fbb.dataBuffer());
TestEq(monsterObject2.inventoryLength(), data.length);
for (int i = 0; i < data.length; i++) {
TestEq(monsterObject2.inventory(i), (int) bb.get(i));
}
fbb.clear();
offset = fbb.createByteVector(data, 3, 4);
str = fbb.createString("ByteMonster");
Monster.startMonster(fbb);
Monster.addName(fbb, str);
Monster.addInventory(fbb, offset);
monster1 = Monster.endMonster(fbb);
Monster.finishMonsterBuffer(fbb, monster1);
Monster monsterObject3 = Monster.getRootAsMonster(fbb.dataBuffer());
TestEq(monsterObject3.inventoryLength(), 4);
TestEq(monsterObject3.inventory(0), (int) data[3]);
fbb.clear();
bb = ByteBuffer.wrap(data);
offset = Monster.createInventoryVector(fbb, bb);
str = fbb.createString("ByteMonster");
Monster.startMonster(fbb);
Monster.addName(fbb, str);
Monster.addInventory(fbb, offset);
monster1 = Monster.endMonster(fbb);
Monster.finishMonsterBuffer(fbb, monster1);
Monster monsterObject4 = Monster.getRootAsMonster(fbb.dataBuffer());
TestEq(monsterObject4.inventoryLength(), data.length);
TestEq(monsterObject4.inventory(8), (int) 8);
fbb.clear();
byte[] largeData = new byte[1024];
offset = fbb.createByteVector(largeData);
str = fbb.createString("ByteMonster");
Monster.startMonster(fbb);
Monster.addName(fbb, str);
Monster.addInventory(fbb, offset);
monster1 = Monster.endMonster(fbb);
Monster.finishMonsterBuffer(fbb, monster1);
Monster monsterObject5 = Monster.getRootAsMonster(fbb.dataBuffer());
TestEq(monsterObject5.inventoryLength(), largeData.length);
TestEq(monsterObject5.inventory(25), (int) largeData[25]);
fbb.clear();
bb = ByteBuffer.wrap(largeData);
bb.position(512);
ByteBuffer bb2 = bb.slice();
TestEq(bb2.arrayOffset(), 512);
offset = fbb.createByteVector(bb2);
str = fbb.createString("ByteMonster");
Monster.startMonster(fbb);
Monster.addName(fbb, str);
Monster.addInventory(fbb, offset);
monster1 = Monster.endMonster(fbb);
Monster.finishMonsterBuffer(fbb, monster1);
Monster monsterObject6 = Monster.getRootAsMonster(fbb.dataBuffer());
TestEq(monsterObject6.inventoryLength(), 512);
TestEq(monsterObject6.inventory(0), (int) largeData[512]);
fbb.clear();
bb = ByteBuffer.wrap(largeData);
bb.limit(256);
offset = fbb.createByteVector(bb);
str = fbb.createString("ByteMonster");
Monster.startMonster(fbb);
Monster.addName(fbb, str);
Monster.addInventory(fbb, offset);
monster1 = Monster.endMonster(fbb);
Monster.finishMonsterBuffer(fbb, monster1);
Monster monsterObject7 = Monster.getRootAsMonster(fbb.dataBuffer());
TestEq(monsterObject7.inventoryLength(), 256);
fbb.clear();
bb = ByteBuffer.allocateDirect(2048);
offset = fbb.createByteVector(bb);
str = fbb.createString("ByteMonster");
Monster.startMonster(fbb);
Monster.addName(fbb, str);
Monster.addInventory(fbb, offset);
monster1 = Monster.endMonster(fbb);
Monster.finishMonsterBuffer(fbb, monster1);
Monster monsterObject8 = Monster.getRootAsMonster(fbb.dataBuffer());
TestEq(monsterObject8.inventoryLength(), 2048);
}
static void TestSharedStringPool() {
FlatBufferBuilder fb = new FlatBufferBuilder(1);
String testString = "My string";
int offset = fb.createSharedString(testString);
for (int i=0; i< 10; i++) {
TestEq(offset, fb.createSharedString(testString));
}
}
static void TestScalarOptional() {
FlatBufferBuilder fbb = new FlatBufferBuilder(1);
ScalarStuff.startScalarStuff(fbb);
int pos = ScalarStuff.endScalarStuff(fbb);
fbb.finish(pos);
ScalarStuff scalarStuff = ScalarStuff.getRootAsScalarStuff(fbb.dataBuffer());
TestEq(scalarStuff.justI8(), (byte)0);
TestEq(scalarStuff.maybeI8(), (byte)0);
TestEq(scalarStuff.defaultI8(), (byte)42);
TestEq(scalarStuff.justU8(), 0);
TestEq(scalarStuff.maybeU8(), 0);
TestEq(scalarStuff.defaultU8(), 42);
TestEq(scalarStuff.justI16(), (short)0);
TestEq(scalarStuff.maybeI16(), (short)0);
TestEq(scalarStuff.defaultI16(), (short)42);
TestEq(scalarStuff.justU16(), 0);
TestEq(scalarStuff.maybeU16(), 0);
TestEq(scalarStuff.defaultU16(), 42);
TestEq(scalarStuff.justI32(), 0);
TestEq(scalarStuff.maybeI32(), 0);
TestEq(scalarStuff.defaultI32(), 42);
TestEq(scalarStuff.justU32(), 0L);
TestEq(scalarStuff.maybeU32(), 0L);
TestEq(scalarStuff.defaultU32(), 42L);
TestEq(scalarStuff.justI64(), 0L);
TestEq(scalarStuff.maybeI64(), 0L);
TestEq(scalarStuff.defaultI64(), 42L);
TestEq(scalarStuff.justU64(), 0L);
TestEq(scalarStuff.maybeU64(), 0L);
TestEq(scalarStuff.defaultU64(), 42L);
TestEq(scalarStuff.justF32(), 0.0f);
TestEq(scalarStuff.maybeF32(), 0f);
TestEq(scalarStuff.defaultF32(), 42.0f);
TestEq(scalarStuff.justF64(), 0.0);
TestEq(scalarStuff.maybeF64(), 0.0);
TestEq(scalarStuff.defaultF64(), 42.0);
TestEq(scalarStuff.justBool(), false);
TestEq(scalarStuff.maybeBool(), false);
TestEq(scalarStuff.defaultBool(), true);
TestEq(scalarStuff.justEnum(), OptionalByte.None);
TestEq(scalarStuff.maybeEnum(), OptionalByte.None);
TestEq(scalarStuff.defaultEnum(), OptionalByte.One);
TestEq(scalarStuff.hasMaybeI8(), false);
TestEq(scalarStuff.hasMaybeI16(), false);
TestEq(scalarStuff.hasMaybeI32(), false);
TestEq(scalarStuff.hasMaybeI64(), false);
TestEq(scalarStuff.hasMaybeU8(), false);
TestEq(scalarStuff.hasMaybeU16(), false);
TestEq(scalarStuff.hasMaybeU32(), false);
TestEq(scalarStuff.hasMaybeU64(), false);
TestEq(scalarStuff.hasMaybeF32(), false);
TestEq(scalarStuff.hasMaybeF64(), false);
TestEq(scalarStuff.hasMaybeBool(), false);
TestEq(scalarStuff.hasMaybeEnum(), false);
fbb.clear();
ScalarStuff.startScalarStuff(fbb);
ScalarStuff.addJustI8(fbb, (byte)5);
ScalarStuff.addMaybeI8(fbb, (byte)5);
ScalarStuff.addDefaultI8(fbb, (byte)5);
ScalarStuff.addJustU8(fbb, 6);
ScalarStuff.addMaybeU8(fbb, 6);
ScalarStuff.addDefaultU8(fbb, 6);
ScalarStuff.addJustI16(fbb, (short)7);
ScalarStuff.addMaybeI16(fbb, (short)7);
ScalarStuff.addDefaultI16(fbb, (short)7);
ScalarStuff.addJustU16(fbb, 8);
ScalarStuff.addMaybeU16(fbb, 8);
ScalarStuff.addDefaultU16(fbb, 8);
ScalarStuff.addJustI32(fbb, 9);
ScalarStuff.addMaybeI32(fbb, 9);
ScalarStuff.addDefaultI32(fbb, 9);
ScalarStuff.addJustU32(fbb, (long)10);
ScalarStuff.addMaybeU32(fbb, (long)10);
ScalarStuff.addDefaultU32(fbb, (long)10);
ScalarStuff.addJustI64(fbb, 11L);
ScalarStuff.addMaybeI64(fbb, 11L);
ScalarStuff.addDefaultI64(fbb, 11L);
ScalarStuff.addJustU64(fbb, 12L);
ScalarStuff.addMaybeU64(fbb, 12L);
ScalarStuff.addDefaultU64(fbb, 12L);
ScalarStuff.addJustF32(fbb, 13.0f);
ScalarStuff.addMaybeF32(fbb, 13.0f);
ScalarStuff.addDefaultF32(fbb, 13.0f);
ScalarStuff.addJustF64(fbb, 14.0);
ScalarStuff.addMaybeF64(fbb, 14.0);
ScalarStuff.addDefaultF64(fbb, 14.0);
ScalarStuff.addJustBool(fbb, true);
ScalarStuff.addMaybeBool(fbb, true);
ScalarStuff.addDefaultBool(fbb, true);
ScalarStuff.addJustEnum(fbb, OptionalByte.Two);
ScalarStuff.addMaybeEnum(fbb, OptionalByte.Two);
ScalarStuff.addDefaultEnum(fbb, OptionalByte.Two);
pos = ScalarStuff.endScalarStuff(fbb);
fbb.finish(pos);
scalarStuff = ScalarStuff.getRootAsScalarStuff(fbb.dataBuffer());
TestEq(scalarStuff.justI8(), (byte)5);
TestEq(scalarStuff.maybeI8(), (byte)5);
TestEq(scalarStuff.defaultI8(), (byte)5);
TestEq(scalarStuff.justU8(), 6);
TestEq(scalarStuff.maybeU8(), 6);
TestEq(scalarStuff.defaultU8(), 6);
TestEq(scalarStuff.justI16(), (short)7);
TestEq(scalarStuff.maybeI16(), (short)7);
TestEq(scalarStuff.defaultI16(), (short)7);
TestEq(scalarStuff.justU16(), 8);
TestEq(scalarStuff.maybeU16(), 8);
TestEq(scalarStuff.defaultU16(), 8);
TestEq(scalarStuff.justI32(), 9);
TestEq(scalarStuff.maybeI32(), 9);
TestEq(scalarStuff.defaultI32(), 9);
TestEq(scalarStuff.justU32(), 10L);
TestEq(scalarStuff.maybeU32(), 10L);
TestEq(scalarStuff.defaultU32(), 10L);
TestEq(scalarStuff.justI64(), 11L);
TestEq(scalarStuff.maybeI64(), 11L);
TestEq(scalarStuff.defaultI64(), 11L);
TestEq(scalarStuff.justU64(), 12L);
TestEq(scalarStuff.maybeU64(), 12L);
TestEq(scalarStuff.defaultU64(), 12L);
TestEq(scalarStuff.justF32(), 13.0f);
TestEq(scalarStuff.maybeF32(), 13.0f);
TestEq(scalarStuff.defaultF32(), 13.0f);
TestEq(scalarStuff.justF64(), 14.0);
TestEq(scalarStuff.maybeF64(), 14.0);
TestEq(scalarStuff.defaultF64(), 14.0);
TestEq(scalarStuff.justBool(), true);
TestEq(scalarStuff.maybeBool(), true);
TestEq(scalarStuff.defaultBool(), true);
TestEq(scalarStuff.justEnum(), OptionalByte.Two);
TestEq(scalarStuff.maybeEnum(), OptionalByte.Two);
TestEq(scalarStuff.defaultEnum(), OptionalByte.Two);
TestEq(scalarStuff.hasMaybeI8(), true);
TestEq(scalarStuff.hasMaybeI16(), true);
TestEq(scalarStuff.hasMaybeI32(), true);
TestEq(scalarStuff.hasMaybeI64(), true);
TestEq(scalarStuff.hasMaybeU8(), true);
TestEq(scalarStuff.hasMaybeU16(), true);
TestEq(scalarStuff.hasMaybeU32(), true);
TestEq(scalarStuff.hasMaybeU64(), true);
TestEq(scalarStuff.hasMaybeF32(), true);
TestEq(scalarStuff.hasMaybeF64(), true);
TestEq(scalarStuff.hasMaybeBool(), true);
TestEq(scalarStuff.hasMaybeEnum(), true);
}
static void TestObject(MonsterT monster) {
TestEq(monster.getHp(), (short) 80);
TestEq(monster.getMana(), (short) 150); // default
TestEq(monster.getName(), "MyMonster");
TestEq(monster.getColor(), Color.Blue);
// monster.friendly() // can't access, deprecated
Vec3T pos = monster.getPos();
TestEq(pos.getX(), 1.0f);
TestEq(pos.getY(), 2.0f);
TestEq(pos.getZ(), 3.0f);
TestEq(pos.getTest1(), 3.0);
// issue: int != byte
TestEq(pos.getTest2(), (int) Color.Green);
TestT t = pos.getTest3();
TestEq(t.getA(), (short) 5);
TestEq(t.getB(), (byte) 6);
TestEq(monster.getTest().getType(), (byte) Any.Monster);
MonsterT monster2 = (MonsterT) monster.getTest().getValue();
TestEq(monster2 != null, true);
TestEq(monster2.getName(), "Fred");
int[] inv = monster.getInventory();
TestEq(inv.length, 5);
int[] expInv = {0, 1, 2, 3, 4};
for (int i = 0; i < inv.length; i++)
TestEq(expInv[i], inv[i]);
TestT[] test4 = monster.getTest4();
TestT test_0 = test4[0];
TestT test_1 = test4[1];
TestEq(test4.length, 2);
TestEq(test_0.getA(), (short) 10);
TestEq(test_0.getB(), (byte) 20);
TestEq(test_1.getA(), (short) 30);
TestEq(test_1.getB(), (byte) 40);
String[] testarrayofstring = monster.getTestarrayofstring();
TestEq(testarrayofstring.length, 2);
TestEq(testarrayofstring[0], "test1");
TestEq(testarrayofstring[1], "test2");
MonsterT[] testarrayoftables = monster.getTestarrayoftables();
TestEq(testarrayoftables.length, 0);
MonsterT enemy = monster.getEnemy();
TestEq(enemy != null, true);
TestEq(enemy.getName(), "Fred");
int[] testnestedflatbuffer = monster.getTestnestedflatbuffer();
TestEq(testnestedflatbuffer.length, 0);
TestEq(monster.getTestempty() == null, true);
TestEq(monster.getTestbool(), true);
boolean[] testarrayofbools = monster.getTestarrayofbools();
TestEq(testarrayofbools.length, 3);
TestEq(testarrayofbools[0], true);
TestEq(testarrayofbools[1], false);
TestEq(testarrayofbools[2], true);
TestEq(monster.getTestf(), 3.14159f);
TestEq(monster.getTestf2(), 3.0f);
TestEq(monster.getTestf3(), 0.0f);
TestEq(monster.getTestf3(), 0.0f);
AbilityT[] testarrayofsortedstruct = monster.getTestarrayofsortedstruct();
TestEq(testarrayofsortedstruct.length, 3);
TestEq(testarrayofsortedstruct[0].getId(), (long) 0);
TestEq(testarrayofsortedstruct[1].getId(), (long) 1);
TestEq(testarrayofsortedstruct[2].getId(), (long) 5);
TestEq(testarrayofsortedstruct[0].getDistance(), (long) 45);
TestEq(testarrayofsortedstruct[1].getDistance(), (long) 21);
TestEq(testarrayofsortedstruct[2].getDistance(), (long) 12);
int[] flex = monster.getFlex();
TestEq(flex.length, 0);
long[] vectorOfLongs = monster.getVectorOfLongs();
TestEq(vectorOfLongs.length, 5);
long l = 1;
for (int i = 0; i < vectorOfLongs.length; i++) {
TestEq(vectorOfLongs[i], l);
l *= 100;
}
double[] vectorOfDoubles = monster.getVectorOfDoubles();
TestEq(vectorOfDoubles.length, 3);
TestEq(vectorOfDoubles[0], -1.7976931348623157E308);
TestEq(vectorOfDoubles[1], 0.0);
TestEq(vectorOfDoubles[2], 1.7976931348623157E308);
TestEq(monster.getParentNamespaceTest() == null, true);
ReferrableT[] vectorOfReferrables = monster.getVectorOfReferrables();
TestEq(vectorOfReferrables.length, 0);
TestEq(monster.getSignedEnum(), (byte) -1);
}
static void TestPackUnpack(ByteBuffer bb) {
Monster m = Monster.getRootAsMonster(bb);
MonsterT mObject = m.unpack();
TestObject(mObject);
FlatBufferBuilder fbb = new FlatBufferBuilder();
int monster = Monster.pack(fbb, mObject);
Monster.finishMonsterBuffer(fbb, monster);
TestBuffer(fbb.dataBuffer());
byte[] bytes = mObject.serializeToBinary();
MonsterT newMonsterT = MonsterT.deserializeFromBinary(bytes);
TestObject(newMonsterT);
}
static <T> void TestEq(T a, T b) {
if ((a == null && a != b) || (a != null && !a.equals(b))) {
System.out.println("" + a.getClass().getName() + " " + b.getClass().getName());
System.out.println("FlatBuffers test FAILED: \'" + a + "\' != \'" + b + "\'");
new Throwable().printStackTrace();
assert false;
System.exit(1);
}
}
}
| {
"content_hash": "f98731c61b5d87fd8961a4116e35e424",
"timestamp": "",
"source": "github",
"line_count": 1519,
"max_line_length": 175,
"avg_line_length": 38.484529295589205,
"alnum_prop": 0.6117383420575456,
"repo_name": "evolutional/flatbuffers",
"id": "ce5751e83edabf88bda5cef32ea251a1ecd54cc8",
"size": "59097",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/JavaTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "10652"
},
{
"name": "C",
"bytes": "1809"
},
{
"name": "C#",
"bytes": "273387"
},
{
"name": "C++",
"bytes": "1994757"
},
{
"name": "CMake",
"bytes": "36877"
},
{
"name": "Dart",
"bytes": "193875"
},
{
"name": "Go",
"bytes": "113267"
},
{
"name": "Java",
"bytes": "341985"
},
{
"name": "JavaScript",
"bytes": "161262"
},
{
"name": "Kotlin",
"bytes": "107334"
},
{
"name": "Lua",
"bytes": "74664"
},
{
"name": "Makefile",
"bytes": "12544"
},
{
"name": "PHP",
"bytes": "165632"
},
{
"name": "Python",
"bytes": "302267"
},
{
"name": "Roff",
"bytes": "664"
},
{
"name": "Rust",
"bytes": "262976"
},
{
"name": "Shell",
"bytes": "27558"
},
{
"name": "TypeScript",
"bytes": "102111"
}
],
"symlink_target": ""
} |
Simple implementation of Chat server using just NodeJS `net` library.
Host and port can be configured in `config.json` file.
Run using `node src` command.
Client can connect with telnet.
Application support messages and separate chat groups.
Live example: `telnet valkovic.eu 465`
Made by Patrik Valkovič
2017/05/24
MIT licence
| {
"content_hash": "28ace2f5e1a8c4dc0a8a5590e950f9c2",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 69,
"avg_line_length": 22.533333333333335,
"alnum_prop": 0.7751479289940828,
"repo_name": "PatrikValkovic/TCPChat",
"id": "fc12c1948c583f07dbcfcccfc214fd014b60ff3f",
"size": "351",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "247"
},
{
"name": "JavaScript",
"bytes": "20677"
}
],
"symlink_target": ""
} |
package com.danieloskarsson.viewinjection.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author Daniel Oskarsson (daniel.oskarsson@gmail.com)
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface OnCreateView {
} | {
"content_hash": "c44d77be5bddb1196b0f39e42e816e4b",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 56,
"avg_line_length": 27.214285714285715,
"alnum_prop": 0.8162729658792651,
"repo_name": "danieloskarsson/android-viewinjection",
"id": "79a141a34b5fb8cbc058dcedac39b1010259d41e",
"size": "381",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "library/AndroidViewInjectionLibrary/src/main/java/com/danieloskarsson/viewinjection/annotations/OnCreateView.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "1122"
},
{
"name": "Java",
"bytes": "8094"
},
{
"name": "Shell",
"bytes": "14968"
}
],
"symlink_target": ""
} |
define(['require', 'log', 'jquery', 'backbone', 'lodash', 'designViewUtils', 'dropElements', 'dagre', 'edge',
'windowFilterProjectionQueryInput', 'joinQueryInput', 'patternOrSequenceQueryInput', 'queryOutput',
'partitionWith', 'jsonValidator', 'constants', 'dragSelect'],
function (require, log, $, Backbone, _, DesignViewUtils, DropElements, dagre, Edge,
WindowFilterProjectionQueryInput, JoinQueryInput, PatternOrSequenceQueryInput, QueryOutput,
PartitionWith, JSONValidator, Constants) {
const TAB_INDEX = 10;
const ENTER_KEY = 13;
const LEFT_ARROW_KEY = 37;
const RIGHT_ARROW_KEY = 39;
const ESCAPE_KEY = 27;
const TAB_KEY = 9;
var constants = {
SOURCE: 'sourceDrop',
SINK: 'sinkDrop',
STREAM: 'streamDrop',
TABLE: 'tableDrop',
WINDOW: 'windowDrop',
TRIGGER: 'triggerDrop',
AGGREGATION: 'aggregationDrop',
FUNCTION: 'functionDrop',
PROJECTION: 'projectionQueryDrop',
FILTER: 'filterQueryDrop',
JOIN: 'joinQueryDrop',
WINDOW_QUERY: 'windowQueryDrop',
FUNCTION_QUERY: 'functionQueryDrop',
PATTERN: 'patternQueryDrop',
SEQUENCE: 'sequenceQueryDrop',
PARTITION: 'partitionDrop',
PARTITION_CONNECTION_POINT: 'partition-connector-in-part',
SELECTOR: 'selector',
MULTI_SELECTOR: 'multi-selector'
};
/**
* @class DesignGrid
* @constructor
* @class DesignGrid Wraps the Ace editor for design view
* @param {Object} options Rendering options for the view
*/
var DesignGrid = function (options) {
var errorMessage = 'unable to find design view grid container';
if (!_.has(options, 'container')) {
log.error(errorMessage);
throw errorMessage;
}
var container = $(_.get(options, 'container'));
if (!container.length > 0) {
log.error(errorMessage);
throw errorMessage;
}
this.options = options;
this.rawExtensions = options.rawExtensions;
this.configurationData = this.options.configurationData;
this.container = this.options.container;
this.application = this.options.application;
this.jsPlumbInstance = options.jsPlumbInstance;
this.currentTabId = this.application.tabController.activeTab.cid;
this.designViewContainer = $('#design-container-' + this.currentTabId);
this.toggleViewButton = $('#toggle-view-button-' + this.currentTabId);
this.designGridContainer = $('#design-grid-container-' + this.currentTabId);
this.selectedElements = [];
this.selectedObjects = [];
};
DesignGrid.prototype.addSelectedElements = function(element){
this.selectedElements.push(element);
};
DesignGrid.prototype.isSelectedElements = function(element){
if (this.selectedElements.includes(element)){
return true;
} else{
return false;
}
};
DesignGrid.prototype.getSelectedElement = function(){
return this.selectedElements;
};
DesignGrid.prototype.resetSelectedElement = function(){
this.selectedElements = [];
};
DesignGrid.prototype.removeFromSelectedElements = function(element){
for (var i = 0; i < this.selectedElements.length; i++) {
if (this.selectedElements[i] == element) {
this.selectedElements.splice(i, 1);
}
}
};
DesignGrid.prototype.render = function () {
var self = this;
// newAgentId --> newAgent ID (Dropped Element ID)
this.newAgentId = "0";
var dropElementsOpts = {};
_.set(dropElementsOpts, 'container', self.container);
_.set(dropElementsOpts, 'configurationData', self.configurationData);
_.set(dropElementsOpts, 'application', self.application);
_.set(dropElementsOpts, 'jsPlumbInstance', self.jsPlumbInstance);
_.set(dropElementsOpts, 'designGrid', self);
this.dropElements = new DropElements(dropElementsOpts);
this.canvas = $(self.container);
// configuring the siddhi app level annotations
var settingsButtonId = self.currentTabId + '-appSettingsId';
var settingsButton = $("<div id='" + settingsButtonId + "' " +
"class='btn app-annotations-button' " +
"data-placement='bottom' data-toggle='tooltip' title='App Annotations'>" +
"<i class='fw fw-settings'></i></div>");
settingsButton.tooltip();
self.canvas.append(settingsButton);
var settingsIconElement = $('#' + settingsButtonId)[0];
settingsIconElement.addEventListener('click', function () {
self.dropElements.formBuilder.DefineFormForAppAnnotations(this);
});
// add text fields to display the siddhi app name and description
var siddhiAppNameNodeId = self.currentTabId + '-siddhiAppNameId';
var siddhiAppName = self.configurationData.getSiddhiAppConfig().getSiddhiAppName();
var siddhiAppNameNode = $("<div id='" + siddhiAppNameNodeId + "' " +
"class='siddhi-app-name-node'>" + siddhiAppName + "</div>");
var siddhiAppDescription = self.configurationData.getSiddhiAppConfig().getSiddhiAppDescription();
var siddhiAppDescriptionNode = $("<div id='siddhi-app-desc-node'>" + siddhiAppDescription + "</div>");
self.canvas.append(siddhiAppNameNode, siddhiAppDescriptionNode);
/**
* @description jsPlumb function opened
*/
self.jsPlumbInstance.ready(function () {
self.jsPlumbInstance.importDefaults({
HoverPaintStyle: {
strokeStyle: '#424242',
strokeWidth: 2
},
Overlays: [["Arrow", {location: 1.0, id: "arrow", foldback: 1, width: 8, length: 8}]],
DragOptions: {cursor: "crosshair"},
Endpoints: [["Dot", {radius: 7}], ["Dot", {radius: 11}]],
EndpointStyle: {
radius: 3
},
ConnectionsDetachable: false,
Connector: ["Bezier", {curviness: 25}]
});
/**
* @function droppable method for the 'stream' & the 'query' objects
*/
self.canvas.droppable
({
accept: '.stream-drag, .table-drag, .window-drag, .trigger-drag, .aggregation-drag,' +
'.projection-query-drag, .filter-query-drag, .join-query-drag, .window-query-drag,' +
'.pattern-query-drag, .sequence-query-drag, .partition-drag, .source-drag, .sink-drag, ' +
'.function-drag, .function-query-drag',
containment: 'grid-container',
/**
*
* @param e --> original event object fired/ normalized by jQuery
* @param ui --> object that contains additional info added by jQuery depending on which
* interaction was used
* @helper clone
*/
drop: function (e, ui) {
var mouseTop = e.pageY - self.canvas.offset().top + self.canvas.scrollTop() - 40;
var mouseLeft = e.pageX - self.canvas.offset().left + self.canvas.scrollLeft() - 60;
// Clone the element in the toolbox in order to drop the clone on the canvas
var droppedElement = ui.helper.clone();
// To further manipulate the jsplumb element, remove the jquery UI clone helper as jsPlumb
// doesn't support it
ui.helper.remove();
$(droppedElement).draggable({containment: "parent"});
// Repaint to reposition all the elements that are on the canvas after the drop/addition of a
// new element on the canvas
self.jsPlumbInstance.repaint(ui.helper);
// If the dropped Element is a Source annotation then->
if ($(droppedElement).hasClass('source-drag')) {
self.handleSourceAnnotation(mouseTop, mouseLeft, false, "Source");
}
// If the dropped Element is a Sink annotation then->
if ($(droppedElement).hasClass('sink-drag')) {
self.handleSinkAnnotation(mouseTop, mouseLeft, false, "Sink");
}
// If the dropped Element is a Stream then->
if ($(droppedElement).hasClass('stream-drag')) {
self.handleStream(mouseTop, mouseLeft, false);
}
// If the dropped Element is a Table then->
if ($(droppedElement).hasClass('table-drag')) {
self.handleTable(mouseTop, mouseLeft, false);
}
// If the dropped Element is a Window(not window query) then->
else if ($(droppedElement).hasClass('window-drag')) {
self.handleWindow(mouseTop, mouseLeft, false);
}
// If the dropped Element is a Trigger then->
else if ($(droppedElement).hasClass('trigger-drag')) {
self.handleTrigger(mouseTop, mouseLeft, false);
}
// If the dropped Element is a Aggregation then->
else if ($(droppedElement).hasClass('aggregation-drag')) {
self.handleAggregation(mouseTop, mouseLeft, false);
}
// If the dropped Element is a Aggregation then->
else if ($(droppedElement).hasClass('function-drag')) {
self.handleFunction(mouseTop, mouseLeft, false);
}
// If the dropped Element is a Projection Query then->
else if ($(droppedElement).hasClass('projection-query-drag')) {
self.handleWindowFilterProjectionQuery(constants.PROJECTION, mouseTop, mouseLeft, false,
"Query");
}
// If the dropped Element is a Filter query then->
else if ($(droppedElement).hasClass('filter-query-drag')) {
self.handleWindowFilterProjectionQuery(constants.FILTER, mouseTop, mouseLeft, false,
"Query");
}
// If the dropped Element is a Window Query then->
else if ($(droppedElement).hasClass('window-query-drag')) {
self.handleWindowFilterProjectionQuery(constants.WINDOW_QUERY, mouseTop, mouseLeft, false,
"Query");
}
// If the dropped Element is a Function Query then->
else if ($(droppedElement).hasClass('function-query-drag')) {
self.handleWindowFilterProjectionQuery(constants.FUNCTION_QUERY, mouseTop, mouseLeft, false,
"Query");
}
// If the dropped Element is a Join Query then->
else if ($(droppedElement).hasClass('join-query-drag')) {
self.handleJoinQuery(mouseTop, mouseLeft, false, "Join Query");
}
// If the dropped Element is a Pattern Query then->
else if ($(droppedElement).hasClass('pattern-query-drag')) {
self.handlePatternQuery(mouseTop, mouseLeft, false, "Pattern Query");
}
// If the dropped Element is a Sequence Query then->
else if ($(droppedElement).hasClass('sequence-query-drag')) {
self.handleSequenceQuery(mouseTop, mouseLeft, false, "Sequence Query");
}
// If the dropped Element is a Partition then->
else if ($(droppedElement).hasClass('partition-drag')) {
self.handlePartition(mouseTop, mouseLeft, false);
}
// set the isDesignViewContentChanged to true
self.configurationData.setIsDesignViewContentChanged(true);
}
});
});
// check the validity of the connections and drop if invalid
function checkConnectionValidityBeforeElementDrop() {
self.jsPlumbInstance.bind('beforeDrop', function (connection) {
var connectionValidity = false;
var target = connection.targetId;
var targetId = target.substr(0, target.indexOf('-'));
/*
* There is no 'in' or 'out' clause(for other connection they will have like 'view74_element_6-out')
* section in partition connection point. So once we substr with '-' we don't get any value. So we
* explicitly set the targetId.
* */
if (targetId === '') {
targetId = target;
}
var targetElement = $('#' + targetId);
var source = connection.sourceId;
var sourceId = source.substr(0, source.indexOf('-'));
/*
* There is no 'in' or 'out' clause(for other connection they will have like 'view74_element_6-out')
* section in partition connection point. So once we substr with '-' we don't get any value. So we
* explicitly set the sourceId.
* */
if (sourceId === '') {
sourceId = source;
}
var sourceElement = $('#' + sourceId);
// avoid the expose of inner-streams outside the group
if (sourceElement.hasClass(constants.STREAM)
&& self.jsPlumbInstance.getGroupFor(sourceId) !== undefined) {
if (self.jsPlumbInstance.getGroupFor(sourceId) !== self.jsPlumbInstance.getGroupFor(targetId)) {
DesignViewUtils.prototype
.errorAlert("Invalid Connection: Inner Streams are not exposed to outside");
return connectionValidity;
} else {
return connectionValidity = true;
}
} else if (targetElement.hasClass(constants.STREAM)
&& self.jsPlumbInstance.getGroupFor(targetId) !== undefined) {
if (self.jsPlumbInstance.getGroupFor(targetId) !== self.jsPlumbInstance.getGroupFor(sourceId)) {
DesignViewUtils.prototype
.errorAlert("Invalid Connection: Inner Streams are not exposed to outside");
return connectionValidity;
} else {
return connectionValidity = true;
}
} else if (targetElement.hasClass(constants.PARTITION_CONNECTION_POINT)) {
if (!sourceElement.hasClass(constants.STREAM)) {
DesignViewUtils.prototype.errorAlert("Invalid Connection: Connect an outer stream");
return connectionValidity;
} else {
var partitionId = targetElement.parent()[0].id;
var partition = self.configurationData.getSiddhiAppConfig().getPartition(partitionId);
var connectedStreamName
= self.configurationData.getSiddhiAppConfig().getStream(sourceId).getName();
var isStreamConnected = partition.checkOuterStreamIsAlreadyConnected(connectedStreamName);
if (isStreamConnected) {
DesignViewUtils.prototype
.errorAlert("Invalid Connection: Stream is already connected to the partition");
return connectionValidity;
} else {
var isStreamDirectlyConnectedToAQuery = false;
_.forEach(partition.getWindowFilterProjectionQueryList(), function (query) {
if (query.getQueryInput() !== undefined
&& query.getQueryInput().getConnectedSource() !== undefined
&& query.getQueryInput().getConnectedSource() === connectedStreamName) {
isStreamDirectlyConnectedToAQuery = true;
}
});
_.forEach(partition.getJoinQueryList(), function (query) {
if (query.getQueryInput() !== undefined) {
if (query.getQueryInput().getFirstConnectedElement() !== undefined
&& query.getQueryInput().getFirstConnectedElement().type
=== constants.STREAM
&& query.getQueryInput().getFirstConnectedElement().name
=== connectedStreamName) {
isStreamDirectlyConnectedToAQuery = true;
} else if (query.getQueryInput().getSecondConnectedElement() !== undefined
&& query.getQueryInput().getSecondConnectedElement().type
=== constants.STREAM
&& query.getQueryInput().getSecondConnectedElement().name
=== connectedStreamName) {
isStreamDirectlyConnectedToAQuery = true;
}
}
});
_.forEach(partition.getPatternQueryList(), function (query) {
if (query.getQueryInput() !== undefined) {
var connectedElementNameList
= query.getQueryInput().getConnectedElementNameList();
_.forEach(connectedElementNameList, function (elementName) {
if (connectedStreamName === elementName) {
isStreamDirectlyConnectedToAQuery = true;
}
});
}
});
_.forEach(partition.getSequenceQueryList(), function (query) {
if (query.getQueryInput() !== undefined) {
var connectedElementNameList
= query.getQueryInput().getConnectedElementNameList();
_.forEach(connectedElementNameList, function (elementName) {
if (connectedStreamName === elementName) {
isStreamDirectlyConnectedToAQuery = true;
}
});
}
});
if (isStreamDirectlyConnectedToAQuery) {
DesignViewUtils.prototype.errorAlert("Invalid Connection: Connected stream is " +
"already directly connected to a query inside the partition.");
return connectionValidity;
} else {
return connectionValidity = true;
}
}
}
} else if (sourceElement.hasClass(constants.PARTITION_CONNECTION_POINT)) {
// check whether the partition connection point has a valid connection with a outer stream.
// If not display a error message.
var sourceConnections = self.jsPlumbInstance.getConnections({target: sourceId});
if (sourceConnections.length === 0) {
DesignViewUtils.prototype.errorAlert("Invalid Connection: Connect a outer stream first");
return connectionValidity;
}
var partitionId = sourceElement.parent()[0].id;
if (self.jsPlumbInstance.getGroupFor(targetId)
!== self.jsPlumbInstance.getGroupFor(partitionId)) {
DesignViewUtils.prototype
.errorAlert("Invalid Connection: Connect to a query input inside the partition");
return connectionValidity;
} else {
if (targetElement.hasClass(constants.PROJECTION)
|| targetElement.hasClass(constants.FILTER)
|| targetElement.hasClass(constants.WINDOW_QUERY)
|| targetElement.hasClass(constants.FUNCTION_QUERY)
|| targetElement.hasClass(constants.PATTERN)
|| targetElement.hasClass(constants.JOIN)
|| targetElement.hasClass(constants.SEQUENCE)) {
return connectionValidity = true;
} else {
DesignViewUtils.prototype
.errorAlert("Invalid Connection: Connect to a query input inside the partition");
return connectionValidity;
}
}
} else if (sourceElement.hasClass(constants.PARTITION)) {
if ($(self.jsPlumbInstance.getGroupFor(targetId)).attr('id') == sourceId) {
return connectionValidity = true;
}
DesignViewUtils.prototype.errorAlert("Invalid Connection: Connect to a partition query");
return connectionValidity;
} else if (sourceElement.hasClass(constants.SOURCE)) {
if (!targetElement.hasClass(constants.STREAM)) {
DesignViewUtils.prototype.errorAlert("Invalid Connection: Connect to a stream");
return connectionValidity;
} else {
return connectionValidity = true;
}
} else if (targetElement.hasClass(constants.SINK)) {
if (sourceElement.hasClass(constants.STREAM)) {
return connectionValidity = true;
}
DesignViewUtils.prototype
.errorAlert("Invalid Connection: Sink input source should be a stream");
return connectionValidity;
} else if (targetElement.hasClass(constants.AGGREGATION)) {
if (!(sourceElement.hasClass(constants.STREAM) || sourceElement.hasClass(constants.TRIGGER))) {
DesignViewUtils.prototype
.errorAlert("Invalid Connection: Aggregation input should be a stream or a trigger");
return connectionValidity;
} else {
return connectionValidity = true;
}
} //we allowing all sinks to be connected to source here if connections points are available to
// connect. This need to be changed if there are use cases to allow specifics to connect
else if (targetElement.hasClass(constants.SOURCE)) {
if (sourceElement.hasClass(constants.SINK)) {
return connectionValidity = true;
}
DesignViewUtils.prototype
.errorAlert("Invalid Connection: http-request sink input source should be a " +
"http-response source");
return connectionValidity;
}
// When connecting streams to a query inside the partition if it is connected to the partition
// connection point, it cannot connect to the query directly
if ((targetElement.hasClass(constants.PROJECTION) || targetElement.hasClass(constants.FILTER)
|| targetElement.hasClass(constants.WINDOW_QUERY) || targetElement.hasClass(constants.JOIN)
|| targetElement.hasClass(constants.FUNCTION_QUERY) || targetElement.hasClass(constants.PATTERN)
|| targetElement.hasClass(constants.SEQUENCE))
&& sourceElement.hasClass(constants.STREAM)) {
var querySavedInsideAPartition
= self.configurationData.getSiddhiAppConfig().getQueryByIdSavedInsideAPartition(targetId);
var isQueryInsideAPartition = querySavedInsideAPartition !== undefined;
if (isQueryInsideAPartition) {
var partitionId = (self.jsPlumbInstance.getGroupFor(targetId)).id;
var partition = self.configurationData.getSiddhiAppConfig().getPartition(partitionId);
var connectedStreamName
= self.configurationData.getSiddhiAppConfig().getStream(sourceId).getName();
var isStreamConnected = partition.checkOuterStreamIsAlreadyConnected(connectedStreamName);
if (isStreamConnected) {
DesignViewUtils.prototype
.errorAlert("Invalid Connection: Stream is already connected to the partition");
return connectionValidity;
}
}
}
if (targetElement.hasClass(constants.PATTERN) || targetElement.hasClass(constants.SEQUENCE)) {
if (!(sourceElement.hasClass(constants.STREAM) || sourceElement.hasClass(constants.TRIGGER))) {
DesignViewUtils.prototype.errorAlert("Invalid Connection");
return connectionValidity;
} else {
return connectionValidity = true;
}
} else if (targetElement.hasClass(constants.PROJECTION) || targetElement.hasClass(constants.FILTER)
|| targetElement.hasClass(constants.WINDOW_QUERY)
|| targetElement.hasClass(constants.FUNCTION_QUERY)) {
if (!(sourceElement.hasClass(constants.STREAM) || sourceElement.hasClass(constants.WINDOW)
|| sourceElement.hasClass(constants.TRIGGER))) {
DesignViewUtils.prototype.errorAlert("Invalid Connection");
return connectionValidity;
} else {
return connectionValidity = true;
}
} else if (targetElement.hasClass(constants.JOIN)) {
if (!(sourceElement.hasClass(constants.STREAM) || sourceElement.hasClass(constants.TABLE)
|| sourceElement.hasClass(constants.AGGREGATION)
|| sourceElement.hasClass(constants.TRIGGER)
|| sourceElement.hasClass(constants.WINDOW))) {
DesignViewUtils.prototype.errorAlert("Invalid Connection");
return connectionValidity;
} else {
var sourceElementObject =
self.configurationData.getSiddhiAppConfig().getDefinitionElementById(sourceId);
if (sourceElementObject !== undefined) {
var connectedElementSourceType = sourceElementObject.type;
} else {
console.log("Cannot find the source element connected to join query");
}
var joinQuery = self.configurationData.getSiddhiAppConfig().getJoinQuery(targetId);
var queryInput = joinQuery.getQueryInput();
if (!queryInput) {
return connectionValidity = true;
} else {
var firstConnectedElement = queryInput.getFirstConnectedElement();
var secondConnectedElement = queryInput.getSecondConnectedElement();
if (!firstConnectedElement && !secondConnectedElement) {
return connectionValidity = true;
} else if (firstConnectedElement !== undefined
&& secondConnectedElement !== undefined) {
DesignViewUtils.prototype
.errorAlert("Invalid Connection: Only two input elements are allowed to " +
"connect in join query!");
return connectionValidity = false;
} else if (firstConnectedElement !== undefined
&& !secondConnectedElement) {
var firstElementType = firstConnectedElement.type;
if (firstElementType === 'STREAM' || firstElementType === 'TRIGGER'
|| firstElementType === 'WINDOW') {
return connectionValidity = true;
} else if (connectedElementSourceType === 'STREAM'
|| connectedElementSourceType === 'TRIGGER'
|| connectedElementSourceType === 'WINDOW') {
return connectionValidity = true;
} else {
DesignViewUtils.prototype
.errorAlert("Invalid Connection: At least one connected input element in " +
"join query should be a stream or a trigger or a window!");
return connectionValidity = false;
}
} else if (!firstConnectedElement && secondConnectedElement !== undefined) {
var secondElementType = secondConnectedElement.type;
if (secondElementType === 'STREAM' || secondElementType === 'TRIGGER'
|| secondElementType === 'WINDOW') {
return connectionValidity = true;
} else if (connectedElementSourceType === 'STREAM'
|| connectedElementSourceType === 'TRIGGER'
|| connectedElementSourceType === 'WINDOW') {
return connectionValidity = true;
} else {
DesignViewUtils.prototype
.errorAlert("Invalid Connection: At least one connected input element in " +
"join query should be a stream or a trigger or a window!");
return connectionValidity = false;
}
}
}
}
} else if (sourceElement.hasClass(constants.PROJECTION) || sourceElement.hasClass(constants.FILTER)
|| sourceElement.hasClass(constants.WINDOW_QUERY) || sourceElement.hasClass(constants.PATTERN)
|| sourceElement.hasClass(constants.JOIN) || sourceElement.hasClass(constants.SEQUENCE)
|| sourceElement.hasClass(constants.FUNCTION_QUERY)) {
if (!(targetElement.hasClass(constants.STREAM) || targetElement.hasClass(constants.TABLE)
|| targetElement.hasClass(constants.WINDOW))) {
DesignViewUtils.prototype.errorAlert("Invalid Connection");
return connectionValidity;
} else {
return connectionValidity = true;
}
}
if (!connectionValidity) {
DesignViewUtils.prototype.errorAlert("Invalid Connection");
}
return connectionValidity;
});
}
// Update the model when a connection is established and bind events for the connection
function updateModelOnConnectionAttach() {
self.jsPlumbInstance.bind('connection', function (connection) {
// set the isDesignViewContentChanged to true
self.configurationData.setIsDesignViewContentChanged(true);
var target = connection.targetId;
var targetId = target.substr(0, target.indexOf('-'));
var targetType;
/*
* There is no 'in' or 'out' clause(for other connection they will have like 'view74_element_6-out')
* section in partition connection point. So once we substr with '-' we don't get any value. So we
* explicitly set the targetId. Simply if targetId is '' that means this connection is related to a
* partition.
* */
if (targetId === '') {
targetId = target;
targetType = 'PARTITION';
} else {
if (self.configurationData.getSiddhiAppConfig().getDefinitionElementById(targetId, true, true)
!== undefined) {
targetType
= self.configurationData.getSiddhiAppConfig()
.getDefinitionElementById(targetId, true, true).type;
} else {
console.log("Target element not found!");
}
}
var targetElement = $('#' + targetId);
var source = connection.sourceId;
var sourceId = source.substr(0, source.indexOf('-'));
var sourceType;
/*
* There is no 'in' or 'out' clause(for other connection they will have like 'view74_element_6-out')
* section in partition connection point. So once we substr with '-' we don't get any value. So we
* explicitly set the sourceId. Simply if sourceId is '' that means this connection is related to a
* partition.
* */
var isFromFaultStream = connection.sourceId.substr(connection.sourceId.indexOf('-')) === '-err-out';
if (sourceId === '') {
sourceId = source;
sourceType = 'PARTITION';
} else {
if (isFromFaultStream) {
// Change the source id to the respective source id of the fault stream
var streamMap = {};
var eventStreamName = '';
self.configurationData.getSiddhiAppConfig().getStreamList().forEach(function(s) {
streamMap[s.getName()] = s;
if (s.getId() === sourceId) {
eventStreamName = s.getName();
}
});
sourceId = streamMap[Constants.FAULT_STREAM_PREFIX + eventStreamName].getId();
}
if (self.configurationData.getSiddhiAppConfig().getDefinitionElementById(sourceId, true, true)
!== undefined) {
sourceType
= self.configurationData.getSiddhiAppConfig()
.getDefinitionElementById(sourceId, true, true).type;
} else {
console.log("Source element not found!");
}
}
var sourceElement = $('#' + sourceId);
var isConnectionMadeInsideAPartition = false;
if (self.jsPlumbInstance.getGroupFor(sourceId) !== undefined
&& self.jsPlumbInstance.getGroupFor(targetId) !== undefined) {
isConnectionMadeInsideAPartition = true;
}
// create and add an edge to the edgeList
var edgeId = '' + sourceId + '_' + targetId + '';
var edgeInTheEdgeList = self.configurationData.getEdge(edgeId);
if (!edgeInTheEdgeList) {
var edgeOptions = {};
_.set(edgeOptions, 'id', edgeId);
_.set(edgeOptions, 'childId', targetId);
_.set(edgeOptions, 'childType', targetType);
_.set(edgeOptions, 'parentId', sourceId);
_.set(edgeOptions, 'parentType', sourceType);
var edge = new Edge(edgeOptions);
self.configurationData.addEdge(edge);
}
var model;
var connectedElementName;
if (targetElement.hasClass(constants.PARTITION_CONNECTION_POINT)
&& sourceElement.hasClass(constants.STREAM)) {
var partitionId = targetElement.parent()[0].id;
var partition = self.configurationData.getSiddhiAppConfig().getPartition(partitionId);
connectedElementName
= self.configurationData.getSiddhiAppConfig().getStream(sourceId).getName();
/*
* check whether the stream is already connected to partition. This validation is done in the
* checkConnectionValidityBeforeElementDrop() function. But that beforedrop event is triggered
* only when user adds connection. It doesn't fire when we programmatically create connections
* (in this case rendering the design view from code). So we need to do the validation here
* again.
* */
var isStreamConnected = partition.checkOuterStreamIsAlreadyConnected(connectedElementName);
if (!isStreamConnected) {
var partitionWithOptions = {};
_.set(partitionWithOptions, 'streamName', connectedElementName);
_.set(partitionWithOptions, 'expression', undefined);
var partitionWithObject = new PartitionWith(partitionWithOptions);
partition.addPartitionWith(partitionWithObject);
}
var partitionElement = $('#' + partitionId);
var newPartitionConnectorInPartNo = self.generateNextConnectionPointIdForPartition(partitionId);
var connectionIn =
$('<div class="' + constants.PARTITION_CONNECTION_POINT + '">')
.attr('id', newPartitionConnectorInPartNo);
partitionElement.append(connectionIn);
self.jsPlumbInstance.makeTarget(connectionIn, {
anchor: 'Left',
maxConnections: 1,
deleteEndpointsOnDetach: true
});
self.jsPlumbInstance.makeSource(connectionIn, {
anchor: 'Right',
deleteEndpointsOnDetach: true
});
} else if (sourceElement.hasClass(constants.SOURCE) && targetElement.hasClass(constants.STREAM)) {
connectedElementName = self.configurationData.getSiddhiAppConfig().getStream(targetId)
.getName();
self.configurationData.getSiddhiAppConfig().getSource(sourceId)
.setConnectedElementName(connectedElementName);
} else if (targetElement.hasClass(constants.SINK) && sourceElement.hasClass(constants.STREAM)) {
connectedElementName = self.configurationData.getSiddhiAppConfig().getStream(sourceId)
.getName();
self.configurationData.getSiddhiAppConfig().getSink(targetId)
.setConnectedElementName(connectedElementName);
} else if (sourceElement.hasClass(constants.SINK) && targetElement.hasClass(constants.SOURCE)) {
connectedElementName = self.configurationData.getSiddhiAppConfig().getSource(targetId)
.getType();
self.configurationData.getSiddhiAppConfig().getSink(sourceId)
.setConnectedRightElementName(connectedElementName);
} else if (targetElement.hasClass(constants.AGGREGATION)
&& (sourceElement.hasClass(constants.STREAM) || sourceElement.hasClass(constants.TRIGGER))) {
if (sourceElement.hasClass(constants.STREAM)) {
connectedElementName = self.configurationData.getSiddhiAppConfig().getStream(sourceId)
.getName();
} else if (sourceElement.hasClass(constants.TRIGGER)) {
connectedElementName = self.configurationData.getSiddhiAppConfig().getTrigger(sourceId)
.getName();
}
self.configurationData.getSiddhiAppConfig().getAggregation(targetId)
.setConnectedSource(connectedElementName);
} else if (sourceElement.hasClass(constants.STREAM) || sourceElement.hasClass(constants.TABLE)
|| sourceElement.hasClass(constants.AGGREGATION) || sourceElement.hasClass(constants.WINDOW)
|| sourceElement.hasClass(constants.TRIGGER)
|| sourceElement.hasClass(constants.PARTITION_CONNECTION_POINT)) {
/*
* Partition connection point represents a stream connection point. so it holds a reference for
* the stream.So that in here we replaces the source element with the actual stream element if a
* connection partition connection pint is found.
* */
if (sourceElement.hasClass(constants.PARTITION_CONNECTION_POINT)) {
var sourceConnection = self.jsPlumbInstance.getConnections({target: sourceId});
var sourceConnectionId = sourceConnection[0].sourceId;
var connectedStreamId = sourceConnectionId.substr(0, sourceConnectionId.indexOf('-'));
connectedElementName = self.configurationData.getSiddhiAppConfig()
.getStream(connectedStreamId).getName();
sourceElement = $('#' + connectedStreamId);
sourceId = connectedStreamId;
}
else if (sourceElement.hasClass(constants.STREAM)) {
connectedElementName = self.configurationData.getSiddhiAppConfig().getStream(sourceId)
.getName();
}
else if (sourceElement.hasClass(constants.TABLE)) {
connectedElementName = self.configurationData.getSiddhiAppConfig().getTable(sourceId)
.getName();
}
else if (sourceElement.hasClass(constants.WINDOW)) {
connectedElementName = self.configurationData.getSiddhiAppConfig().getWindow(sourceId)
.getName();
}
else if (sourceElement.hasClass(constants.AGGREGATION)) {
connectedElementName = self.configurationData.getSiddhiAppConfig().getAggregation(sourceId)
.getName();
}
else if (sourceElement.hasClass(constants.TRIGGER)) {
connectedElementName = self.configurationData.getSiddhiAppConfig().getTrigger(sourceId)
.getName();
}
if ((sourceElement.hasClass(constants.STREAM) || sourceElement.hasClass(constants.WINDOW)
|| sourceElement.hasClass(constants.TRIGGER))
&& (targetElement.hasClass(constants.PROJECTION) || targetElement.hasClass(constants.FILTER)
|| targetElement.hasClass(constants.WINDOW_QUERY)
|| targetElement.hasClass(constants.FUNCTION_QUERY))) {
model = self.configurationData.getSiddhiAppConfig()
.getWindowFilterProjectionQuery(targetId);
var type;
if (targetElement.hasClass(constants.PROJECTION)) {
type = 'PROJECTION';
}
else if (targetElement.hasClass(constants.FILTER)) {
type = 'FILTER';
}
else if (targetElement.hasClass(constants.WINDOW_QUERY)) {
type = 'WINDOW';
}
else if (targetElement.hasClass(constants.FUNCTION_QUERY)) {
type = 'FUNCTION';
}
if (!model.getQueryInput()) {
var queryInputOptions = {};
_.set(queryInputOptions, 'type', type);
_.set(queryInputOptions, 'from', connectedElementName);
var queryInputObject = new WindowFilterProjectionQueryInput(queryInputOptions);
model.setQueryInput(queryInputObject);
} else {
model.getQueryInput().setConnectedSource(connectedElementName);
}
} else if (targetElement.hasClass(constants.JOIN)) {
model = self.configurationData.getSiddhiAppConfig().getJoinQuery(targetId);
var queryInput = model.getQueryInput();
var sourceElementObject =
self.configurationData.getSiddhiAppConfig().getDefinitionElementById(sourceId);
var connectedElement;
if (sourceElementObject !== undefined) {
var connectedElementSourceName = (sourceElementObject.element).getName();
var connectedElementSourceType = sourceElementObject.type;
connectedElement = {
name: connectedElementSourceName,
type: connectedElementSourceType
};
if (!queryInput) {
var joinQueryInput = new JoinQueryInput();
joinQueryInput.setFirstConnectedElement(connectedElement);
model.setQueryInput(joinQueryInput);
} else {
var firstConnectedElement = queryInput.getFirstConnectedElement();
var secondConnectedElement = queryInput.getSecondConnectedElement();
if (!firstConnectedElement) {
queryInput.setFirstConnectedElement(connectedElement);
} else if (!secondConnectedElement) {
queryInput.setSecondConnectedElement(connectedElement);
} else {
console.log("Error: First and second input elements are already filled in " +
"join query!");
}
}
}
} else if (sourceElement.hasClass(constants.STREAM)
|| sourceElement.hasClass(constants.TRIGGER)) {
if (sourceElement.hasClass(constants.STREAM)) {
connectedElementName =
self.configurationData.getSiddhiAppConfig().getStream(sourceId).getName();
} else {
connectedElementName =
self.configurationData.getSiddhiAppConfig().getTrigger(sourceId).getName();
}
if (targetElement.hasClass(constants.PATTERN)) {
model = self.configurationData.getSiddhiAppConfig().getPatternQuery(targetId);
if (!model.getQueryInput()) {
var patternQueryInputOptions = {};
_.set(patternQueryInputOptions, 'type', 'PATTERN');
var patternQueryInputObject =
new PatternOrSequenceQueryInput(patternQueryInputOptions);
patternQueryInputObject.addConnectedElementName(connectedElementName);
model.setQueryInput(patternQueryInputObject);
} else {
model.getQueryInput().addConnectedElementName(connectedElementName);
}
} else if (targetElement.hasClass(constants.SEQUENCE)) {
model = self.configurationData.getSiddhiAppConfig().getSequenceQuery(targetId);
if (!model.getQueryInput()) {
var sequenceQueryInputOptions = {};
_.set(sequenceQueryInputOptions, 'type', 'SEQUENCE');
var sequenceQueryInputObject =
new PatternOrSequenceQueryInput(sequenceQueryInputOptions);
sequenceQueryInputObject.addConnectedElementName(connectedElementName);
model.setQueryInput(sequenceQueryInputObject);
} else {
model.getQueryInput().addConnectedElementName(connectedElementName);
}
}
}
}
else if (targetElement.hasClass(constants.STREAM) || targetElement.hasClass(constants.TABLE)
|| targetElement.hasClass(constants.WINDOW)) {
if (sourceElement.hasClass(constants.PROJECTION) || sourceElement.hasClass(constants.FILTER)
|| sourceElement.hasClass(constants.WINDOW_QUERY) || sourceElement.hasClass(constants.JOIN)
|| sourceElement.hasClass(constants.PATTERN)
|| sourceElement.hasClass(constants.FUNCTION_QUERY)
|| sourceElement.hasClass(constants.SEQUENCE)) {
if (targetElement.hasClass(constants.STREAM)) {
connectedElementName = self.configurationData.getSiddhiAppConfig().getStream(targetId)
.getName();
}
else if (targetElement.hasClass(constants.TABLE)) {
connectedElementName = self.configurationData.getSiddhiAppConfig().getTable(targetId)
.getName();
}
else if (targetElement.hasClass(constants.WINDOW)) {
connectedElementName = self.configurationData.getSiddhiAppConfig().getWindow(targetId)
.getName();
}
if (sourceElement.hasClass(constants.PROJECTION) || sourceElement.hasClass(constants.FILTER)
|| sourceElement.hasClass(constants.WINDOW_QUERY)
|| sourceElement.hasClass(constants.FUNCTION_QUERY)) {
model = self.configurationData.getSiddhiAppConfig()
.getWindowFilterProjectionQuery(sourceId);
} else if (sourceElement.hasClass(constants.JOIN)) {
model = self.configurationData.getSiddhiAppConfig().getJoinQuery(sourceId);
} else if (sourceElement.hasClass(constants.PATTERN)) {
model = self.configurationData.getSiddhiAppConfig().getPatternQuery(sourceId);
} else if (sourceElement.hasClass(constants.SEQUENCE)) {
model = self.configurationData.getSiddhiAppConfig().getSequenceQuery(sourceId);
}
if (!model.getQueryOutput()) {
var queryOutputOptions = {};
_.set(queryOutputOptions, 'target', connectedElementName);
var patternQueryOutputObject = new QueryOutput(queryOutputOptions);
model.setQueryOutput(patternQueryOutputObject);
} else {
model.getQueryOutput().setTarget(connectedElementName);
}
}
}
// do not check for json validity if the design is still generating from the data sent from backend
if (!self.configurationData.getIsStillDrawingGraph()) {
if (sourceType === 'PARTITION') {
sourceId = sourceElement.parent().attr('id');
} else if (targetType === 'PARTITION') {
targetId = targetElement.parent().attr('id');
}
// validate source and target elements
checkJSONValidityOfElement(self, sourceId, true);
checkJSONValidityOfElement(self, targetId, true);
}
var connectionObject = connection.connection;
// add a overlay of a close icon for connection. connection can be detached by clicking on it
var close_icon_overlay = connectionObject.addOverlay([
"Custom", {
create: function () {
return $(
'<span><i class="fw fw-delete" id="' + self.currentTabId + connectionObject.id +
'"data-toggle="popover"></i></span>');
},
location: 0.60,
id: "close",
events: {
click: function () {
popOverForConnector();
}
}
}
]);
function popOverForConnector() {
$('#' + self.currentTabId + connectionObject.id).popover({
trigger: 'focus',
title: 'Confirmation',
html: true,
content: function () {
return $('.pop-over').html();
}
});
$('#' + self.currentTabId + connectionObject.id).off();
$('#' + self.currentTabId + connectionObject.id).popover("show");
$('.btn_no').focus();
$(".overlayed-container ").fadeTo(200, 1);
// Custom jQuery to hide popover on click of the close button
$("#" + self.currentTabId + connectionObject.id).siblings(".popover").on("click", ".popover-footer .btn_yes",
function () {
if (connectionObject.connector !== null) {
self.jsPlumbInstance.deleteConnection(connectionObject);
}
$(".overlayed-container ").fadeOut(200);
$(this).parents(".popover").popover('hide');
});
$("#" + self.currentTabId + connectionObject.id).siblings(".popover").on("click", ".popover-footer .btn_no",
function () {
$(".overlayed-container ").fadeOut(200);
$(this).parents(".popover").popover('hide');
close_icon_overlay.setVisible(false);
});
// Dismiss the pop-over by clicking outside
$('.overlayed-container ').off('click');
$('.overlayed-container ').on('click', function (e) {
$('[data-toggle="popover"]').each(function () {
if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(
e.target).length === 0) {
$(this).popover('hide');
$(".overlayed-container ").fadeOut(200);
close_icon_overlay.setVisible(false);
}
});
});
$(".btn_no").on("keyup", function (e) {
if (e.which === ESCAPE_KEY && $("#" + self.currentTabId + connectionObject.id).popover()) {
$("#" + self.currentTabId + connectionObject.id).popover('hide');
$(".overlayed-container ").fadeOut(200);
close_icon_overlay.setVisible(false);
}
});
//Navigation using arrow keys
$(".btn_no").on('keydown', function (e) {
if (e.keyCode == RIGHT_ARROW_KEY) {
$('.btn_yes').focus();
}
});
$(".btn_yes").on('keydown', function (e) {
if (e.keyCode == LEFT_ARROW_KEY) {
$('.btn_no').focus();
}
});
$(".btn_no").on('keydown', function (e) {
if (e.keyCode == TAB_KEY) {
e.preventDefault();
}
if (e.keyCode == ENTER_KEY) {
e.stopPropagation();
}
});
//Stop tab propagation and enter propagation when popover showed
$(".btn_yes").on('keydown', function (e) {
if (e.keyCode == TAB_KEY) {
e.preventDefault();
}
if (e.keyCode == ENTER_KEY) {
e.stopPropagation();
}
});
}
if (isConnectionMadeInsideAPartition) {
close_icon_overlay.setVisible(false);
// show the close icon when mouse is over the connection
connectionObject.bind('mouseenter', function () {
close_icon_overlay.setVisible(true);
});
// hide the close icon when the mouse is not on the connection path
connectionObject.bind('mouseleave', function () {
if ($("#" + self.currentTabId + connectionObject.id).siblings(".popover").length == 0) {
close_icon_overlay.setVisible(false);
}
});
} else {
close_icon_overlay.setVisible(false);
// show the close icon when mouse is over the connection
connectionObject.bind('mouseover', function () {
close_icon_overlay.setVisible(true);
});
// hide the close icon when the mouse is not on the connection path
connectionObject.bind('mouseout', function () {
if ($("#" + self.currentTabId + connectionObject.id).siblings(".popover").length == 0) {
close_icon_overlay.setVisible(false);
}
});
}
});
}
// Update the model before detaching a connection
function updateModelOnBeforeConnectionDetach() {
self.jsPlumbInstance.bind('beforeDetach', function (connection) {
var target = connection.targetId;
var targetId = target.substr(0, target.indexOf('-'));
/*
* There is no 'in' or 'out' clause(for other connection they will have like 'view74_element_6-out')
* section in partition connection point. So once we substr with '-' we don't get any value. So we
* explicitly set the targetId. Simply if targetId is '' that means this connection is related to a
* partition.
* */
if (targetId === '') {
targetId = target;
} else if (!self.configurationData.getSiddhiAppConfig()
.getDefinitionElementById(targetId, true, true)) {
console.log("Target element not found!");
}
var targetElement = $('#' + targetId);
var source = connection.sourceId;
var sourceId = source.substr(0, source.indexOf('-'));
/*
* There is no 'in' or 'out' clause(for other connection they will have like 'view74_element_6-out')
* section in partition connection point. So once we substr with '-' we don't get any value. So we
* explicitly set the sourceId. Simply if sourceId is '' that means this connection is related to a
* partition.
* */
if (sourceId === '') {
sourceId = source;
} else if (!self.configurationData.getSiddhiAppConfig()
.getDefinitionElementById(sourceId, true, true)) {
console.log("Source element not found!");
}
var sourceElement = $('#' + sourceId);
// removing edge from the edgeList
var edgeId = '' + sourceId + '_' + targetId + '';
self.configurationData.removeEdge(edgeId);
if (targetElement.hasClass(constants.PARTITION_CONNECTION_POINT)
&& sourceElement.hasClass(constants.STREAM)) {
var partitionId = targetElement.parent()[0].id;
var partition = self.configurationData.getSiddhiAppConfig().getPartition(partitionId);
var disconnectedElementName
= self.configurationData.getSiddhiAppConfig().getStream(sourceId).getName();
partition.removePartitionWith(disconnectedElementName);
var connections = self.jsPlumbInstance.getConnections({source: targetId});
_.forEach(connections, function (connection) {
self.jsPlumbInstance.deleteConnection(connection);
});
targetElement.detach();
// validate the partition
checkJSONValidityOfElement(self, partitionId, true);
}
});
}
// Update the model when a connection is detached
function updateModelOnConnectionDetach() {
self.jsPlumbInstance.bind('connectionDetached', function (connection) {
// set the isDesignViewContentChanged to true
self.configurationData.setIsDesignViewContentChanged(true);
var target = connection.targetId;
var targetId = target.substr(0, target.indexOf('-'));
/*
* There is no 'in' or 'out' clause(for other connection they will have like 'view74_element_6-out')
* section in partition connection point. So once we substr with '-' we don't get any value. So we
* explicitly set the targetId. Simply if targetId is '' that means this connection is related to a
* partition.
* */
if (targetId === '') {
targetId = target;
} else if (!self.configurationData.getSiddhiAppConfig()
.getDefinitionElementById(targetId, true, true)) {
console.log("Target element not found!");
}
var targetElement = $('#' + targetId);
var source = connection.sourceId;
var sourceId = source.substr(0, source.indexOf('-'));
/*
* There is no 'in' or 'out' clause(for other connection they will have like 'view74_element_6-out')
* section in partition connection point. So once we substr with '-' we don't get any value. So we
* explicitly set the sourceId. Simply if sourceId is '' that means this connection is related to a
* partition.
* */
if (sourceId === '') {
sourceId = source;
} else if (!self.configurationData.getSiddhiAppConfig()
.getDefinitionElementById(sourceId, true, true)) {
console.log("Source element not found!");
}
var sourceElement = $('#' + sourceId);
// removing edge from the edgeList
var edgeId = '' + sourceId + '_' + targetId + '';
self.configurationData.removeEdge(edgeId);
var model;
if (sourceElement.hasClass(constants.SOURCE) && targetElement.hasClass(constants.STREAM)) {
self.configurationData.getSiddhiAppConfig().getSource(sourceId)
.setConnectedElementName(undefined);
} else if (targetElement.hasClass(constants.SINK) && sourceElement.hasClass(constants.STREAM)) {
self.configurationData.getSiddhiAppConfig().getSink(targetId)
.setConnectedElementName(undefined);
} else if (targetElement.hasClass(constants.AGGREGATION)
&& (sourceElement.hasClass(constants.STREAM) || sourceElement.hasClass(constants.TRIGGER))) {
model = self.configurationData.getSiddhiAppConfig().getAggregation(targetId)
model.setConnectedSource(undefined);
if(sourceElement.hasClass(constants.STREAM)) {
model.resetInputModel(model);
}
} else if (sourceElement.hasClass(constants.STREAM) || sourceElement.hasClass(constants.TABLE)
|| sourceElement.hasClass(constants.AGGREGATION) || sourceElement.hasClass(constants.WINDOW)
|| sourceElement.hasClass(constants.TRIGGER)
|| sourceElement.hasClass(constants.PARTITION_CONNECTION_POINT)) {
// if the sourceElement has the class constants.PARTITION_CONNECTION_POINT then that is
// basically a stream because a connection point holds a connection to a stream.
// So we replace that sourceElement with the actual stream element.
if (sourceElement.hasClass(constants.PARTITION_CONNECTION_POINT)) {
var sourceConnection = self.jsPlumbInstance.getConnections({target: sourceId});
var sourceConnectionId = sourceConnection[0].sourceId;
var connectedStreamId = sourceConnectionId.substr(0, sourceConnectionId.indexOf('-'));
sourceElement = $('#' + connectedStreamId);
sourceId = connectedStreamId;
}
if ((sourceElement.hasClass(constants.STREAM) || sourceElement.hasClass(constants.WINDOW)
|| sourceElement.hasClass(constants.TRIGGER))
&& (targetElement.hasClass(constants.PROJECTION) || targetElement.hasClass(constants.FILTER)
|| targetElement.hasClass(constants.WINDOW_QUERY)
|| targetElement.hasClass(constants.FUNCTION_QUERY))) {
model = self.configurationData.getSiddhiAppConfig()
.getWindowFilterProjectionQuery(targetId);
model.resetInputModel(model);
} else if (targetElement.hasClass(constants.JOIN)) {
model = self.configurationData.getSiddhiAppConfig().getJoinQuery(targetId);
var queryInput = model.getQueryInput();
var sourceElementObject =
self.configurationData.getSiddhiAppConfig().getDefinitionElementById(sourceId);
if (sourceElementObject !== undefined) {
var disconnectedElementSourceName = (sourceElementObject.element).getName();
if (!queryInput) {
console.log("Join query output is undefined!");
return;
}
var firstConnectedElement = queryInput.getFirstConnectedElement();
var secondConnectedElement = queryInput.getSecondConnectedElement();
if (!firstConnectedElement && !secondConnectedElement) {
console.log("firstConnectedElement and secondConnectedElement are undefined!");
} else if (firstConnectedElement &&
(firstConnectedElement.name === disconnectedElementSourceName ||
!firstConnectedElement.name)) {
queryInput.setFirstConnectedElement(undefined);
} else if (secondConnectedElement
&& (secondConnectedElement.name === disconnectedElementSourceName ||
!secondConnectedElement.name)) {
queryInput.setSecondConnectedElement(undefined);
} else {
console.log("Error: Disconnected source name not found in join query!");
return;
}
// if left or sources are created then remove data from those sources
if (queryInput.getLeft() !== undefined
&& queryInput.getLeft().getConnectedSource() === disconnectedElementSourceName) {
queryInput.setLeft(undefined);
} else if (queryInput.getRight() !== undefined
&& queryInput.getRight().getConnectedSource() === disconnectedElementSourceName) {
queryInput.setRight(undefined);
}
model.resetInputModel(model);
}
} else if (sourceElement.hasClass(constants.STREAM)
|| sourceElement.hasClass(constants.TRIGGER)) {
var disconnectedElementName;
if (sourceElement.hasClass(constants.STREAM)) {
disconnectedElementName =
self.configurationData.getSiddhiAppConfig().getStream(sourceId).getName();
} else {
disconnectedElementName =
self.configurationData.getSiddhiAppConfig().getTrigger(sourceId).getName();
}
if (targetElement.hasClass(constants.PATTERN)) {
model = self.configurationData.getSiddhiAppConfig().getPatternQuery(targetId);
model.resetInputModel(model, disconnectedElementName);
} else if (targetElement.hasClass(constants.SEQUENCE)) {
model = self.configurationData.getSiddhiAppConfig().getSequenceQuery(targetId);
model.resetInputModel(model, disconnectedElementName);
}
}
} else if (targetElement.hasClass(constants.STREAM) || targetElement.hasClass(constants.TABLE)
|| targetElement.hasClass(constants.WINDOW)) {
if (sourceElement.hasClass(constants.PROJECTION) || sourceElement.hasClass(constants.FILTER)
|| sourceElement.hasClass(constants.WINDOW_QUERY)
|| sourceElement.hasClass(constants.FUNCTION_QUERY)
|| sourceElement.hasClass(constants.JOIN)
|| sourceElement.hasClass(constants.PATTERN)
|| sourceElement.hasClass(constants.SEQUENCE)) {
if (sourceElement.hasClass(constants.PROJECTION) || sourceElement.hasClass(constants.FILTER)
|| sourceElement.hasClass(constants.WINDOW_QUERY)
|| sourceElement.hasClass(constants.FUNCTION_QUERY)) {
model = self.configurationData.getSiddhiAppConfig()
.getWindowFilterProjectionQuery(sourceId);
} else if (sourceElement.hasClass(constants.JOIN)) {
model = self.configurationData.getSiddhiAppConfig().getJoinQuery(sourceId);
} else if (sourceElement.hasClass(constants.PATTERN)) {
model = self.configurationData.getSiddhiAppConfig().getPatternQuery(sourceId);
} else if (sourceElement.hasClass(constants.SEQUENCE)) {
model = self.configurationData.getSiddhiAppConfig().getSequenceQuery(sourceId);
}
model.resetOutputModel(model);
}
}
// validate source and target elements
checkJSONValidityOfElement(self, sourceId, true);
checkJSONValidityOfElement(self, targetId, true);
});
}
function addMemberToPartitionGroup(self) {
self.jsPlumbInstance.bind('group:addMember', function (event) {
// set the isDesignViewContentChanged to true
self.configurationData.setIsDesignViewContentChanged(true);
var partitionId = $(event.group).attr('id');
var partition = self.configurationData.getSiddhiAppConfig().getPartition(partitionId);
// check whether member is already added to the group
if (partition.isElementInsidePartition(event.el.id)) {
return;
}
var errorMessage = '';
var isGroupMemberValid = false;
if ($(event.el).hasClass(constants.FILTER) || $(event.el).hasClass(constants.PROJECTION)
|| $(event.el).hasClass(constants.WINDOW_QUERY)
|| $(event.el).hasClass(constants.FUNCTION_QUERY)
|| $(event.el).hasClass(constants.JOIN)
|| $(event.el).hasClass(constants.SEQUENCE) || $(event.el).hasClass(constants.PATTERN)
|| $(event.el).hasClass(constants.STREAM)) {
var elementId = event.el.id;
var sourceConnectionPointId = elementId + '-out';
var targetConnectionPointId = elementId + '-in';
var noOfSourceConnections
= self.jsPlumbInstance.getConnections({source: sourceConnectionPointId});
var noOfTargetConnections
= self.jsPlumbInstance.getConnections({target: targetConnectionPointId});
var totalConnection = noOfSourceConnections.length + noOfTargetConnections.length;
if (totalConnection === 0) {
isGroupMemberValid = true;
if ($(event.el).hasClass(constants.STREAM)) {
var streamObject = self.configurationData.getSiddhiAppConfig().getStream(elementId);
var streamObjectCopy = _.cloneDeep(streamObject);
var streamName = streamObjectCopy.getName();
var firstCharacterInStreamName = (streamName).charAt(0);
if (firstCharacterInStreamName !== '#') {
streamName = '#' + streamName;
}
// check if there is an inner stream with the same name exists. If yes do not add
// the element to the partition
var isStreamNameUsed
= self.dropElements.formBuilder.formUtils
.isStreamDefinitionNameUsedInPartition(partitionId, streamName);
if (!isStreamNameUsed) {
streamObjectCopy.setName(streamName);
var textNode = $('#' + elementId).parent().find('.streamNameNode');
textNode.html(streamName);
self.configurationData.getSiddhiAppConfig().removeStream(elementId);
partition.addStream(streamObjectCopy);
JSONValidator.prototype
.validateInnerStream(streamObjectCopy, self.jsPlumbInstance, true);
} else {
isGroupMemberValid = false;
errorMessage = ' An inner stream with the same name is already added to the ' +
'partition.';
}
} else if ($(event.el).hasClass(constants.PROJECTION)) {
var projectionQueryObject = self.configurationData.getSiddhiAppConfig()
.getWindowFilterProjectionQuery(elementId);
var projectionQueryObjectCopy = _.cloneDeep(projectionQueryObject);
self.configurationData.getSiddhiAppConfig()
.removeWindowFilterProjectionQuery(elementId);
partition.addWindowFilterProjectionQuery(projectionQueryObjectCopy);
} else if ($(event.el).hasClass(constants.FILTER)) {
var filterQueryObject = self.configurationData.getSiddhiAppConfig()
.getWindowFilterProjectionQuery(elementId);
var filterQueryObjectCopy = _.cloneDeep(filterQueryObject);
self.configurationData.getSiddhiAppConfig()
.removeWindowFilterProjectionQuery(elementId);
partition.addWindowFilterProjectionQuery(filterQueryObjectCopy);
} else if ($(event.el).hasClass(constants.WINDOW_QUERY)) {
var windowQueryObject = self.configurationData.getSiddhiAppConfig()
.getWindowFilterProjectionQuery(elementId);
var windowQueryObjectCopy = _.cloneDeep(windowQueryObject);
self.configurationData.getSiddhiAppConfig()
.removeWindowFilterProjectionQuery(elementId);
partition.addWindowFilterProjectionQuery(windowQueryObjectCopy);
} else if ($(event.el).hasClass(constants.FUNCTION_QUERY)) {
var functionQueryObject = self.configurationData.getSiddhiAppConfig()
.getWindowFilterProjectionQuery(elementId);
var functionQueryObjectCopy = _.cloneDeep(functionQueryObject);
self.configurationData.getSiddhiAppConfig()
.removeWindowFilterProjectionQuery(elementId);
partition.addWindowFilterProjectionQuery(functionQueryObjectCopy);
} else if ($(event.el).hasClass(constants.PATTERN)) {
var patternQueryObject = self.configurationData.getSiddhiAppConfig()
.getPatternQuery(elementId);
var patternQueryObjectCopy = _.cloneDeep(patternQueryObject);
self.configurationData.getSiddhiAppConfig().removePatternQuery(elementId);
partition.addPatternQuery(patternQueryObjectCopy);
} else if ($(event.el).hasClass(constants.SEQUENCE)) {
var sequenceQueryObject = self.configurationData.getSiddhiAppConfig()
.getSequenceQuery(elementId);
var sequenceQueryObjectCopy = _.cloneDeep(sequenceQueryObject);
self.configurationData.getSiddhiAppConfig().removeSequenceQuery(elementId);
partition.addSequenceQuery(sequenceQueryObjectCopy);
} else if ($(event.el).hasClass(constants.JOIN)) {
var joinQueryObject = self.configurationData.getSiddhiAppConfig()
.getJoinQuery(elementId);
var joinQueryObjectCopy = _.cloneDeep(joinQueryObject);
self.configurationData.getSiddhiAppConfig().removeJoinQuery(elementId);
partition.addJoinQuery(joinQueryObjectCopy);
}
}
}
if (!isGroupMemberValid) {
DesignViewUtils.prototype
.warnAlert('This element cannot be added to partition.' + errorMessage);
self.jsPlumbInstance.removeFromGroup(event.group, event.el, false);
var elementClientX = $(event.el).attr('data-x');
var elementClientY = $(event.el).attr('data-y');
var detachedElement = $(event.el).detach();
detachedElement.css({
left: parseInt(elementClientX) - self.canvas.offset().left,
top: parseInt(elementClientY) - self.canvas.offset().top
});
self.canvas.append(detachedElement);
self.jsPlumbInstance.repaintEverything();
}
});
}
function checkJSONValidityOfElement(self, elementId, doNotShowErrorMessages) {
var element = self.configurationData.getSiddhiAppConfig()
.getDefinitionElementById(elementId, true, true, true);
if (element !== undefined) {
var type = element.type;
var elementObject = element.element;
if (type === 'STREAM') {
// If this is an inner stream perform validation
var streamSavedInsideAPartition
= self.configurationData.getSiddhiAppConfig()
.getStreamSavedInsideAPartition(elementObject.getId());
// if streamSavedInsideAPartition is undefined then the stream is not inside a partition
if (streamSavedInsideAPartition !== undefined) {
JSONValidator.prototype.validateInnerStream(elementObject, self.jsPlumbInstance, true);
}
} else if (type === 'WINDOW_FILTER_PROJECTION_QUERY') {
JSONValidator.prototype.validateWindowFilterProjectionQuery(elementObject,
doNotShowErrorMessages);
} else if (type === 'PATTERN_QUERY') {
JSONValidator.prototype.validatePatternOrSequenceQuery(elementObject, 'Pattern Query',
doNotShowErrorMessages);
} else if (type === 'SEQUENCE_QUERY') {
JSONValidator.prototype.validatePatternOrSequenceQuery(elementObject, 'Sequence Query',
doNotShowErrorMessages);
} else if (type === 'JOIN_QUERY') {
JSONValidator.prototype.validateJoinQuery(elementObject, doNotShowErrorMessages);
} else if (type === 'SOURCE') {
JSONValidator.prototype.validateSourceOrSinkAnnotation(elementObject, 'Source',
doNotShowErrorMessages);
} else if (type === 'SINK') {
JSONValidator.prototype.validateSourceOrSinkAnnotation(elementObject, 'Sink',
doNotShowErrorMessages);
} else if (type === 'AGGREGATION') {
JSONValidator.prototype.validateAggregation(elementObject, doNotShowErrorMessages);
} else if (type === 'PARTITION') {
JSONValidator.prototype.validatePartition(elementObject, self.jsPlumbInstance,
doNotShowErrorMessages);
}
}
}
checkConnectionValidityBeforeElementDrop();
updateModelOnConnectionAttach();
updateModelOnBeforeConnectionDetach();
updateModelOnConnectionDetach();
addMemberToPartitionGroup(self);
self.drawGraphFromAppData();
self.enableMultipleSelection();
};
DesignGrid.prototype.drawGraphFromAppData = function () {
var self = this;
//Send SiddhiApp Config to the backend and get tooltips
var sendingString = JSON.stringify(self.configurationData.siddhiAppConfig);
var response = this.getTooltips(sendingString);
var tooltipList = [];
if (response.status === "success") {
tooltipList = response.tooltipList;
} else {
log.error(response.errorMessage);
}
// set isStillDrawingGraph to true since the graph drawing has begun
self.configurationData.setIsStillDrawingGraph(true);
_.forEach(self.configurationData.getSiddhiAppConfig().getSourceList(), function (source) {
var sourceId = source.getId();
var sourceName = source.getType();
var array = sourceId.split("_");
var lastArrayEntry = parseInt(array[array.length - 1]);
var mouseTop = lastArrayEntry * 100 - self.canvas.offset().top + self.canvas.scrollTop() - 40;
var mouseLeft = lastArrayEntry * 200 - self.canvas.offset().left + self.canvas.scrollLeft() - 60;
var sourceToolTip = '';
var toolTipObject = _.find(tooltipList, function (toolTip) {
return toolTip.id === sourceId;
});
if (toolTipObject !== undefined) {
sourceToolTip = toolTipObject.text;
}
self.handleSourceAnnotation(mouseTop, mouseLeft, true, sourceName, sourceId, sourceToolTip);
});
_.forEach(self.configurationData.getSiddhiAppConfig().getSinkList(), function (sink) {
var sinkId = sink.getId();
var sinkName = sink.getType();
var array = sinkId.split("_");
var lastArrayEntry = parseInt(array[array.length - 1]);
var mouseTop = lastArrayEntry * 100 - self.canvas.offset().top + self.canvas.scrollTop() - 40;
var mouseLeft = lastArrayEntry * 200 - self.canvas.offset().left + self.canvas.scrollLeft() - 60;
var sinkToolTip = '';
var toolTipObject = _.find(tooltipList, function (toolTip) {
return toolTip.id === sinkId;
});
if (toolTipObject !== undefined) {
sinkToolTip = toolTipObject.text;
}
self.handleSinkAnnotation(mouseTop, mouseLeft, true, sinkName, sinkId, sinkToolTip);
});
_.forEach(self.configurationData.getSiddhiAppConfig().getStreamList(), function (stream) {
var streamId = stream.getId();
var streamName = stream.getName();
var array = streamId.split("_");
var lastArrayEntry = parseInt(array[array.length - 1]);
var mouseTop = lastArrayEntry * 100 - self.canvas.offset().top + self.canvas.scrollTop() - 40;
var mouseLeft = lastArrayEntry * 200 - self.canvas.offset().left + self.canvas.scrollLeft() - 60;
var streamToolTip = '';
var toolTipObject = _.find(tooltipList, function (toolTip) {
return toolTip.id === streamId;
});
if (toolTipObject !== undefined) {
streamToolTip = toolTipObject.text;
}
self.handleStream(mouseTop, mouseLeft, true, streamId, streamName, streamToolTip, stream);
});
_.forEach(self.configurationData.getSiddhiAppConfig().getTableList(), function (table) {
var tableId = table.getId();
var tableName = table.getName();
var array = tableId.split("_");
var lastArrayEntry = parseInt(array[array.length - 1]);
var mouseTop = lastArrayEntry * 100 - self.canvas.offset().top + self.canvas.scrollTop() - 40;
var mouseLeft = lastArrayEntry * 200 - self.canvas.offset().left + self.canvas.scrollLeft() - 60;
var tableToolTip = '';
var toolTipObject = _.find(tooltipList, function (toolTip) {
return toolTip.id === tableId;
});
if (toolTipObject !== undefined) {
tableToolTip = toolTipObject.text;
}
self.handleTable(mouseTop, mouseLeft, true, tableId, tableName, tableToolTip);
});
_.forEach(self.configurationData.getSiddhiAppConfig().getWindowList(), function (window) {
var windowId = window.getId();
var windowName = window.getName();
var array = windowId.split("_");
var lastArrayEntry = parseInt(array[array.length - 1]);
var mouseTop = lastArrayEntry * 100 - self.canvas.offset().top + self.canvas.scrollTop() - 40;
var mouseLeft = lastArrayEntry * 200 - self.canvas.offset().left + self.canvas.scrollLeft() - 60;
var windowToolTip = '';
var toolTipObject = _.find(tooltipList, function (toolTip) {
return toolTip.id === windowId;
});
if (toolTipObject !== undefined) {
windowToolTip = toolTipObject.text;
}
self.handleWindow(mouseTop, mouseLeft, true, windowId, windowName, windowToolTip);
});
_.forEach(self.configurationData.getSiddhiAppConfig().getTriggerList(), function (trigger) {
var triggerId = trigger.getId();
var triggerName = trigger.getName();
var array = triggerId.split("_");
var lastArrayEntry = parseInt(array[array.length - 1]);
var mouseTop = lastArrayEntry * 100 - self.canvas.offset().top + self.canvas.scrollTop() - 40;
var mouseLeft = lastArrayEntry * 200 - self.canvas.offset().left + self.canvas.scrollLeft() - 60;
var triggerToolTip = '';
var toolTipObject = _.find(tooltipList, function (toolTip) {
return toolTip.id === triggerId;
});
if (toolTipObject !== undefined) {
triggerToolTip = toolTipObject.text;
}
self.handleTrigger(mouseTop, mouseLeft, true, triggerId, triggerName, triggerToolTip);
});
_.forEach(self.configurationData.getSiddhiAppConfig().getAggregationList(), function (aggregation) {
var aggregationId = aggregation.getId();
var aggregationName = aggregation.getName();
var array = aggregationId.split("_");
var lastArrayEntry = parseInt(array[array.length - 1]);
var mouseTop = lastArrayEntry * 100 - self.canvas.offset().top + self.canvas.scrollTop() - 40;
var mouseLeft = lastArrayEntry * 200 - self.canvas.offset().left + self.canvas.scrollLeft() - 60;
var aggregationToolTip = '';
var toolTipObject = _.find(tooltipList, function (toolTip) {
return toolTip.id === aggregationId;
});
if (toolTipObject !== undefined) {
aggregationToolTip = toolTipObject.text;
}
self.handleAggregation(mouseTop, mouseLeft, true, aggregationId, aggregationName, aggregationToolTip);
});
_.forEach(self.configurationData.getSiddhiAppConfig().getFunctionList(), function (functionObject) {
var functionId = functionObject.getId();
var functionName = functionObject.getName();
var array = functionId.split("_");
var lastArrayEntry = parseInt(array[array.length - 1]);
var mouseTop = lastArrayEntry * 100 - self.canvas.offset().top + self.canvas.scrollTop() - 40;
var mouseLeft = lastArrayEntry * 200 - self.canvas.offset().left + self.canvas.scrollLeft() - 60;
var functionToolTip = '';
var toolTipObject = _.find(tooltipList, function (toolTip) {
return toolTip.id === functionId;
});
if (toolTipObject !== undefined) {
functionToolTip = toolTipObject.text;
}
self.handleFunction(mouseTop, mouseLeft, true, functionId, functionName, functionToolTip);
});
_.forEach(self.configurationData.getSiddhiAppConfig().getPatternQueryList(), function (patternQuery) {
var patternQueryId = patternQuery.getId();
var patternQueryName = patternQuery.getQueryName();
var array = patternQueryId.split("_");
var lastArrayEntry = parseInt(array[array.length - 1]);
var mouseTop = lastArrayEntry * 100 - self.canvas.offset().top + self.canvas.scrollTop() - 40;
var mouseLeft = lastArrayEntry * 200 - self.canvas.offset().left + self.canvas.scrollLeft() - 60;
var patternQueryToolTip = '';
var toolTipObject = _.find(tooltipList, function (toolTip) {
return toolTip.id === patternQueryId;
});
if (toolTipObject !== undefined) {
patternQueryToolTip = toolTipObject.text;
}
self.handlePatternQuery(mouseTop, mouseLeft, true, patternQueryName, patternQueryId,
patternQueryToolTip);
});
_.forEach(self.configurationData.getSiddhiAppConfig().getSequenceQueryList(), function (sequenceQuery) {
var sequenceQueryId = sequenceQuery.getId();
var sequenceQueryName = sequenceQuery.getQueryName();
var array = sequenceQueryId.split("_");
var lastArrayEntry = parseInt(array[array.length - 1]);
var mouseTop = lastArrayEntry * 100 - self.canvas.offset().top + self.canvas.scrollTop() - 40;
var mouseLeft = lastArrayEntry * 200 - self.canvas.offset().left + self.canvas.scrollLeft() - 60;
var sequenceQueryToolTip = '';
var toolTipObject = _.find(tooltipList, function (toolTip) {
return toolTip.id === sequenceQueryId;
});
if (toolTipObject !== undefined) {
sequenceQueryToolTip = toolTipObject.text;
}
self.handleSequenceQuery(mouseTop, mouseLeft, true, sequenceQueryName, sequenceQueryId,
sequenceQueryToolTip);
});
_.forEach(self.configurationData.getSiddhiAppConfig().getWindowFilterProjectionQueryList(),
function (windowFilterProjectionQuery) {
var queryId = windowFilterProjectionQuery.getId();
var queryName = windowFilterProjectionQuery.getQueryName();
var querySubType = windowFilterProjectionQuery.getQueryInput().getType();
var queryType;
if (querySubType === 'PROJECTION') {
queryType = constants.PROJECTION;
} else if (querySubType === 'FILTER') {
queryType = constants.FILTER;
} else if (querySubType === 'WINDOW') {
queryType = constants.WINDOW_QUERY;
} else if (querySubType === 'FUNCTION') {
queryType = constants.FUNCTION_QUERY;
}
var array = queryId.split("_");
var lastArrayEntry = parseInt(array[array.length - 1]);
var mouseTop = lastArrayEntry * 100 - self.canvas.offset().top + self.canvas.scrollTop() - 40;
var mouseLeft = lastArrayEntry * 200 - self.canvas.offset().left + self.canvas.scrollLeft() - 60;
var queryToolTip = '';
var toolTipObject = _.find(tooltipList, function (toolTip) {
return toolTip.id === queryId;
});
if (toolTipObject !== undefined) {
queryToolTip = toolTipObject.text;
}
self.handleWindowFilterProjectionQuery(queryType, mouseTop, mouseLeft, true, queryName, queryId,
queryToolTip);
});
_.forEach(self.configurationData.getSiddhiAppConfig().getJoinQueryList(), function (joinQuery) {
var joinQueryId = joinQuery.getId();
var joinQueryName = joinQuery.getQueryName();
var array = joinQueryId.split("_");
var lastArrayEntry = parseInt(array[array.length - 1]);
var mouseTop = lastArrayEntry * 100 - self.canvas.offset().top + self.canvas.scrollTop() - 40;
var mouseLeft = lastArrayEntry * 200 - self.canvas.offset().left + self.canvas.scrollLeft() - 60;
var joinQueryToolTip = '';
var toolTipObject = _.find(tooltipList, function (toolTip) {
return toolTip.id === joinQueryId;
});
if (toolTipObject !== undefined) {
joinQueryToolTip = toolTipObject.text;
}
self.handleJoinQuery(mouseTop, mouseLeft, true, joinQueryName, joinQueryId, joinQueryToolTip);
});
_.forEach(self.configurationData.getSiddhiAppConfig().getPartitionList(), function (partition) {
var partitionId = partition.getId();
var array = partitionId.split("_");
var lastArrayEntry = parseInt(array[array.length - 1]);
var mouseTop = lastArrayEntry * 100 - self.canvas.offset().top + self.canvas.scrollTop() - 40;
var mouseLeft = lastArrayEntry * 200 - self.canvas.offset().left + self.canvas.scrollLeft() - 60;
var partitionToolTip = '';
var toolTipObject = _.find(tooltipList, function (toolTip) {
return toolTip.id === partitionId;
});
if (toolTipObject !== undefined) {
partitionToolTip = toolTipObject.text;
}
self.handlePartition(mouseTop, mouseLeft, true, partitionId, partitionToolTip);
var jsPlumbPartitionGroup = self.jsPlumbInstance.getGroup(partitionId);
_.forEach(partition.getStreamList(), function (stream) {
var streamId = stream.getId();
var streamName = stream.getName();
var array = streamId.split("_");
var lastArrayEntry = parseInt(array[array.length - 1]);
var mouseTop = lastArrayEntry * 100 - self.canvas.offset().top + self.canvas.scrollTop() - 40;
var mouseLeft = lastArrayEntry * 200 - self.canvas.offset().left + self.canvas.scrollLeft() - 60;
var streamToolTip = '';
var toolTipObject = _.find(tooltipList, function (toolTip) {
return toolTip.id === streamId;
});
if (toolTipObject !== undefined) {
streamToolTip = toolTipObject.text;
}
self.handleStream(mouseTop, mouseLeft, true, streamId, streamName, streamToolTip, stream);
var streamElement = $('#' + streamId)[0];
self.jsPlumbInstance.addToGroup(jsPlumbPartitionGroup, streamElement);
});
_.forEach(partition.getPatternQueryList(), function (patternQuery) {
var patternQueryId = patternQuery.getId();
var patternQueryName = patternQuery.getQueryName();
var array = patternQueryId.split("_");
var lastArrayEntry = parseInt(array[array.length - 1]);
var mouseTop = lastArrayEntry * 100 - self.canvas.offset().top + self.canvas.scrollTop() - 40;
var mouseLeft = lastArrayEntry * 200 - self.canvas.offset().left + self.canvas.scrollLeft() - 60;
var patternQueryToolTip = '';
var toolTipObject = _.find(tooltipList, function (toolTip) {
return toolTip.id === patternQueryId;
});
if (toolTipObject !== undefined) {
patternQueryToolTip = toolTipObject.text;
}
self.handlePatternQuery(mouseTop, mouseLeft, true, patternQueryName, patternQueryId,
patternQueryToolTip);
var patternElement = $('#' + patternQueryId)[0];
self.jsPlumbInstance.addToGroup(jsPlumbPartitionGroup, patternElement);
});
_.forEach(partition.getSequenceQueryList(), function (sequenceQuery) {
var sequenceQueryId = sequenceQuery.getId();
var sequenceQueryName = sequenceQuery.getQueryName();
var array = sequenceQueryId.split("_");
var lastArrayEntry = parseInt(array[array.length - 1]);
var mouseTop = lastArrayEntry * 100 - self.canvas.offset().top + self.canvas.scrollTop() - 40;
var mouseLeft = lastArrayEntry * 200 - self.canvas.offset().left + self.canvas.scrollLeft() - 60;
var sequenceQueryToolTip = '';
var toolTipObject = _.find(tooltipList, function (toolTip) {
return toolTip.id === sequenceQueryId;
});
if (toolTipObject !== undefined) {
sequenceQueryToolTip = toolTipObject.text;
}
self.handleSequenceQuery(mouseTop, mouseLeft, true, sequenceQueryName, sequenceQueryId,
sequenceQueryToolTip);
var sequenceElement = $('#' + sequenceQueryId)[0];
self.jsPlumbInstance.addToGroup(jsPlumbPartitionGroup, sequenceElement);
});
_.forEach(partition.getWindowFilterProjectionQueryList(),
function (windowFilterProjectionQuery) {
var queryId = windowFilterProjectionQuery.getId();
var queryName = windowFilterProjectionQuery.getQueryName();
var querySubType = windowFilterProjectionQuery.getQueryInput().getType();
var queryType;
if (querySubType === 'PROJECTION') {
queryType = constants.PROJECTION;
} else if (querySubType === 'FILTER') {
queryType = constants.FILTER;
} else if (querySubType === 'WINDOW') {
queryType = constants.WINDOW_QUERY;
} else if (querySubType === 'FUNCTION') {
queryType = constants.FUNCTION_QUERY;
}
var array = queryId.split("_");
var lastArrayEntry = parseInt(array[array.length - 1]);
var mouseTop
= lastArrayEntry * 100 - self.canvas.offset().top + self.canvas.scrollTop() - 40;
var mouseLeft
= lastArrayEntry * 200 - self.canvas.offset().left + self.canvas.scrollLeft() - 60;
var queryToolTip = '';
var toolTipObject = _.find(tooltipList, function (toolTip) {
return toolTip.id === queryId;
});
if (toolTipObject !== undefined) {
queryToolTip = toolTipObject.text;
}
self.handleWindowFilterProjectionQuery(
queryType, mouseTop, mouseLeft, true, queryName, queryId, queryToolTip);
var queryElement = $('#' + queryId)[0];
self.jsPlumbInstance.addToGroup(jsPlumbPartitionGroup, queryElement);
});
_.forEach(partition.getJoinQueryList(), function (joinQuery) {
var joinQueryId = joinQuery.getId();
var joinQueryName = joinQuery.getQueryName();
var array = joinQueryId.split("_");
var lastArrayEntry = parseInt(array[array.length - 1]);
var mouseTop = lastArrayEntry * 100 - self.canvas.offset().top + self.canvas.scrollTop() - 40;
var mouseLeft = lastArrayEntry * 200 - self.canvas.offset().left + self.canvas.scrollLeft() - 60;
var joinQueryToolTip = '';
var toolTipObject = _.find(tooltipList, function (toolTip) {
return toolTip.id === joinQueryId;
});
if (toolTipObject !== undefined) {
joinQueryToolTip = toolTipObject.text;
}
self.handleJoinQuery(mouseTop, mouseLeft, true, joinQueryName, joinQueryId, joinQueryToolTip);
var joinElement = $('#' + joinQueryId)[0];
self.jsPlumbInstance.addToGroup(jsPlumbPartitionGroup, joinElement);
});
});
_.forEach(self.configurationData.edgeList, function (edge) {
var targetId;
var sourceId;
var paintStyle = {
strokeWidth: 2,
stroke: '#424242',
outlineStroke: "transparent",
outlineWidth: "3"
};
if (edge.getChildType() === 'PARTITION') {
targetId = edge.getChildId();
sourceId = edge.getParentId() + '-out';
} else if (edge.getParentType() === 'PARTITION') {
targetId = edge.getChildId() + '-in';
sourceId = edge.getParentId();
} else if (edge.getParentType() === 'SINK' && edge.getChildType() === 'SOURCE') {
targetId = edge.getChildId() + '-in';
sourceId = edge.getParentId() + '-out';
paintStyle = {
strokeWidth: 2, stroke: "#424242", dashstyle: "2 3", outlineStroke: "transparent",
outlineWidth: "3"
}
} else {
// check if the edge is originating from a fault stream. if so get the corresponding event stream
// and draw the edge from the -err-out connector.
if (edge.isFromFaultStream()) {
sourceId = edge.getParentId() + '-err-out';
paintStyle = {
strokeWidth: 2, stroke: "#FF0000", dashstyle: "2 3", outlineStroke: "transparent",
outlineWidth: "3"
};
} else {
sourceId = edge.getParentId() + '-out';
}
targetId = edge.getChildId() + '-in';
}
self.jsPlumbInstance.connect({
source: sourceId,
target: targetId,
paintStyle: paintStyle
});
});
// re-align the elements
self.autoAlignElements();
/*
* In here we set a timeout because when drawing the graph jsplumb triggers a 'addMember' event (when adding
* an element to the partition) an it takes some time to execute. So that we add a timeout and set the
* isDesignViewContentChange to false.
* */
setTimeout(function () {
// set the isDesignViewContentChanged to false
self.configurationData.setIsDesignViewContentChanged(false);
// set isStillDrawingGraph to false since the graph drawing is done
self.configurationData.setIsStillDrawingGraph(false);
}, 100);
};
/**
* @function Auto align and center the diagram
*/
DesignGrid.prototype.autoAlignElements = function () {
var self = this;
// Create a new graph instance
var graph = new dagre.graphlib.Graph({compound: true});
// Sets the graph to grow from left to right, and also to separate the distance between each node
graph.setGraph({rankdir: 'LR', edgesep: 10, ranksep: 100, nodesep: 50});
// This sets the default edge label to `null` as edges/arrows in the design view will
// never have any labels/names to display on the screen
graph.setDefaultEdgeLabel(function () {
return {};
});
// Obtain all the draggable UI elements and add them into the nodes[] array
var currentTabElement = document.getElementById(self.currentTabId);
var nodes = [];
Array.prototype.push.apply(nodes, currentTabElement.getElementsByClassName(constants.SOURCE));
Array.prototype.push.apply(nodes, currentTabElement.getElementsByClassName(constants.SINK));
Array.prototype.push.apply(nodes, currentTabElement.getElementsByClassName(constants.STREAM));
Array.prototype.push.apply(nodes, currentTabElement.getElementsByClassName(constants.TABLE));
Array.prototype.push.apply(nodes, currentTabElement.getElementsByClassName(constants.WINDOW));
Array.prototype.push.apply(nodes, currentTabElement.getElementsByClassName(constants.TRIGGER));
Array.prototype.push.apply(nodes, currentTabElement.getElementsByClassName(constants.AGGREGATION));
Array.prototype.push.apply(nodes, currentTabElement.getElementsByClassName(constants.FUNCTION));
Array.prototype.push.apply(nodes, currentTabElement.getElementsByClassName(constants.PROJECTION));
Array.prototype.push.apply(nodes, currentTabElement.getElementsByClassName(constants.FILTER));
Array.prototype.push.apply(nodes, currentTabElement.getElementsByClassName(constants.WINDOW_QUERY));
Array.prototype.push.apply(nodes, currentTabElement.getElementsByClassName(constants.FUNCTION_QUERY));
Array.prototype.push.apply(nodes, currentTabElement.getElementsByClassName(constants.JOIN));
Array.prototype.push.apply(nodes, currentTabElement.getElementsByClassName(constants.PATTERN));
Array.prototype.push.apply(nodes, currentTabElement.getElementsByClassName(constants.SEQUENCE));
Array.prototype.push.apply(nodes, currentTabElement.getElementsByClassName(constants.PARTITION));
// Create an empty JSON to store information of the given graph's nodes, edges and groups.
var graphJSON = [];
graphJSON.nodes = [];
graphJSON.edges = [];
graphJSON.groups = [];
// For every node object in the nodes[] array
var i = 0;
nodes.forEach(function (node) {
// Add each node to the dagre graph object
graph.setNode(node.id, {width: node.offsetWidth, height: node.offsetHeight});
// Add each node information to the graphJSON object
graphJSON.nodes[i] = {
id: node.id,
width: node.offsetWidth,
height: node.offsetHeight
};
i++;
});
// For every edge in the jsplumb instance
i = 0;
var edges = self.jsPlumbInstance.getAllConnections();
// Get the edge information and add it too graphJSON.edges[] array
// Note - This loop is used to exclude the edges between nodes and partition connections
edges.forEach(function (edge) {
var source;
var target;
var sourceId;
var targetId;
// Get the current edge's parent and child Id's
var parent = edge.sourceId;
var child = edge.targetId;
// If the current edge's parent is a partition connection
if (parent.includes('_pc')) {
// Loop through the edges again
edges.forEach(function (value) {
// Get the inner loops edge (value) targetId as child
child = value.targetId;
// If child is a partition connection
if (child.includes('_pc')) {
// If the parent partition connection Id is equal to the child partition connection Id
if (parent === child) {
// Link inner edge's (value) sourceId with the outer edge's target Id as a single edge
source = value.sourceId;
target = edge.targetId;
sourceId = source.substr(0, source.indexOf('-'));
targetId = target.substr(0, target.indexOf('-'));
}
}
});
} else if (!child.includes('_pc')) {
// If the child of the current edge is *not* a partition connection
source = edge.sourceId;
target = edge.targetId;
sourceId = source.substr(0, source.indexOf('-'));
targetId = target.substr(0, target.indexOf('-'));
}
// Set the sourceId and targetId to graphJSON if they are not undefined
if (sourceId !== undefined && targetId !== undefined) {
graphJSON.edges[i] = {
parent: sourceId,
child: targetId
};
i++;
}
});
// Once the needed edge information has been obtained and added to the graphJSON variable
// then the edges can be set to the dagre graph variable.
graphJSON.edges.forEach(function (edge) {
graph.setEdge(edge.parent, edge.child);
});
// For every group/partition element
i = 0;
var groups = [];
Array.prototype.push.apply(groups, currentTabElement.getElementsByClassName(constants.PARTITION));
groups.forEach(function (partition) {
// Add the group information to the graphJSON object
graphJSON.groups[i] = {
id: null,
children: []
};
graphJSON.groups[i].id = partition.id;
// Identify the children in each group/partition element
var c = 0;
var children = partition.childNodes;
children.forEach(function (child) {
// If the children is of the following types, then only can they be considered as a child
// of the group
var className = child.className;
if (className.includes(constants.STREAM) || className.includes(constants.PROJECTION) ||
className.includes(constants.FILTER) || className.includes(constants.WINDOW_QUERY) ||
className.includes(constants.FUNCTION_QUERY) || className.includes(constants.JOIN) ||
className.includes(constants.PATTERN) || className.includes(constants.SEQUENCE)) {
// Set the child to it's respective group in the dagre graph object
graph.setParent(child.id, partition.id);
// Add the child information of each group to the graphJSON object
graphJSON.groups[i].children[c] = child.id;
c++;
}
});
i++;
});
// This command tells dagre to calculate and finalize the final layout of how the
// nodes in the graph should be placed
dagre.layout(graph);
// Set the default minimum and maximum coordinates to zero
var minimumCoordinate = {x: 0, y: 0};
var maximumCoordinate = {x: 0, y: 0};
// Traverse through every node and find the minimum and maximum x & y coordinates
// The minimum and maximum x & y coordinates have to be found to obtain the size of the graph
graph.nodes().forEach(function (nodeId) {
// Get the instance of the dagre node of 'nodeId'
var node = graph.node(nodeId);
// Get the minimum x & y coordinates of the current node
var minX = node.x - (node.width / 2);
var minY = node.y - (node.height / 2);
// Get the maximum x & y coordinates of the current node
var maxX = node.x + (node.width / 2);
var maxY = node.y + (node.height / 2);
// Find the minimum and maximum 'x' coordinates from all nodes
if (maxX > maximumCoordinate.x || maximumCoordinate.x === 0) {
maximumCoordinate.x = maxX;
}
if (minX < minimumCoordinate.x || minimumCoordinate.x === 0) {
minimumCoordinate.x = minX;
}
// Find the minimum and maximum 'y' coordinates from all the nodes
if (maxY > maximumCoordinate.y || maximumCoordinate.y === 0) {
maximumCoordinate.y = maxY;
}
if (minY < minimumCoordinate.y || minimumCoordinate.y === 0) {
minimumCoordinate.y = minY;
}
});
// Obtain the width and the height of the current design-grid instance
var gridWidth = this.designGridContainer.width();
var gridHeight = this.designGridContainer.height();
// The difference in the largest and smallest 'x' coordinates gives the graph width
var graphWidth = maximumCoordinate.x - minimumCoordinate.x;
// The difference in the largest and smallest 'y' coordinates gives the graph height
var graphHeight = maximumCoordinate.y - minimumCoordinate.y;
// Set the centerLeft and centerTop coordinates to default 20
// NOTE - The 'centerLeft' and 'centerTop' variables are the values that have to be added
// to the final 'left' and 'top' CSS positions of the graph to align the graph to the
// center of the design-grid
var centerLeft = 20;
var centerTop = 20;
if (gridWidth > graphWidth) {
centerLeft = (gridWidth - graphWidth) / 2;
}
if (gridHeight > graphHeight) {
centerTop = (gridHeight - graphHeight) / 2;
}
// Re-align the elements in the grid based on the graph layout given by dagre
graph.nodes().forEach(function (nodeId) {
// Get a dagre instance of the node of `nodeId`
var node = graph.node(nodeId);
// Get a JQuery instance of the node of `nodeId`
var $node = $("#" + nodeId);
// Identify if the node is in a partiton or not using the information
// in the graphJSON object
var isInPartition = false;
var partitionId = -1;
graphJSON.groups.forEach(function (group) {
group.children.forEach(function (child) {
if (nodeId === child) {
isInPartition = true;
partitionId = group.id;
}
});
});
// Note that dagre defines the left(x) & top(y) positions from the center of the element
// This has to be converted to the actual left and top position of a JQuery element
if (isInPartition) {
// If the current node is in a partition, then that node must be added relative to the position
// of it's parent partition
var partitionNode = graph.node(partitionId);
// Identify the left and top value
var partitionNodeLeft = partitionNode.x - (partitionNode.width / 2) + centerLeft;
var partitionNodeTop = partitionNode.y - (partitionNode.height / 2) + centerTop;
// Identify the node's left and top position relative to it's partition's top and left position
var left = node.x - (node.width / 2) + centerLeft - partitionNodeLeft;
var top = node.y - (node.height / 2) + centerTop - partitionNodeTop;
// Set the inner node's left and top position
$node.css("left", left + "px");
$node.css("top", top + "px");
} else {
// If the node is not in a partition then it's left and top positions are obtained relative to
// the entire grid
var left = node.x - (node.width / 2) + centerLeft;
var top = node.y - (node.height / 2) + centerTop;
// Set the node's left and top positions
$node.css("left", left + "px");
$node.css("top", top + "px");
}
// Resize the node with the new width and height defined by dagre
// The node size can only change for partition nodes
$node.css("width", node.width + "px");
$node.css("height", node.height + "px");
});
// Redraw the edges in jsplumb
self.jsPlumbInstance.repaintEverything();
};
DesignGrid.prototype.handleSourceAnnotation = function (mouseTop, mouseLeft, isCodeToDesignMode, sourceName,
sourceId, sourceToolTip) {
var self = this;
var elementId;
if (isCodeToDesignMode !== undefined && !isCodeToDesignMode) {
elementId = self.getNewAgentId();
} else if (isCodeToDesignMode !== undefined && isCodeToDesignMode) {
if (sourceId !== undefined) {
elementId = sourceId;
self.generateNextNewAgentId();
} else {
console.log("sourceId parameter is undefined");
}
} else {
console.log("isCodeToDesignMode parameter is undefined");
}
var newAgent = $('<div>').attr({
'id': elementId,
'tabindex': TAB_INDEX
}).addClass(constants.SOURCE);
if (isCodeToDesignMode) {
newAgent.attr('title', sourceToolTip);
}
self.canvas.append(newAgent);
// Drop the source element. Inside this a it generates the source definition form.
self.dropElements.dropSource(newAgent, elementId, mouseTop, mouseLeft, isCodeToDesignMode, sourceName);
self.configurationData.getSiddhiAppConfig()
.setFinalElementCount(self.configurationData.getSiddhiAppConfig().getFinalElementCount() + 1);
self.dropElements.registerElementEventListeners(newAgent);
self.enableMultipleSelection();
};
DesignGrid.prototype.handleSinkAnnotation = function (mouseTop, mouseLeft, isCodeToDesignMode, sinkName,
sinkId, sinkToolTip) {
var self = this;
var elementId;
if (isCodeToDesignMode !== undefined && !isCodeToDesignMode) {
elementId = self.getNewAgentId();
} else if (isCodeToDesignMode !== undefined && isCodeToDesignMode) {
if (sinkId !== undefined) {
elementId = sinkId;
self.generateNextNewAgentId();
} else {
console.log("sinkId parameter is undefined");
}
} else {
console.log("isCodeToDesignMode parameter is undefined");
}
var newAgent = $('<div>').attr({
'id': elementId,
'tabindex': TAB_INDEX
}).addClass(constants.SINK);
if (isCodeToDesignMode) {
newAgent.attr('title', sinkToolTip);
}
self.canvas.append(newAgent);
// Drop the sink element. Inside this a it generates the sink definition form.
self.dropElements.dropSink(newAgent, elementId, mouseTop, mouseLeft, isCodeToDesignMode, sinkName);
self.configurationData.getSiddhiAppConfig()
.setFinalElementCount(self.configurationData.getSiddhiAppConfig().getFinalElementCount() + 1);
self.dropElements.registerElementEventListeners(newAgent);
self.enableMultipleSelection();
};
DesignGrid.prototype.handleStream = function (mouseTop, mouseLeft, isCodeToDesignMode, streamId, streamName,
streamToolTip, stream) {
var self = this;
var elementId;
if (isCodeToDesignMode !== undefined && !isCodeToDesignMode) {
elementId = stream && stream.getId() ? stream.getId() : self.getNewAgentId();
} else if (isCodeToDesignMode !== undefined && isCodeToDesignMode) {
if (streamId !== undefined) {
elementId = streamId;
self.generateNextNewAgentId();
} else {
console.log("streamId parameter is undefined");
}
} else {
console.log("isCodeToDesignMode parameter is undefined");
}
var newAgent = $('<div>').attr({
'id': elementId,
'tabindex': TAB_INDEX
}).addClass(constants.STREAM);
var inFaultStreamCreationPath = false;
// If this is a fault stream, hide it
if (stream && stream.isFaultStream()) {
newAgent.hide();
inFaultStreamCreationPath = true;
}
if (isCodeToDesignMode) {
newAgent.attr('title', streamToolTip);
}
self.canvas.append(newAgent);
// Drop the stream element. Inside this a it generates the stream definition form.
self.dropElements.dropStream(newAgent, elementId, mouseTop, mouseLeft, isCodeToDesignMode,
false, streamName, stream && stream.hasFaultStream(), inFaultStreamCreationPath);
self.configurationData.getSiddhiAppConfig()
.setFinalElementCount(self.configurationData.getSiddhiAppConfig().getFinalElementCount() + 1);
self.dropElements.registerElementEventListeners(newAgent);
self.enableMultipleSelection();
};
DesignGrid.prototype.handleTable = function (mouseTop, mouseLeft, isCodeToDesignMode, tableId, tableName,
tableToolTip) {
var self = this;
var elementId;
if (isCodeToDesignMode !== undefined && !isCodeToDesignMode) {
elementId = self.getNewAgentId();
} else if (isCodeToDesignMode !== undefined && isCodeToDesignMode) {
if (tableId !== undefined) {
elementId = tableId;
self.generateNextNewAgentId();
} else {
console.log("tableId parameter is undefined");
}
} else {
console.log("isCodeToDesignMode parameter is undefined");
}
var newAgent = $('<div>').attr({
'id': elementId,
'tabindex': TAB_INDEX
}).addClass(constants.TABLE);
if (isCodeToDesignMode) {
newAgent.attr('title', tableToolTip);
}
self.canvas.append(newAgent);
// Drop the Table element. Inside this a it generates the table definition form.
self.dropElements.dropTable(newAgent, elementId, mouseTop, mouseLeft, isCodeToDesignMode, tableName);
self.configurationData.getSiddhiAppConfig()
.setFinalElementCount(self.configurationData.getSiddhiAppConfig().getFinalElementCount() + 1);
self.dropElements.registerElementEventListeners(newAgent);
self.enableMultipleSelection();
};
DesignGrid.prototype.handleWindow = function (mouseTop, mouseLeft, isCodeToDesignMode, windowId, windowName,
windowToolTip) {
var self = this;
var elementId;
if (isCodeToDesignMode !== undefined && !isCodeToDesignMode) {
elementId = self.getNewAgentId();
} else if (isCodeToDesignMode !== undefined && isCodeToDesignMode) {
if (windowId !== undefined) {
elementId = windowId;
self.generateNextNewAgentId();
} else {
console.log("windowId parameter is undefined");
}
} else {
console.log("isCodeToDesignMode parameter is undefined");
}
var newAgent = $('<div>').attr({
'id': elementId,
'tabindex': TAB_INDEX
}).addClass(constants.WINDOW);
if (isCodeToDesignMode) {
newAgent.attr('title', windowToolTip);
}
self.canvas.append(newAgent);
// Drop the Table element. Inside this a it generates the table definition form.
self.dropElements.dropWindow(newAgent, elementId, mouseTop, mouseLeft, isCodeToDesignMode, windowName);
self.configurationData.getSiddhiAppConfig()
.setFinalElementCount(self.configurationData.getSiddhiAppConfig().getFinalElementCount() + 1);
self.dropElements.registerElementEventListeners(newAgent);
self.enableMultipleSelection();
};
DesignGrid.prototype.handleTrigger = function (mouseTop, mouseLeft, isCodeToDesignMode, triggerId,
triggerName, triggerToolTip) {
var self = this;
var elementId;
if (isCodeToDesignMode !== undefined && !isCodeToDesignMode) {
elementId = self.getNewAgentId();
} else if (isCodeToDesignMode !== undefined && isCodeToDesignMode) {
if (triggerId !== undefined) {
elementId = triggerId;
self.generateNextNewAgentId();
} else {
console.log("triggerId parameter is undefined");
}
} else {
console.log("isCodeToDesignMode parameter is undefined");
}
var newAgent = $('<div>').attr({
'id': elementId,
'tabindex': TAB_INDEX
}).addClass(constants.TRIGGER);
if (isCodeToDesignMode) {
newAgent.attr('title', triggerToolTip);
}
self.canvas.append(newAgent);
// Drop the Trigger element. Inside this a it generates the trigger definition form.
self.dropElements.dropTrigger(newAgent, elementId, mouseTop, mouseLeft, isCodeToDesignMode, triggerName);
self.configurationData.getSiddhiAppConfig()
.setFinalElementCount(self.configurationData.getSiddhiAppConfig().getFinalElementCount() + 1);
self.dropElements.registerElementEventListeners(newAgent);
self.enableMultipleSelection();
};
DesignGrid.prototype.handleAggregation = function (mouseTop, mouseLeft, isCodeToDesignMode, aggregationId,
aggregationName, aggregationToolTip) {
var self = this;
var elementId;
if (isCodeToDesignMode !== undefined && !isCodeToDesignMode) {
elementId = self.getNewAgentId();
} else if (isCodeToDesignMode !== undefined && isCodeToDesignMode) {
if (aggregationId !== undefined) {
elementId = aggregationId;
self.generateNextNewAgentId();
} else {
console.log("aggregationId parameter is undefined");
}
} else {
console.log("isCodeToDesignMode parameter is undefined");
}
var newAgent = $('<div>').attr({
'id': elementId,
'tabindex': TAB_INDEX
}).addClass(constants.AGGREGATION);
if (isCodeToDesignMode) {
newAgent.attr('title', aggregationToolTip);
}
self.canvas.append(newAgent);
// Drop the Aggregation element. Inside this a it generates the aggregation definition form.
self.dropElements.dropAggregation(newAgent, elementId, mouseTop, mouseLeft, isCodeToDesignMode,
aggregationName);
self.configurationData.getSiddhiAppConfig()
.setFinalElementCount(self.configurationData.getSiddhiAppConfig().getFinalElementCount() + 1);
self.dropElements.registerElementEventListeners(newAgent);
self.enableMultipleSelection();
};
DesignGrid.prototype.handleFunction = function (mouseTop, mouseLeft, isCodeToDesignMode, functionId,
functionName, functionToolTip) {
var self = this;
var elementId;
if (isCodeToDesignMode !== undefined && !isCodeToDesignMode) {
elementId = self.getNewAgentId();
} else if (isCodeToDesignMode !== undefined && isCodeToDesignMode) {
if (functionId !== undefined) {
elementId = functionId;
self.generateNextNewAgentId();
} else {
console.log("functionId parameter is undefined");
}
} else {
console.log("isCodeToDesignMode parameter is undefined");
}
var newAgent = $('<div>').attr({
'id': elementId,
'tabindex': TAB_INDEX
}).addClass(constants.FUNCTION);
if (isCodeToDesignMode) {
newAgent.attr('title', functionToolTip);
}
self.canvas.append(newAgent);
// Drop the Function element. Inside this a it generates the function definition form.
self.dropElements.dropFunction(newAgent, elementId, mouseTop, mouseLeft, isCodeToDesignMode, functionName);
self.configurationData.getSiddhiAppConfig()
.setFinalElementCount(self.configurationData.getSiddhiAppConfig().getFinalElementCount() + 1);
self.dropElements.registerElementEventListeners(newAgent);
self.enableMultipleSelection();
};
DesignGrid.prototype.handleWindowFilterProjectionQuery = function (type, mouseTop, mouseLeft,
isCodeToDesignMode, queryName, queryId,
queryToolTip) {
var self = this;
var elementId;
if (isCodeToDesignMode !== undefined && !isCodeToDesignMode) {
elementId = self.getNewAgentId();
} else if (isCodeToDesignMode !== undefined && isCodeToDesignMode) {
if (queryId !== undefined) {
elementId = queryId;
self.generateNextNewAgentId();
} else {
console.log("queryId parameter is undefined");
}
} else {
console.log("isCodeToDesignMode parameter is undefined");
}
var newAgent = $('<div>').attr({
'id': elementId,
'tabindex': TAB_INDEX
}).addClass(type);
if (isCodeToDesignMode) {
newAgent.attr('title', queryToolTip);
}
self.canvas.append(newAgent);
// Drop the element instantly since its projections will be set only when the user requires it
self.dropElements.dropWindowFilterProjectionQuery(newAgent, elementId, type, mouseTop, mouseLeft, queryName,
isCodeToDesignMode);
self.configurationData.getSiddhiAppConfig()
.setFinalElementCount(self.configurationData.getSiddhiAppConfig().getFinalElementCount() + 1);
self.dropElements.registerElementEventListeners(newAgent);
self.enableMultipleSelection();
};
DesignGrid.prototype.handleJoinQuery = function (mouseTop, mouseLeft, isCodeToDesignMode, joinQueryName,
joinQueryId, joinQueryToolTip) {
var self = this;
var elementId;
if (isCodeToDesignMode !== undefined && !isCodeToDesignMode) {
elementId = self.getNewAgentId();
} else if (isCodeToDesignMode !== undefined && isCodeToDesignMode) {
if (joinQueryId !== undefined) {
elementId = joinQueryId;
self.generateNextNewAgentId();
} else {
console.log("queryId parameter is undefined");
}
} else {
console.log("isCodeToDesignMode parameter is undefined");
}
var newAgent = $('<div>').attr({
'id': elementId,
'tabindex': TAB_INDEX
}).addClass(constants.JOIN);
if (isCodeToDesignMode) {
newAgent.attr('title', joinQueryToolTip);
}
self.canvas.append(newAgent);
// Drop the element instantly since its projections will be set only when the user requires it
self.dropElements.dropJoinQuery(newAgent, elementId, mouseTop, mouseLeft, joinQueryName,
isCodeToDesignMode);
self.configurationData.getSiddhiAppConfig()
.setFinalElementCount(self.configurationData.getSiddhiAppConfig().getFinalElementCount() + 1);
self.dropElements.registerElementEventListeners(newAgent);
self.enableMultipleSelection();
};
DesignGrid.prototype.handlePatternQuery = function (mouseTop, mouseLeft, isCodeToDesignMode, patternQueryName,
patternQueryId, patternQueryToolTip) {
var self = this;
var elementId;
if (isCodeToDesignMode !== undefined && !isCodeToDesignMode) {
elementId = self.getNewAgentId();
} else if (isCodeToDesignMode !== undefined && isCodeToDesignMode) {
if (patternQueryId !== undefined) {
elementId = patternQueryId;
self.generateNextNewAgentId();
} else {
console.log("patternQueryId parameter is undefined");
}
} else {
console.log("isCodeToDesignMode parameter is undefined");
}
var newAgent = $('<div>').attr({
'id': elementId,
'tabindex': TAB_INDEX
}).addClass(constants.PATTERN);
if (isCodeToDesignMode) {
newAgent.attr('title', patternQueryToolTip);
}
self.canvas.append(newAgent);
// Drop the element instantly since its projections will be set only when the user requires it
self.dropElements.dropPatternQuery(newAgent, elementId, mouseTop, mouseLeft, isCodeToDesignMode,
patternQueryName);
self.configurationData.getSiddhiAppConfig()
.setFinalElementCount(self.configurationData.getSiddhiAppConfig().getFinalElementCount() + 1);
self.dropElements.registerElementEventListeners(newAgent);
self.enableMultipleSelection();
};
DesignGrid.prototype.handleSequenceQuery = function (mouseTop, mouseLeft, isCodeToDesignMode, sequenceQueryName,
sequenceQueryId, sequenceQueryToolTip) {
var self = this;
var elementId;
if (isCodeToDesignMode !== undefined && !isCodeToDesignMode) {
elementId = self.getNewAgentId();
} else if (isCodeToDesignMode !== undefined && isCodeToDesignMode) {
if (sequenceQueryId !== undefined) {
elementId = sequenceQueryId;
self.generateNextNewAgentId();
} else {
console.log("sequenceQueryId parameter is undefined");
}
} else {
console.log("isCodeToDesignMode parameter is undefined");
}
var newAgent = $('<div>').attr({
'id': elementId,
'tabindex': TAB_INDEX
}).addClass(constants.SEQUENCE);
if (isCodeToDesignMode) {
newAgent.attr('title', sequenceQueryToolTip);
}
self.canvas.append(newAgent);
// Drop the element instantly since its projections will be set only when the user requires it
self.dropElements.dropSequenceQuery(newAgent, elementId, mouseTop, mouseLeft, isCodeToDesignMode,
sequenceQueryName);
self.configurationData.getSiddhiAppConfig()
.setFinalElementCount(self.configurationData.getSiddhiAppConfig().getFinalElementCount() + 1);
self.dropElements.registerElementEventListeners(newAgent);
self.enableMultipleSelection();
};
DesignGrid.prototype.handlePartition = function (mouseTop, mouseLeft, isCodeToDesignMode, partitionId,
partitionToolTip) {
var self = this;
var elementId;
if (isCodeToDesignMode !== undefined && !isCodeToDesignMode) {
elementId = self.getNewAgentId();
} else if (isCodeToDesignMode !== undefined && isCodeToDesignMode) {
if (partitionId !== undefined) {
elementId = partitionId;
self.generateNextNewAgentId();
} else {
console.log("partitionId parameter is undefined");
}
} else {
console.log("isCodeToDesignMode parameter is undefined");
}
var newAgent = $('<div>').attr({
'id': elementId,
'tabindex': TAB_INDEX
}).addClass(constants.PARTITION);
if (isCodeToDesignMode) {
newAgent.attr('title', partitionToolTip);
}
self.canvas.append(newAgent);
// Drop the element instantly since its projections will be set only when the user requires it
self.dropElements.dropPartition(newAgent, elementId, mouseTop, mouseLeft, isCodeToDesignMode);
self.configurationData.getSiddhiAppConfig()
.setFinalElementCount(self.configurationData.getSiddhiAppConfig().getFinalElementCount() + 1);
self.dropElements.registerElementEventListeners(newAgent);
self.enableMultipleSelection();
};
DesignGrid.prototype.generateNextNewAgentId = function () {
var newId = parseInt(this.newAgentId) + 1;
this.newAgentId = "" + newId + "";
return this.currentTabId + "_element_" + this.newAgentId;
};
DesignGrid.prototype.getNewAgentId = function () {
var self = this;
return self.generateNextNewAgentId();
};
DesignGrid.prototype.generateNextConnectionPointIdForPartition = function (partitionId) {
var partitionElement = $('#' + partitionId);
var partitionConnections = partitionElement.find('.' + constants.PARTITION_CONNECTION_POINT);
var partitionIds = [];
_.forEach(partitionConnections, function (connection) {
partitionIds.push(parseInt((connection.id).slice(-1)));
});
var maxId = partitionIds.reduce(function (a, b) {
return Math.max(a, b);
});
return partitionId + '_pc' + (maxId + 1);
};
DesignGrid.prototype.enableMultipleSelection = function () {
var self = this;
var selector = $('<div>').attr('id', constants.MULTI_SELECTOR).addClass(constants.SELECTOR);
self.canvas.append(selector);
new DragSelect({
selectables: document.querySelectorAll('.jtk-draggable'),
selector: document.getElementById(constants.MULTI_SELECTOR),
area: document.getElementById('design-grid-container-' + self.currentTabId),
multiSelectKeys: ['ctrlKey', 'shiftKey'],
onElementSelect: function (element) {
if (!self.selectedObjects.includes(element, 0)) {
self.jsPlumbInstance.addToDragSelection(element);
self.addSelectedElements(element);
$(element).focus();
$(element).addClass('selected-container');
self.selectedObjects.push(element);
}
},
onElementUnselect: function (element) {
self.jsPlumbInstance.removeFromDragSelection(element);
self.removeFromSelectedElements(element);
for (var i = 0; i < self.selectedObjects.length; i++) {
if (self.selectedObjects[i] == element) {
self.selectedObjects.splice(i, 1);
}
}
$(element).removeClass('selected-container focused-container');
self.selectedObjects = [];
}
});
};
/**
* Generate tooltips for all the elements
*
* @param designViewJSON siddhiAppConfig
*/
DesignGrid.prototype.getTooltips = function (designViewJSON) {
var self = this;
var result = {};
self.tooltipsURL = window.location.protocol + "//" + window.location.host + "/editor/tooltips";
$.ajax({
type: "POST",
url: self.tooltipsURL,
data: self.options.application.utils.base64EncodeUnicode(designViewJSON),
async: false,
success: function (response) {
result = {status: "success", tooltipList: response};
},
error: function (error) {
if (error.responseText) {
result = {status: "fail", errorMessage: error.responseText};
} else {
result = {status: "fail", errorMessage: "Error Occurred while processing your request"};
}
}
});
return result;
};
return DesignGrid;
});
| {
"content_hash": "e2c3fb7454037246b33578216b58e86c",
"timestamp": "",
"source": "github",
"line_count": 2728,
"max_line_length": 133,
"avg_line_length": 57.683651026392965,
"alnum_prop": 0.5071523439734115,
"repo_name": "Niveathika92/carbon-analytics",
"id": "5e20bbcef3b95e125e45c4cf4c6729f11486872d",
"size": "158035",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "components/org.wso2.carbon.siddhi.editor.core/src/main/resources/web/js/design-view/design-grid.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "40449"
},
{
"name": "Batchfile",
"bytes": "16377"
},
{
"name": "CSS",
"bytes": "660253"
},
{
"name": "Groovy",
"bytes": "5041"
},
{
"name": "HTML",
"bytes": "773783"
},
{
"name": "Java",
"bytes": "4359050"
},
{
"name": "JavaScript",
"bytes": "19019487"
},
{
"name": "PHP",
"bytes": "328"
},
{
"name": "PLSQL",
"bytes": "4761"
},
{
"name": "Shell",
"bytes": "17901"
}
],
"symlink_target": ""
} |
**NeedsWork** | [#roslyn/57589](https://github.com/dotnet/roslyn/issues/57589#issuecomment-985038558)
## API Review
* Most of the generator examples we've seen as motivating examples are v1 generators that, when factored into incremental generators, have perfectly fine performance.
* Doesn't help with Hot Reload or EnC scenarios, which need full implementation results
* Only for the application of edits, not for things like intellisense
* Workaround is available: register 2 generators, one that registers partials with empty bodies, one that provides the real implementation with our existing API
* If you did it this way, it would require partial consistency, whereas the ReferenceSourceOnly version could make it harder to ensure that these things line up.
Would have errors
* Might have been nice if we had done a slightly different design. What if we just did RegisterSourceOutput, and put a flag on it?
* Would that cause us to have to run generators twice, even if they didn't check that flag?
* Can RegisterReferenceSourceOutput actually change the reference assembly output?
* They probably can do that, so we're ok
* Might need a slightly better name
* We'll bikeshed over this when we have perf data.
### Conclusion
We think the API shape is reasonable (modulo the name), but we would like data on whether it actually helps our motivating generators before shipping the API for real.
| {
"content_hash": "d0ba96751db263345a4729d034a1db86",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 167,
"avg_line_length": 72.2,
"alnum_prop": 0.7721606648199446,
"repo_name": "dotnet/apireviews",
"id": "30b5ebe97d7e50646d7ee76920ec08f15477b034",
"size": "1522",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "2021/12-02-roslyn-reviews/README.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
/**
* Name : BarLineSvc.js
* Module : Norris::App::Services
* Location : /norris/app/script/services/
*
* History :
* Version Date Programmer
* =================================================
* 0.0.1 2015/04/11 Faggin Andrea
* -------------------------------------------------
* Codifica modulo
* =================================================
*/
'use strict';
angular.module("Services")
.factory('BarLineSvc', ["ColorsSvc", function (ColorsSvc) {
return {
/**
* Description
* Fills the model data from an array of raw data
* @method fillLineData
* @param {Array} series
* @param {Array} labels
* @param {Array} inData
* @param {Array} outData
* @return Array
*/
fillLineData : function (series,labels,inData,outData) {
var util = [];
var outData = [];
//Push series identifier
util.push("Series");
//Push series values
for(var i=0;i<series.length;i++){
util.push(series[i]);
}
outData.push(util);
//Then push labels
for(var i=1; i<=labels.length;i++){
util = [];
util.push(labels[i-1]);
//For each serie push data
for(var j=1;j<=series.length;j++){
util.push(inData[j-1][i-1]);
}
outData.push(util);
}
return outData;
}
,
/**
* Description
* Sets the data colors from an Array of data
* @method setColors
* @param {Array} colors
* @return Array
*/
setColors : function (colors) {
var util = [];
for(var i=0;i<colors.length;i++){
var rgb = colors[i];
var color = ColorsSvc.rgbToHex(rgb.red, rgb.green, rgb.blue);
util.push(color);
}
return util;
}
,
/**
* Description
* Sets the Bar/LineChart options Object from raw data
* @method setOpts
* @param {String} title
* @param {String} xAxisName
* @param {String} yAxisName
* @param {Boolean} showGrid
* @param {Boolean} showLegend
* @param {String} legendPosition
* @param {Number} seriesCount
* @return Object
*/
setOpts: function (title, xAxisName, yAxisName, showGrid, showLegend, legendPosition, seriesCount) {
var options = { displayExactValues: true
, curveType: 'function'
, animation: { duration: 500
, easing: 'out'
}
, title: title
, hAxis: { title: xAxisName }
, vAxis: { title: yAxisName }
};
if(showGrid == true) {
options.hAxis.gridlines = { color: '#CCC' };
options.vAxis.gridlines = { color: '#CCC' };
} else {
options.hAxis.gridlines = { color: 'transparent' };
options.vAxis.gridlines = { color: 'transparent' };
}
if (showLegend == true) {
options.legend = { position: legendPosition };
if (legendPosition == "left") {
options.series = [];
for (var i=0;i<seriesCount;i++){
options.series.push({targetAxisIndex: "1"});
}
}
}
return options;
}
}
}]); | {
"content_hash": "badfa4eeeb1f8118f6a0a2974d8159a9",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 114,
"avg_line_length": 43.080357142857146,
"alnum_prop": 0.3351295336787565,
"repo_name": "FlameTech/Norris",
"id": "306b32e6a3f0f1a649aa3960bdf813076045fda3",
"size": "4825",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "RQ/Codice/app/scripts/services/BarLineSvc.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2888"
},
{
"name": "HTML",
"bytes": "17800"
},
{
"name": "JavaScript",
"bytes": "550823"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Revis. gen. pl. (Leipzig) 3: 481 (1898)
#### Original name
Cucurbitaria subcaespitosa G.H. Otth
### Remarks
null | {
"content_hash": "f6de638ba17f9bdc519dd527111d3358",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 15.384615384615385,
"alnum_prop": 0.7,
"repo_name": "mdoering/backbone",
"id": "a3a0e92428e286da6419a06ee38b95b6b3b8216c",
"size": "273",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Cucurbitariaceae/Cucurbitaria/Cucurbitaria subcaespitosa/ Syn. Gibberidea subcaespitosa/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
[](http://github.com/badges/stability-badges)
[](https://travis-ci.org/psiphp/content-type)
[](https://styleci.io/repos/59910930)
[](https://scrutinizer-ci.com/g/psiphp/content-type/?branch=master)
[](https://packagist.org/packages/psiphp/content-type)
[](https://packagist.org/packages/psiphp/content-type)
This component is part of the Psi Content Management Framework
The content-type component provides a facility to unify form, storage and
(frontend) view through the mapping of "content types" to object properties.
Example content types might include "markdown", "image", "image_collection",
"geolocation", etc.
## Documentation
Documentation is in progress, there may be documentation in [doc/index.rst](https://github.com/psiphp/content-type/blob/master/docs/index.rst).
## Installation
Require in `composer.json`:
```bash
$ composer require 'psiphp/content-type'
```
## Contributing
All contributions are welcome, go ahead and make a PR!
| {
"content_hash": "9a86c2a016c06dd24806a9f877532837",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 158,
"avg_line_length": 44.303030303030305,
"alnum_prop": 0.7701778385772914,
"repo_name": "psiphp/content-type",
"id": "84cf654ce60ac85dbc5a304996c3a93270f4e1b1",
"size": "1482",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "198422"
},
{
"name": "Shell",
"bytes": "157"
}
],
"symlink_target": ""
} |
Rails.application.config.middleware.use OmniAuth::Builder do
provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET'], scope: "user:email,repo,delete_repo,read:org"
end
| {
"content_hash": "a9781bf80f3be7cf6e1c1a392b539faf",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 106,
"avg_line_length": 57.333333333333336,
"alnum_prop": 0.7616279069767442,
"repo_name": "theodi/git-data-publisher",
"id": "10cd649915f6fcda138a1c650099cc02446905d9",
"size": "172",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "config/initializers/omniauth.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1205"
},
{
"name": "HTML",
"bytes": "17972"
},
{
"name": "JavaScript",
"bytes": "696"
},
{
"name": "Ruby",
"bytes": "65572"
}
],
"symlink_target": ""
} |
<!-- MAIN CONTENT -->
<div id="content">
<div class="row hidden-print">
<div class="col-xs-12 col-sm-9 col-md-9 col-lg-9">
<h1 class="page-title txt-color-blueDark">
<a class="backHome" href="/bo"><i class="fa fa-home"></i> Menu</a>
<span>>
<a href="/bo/comercial">Comercial</a> > Cuentas Por Pagar
</span>
</h1>
</div>
</div>
<?php if($this->session->flashdata('error')) {
echo '<div class="alert alert-danger fade in">
<button class="close" data-dismiss="alert">
×
</button>
<i class="fa-fw fa fa-check"></i>
<strong>Error </strong> '.$this->session->flashdata('error').'
</div>';
}
?>
<!-- START ROW -->
<div class="row">
<!-- NEW COL START -->
<article class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="well">
<div class="row">
<form class="smart-form" id="reporte-form" method="post">
<div class="row hidden-print">
<section class="col col-lg-3 col-md-3 col-sm-12 col-xs-12">
<label class="input"> <i class="icon-append fa fa-calendar"></i>
<input type="text" name="startdate" id="startdate" placeholder="Del">
</label>
</section>
<section class="col col-lg-3 col-md-3 col-sm-12 col-xs-12">
<label class="input"> <i class="icon-append fa fa-calendar"></i>
<input type="text" name="finishdate" id="finishdate" placeholder="Al">
</label>
</section>
<section class="col col-lg-3 col-md-3 col-sm-12 col-xs-12">
<label class="input">
<a id="genera-reporte" class="btn btn-primary col-xs-12 col-lg-12 col-md-12 col-sm-12">Consultar</a>
</label>
</section>
<section class="col col-lg-3 col-md-3 col-sm-6 col-xs-12">
<label class="input">
<a id="imprimir-2" onclick="reporte_excel_comprar_usr()" class="btn btn-primary col-xs-12 col-lg-12 col-md-12 col-sm-12"><i class="fa fa-print"></i> Crear excel / Pagar</a>
</label>
</section>
</div>
</form>
</div>
</div>
<!-- Widget ID (each widget will need unique ID)-->
<div class="jarviswidget jarviswidget-color-blueDark" id="nuevos_afiliados" data-widget-editbutton="false">
<!-- widget options:
usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false">
data-widget-colorbutton="false"
data-widget-editbutton="false"
data-widget-togglebutton="false"
data-widget-deletebutton="false"
data-widget-fullscreenbutton="false"
data-widget-custombutton="false"
data-widget-collapsed="true"
data-widget-sortable="false"
-->
<header>
<span class="widget-icon"> <i class="fa fa-table"></i> </span>
<h2>Export to PDF / Excel</h2>
</header>
<!-- widget div-->
<div>
<!-- widget edit box -->
<div class="jarviswidget-editbox">
. <!-- This area used as dropdown edit box -->
.
</div>
<!-- end widget edit box -->
<!-- widget content -->
<div class="widget-body no-padding" id="reporte_div">
</div>
<!-- end widget content -->
</div>
<!-- end widget div -->
</div>
<!-- end widget -->
<div class="well" id="well-print-af" style="display: none;">
<div class="row">
<form class="smart-form" id="reporte-form" method="post">
<div class="row" >
<section class="col col-lg-3 col-md-3 col-sm-6 col-xs-12">
<label class="input">
<a id="imprimir-2" href="reporte_afiliados_excel" class="btn btn-primary col-xs-12 col-lg-12 col-md-12 col-sm-12"><i class="fa fa-print"></i> Crear excel</a>
</label>
</section>
</div>
</form>
</div>
</div>
<div class="well" id="well-print-usr" style="display: none;">
<div class="row">
<form class="smart-form" id="reporte-form" method="post">
<div class="row" >
<section class="col col-lg-9 col-md-9 hidden-sm hidden-xs">
</section>
<section class="col col-lg-3 col-md-3 col-sm-6 col-xs-12">
<label class="input">
<a id="imprimir-2" onclick="reporte_excel_comprar_usr()" class="btn btn-primary col-xs-12 col-lg-12 col-md-12 col-sm-12"><i class="fa fa-print"></i> Crear excel / Pagar</a>
</label>
</section>
</div>
</form>
</div>
</div>
</article>
<!-- NEW WIDGET START -->
<!-- WIDGET END -->
</div>
</div>
<div class="row">
<!-- a blank row to get started -->
<div class="col-sm-12">
<br />
<br />
</div>
</div>
<!-- END MAIN CONTENT -->
<!-- PAGE RELATED PLUGIN(S) -->
<script src="/template/js/plugin/datatables/jquery.dataTables.min.js"></script>
<script src="/template/js/plugin/datatables/dataTables.colVis.min.js"></script>
<script src="/template/js/plugin/datatables/dataTables.tableTools.min.js"></script>
<script src="/template/js/plugin/datatables/dataTables.bootstrap.min.js"></script>
<script src="/template/js/plugin/datatable-responsive/datatables.responsive.min.js"></script>
<script src="/template/js/spin.js"></script>
<script type="text/javascript">
$("#tipo-reporte").change(function()
{
if($("#tipo-reporte").val()==24)
{
$("#startdate").prop( "disabled", true );
$("#finishdate").prop( "disabled", true );
}
else
{
$("#startdate").prop( "disabled", false);
$("#finishdate").prop( "disabled", false );
}
});
</script>
<script type="text/javascript">
$("#genera-reporte").click(function()
{
var inicio=$("#startdate").val();
var fin=$("#finishdate").val();
if(inicio=='')
{
alert('Introduzca fecha de inicio');
}
else
{
if(fin=='')
{
alert('Introduzca fecha de fin');
}
else
{
$("#nuevos_afiliados").show();
var opts = {
lines: 12 // The number of lines to draw
, length: 28 // The length of each line
, width: 14 // The line thickness
, radius: 42 // The radius of the inner circle
, scale: 1 // Scales overall size of the spinner
, corners: 1 // Corner roundness (0..1)
, color: '#000' // #rgb or #rrggbb or array of colors
, opacity: 0.25 // Opacity of the lines
, rotate: 0 // The rotation offset
, direction: 1 // 1: clockwise, -1: counterclockwise
, speed: 1 // Rounds per second
, trail: 60 // Afterglow percentage
, fps: 20 // Frames per second when using setTimeout() as a fallback for CSS
, zIndex: 2e9 // The z-index (defaults to 2000000000)
, className: 'spinner' // The CSS class to assign to the spinner
, top: '50%' // Top position relative to parent
, left: '50%' // Left position relative to parent
, shadow: false // Whether to render a shadow
, hwaccel: false // Whether to use hardware acceleration
, position: 'absolute' // Element positioning
}
var target = document.getElementById('nuevos_afiliados')
var spinner = new Spinner(opts).spin(target);
$.ajax({
type: "POST",
url: "reporte_cobros",
data: {
fecha_inicio : inicio,
fecha_fin : fin
},
success: function( msg )
{
$(".spinner").addClass('hide');
$(".spinner").html('');
$("#reporte_div").html(msg);
var responsiveHelper_dt_basic = undefined;
var responsiveHelper_datatable_fixed_column = undefined;
var responsiveHelper_datatable_col_reorder = undefined;
var responsiveHelper_datatable_tabletools = undefined;
var breakpointDefinition = {
tablet : 1024,
phone : 480
};
var otable = $('#datatable_fixed_column2').DataTable({
//"bFilter": false,
//"bInfo": false,
//"bLengthChange": false
//"bAutoWidth": false,
//"bPaginate": false,
//"bStateSave": true // saves sort state using localStorage
"sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6 hidden-xs'f><'col-sm-6 col-xs-12 hidden-xs'<'toolbar'>>r>"+
"t"+
"<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
"autoWidth" : true,
"preDrawCallback" : function() {
// Initialize the responsive datatables helper once.
if (!responsiveHelper_datatable_fixed_column) {
responsiveHelper_datatable_fixed_column = new ResponsiveDatatablesHelper($('#datatable_fixed_column2'), breakpointDefinition);
}
},
"rowCallback" : function(nRow) {
responsiveHelper_datatable_fixed_column.createExpandIcon(nRow);
},
"drawCallback" : function(oSettings) {
responsiveHelper_datatable_fixed_column.respond();
}
});
$("div.toolbar").html('<div class="text-right"><img src="/template/img/logo.png" alt="SmartAdmin" style="width: 111px; margin-top: 3px; margin-right: 10px;"></div>');
// Apply the filter
$("#datatable_fixed_column2 thead th input[type=text]").on( 'keyup change', function () {
otable
.column( $(this).parent().index()+':visible' )
.search( this.value )
.draw();
} );
$("#well-print-red").hide();
$("#row-print-red").hide();
$("#well-print-af").hide();
$("#row-print-af").hide();
$("#well-print-web").hide();
$("#row-print-web").hide();
$("#well-print-usr").show();
$("#row-print-usr").show();
// custom toolbar
}
});
}
}
});
function reporte_excel_comprar_usr()
{
var inicio=$("#startdate").val();
var fin=$("#finishdate").val();
if(inicio=='')
{
alert('Introduzca fecha de inicio');
}
else
{
if(fin=='')
{
alert('Introduzca fecha de fin');
}
else
{
window.location="reporte_cobros_excel?inicio="+inicio+"&&fin="+fin;
}
}
}
</script>
<script type="text/javascript">
// DO NOT REMOVE : GLOBAL FUNCTIONS!
$(document).ready(function() {
pageSetUp();
/* // DOM Position key index //
l - Length changing (dropdown)
f - Filtering input (search)
t - The Table! (datatable)
i - Information (records)
p - Pagination (paging)
r - pRocessing
< and > - div elements
<"#id" and > - div with an id
<"class" and > - div with a class
<"#id.class" and > - div with an id and class
Also see: http://legacy.datatables.net/usage/features
*/
/* BASIC ;*/
var responsiveHelper_dt_basic = undefined;
var responsiveHelper_datatable_fixed_column = undefined;
var responsiveHelper_datatable_col_reorder = undefined;
var responsiveHelper_datatable_tabletools = undefined;
var breakpointDefinition = {
tablet : 1024,
phone : 480
};
$('#dt_basic').dataTable({
"sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-12 hidden-xs'l>r>"+
"t"+
"<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
"autoWidth" : true,
"preDrawCallback" : function() {
// Initialize the responsive datatables helper once.
if (!responsiveHelper_dt_basic) {
responsiveHelper_dt_basic = new ResponsiveDatatablesHelper($('#dt_basic'), breakpointDefinition);
}
},
"rowCallback" : function(nRow) {
responsiveHelper_dt_basic.createExpandIcon(nRow);
},
"drawCallback" : function(oSettings) {
responsiveHelper_dt_basic.respond();
}
});
/* END BASIC */
/* COLUMN FILTER */
var otable = $('#datatable_fixed_column').DataTable({
//"bFilter": false,
//"bInfo": false,
//"bLengthChange": false
//"bAutoWidth": false,
//"bPaginate": false,
//"bStateSave": true // saves sort state using localStorage
"sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6 hidden-xs'f><'col-sm-6 col-xs-12 hidden-xs'<'toolbar'>>r>"+
"t"+
"<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
"autoWidth" : true,
"preDrawCallback" : function() {
// Initialize the responsive datatables helper once.
if (!responsiveHelper_datatable_fixed_column) {
responsiveHelper_datatable_fixed_column = new ResponsiveDatatablesHelper($('#datatable_fixed_column'), breakpointDefinition);
}
},
"rowCallback" : function(nRow) {
responsiveHelper_datatable_fixed_column.createExpandIcon(nRow);
},
"drawCallback" : function(oSettings) {
responsiveHelper_datatable_fixed_column.respond();
}
});
// custom toolbar
$("div.toolbar").html('<div class="text-right"><img src="/template/img/logo.png" alt="SmartAdmin" style="width: 111px; margin-top: 3px; margin-right: 10px;"></div>');
// Apply the filter
$("#datatable_fixed_column thead th input[type=text]").on( 'keyup change', function () {
otable
.column( $(this).parent().index()+':visible' )
.search( this.value )
.draw();
} );
/* END COLUMN FILTER */
/* COLUMN SHOW - HIDE */
$('#datatable_col_reorder').dataTable({
"sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-6 hidden-xs'C>r>"+
"t"+
"<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-sm-6 col-xs-12'p>>",
"autoWidth" : true,
"preDrawCallback" : function() {
// Initialize the responsive datatables helper once.
if (!responsiveHelper_datatable_col_reorder) {
responsiveHelper_datatable_col_reorder = new ResponsiveDatatablesHelper($('#datatable_col_reorder'), breakpointDefinition);
}
},
"rowCallback" : function(nRow) {
responsiveHelper_datatable_col_reorder.createExpandIcon(nRow);
},
"drawCallback" : function(oSettings) {
responsiveHelper_datatable_col_reorder.respond();
}
});
/* END COLUMN SHOW - HIDE */
/* TABLETOOLS */
$('#datatable_tabletools').dataTable({
// Tabletools options:
// https://datatables.net/extensions/tabletools/button_options
"sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-6 hidden-xs'T>r>"+
"t"+
"<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-sm-6 col-xs-12'p>>",
"oTableTools": {
"aButtons": [
"copy",
"csv",
"xls",
{
"sExtends": "pdf",
"sTitle": "SmartAdmin_PDF",
"sPdfMessage": "SmartAdmin PDF Export",
"sPdfSize": "letter"
},
{
"sExtends": "print",
"sMessage": "Generated by SmartAdmin <i>(press Esc to close)</i>"
}
],
"sSwfPath": "/template/js/plugin/datatables/swf/copy_csv_xls_pdf.swf"
},
"autoWidth" : true,
"preDrawCallback" : function() {
// Initialize the responsive datatables helper once.
if (!responsiveHelper_datatable_tabletools) {
responsiveHelper_datatable_tabletools = new ResponsiveDatatablesHelper($('#datatable_tabletools'), breakpointDefinition);
}
},
"rowCallback" : function(nRow) {
responsiveHelper_datatable_tabletools.createExpandIcon(nRow);
},
"drawCallback" : function(oSettings) {
responsiveHelper_datatable_tabletools.respond();
}
});
$('#startdate').datepicker({
dateFormat : 'yy-mm-dd',
prevText : '<i class="fa fa-chevron-left"></i>',
nextText : '<i class="fa fa-chevron-right"></i>',
onSelect : function(selectedDate) {
$('#finishdate').datepicker('option', 'minDate', selectedDate);
}
});
$('#finishdate').datepicker({
dateFormat : 'yy-mm-dd',
prevText : '<i class="fa fa-chevron-left"></i>',
nextText : '<i class="fa fa-chevron-right"></i>',
onSelect : function(selectedDate) {
$('#startdate').datepicker('option', 'maxDate', selectedDate);
}
});
/* END TABLETOOLS */
})
</script> | {
"content_hash": "3edfc0d9f44449e541784b8cbcb945a9",
"timestamp": "",
"source": "github",
"line_count": 514,
"max_line_length": 188,
"avg_line_length": 33.09727626459144,
"alnum_prop": 0.543146014577945,
"repo_name": "networksoft/erp.wellnet",
"id": "68ec124d6c43e476915ca98060f63b85fab749a1",
"size": "17013",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/views/website/bo/comercial/Cuentas/PorPagar.php",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "383"
},
{
"name": "Batchfile",
"bytes": "310"
},
{
"name": "C",
"bytes": "479526"
},
{
"name": "CSS",
"bytes": "916036"
},
{
"name": "Groff",
"bytes": "60910"
},
{
"name": "HTML",
"bytes": "7195685"
},
{
"name": "JavaScript",
"bytes": "1616267"
},
{
"name": "Makefile",
"bytes": "16519"
},
{
"name": "PHP",
"bytes": "12824429"
},
{
"name": "Perl",
"bytes": "50950"
},
{
"name": "Shell",
"bytes": "27957"
}
],
"symlink_target": ""
} |
<?php
class CompanyEstados extends ActiveRecord{
} | {
"content_hash": "f125f7f5b448640f921c5b548251392a",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 42,
"avg_line_length": 10.6,
"alnum_prop": 0.7735849056603774,
"repo_name": "jaimeirazabal1/empleolisto",
"id": "abdfa2e05d368e311b8ca3f84d7f752fea58d296",
"size": "53",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "default/app/models/company_estados.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "907"
},
{
"name": "CSS",
"bytes": "32351"
},
{
"name": "HTML",
"bytes": "139541"
},
{
"name": "JavaScript",
"bytes": "80699"
},
{
"name": "PHP",
"bytes": "731905"
}
],
"symlink_target": ""
} |
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/* IndexCell.cs --
* Ars Magna project, http://arsmagna.ru
* -------------------------------------------------------
* Status: poor
*/
#region Using directives
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using AM;
using AM.Collections;
using AM.IO;
using AM.Runtime;
using CodeJam;
using JetBrains.Annotations;
using MoonSharp.Interpreter;
using Newtonsoft.Json;
#endregion
namespace ManagedIrbis.Reports
{
/// <summary>
///
/// </summary>
[PublicAPI]
[MoonSharpUserData]
public sealed class IndexCell
: ReportCell
{
#region Properties
/// <summary>
/// Format.
/// </summary>
[CanBeNull]
[JsonProperty("format")]
[XmlAttribute("format")]
public string Format { get; set; }
#endregion
#region Construction
/// <summary>
/// Constructor.
/// </summary>
public IndexCell()
{
Format = "{Index})";
}
/// <summary>
/// Constructor.
/// </summary>
public IndexCell
(
[CanBeNull] string format
)
{
Format = format;
}
#endregion
#region Private members
#endregion
#region Public methods
#endregion
#region ReportCell members
/// <inheritdoc cref="ReportCell.Compute"/>
public override string Compute
(
ReportContext context
)
{
Code.NotNull(context, "context");
OnBeforeCompute(context);
string result = null;
string format = Format;
if (!string.IsNullOrEmpty(format))
{
string index = (context.Index + 1)
.ToInvariantString();
string total = context.Records.Count
.ToInvariantString();
result = format
.Replace("{Index}", index)
.Replace("{Total}", total);
}
OnAfterCompute(context);
return result;
}
/// <inheritdoc cref="ReportCell.Render" />
public override void Render
(
ReportContext context
)
{
Code.NotNull(context, "context");
ReportDriver driver = context.Driver;
driver.BeginCell(context, this);
string text = Compute(context);
driver.Write(context, text);
driver.EndCell(context, this);
}
#endregion
#region Object members
#endregion
}
}
| {
"content_hash": "7559ec8b2bc6b7fce3dddb301db68c76",
"timestamp": "",
"source": "github",
"line_count": 143,
"max_line_length": 84,
"avg_line_length": 20.937062937062937,
"alnum_prop": 0.5167000668002673,
"repo_name": "amironov73/ManagedIrbis",
"id": "372aafe67aba9a003afae383bbda008726222452",
"size": "2996",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source/Classic/Libs/ManagedIrbis/Source/Reports/Cells/IndexCell.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ANTLR",
"bytes": "92910"
},
{
"name": "ASP.NET",
"bytes": "413"
},
{
"name": "Batchfile",
"bytes": "33021"
},
{
"name": "C",
"bytes": "24669"
},
{
"name": "C#",
"bytes": "19567730"
},
{
"name": "CSS",
"bytes": "170"
},
{
"name": "F*",
"bytes": "362819"
},
{
"name": "HTML",
"bytes": "5592"
},
{
"name": "JavaScript",
"bytes": "5342"
},
{
"name": "Pascal",
"bytes": "152697"
},
{
"name": "Shell",
"bytes": "524"
},
{
"name": "Smalltalk",
"bytes": "29356"
},
{
"name": "TeX",
"bytes": "44337"
},
{
"name": "VBA",
"bytes": "46543"
},
{
"name": "Witcher Script",
"bytes": "40165"
}
],
"symlink_target": ""
} |
/*
* PLUGIN DISKSPACE
*
* Spanish language file.
*
* Author:
*/
theUILang.diskNotification = "Warning! The disk is full. rTorrent may not run correctly, and no data will be downloaded until you free some disk space.";
thePlugins.get("diskspace").langLoaded(); | {
"content_hash": "23250a2a0e0a60c116684041c1ef1f82",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 154,
"avg_line_length": 24.545454545454547,
"alnum_prop": 0.7148148148148148,
"repo_name": "darkpsy/rtorrent-ui",
"id": "828ba7d6694deb8302035e1ace4631de046f99bf",
"size": "272",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "plugins/diskspace/lang/es.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "13"
},
{
"name": "CSS",
"bytes": "119610"
},
{
"name": "HTML",
"bytes": "33939"
},
{
"name": "JavaScript",
"bytes": "1731969"
},
{
"name": "PHP",
"bytes": "603087"
},
{
"name": "Shell",
"bytes": "3628"
}
],
"symlink_target": ""
} |
package com.javadeobfuscator.deobfuscator.org.objectweb.asm.commons;
import com.javadeobfuscator.deobfuscator.org.objectweb.asm.AnnotationVisitor;
import com.javadeobfuscator.deobfuscator.org.objectweb.asm.Label;
import com.javadeobfuscator.deobfuscator.org.objectweb.asm.MethodVisitor;
import com.javadeobfuscator.deobfuscator.org.objectweb.asm.Opcodes;
import com.javadeobfuscator.deobfuscator.org.objectweb.asm.Type;
import com.javadeobfuscator.deobfuscator.org.objectweb.asm.TypePath;
/**
* A {@link MethodVisitor} that renumbers local variables in their order of
* appearance. This adapter allows one to easily add new local variables to a
* method. It may be used by inheriting from this class, but the preferred way
* of using it is via delegation: the next visitor in the chain can indeed add
* new locals when needed by calling {@link #newLocal} on this adapter (this
* requires a reference back to this {@link LocalVariablesSorter}).
*
* @author Chris Nokleberg
* @author Eugene Kuleshov
* @author Eric Bruneton
*/
public class LocalVariablesSorter extends MethodVisitor {
private static final Type OBJECT_TYPE = Type
.getObjectType("java/lang/Object");
/**
* Mapping from old to new local variable indexes. A local variable at index
* i of size 1 is remapped to 'mapping[2*i]', while a local variable at
* index i of size 2 is remapped to 'mapping[2*i+1]'.
*/
private int[] mapping = new int[40];
/**
* Array used to store stack map local variable types after remapping.
*/
private Object[] newLocals = new Object[20];
/**
* Index of the first local variable, after formal parameters.
*/
protected final int firstLocal;
/**
* Index of the next local variable to be created by {@link #newLocal}.
*/
protected int nextLocal;
/**
* Creates a new {@link LocalVariablesSorter}. <i>Subclasses must not use
* this constructor</i>. Instead, they must use the
* {@link #LocalVariablesSorter(int, int, String, MethodVisitor)} version.
*
* @param access
* access flags of the adapted method.
* @param desc
* the method's descriptor (see {@link Type Type}).
* @param mv
* the method visitor to which this adapter delegates calls.
* @throws IllegalStateException
* If a subclass calls this constructor.
*/
public LocalVariablesSorter(final int access, final String desc,
final MethodVisitor mv) {
this(Opcodes.ASM6, access, desc, mv);
if (getClass() != LocalVariablesSorter.class) {
throw new IllegalStateException();
}
}
/**
* Creates a new {@link LocalVariablesSorter}.
*
* @param api
* the ASM API version implemented by this visitor. Must be one
* of {@link Opcodes#ASM4}, {@link Opcodes#ASM5} or {@link Opcodes#ASM6}.
* @param access
* access flags of the adapted method.
* @param desc
* the method's descriptor (see {@link Type Type}).
* @param mv
* the method visitor to which this adapter delegates calls.
*/
protected LocalVariablesSorter(final int api, final int access,
final String desc, final MethodVisitor mv) {
super(api, mv);
Type[] args = Type.getArgumentTypes(desc);
nextLocal = (Opcodes.ACC_STATIC & access) == 0 ? 1 : 0;
for (int i = 0; i < args.length; i++) {
nextLocal += args[i].getSize();
}
firstLocal = nextLocal;
}
@Override
public void visitVarInsn(final int opcode, final int var) {
Type type;
switch (opcode) {
case Opcodes.LLOAD:
case Opcodes.LSTORE:
type = Type.LONG_TYPE;
break;
case Opcodes.DLOAD:
case Opcodes.DSTORE:
type = Type.DOUBLE_TYPE;
break;
case Opcodes.FLOAD:
case Opcodes.FSTORE:
type = Type.FLOAT_TYPE;
break;
case Opcodes.ILOAD:
case Opcodes.ISTORE:
type = Type.INT_TYPE;
break;
default:
// case Opcodes.ALOAD:
// case Opcodes.ASTORE:
// case RET:
type = OBJECT_TYPE;
break;
}
mv.visitVarInsn(opcode, remap(var, type));
}
@Override
public void visitIincInsn(final int var, final int increment) {
mv.visitIincInsn(remap(var, Type.INT_TYPE), increment);
}
@Override
public void visitMaxs(final int maxStack, final int maxLocals) {
mv.visitMaxs(maxStack, nextLocal);
}
@Override
public void visitLocalVariable(final String name, final String desc,
final String signature, final Label start, final Label end,
final int index) {
int newIndex = remap(index, Type.getType(desc));
mv.visitLocalVariable(name, desc, signature, start, end, newIndex);
}
@Override
public AnnotationVisitor visitLocalVariableAnnotation(int typeRef,
TypePath typePath, Label[] start, Label[] end, int[] index,
String desc, boolean visible) {
Type t = Type.getType(desc);
int[] newIndex = new int[index.length];
for (int i = 0; i < newIndex.length; ++i) {
newIndex[i] = remap(index[i], t);
}
return mv.visitLocalVariableAnnotation(typeRef, typePath, start, end,
newIndex, desc, visible);
}
@Override
public void visitFrame(final int type, final int nLocal,
final Object[] local, final int nStack, final Object[] stack) {
if (type != Opcodes.F_NEW) { // uncompressed frame
throw new IllegalStateException(
"ClassReader.accept() should be called with EXPAND_FRAMES flag");
}
// creates a copy of newLocals
Object[] oldLocals = new Object[newLocals.length];
System.arraycopy(newLocals, 0, oldLocals, 0, oldLocals.length);
updateNewLocals(newLocals);
// copies types from 'local' to 'newLocals'
// 'newLocals' already contains the variables added with 'newLocal'
int index = 0; // old local variable index
int number = 0; // old local variable number
for (; number < nLocal; ++number) {
Object t = local[number];
int size = t == Opcodes.LONG || t == Opcodes.DOUBLE ? 2 : 1;
if (t != Opcodes.TOP) {
Type typ = OBJECT_TYPE;
if (t == Opcodes.INTEGER) {
typ = Type.INT_TYPE;
} else if (t == Opcodes.FLOAT) {
typ = Type.FLOAT_TYPE;
} else if (t == Opcodes.LONG) {
typ = Type.LONG_TYPE;
} else if (t == Opcodes.DOUBLE) {
typ = Type.DOUBLE_TYPE;
} else if (t instanceof String) {
typ = Type.getObjectType((String) t);
}
setFrameLocal(remap(index, typ), t);
}
index += size;
}
// removes TOP after long and double types as well as trailing TOPs
index = 0;
number = 0;
for (int i = 0; index < newLocals.length; ++i) {
Object t = newLocals[index++];
if (t != null && t != Opcodes.TOP) {
newLocals[i] = t;
number = i + 1;
if (t == Opcodes.LONG || t == Opcodes.DOUBLE) {
index += 1;
}
} else {
newLocals[i] = Opcodes.TOP;
}
}
// visits remapped frame
mv.visitFrame(type, number, newLocals, nStack, stack);
// restores original value of 'newLocals'
newLocals = oldLocals;
}
// -------------
/**
* Creates a new local variable of the given type.
*
* @param type
* the type of the local variable to be created.
* @return the identifier of the newly created local variable.
*/
public int newLocal(final Type type) {
Object t;
switch (type.getSort()) {
case Type.BOOLEAN:
case Type.CHAR:
case Type.BYTE:
case Type.SHORT:
case Type.INT:
t = Opcodes.INTEGER;
break;
case Type.FLOAT:
t = Opcodes.FLOAT;
break;
case Type.LONG:
t = Opcodes.LONG;
break;
case Type.DOUBLE:
t = Opcodes.DOUBLE;
break;
case Type.ARRAY:
t = type.getDescriptor();
break;
// case Type.OBJECT:
default:
t = type.getInternalName();
break;
}
int local = newLocalMapping(type);
setLocalType(local, type);
setFrameLocal(local, t);
return local;
}
/**
* Notifies subclasses that a new stack map frame is being visited. The
* array argument contains the stack map frame types corresponding to the
* local variables added with {@link #newLocal}. This method can update
* these types in place for the stack map frame being visited. The default
* implementation of this method does nothing, i.e. a local variable added
* with {@link #newLocal} will have the same type in all stack map frames.
* But this behavior is not always the desired one, for instance if a local
* variable is added in the middle of a try/catch block: the frame for the
* exception handler should have a TOP type for this new local.
*
* @param newLocals
* the stack map frame types corresponding to the local variables
* added with {@link #newLocal} (and null for the others). The
* format of this array is the same as in
* {@link MethodVisitor#visitFrame}, except that long and double
* types use two slots. The types for the current stack map frame
* must be updated in place in this array.
*/
protected void updateNewLocals(Object[] newLocals) {
}
/**
* Notifies subclasses that a local variable has been added or remapped. The
* default implementation of this method does nothing.
*
* @param local
* a local variable identifier, as returned by {@link #newLocal
* newLocal()}.
* @param type
* the type of the value being stored in the local variable.
*/
protected void setLocalType(final int local, final Type type) {
}
private void setFrameLocal(final int local, final Object type) {
int l = newLocals.length;
if (local >= l) {
Object[] a = new Object[Math.max(2 * l, local + 1)];
System.arraycopy(newLocals, 0, a, 0, l);
newLocals = a;
}
newLocals[local] = type;
}
private int remap(final int var, final Type type) {
if (var + type.getSize() <= firstLocal) {
return var;
}
int key = 2 * var + type.getSize() - 1;
int size = mapping.length;
if (key >= size) {
int[] newMapping = new int[Math.max(2 * size, key + 1)];
System.arraycopy(mapping, 0, newMapping, 0, size);
mapping = newMapping;
}
int value = mapping[key];
if (value == 0) {
value = newLocalMapping(type);
setLocalType(value, type);
mapping[key] = value + 1;
} else {
value--;
}
return value;
}
protected int newLocalMapping(final Type type) {
int local = nextLocal;
nextLocal += type.getSize();
return local;
}
}
| {
"content_hash": "8a90a2258e43c622900391a4a53fe179",
"timestamp": "",
"source": "github",
"line_count": 339,
"max_line_length": 88,
"avg_line_length": 34.982300884955755,
"alnum_prop": 0.5743317311746353,
"repo_name": "FFY00/deobfuscator",
"id": "30a71fab75048fd026c46e6df030703fa66133c6",
"size": "13518",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/javadeobfuscator/deobfuscator/org/objectweb/asm/commons/LocalVariablesSorter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "23338"
},
{
"name": "Jasmin",
"bytes": "41372"
},
{
"name": "Java",
"bytes": "2375823"
}
],
"symlink_target": ""
} |
SET @sName = 'bx_timeline';
-- TABLES
CREATE TABLE IF NOT EXISTS `bx_timeline_events` (
`id` int(11) NOT NULL auto_increment,
`owner_id` int(11) NOT NULL default '0',
`system` tinyint(4) NOT NULL default '1',
`type` varchar(255) NOT NULL,
`action` varchar(255) NOT NULL,
`object_id` int(11) NOT NULL default '0',
`object_owner_id` int(11) NOT NULL default '0',
`object_privacy_view` varchar(16) NOT NULL default '3',
`content` text NOT NULL,
`title` varchar(255) NOT NULL,
`description` text NOT NULL,
`location` text NOT NULL,
`views` int(11) unsigned NOT NULL default '0',
`rate` float NOT NULL default '0',
`votes` int(11) unsigned NOT NULL default '0',
`rrate` float NOT NULL default '0',
`rvotes` int(11) NOT NULL default '0',
`score` int(11) NOT NULL default '0',
`sc_up` int(11) NOT NULL default '0',
`sc_down` int(11) NOT NULL default '0',
`comments` int(11) unsigned NOT NULL default '0',
`reports` int(11) unsigned NOT NULL default '0',
`reposts` int(11) unsigned NOT NULL default '0',
`date` int(11) NOT NULL default '0',
`published` int(11) NOT NULL default '0',
`status` enum ('active', 'awaiting', 'failed', 'hidden', 'deleted') NOT NULL DEFAULT 'active',
`active` tinyint(4) NOT NULL default '1',
`pinned` int(11) NOT NULL default '0',
`sticked` int(11) NOT NULL default '0',
`promoted` int(11) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `owner_id` (`owner_id`),
KEY `object_id` (`object_id`),
FULLTEXT KEY `search_fields` (`title`, `description`)
);
CREATE TABLE IF NOT EXISTS `bx_timeline_handlers` (
`id` int(11) NOT NULL auto_increment,
`group` varchar(64) NOT NULL default '',
`type` enum('insert','update','delete') NOT NULL DEFAULT 'insert',
`alert_unit` varchar(64) NOT NULL default '',
`alert_action` varchar(64) NOT NULL default '',
`content` text NOT NULL,
`privacy` varchar(64) NOT NULL default '',
PRIMARY KEY (`id`),
UNIQUE `handler` (`group`, `type`),
UNIQUE `alert` (`alert_unit`, `alert_action`)
);
INSERT INTO `bx_timeline_handlers`(`group`, `type`, `alert_unit`, `alert_action`, `content`) VALUES
('common_post', 'insert', 'timeline_common_post', '', ''),
('common_repost', 'insert', 'timeline_common_repost', '', ''),
('profile', 'delete', 'profile', 'delete', ''),
('comment', 'insert', 'comment', 'added', 'a:5:{s:11:"module_name";s:6:"system";s:13:"module_method";s:17:"get_timeline_post";s:12:"module_class";s:17:"TemplCmtsServices";s:9:"groupable";i:0;s:8:"group_by";s:0:"";}'),
('comment', 'update', 'comment', 'edited', ''),
('comment', 'delete', 'comment', 'deleted', '');
CREATE TABLE IF NOT EXISTS `bx_timeline_cache` (
`type` varchar(32) NOT NULL default '',
`context_id` int(11) NOT NULL default '0',
`profile_id` int(11) NOT NULL default '0',
`event_id` int(11) NOT NULL default '0',
`date` int(11) NOT NULL default '0',
`important` tinyint(4) NOT NULL default '0',
PRIMARY KEY `item` (`type`, `context_id`, `profile_id`, `event_id`)
);
-- TABLE: mute
CREATE TABLE IF NOT EXISTS `bx_timeline_mute` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`initiator` int(11) NOT NULL,
`content` int(11) NOT NULL,
`mutual` tinyint(4) NOT NULL,
`added` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `initiator` (`initiator`,`content`),
KEY `content` (`content`)
);
-- TABLES: STORAGES, TRANSCODERS, UPLOADERS
CREATE TABLE IF NOT EXISTS `bx_timeline_photos` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`profile_id` int(10) unsigned NOT NULL,
`remote_id` varchar(128) NOT NULL,
`path` varchar(255) NOT NULL,
`file_name` varchar(255) NOT NULL,
`mime_type` varchar(128) NOT NULL,
`ext` varchar(32) NOT NULL,
`size` bigint(20) NOT NULL,
`added` int(11) NOT NULL,
`modified` int(11) NOT NULL,
`private` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `remote_id` (`remote_id`)
);
CREATE TABLE IF NOT EXISTS `bx_timeline_photos_processed` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`profile_id` int(10) unsigned NOT NULL,
`remote_id` varchar(128) NOT NULL,
`path` varchar(255) NOT NULL,
`file_name` varchar(255) NOT NULL,
`mime_type` varchar(128) NOT NULL,
`ext` varchar(32) NOT NULL,
`size` bigint(20) NOT NULL,
`added` int(11) NOT NULL,
`modified` int(11) NOT NULL,
`private` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `remote_id` (`remote_id`)
);
CREATE TABLE IF NOT EXISTS `bx_timeline_photos2events` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`event_id` int(11) NOT NULL DEFAULT '0',
`media_id` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `media` (`event_id`, `media_id`)
);
CREATE TABLE IF NOT EXISTS `bx_timeline_videos` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`profile_id` int(10) unsigned NOT NULL,
`remote_id` varchar(128) NOT NULL,
`path` varchar(255) NOT NULL,
`file_name` varchar(255) NOT NULL,
`mime_type` varchar(128) NOT NULL,
`ext` varchar(32) NOT NULL,
`size` bigint(20) NOT NULL,
`dimensions` varchar(12) NOT NULL,
`added` int(11) NOT NULL,
`modified` int(11) NOT NULL,
`private` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `remote_id` (`remote_id`)
);
CREATE TABLE IF NOT EXISTS `bx_timeline_videos_processed` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`profile_id` int(10) unsigned NOT NULL,
`remote_id` varchar(128) NOT NULL,
`path` varchar(255) NOT NULL,
`file_name` varchar(255) NOT NULL,
`mime_type` varchar(128) NOT NULL,
`ext` varchar(32) NOT NULL,
`size` bigint(20) NOT NULL,
`added` int(11) NOT NULL,
`modified` int(11) NOT NULL,
`private` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `remote_id` (`remote_id`)
);
CREATE TABLE IF NOT EXISTS `bx_timeline_videos2events` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`event_id` int(11) NOT NULL DEFAULT '0',
`media_id` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `media` (`event_id`, `media_id`)
);
-- TABLES: LINKS
CREATE TABLE IF NOT EXISTS `bx_timeline_links` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`profile_id` int(10) unsigned NOT NULL,
`media_id` int(11) NOT NULL DEFAULT '0',
`url` varchar(255) NOT NULL,
`title` varchar(255) NOT NULL,
`text` text NOT NULL,
`added` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `profile_id` (`profile_id`)
);
CREATE TABLE IF NOT EXISTS `bx_timeline_links2events` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`event_id` int(11) NOT NULL DEFAULT '0',
`link_id` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `link` (`link_id`, `event_id`)
);
-- TABLES: REPOSTS
CREATE TABLE IF NOT EXISTS `bx_timeline_reposts_track` (
`event_id` int(11) NOT NULL default '0',
`author_id` int(11) NOT NULL default '0',
`author_nip` int(11) unsigned NOT NULL default '0',
`reposted_id` int(11) NOT NULL default '0',
`date` int(11) NOT NULL default '0',
UNIQUE KEY `event_id` (`event_id`),
KEY `repost` (`reposted_id`, `author_nip`)
);
-- TABLES: COMMENTS
CREATE TABLE IF NOT EXISTS `bx_timeline_comments` (
`cmt_id` int(11) NOT NULL AUTO_INCREMENT,
`cmt_parent_id` int(11) NOT NULL DEFAULT '0',
`cmt_vparent_id` int(11) NOT NULL DEFAULT '0',
`cmt_object_id` int(11) NOT NULL DEFAULT '0',
`cmt_author_id` int(11) NOT NULL DEFAULT '0',
`cmt_level` int(11) NOT NULL DEFAULT '0',
`cmt_text` text NOT NULL,
`cmt_time` int(11) unsigned NOT NULL DEFAULT '0',
`cmt_replies` int(11) NOT NULL DEFAULT '0',
`cmt_pinned` int(11) NOT NULL default '0',
PRIMARY KEY (`cmt_id`),
KEY `cmt_object_id` (`cmt_object_id`,`cmt_parent_id`),
FULLTEXT KEY `search_fields` (`cmt_text`)
);
-- TABLE: views
CREATE TABLE IF NOT EXISTS `bx_timeline_views_track` (
`object_id` int(11) NOT NULL default '0',
`viewer_id` int(11) NOT NULL default '0',
`viewer_nip` int(11) unsigned NOT NULL default '0',
`date` int(11) NOT NULL default '0',
KEY `id` (`object_id`,`viewer_id`,`viewer_nip`)
);
-- TABLES: VOTES
CREATE TABLE IF NOT EXISTS `bx_timeline_votes` (
`object_id` int(11) NOT NULL default '0',
`count` int(11) NOT NULL default '0',
`sum` int(11) NOT NULL default '0',
UNIQUE KEY `object_id` (`object_id`)
);
CREATE TABLE IF NOT EXISTS `bx_timeline_votes_track` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`object_id` int(11) NOT NULL default '0',
`author_id` int(11) NOT NULL default '0',
`author_nip` int(11) unsigned NOT NULL default '0',
`value` tinyint(4) NOT NULL default '0',
`date` int(11) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `vote` (`object_id`, `author_nip`)
);
CREATE TABLE IF NOT EXISTS `bx_timeline_reactions` (
`object_id` int(11) NOT NULL default '0',
`reaction` varchar(32) NOT NULL default '',
`count` int(11) NOT NULL default '0',
`sum` int(11) NOT NULL default '0',
UNIQUE KEY `reaction` (`object_id`, `reaction`)
);
CREATE TABLE IF NOT EXISTS `bx_timeline_reactions_track` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`object_id` int(11) NOT NULL default '0',
`author_id` int(11) NOT NULL default '0',
`author_nip` int(11) unsigned NOT NULL default '0',
`reaction` varchar(32) NOT NULL default '',
`value` tinyint(4) NOT NULL default '0',
`date` int(11) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `vote` (`object_id`, `author_nip`)
);
-- TABLE: metas
CREATE TABLE IF NOT EXISTS `bx_timeline_meta_keywords` (
`object_id` int(10) unsigned NOT NULL,
`keyword` varchar(255) NOT NULL,
KEY `object_id` (`object_id`),
KEY `keyword` (`keyword`)
);
CREATE TABLE IF NOT EXISTS `bx_timeline_meta_locations` (
`object_id` int(10) unsigned NOT NULL,
`lat` double NOT NULL,
`lng` double NOT NULL,
`country` varchar(2) NOT NULL,
`state` varchar(255) NOT NULL,
`city` varchar(255) NOT NULL,
`zip` varchar(255) NOT NULL,
`street` varchar(255) NOT NULL,
`street_number` varchar(255) NOT NULL,
PRIMARY KEY (`object_id`),
KEY `country_state_city` (`country`,`state`(8),`city`(8))
);
CREATE TABLE IF NOT EXISTS `bx_timeline_meta_mentions` (
`object_id` int(10) unsigned NOT NULL,
`profile_id` int(10) unsigned NOT NULL,
KEY `object_id` (`object_id`),
KEY `profile_id` (`profile_id`)
);
-- TABLE: reports
CREATE TABLE IF NOT EXISTS `bx_timeline_reports` (
`object_id` int(11) NOT NULL default '0',
`count` int(11) NOT NULL default '0',
UNIQUE KEY `object_id` (`object_id`)
);
CREATE TABLE IF NOT EXISTS `bx_timeline_reports_track` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`object_id` int(11) NOT NULL default '0',
`author_id` int(11) NOT NULL default '0',
`author_nip` int(11) unsigned NOT NULL default '0',
`type` varchar(32) NOT NULL default '',
`text` text NOT NULL default '',
`date` int(11) NOT NULL default '0',
`checked_by` int(11) NOT NULL default '0',
`status` tinyint(11) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `report` (`object_id`, `author_nip`)
);
-- TABLE: hot track
CREATE TABLE IF NOT EXISTS `bx_timeline_hot_track` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`event_id` int(11) NOT NULL default '0',
`value` int(11) NOT NULL default '0',
PRIMARY KEY (`id`),
UNIQUE KEY `event_id` (`event_id`)
);
-- TABLE: scores
CREATE TABLE IF NOT EXISTS `bx_timeline_scores` (
`object_id` int(11) NOT NULL default '0',
`count_up` int(11) NOT NULL default '0',
`count_down` int(11) NOT NULL default '0',
UNIQUE KEY `object_id` (`object_id`)
);
CREATE TABLE IF NOT EXISTS `bx_timeline_scores_track` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`object_id` int(11) NOT NULL default '0',
`author_id` int(11) NOT NULL default '0',
`author_nip` int(11) unsigned NOT NULL default '0',
`type` varchar(8) NOT NULL default '',
`date` int(11) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `vote` (`object_id`, `author_nip`)
);
-- STORAGES, TRANSCODERS, UPLOADERS
SET @sStorageEngine = (SELECT `value` FROM `sys_options` WHERE `name` = 'sys_storage_default');
INSERT INTO `sys_objects_uploader` (`object`, `active`, `override_class_name`, `override_class_file`) VALUES
('bx_timeline_simple_photo', 1, 'BxTimelineUploaderSimpleAttach', 'modules/boonex/timeline/classes/BxTimelineUploaderSimpleAttach.php'),
('bx_timeline_simple_video', 1, 'BxTimelineUploaderSimpleAttach', 'modules/boonex/timeline/classes/BxTimelineUploaderSimpleAttach.php'),
('bx_timeline_html5_photo', 1, 'BxTimelineUploaderHTML5Attach', 'modules/boonex/timeline/classes/BxTimelineUploaderHTML5Attach.php'),
('bx_timeline_html5_video', 1, 'BxTimelineUploaderHTML5Attach', 'modules/boonex/timeline/classes/BxTimelineUploaderHTML5Attach.php'),
('bx_timeline_record_video', 1, 'BxTimelineUploaderRecordVideoAttach', 'modules/boonex/timeline/classes/BxTimelineUploaderRecordVideoAttach.php');
INSERT INTO `sys_objects_storage` (`object`, `engine`, `params`, `token_life`, `cache_control`, `levels`, `table_files`, `ext_mode`, `ext_allow`, `ext_deny`, `quota_size`, `current_size`, `quota_number`, `current_number`, `max_file_size`, `ts`) VALUES
('bx_timeline_photos', @sStorageEngine, '', 360, 2592000, 3, 'bx_timeline_photos', 'allow-deny', 'jpg,jpeg,jpe,gif,png', '', 0, 0, 0, 0, 0, 0),
('bx_timeline_photos_processed', @sStorageEngine, '', 360, 2592000, 3, 'bx_timeline_photos_processed', 'allow-deny', 'jpg,jpeg,jpe,gif,png', '', 0, 0, 0, 0, 0, 0),
('bx_timeline_videos', @sStorageEngine, 'a:1:{s:6:"fields";a:1:{s:10:"dimensions";s:17:"getFileDimensions";}}', 360, 2592000, 3, 'bx_timeline_videos', 'allow-deny', 'avi,flv,mpg,mpeg,wmv,mp4,m4v,mov,qt,divx,xvid,3gp,3g2,webm,mkv,ogv,ogg,rm,rmvb,asf,drc', '', 0, 0, 0, 0, 0, 0),
('bx_timeline_videos_processed', @sStorageEngine, '', 360, 2592000, 3, 'bx_timeline_videos_processed', 'allow-deny', 'jpg,jpeg,jpe,gif,png,avi,flv,mpg,mpeg,wmv,mp4,m4v,mov,qt,divx,xvid,3gp,3g2,webm,mkv,ogv,ogg,rm,rmvb,asf,drc', '', 0, 0, 0, 0, 0, 0);
INSERT INTO `sys_objects_transcoder` (`object`, `storage_object`, `source_type`, `source_params`, `private`, `atime_tracking`, `atime_pruning`, `ts`, `override_class_name`, `override_class_file`) VALUES
('bx_timeline_photos_preview', 'bx_timeline_photos_processed', 'Storage', 'a:1:{s:6:"object";s:18:"bx_timeline_photos";}', 'no', '1', '2592000', '0', '', ''),
('bx_timeline_photos_view', 'bx_timeline_photos_processed', 'Storage', 'a:1:{s:6:"object";s:18:"bx_timeline_photos";}', 'no', '1', '2592000', '0', '', ''),
('bx_timeline_photos_medium', 'bx_timeline_photos_processed', 'Storage', 'a:1:{s:6:"object";s:18:"bx_timeline_photos";}', 'no', '1', '2592000', '0', '', ''),
('bx_timeline_photos_big', 'bx_timeline_photos_processed', 'Storage', 'a:1:{s:6:"object";s:18:"bx_timeline_photos";}', 'no', '1', '2592000', '0', '', ''),
('bx_timeline_videos_poster', 'bx_timeline_videos_processed', 'Storage', 'a:1:{s:6:"object";s:18:"bx_timeline_videos";}', 'no', '0', '0', '0', 'BxDolTranscoderVideo', ''),
('bx_timeline_videos_mp4', 'bx_timeline_videos_processed', 'Storage', 'a:1:{s:6:"object";s:18:"bx_timeline_videos";}', 'no', '0', '0', '0', 'BxDolTranscoderVideo', ''),
('bx_timeline_videos_mp4_hd', 'bx_timeline_videos_processed', 'Storage', 'a:1:{s:6:"object";s:18:"bx_timeline_videos";}', 'no', '0', '0', '0', 'BxDolTranscoderVideo', '');
INSERT INTO `sys_transcoder_filters` (`transcoder_object`, `filter`, `filter_params`, `order`) VALUES
('bx_timeline_photos_preview', 'Resize', 'a:3:{s:1:"w";s:3:"100";s:1:"h";s:3:"100";s:13:"square_resize";s:1:"1";}', '0'),
('bx_timeline_photos_view', 'Resize', 'a:1:{s:1:"w";s:3:"300";}', '0'),
('bx_timeline_photos_medium', 'Resize', 'a:1:{s:1:"w";s:3:"600";}', '0'),
('bx_timeline_photos_big', 'Resize', 'a:2:{s:1:"w";s:4:"1200";s:1:"h";s:4:"1200";}', '0'),
('bx_timeline_videos_poster', 'Poster', 'a:2:{s:1:"h";s:3:"318";s:10:"force_type";s:3:"jpg";}', 0),
('bx_timeline_videos_mp4', 'Mp4', 'a:2:{s:1:"h";s:3:"318";s:10:"force_type";s:3:"mp4";}', 0),
('bx_timeline_videos_mp4_hd', 'Mp4', 'a:3:{s:1:"h";s:3:"720";s:13:"video_bitrate";s:4:"1536";s:10:"force_type";s:3:"mp4";}', 0);
-- Forms -> Post
INSERT INTO `sys_objects_form` (`object`, `module`, `title`, `action`, `form_attrs`, `submit_name`, `table`, `key`, `uri`, `uri_title`, `params`, `deletable`, `active`, `override_class_name`, `override_class_file`) VALUES
('bx_timeline_post', @sName, '_bx_timeline_form_post', '', '', 'tlb_do_submit', 'bx_timeline_events', 'id', '', '', '', 0, 1, 'BxTimelineFormPost', 'modules/boonex/timeline/classes/BxTimelineFormPost.php');
INSERT INTO `sys_form_displays` (`display_name`, `module`, `object`, `title`, `view_mode`) VALUES
('bx_timeline_post_add', @sName, 'bx_timeline_post', '_bx_timeline_form_post_display_add', 0),
('bx_timeline_post_add_public', @sName, 'bx_timeline_post', '_bx_timeline_form_post_display_add_public', 0),
('bx_timeline_post_add_profile', @sName, 'bx_timeline_post', '_bx_timeline_form_post_display_add_profile', 0),
('bx_timeline_post_edit', @sName, 'bx_timeline_post', '_bx_timeline_form_post_display_edit', 0),
('bx_timeline_post_view', @sName, 'bx_timeline_post', '_bx_timeline_form_post_display_view', 1);
INSERT INTO `sys_form_inputs` (`object`, `module`, `name`, `value`, `values`, `checked`, `type`, `caption_system`, `caption`, `info`, `required`, `collapsed`, `html`, `attrs`, `attrs_tr`, `attrs_wrapper`, `checker_func`, `checker_params`, `checker_error`, `db_pass`, `db_params`, `editable`, `deletable`) VALUES
('bx_timeline_post', @sName, 'type', 'post', '', 0, 'hidden', '_bx_timeline_form_post_input_sys_type', '', '', 0, 0, 0, '', '', '', '', '', '', 'Xss', '', 0, 0),
('bx_timeline_post', @sName, 'action', '', '', 0, 'hidden', '_bx_timeline_form_post_input_sys_action', '', '', 0, 0, 0, '', '', '', '', '', '', 'Xss', '', 0, 0),
('bx_timeline_post', @sName, 'owner_id', '0', '', 0, 'hidden', '_bx_timeline_form_post_input_sys_owner_id', '', '', 0, 0, 0, '', '', '', '', '', '', 'Int', '', 1, 0),
('bx_timeline_post', @sName, 'text', '', '', 0, 'textarea', '_bx_timeline_form_post_input_sys_text', '_bx_timeline_form_post_input_text', '', 0, 0, 3, 'a:1:{s:12:"autocomplete";s:3:"off";}', '', '', '', '', '', 'XssHtml', '', 1, 0),
('bx_timeline_post', @sName, 'anonymous', '', '', 0, 'switcher', '_sys_form_input_sys_anonymous', '_sys_form_input_anonymous', '', 0, 0, 0, '', '', '', '', '', '', '', '', 1, 0),
('bx_timeline_post', @sName, 'date', '', '', 0, 'datetime', '_bx_timeline_form_post_input_sys_date', '_bx_timeline_form_post_input_date', '', 0, 0, 0, '', '', '', '', '', '', 'DateTimeUtc', '', 1, 0),
('bx_timeline_post', @sName, 'published', '', '', 0, 'datetime', '_bx_timeline_form_post_input_sys_date_published', '_bx_timeline_form_post_input_date_published', '_bx_timeline_form_post_input_date_published_info', 0, 0, 0, '', '', '', '', '', '', 'DateTimeUtc', '', 1, 0),
('bx_timeline_post', @sName, 'object_privacy_view', '', '', 0, 'custom', '_bx_timeline_form_post_input_sys_object_privacy_view', '_bx_timeline_form_post_input_object_privacy_view', '', 1, 0, 0, '', '', '', '', '', '', '', '', 0, 0),
('bx_timeline_post', @sName, 'location', '', '', 0, 'location', '_sys_form_input_sys_location', '', '', 0, 0, 0, '', '', '', '', '', '', '', '', 1, 0),
('bx_timeline_post', @sName, 'link', '', '', 0, 'custom', '_bx_timeline_form_post_input_sys_link', '', '', 0, 0, 0, '', '', '', '', '', '', '', '', 1, 0),
('bx_timeline_post', @sName, 'photo', 'a:1:{i:0;s:23:"bx_timeline_html5_photo";}', 'a:2:{s:24:"bx_timeline_simple_photo";s:26:"_sys_uploader_simple_title";s:23:"bx_timeline_html5_photo";s:25:"_sys_uploader_html5_title";}', 0, 'files', '_bx_timeline_form_post_input_sys_photo', '_bx_timeline_form_post_input_photo', '', 0, 0, 0, '', '', '', '', '', '', '', '', 1, 0),
('bx_timeline_post', @sName, 'video', 'a:2:{i:0;s:23:"bx_timeline_html5_video";i:1;s:24:"bx_timeline_record_video";}', 'a:3:{s:24:"bx_timeline_simple_video";s:26:"_sys_uploader_simple_title";s:23:"bx_timeline_html5_video";s:25:"_sys_uploader_html5_title";s:24:"bx_timeline_record_video";s:32:"_sys_uploader_record_video_title";}', 0, 'files', '_bx_timeline_form_post_input_sys_video', '_bx_timeline_form_post_input_video', '', 0, 0, 0, '', '', '', '', '', '', '', '', 1, 0),
('bx_timeline_post', @sName, 'attachments', '', '', 0, 'custom', '_bx_timeline_form_post_input_sys_attachments', '', '', 0, 0, 0, '', '', '', '', '', '', '', '', 1, 0),
('bx_timeline_post', @sName, 'controls', '', 'tlb_do_submit,tlb_do_cancel', 0, 'input_set', '', '', '', 0, 0, 0, '', '', '', '', '', '', '', '', 0, 0),
('bx_timeline_post', @sName, 'tlb_do_submit', '_bx_timeline_form_post_input_do_submit', '', 0, 'submit', '_bx_timeline_form_post_input_sys_do_submit', '', '', 0, 0, 0, '', '', '', '', '', '', '', '', 0, 0),
('bx_timeline_post', @sName, 'tlb_do_cancel', '_bx_timeline_form_post_input_do_cancel', '', 0, 'button', '_bx_timeline_form_post_input_sys_do_cancel', '', '', 0, 0, 0, 'a:2:{s:7:"onclick";s:51:"{js_object_view}.editPostCancel(this, {content_id})";s:5:"class";s:22:"bx-def-margin-sec-left";}', '', '', '', '', '', '', '', 0, 0);
INSERT INTO `sys_form_display_inputs` (`display_name`, `input_name`, `visible_for_levels`, `active`, `order`) VALUES
('bx_timeline_post_add', 'type', 2147483647, 1, 0),
('bx_timeline_post_add', 'action', 2147483647, 1, 1),
('bx_timeline_post_add', 'text', 2147483647, 1, 2),
('bx_timeline_post_add', 'attachments', 2147483647, 1, 3),
('bx_timeline_post_add', 'owner_id', 2147483647, 1, 4),
('bx_timeline_post_add', 'object_privacy_view', 2147483647, 1, 5),
('bx_timeline_post_add', 'published', 192, 1, 6),
('bx_timeline_post_add', 'location', 2147483647, 1, 7),
('bx_timeline_post_add', 'link', 2147483647, 1, 8),
('bx_timeline_post_add', 'photo', 2147483647, 1, 9),
('bx_timeline_post_add', 'video', 2147483647, 1, 10),
('bx_timeline_post_add', 'tlb_do_submit', 2147483647, 1, 11),
('bx_timeline_post_add_public', 'type', 2147483647, 1, 0),
('bx_timeline_post_add_public', 'action', 2147483647, 1, 1),
('bx_timeline_post_add_public', 'owner_id', 2147483647, 1, 2),
('bx_timeline_post_add_public', 'text', 2147483647, 1, 3),
('bx_timeline_post_add_public', 'attachments', 2147483647, 1, 4),
('bx_timeline_post_add_public', 'object_privacy_view', 2147483647, 1, 5),
('bx_timeline_post_add_public', 'published', 192, 1, 6),
('bx_timeline_post_add_public', 'location', 2147483647, 1, 7),
('bx_timeline_post_add_public', 'link', 2147483647, 1, 8),
('bx_timeline_post_add_public', 'photo', 2147483647, 1, 9),
('bx_timeline_post_add_public', 'video', 2147483647, 1, 10),
('bx_timeline_post_add_public', 'tlb_do_submit', 2147483647, 1, 11),
('bx_timeline_post_add_profile', 'type', 2147483647, 1, 0),
('bx_timeline_post_add_profile', 'action', 2147483647, 1, 1),
('bx_timeline_post_add_profile', 'owner_id', 2147483647, 1, 2),
('bx_timeline_post_add_profile', 'text', 2147483647, 1, 3),
('bx_timeline_post_add_profile', 'attachments', 2147483647, 1, 4),
('bx_timeline_post_add_profile', 'object_privacy_view', 2147483647, 1, 5),
('bx_timeline_post_add_profile', 'published', 192, 1, 6),
('bx_timeline_post_add_profile', 'location', 2147483647, 1, 7),
('bx_timeline_post_add_profile', 'link', 2147483647, 1, 8),
('bx_timeline_post_add_profile', 'photo', 2147483647, 1, 9),
('bx_timeline_post_add_profile', 'video', 2147483647, 1, 10),
('bx_timeline_post_add_profile', 'tlb_do_submit', 2147483647, 1, 11),
('bx_timeline_post_edit', 'type', 2147483647, 1, 1),
('bx_timeline_post_edit', 'action', 2147483647, 1, 2),
('bx_timeline_post_edit', 'owner_id', 2147483647, 1, 3),
('bx_timeline_post_edit', 'text', 2147483647, 1, 4),
('bx_timeline_post_edit', 'attachments', 2147483647, 1, 5),
('bx_timeline_post_edit', 'published', 192, 1, 6),
('bx_timeline_post_edit', 'location', 2147483647, 1, 7),
('bx_timeline_post_edit', 'link', 2147483647, 1, 8),
('bx_timeline_post_edit', 'photo', 2147483647, 1, 9),
('bx_timeline_post_edit', 'video', 2147483647, 1, 10),
('bx_timeline_post_edit', 'controls', 2147483647, 1, 11),
('bx_timeline_post_edit', 'tlb_do_submit', 2147483647, 1, 12),
('bx_timeline_post_edit', 'tlb_do_cancel', 2147483647, 1, 13);
-- Forms -> Attach link
INSERT INTO `sys_objects_form` (`object`, `module`, `title`, `action`, `form_attrs`, `submit_name`, `table`, `key`, `uri`, `uri_title`, `params`, `deletable`, `active`, `override_class_name`, `override_class_file`) VALUES
('bx_timeline_attach_link', @sName, '_bx_timeline_form_attach_link', '', '', 'do_submit', 'bx_timeline_links', 'id', '', '', '', 0, 1, '', '');
INSERT INTO `sys_form_displays` (`display_name`, `module`, `object`, `title`, `view_mode`) VALUES
('bx_timeline_attach_link_add', @sName, 'bx_timeline_attach_link', '_bx_timeline_form_attach_link_display_add', 0);
INSERT INTO `sys_form_inputs` (`object`, `module`, `name`, `value`, `values`, `checked`, `type`, `caption_system`, `caption`, `info`, `required`, `collapsed`, `html`, `attrs`, `attrs_tr`, `attrs_wrapper`, `checker_func`, `checker_params`, `checker_error`, `db_pass`, `db_params`, `editable`, `deletable`) VALUES
('bx_timeline_attach_link', @sName, 'event_id', '0', '', 0, 'hidden', '_bx_timeline_form_attach_link_input_sys_event_id', '', '', 0, 0, 0, '', '', '', '', '', '', '', '', 0, 0),
('bx_timeline_attach_link', @sName, 'url', '', '', 0, 'text', '_bx_timeline_form_attach_link_input_sys_url', '_bx_timeline_form_attach_link_input_url', '', 0, 0, 0, '', '', '', 'Preg', 'a:1:{s:4:"preg";s:0:"";}', '_bx_timeline_form_attach_link_input_url_err', '', '', 0, 0),
('bx_timeline_attach_link', @sName, 'controls', '', 'do_submit,do_cancel', 0, 'input_set', '', '', '', 0, 0, 0, '', '', '', '', '', '', '', '', 0, 0),
('bx_timeline_attach_link', @sName, 'do_submit', '_bx_timeline_form_attach_link_input_do_submit', '', 0, 'submit', '_bx_timeline_form_attach_link_input_sys_do_submit', '', '', 0, 0, 0, '', '', '', '', '', '', '', '', 0, 0),
('bx_timeline_attach_link', @sName, 'do_cancel', '_bx_timeline_form_attach_link_input_do_cancel', '', 0, 'button', '_bx_timeline_form_attach_link_input_do_cancel', '', '', 0, 0, 0, 'a:2:{s:7:"onclick";s:45:"$(''.bx-popup-applied:visible'').dolPopupHide()";s:5:"class";s:22:"bx-def-margin-sec-left";}', '', '', '', '', '', '', '', 0, 0);
INSERT INTO `sys_form_display_inputs` (`display_name`, `input_name`, `visible_for_levels`, `active`, `order`) VALUES
('bx_timeline_attach_link_add', 'event_id', 2147483647, 1, 1),
('bx_timeline_attach_link_add', 'url', 2147483647, 1, 2),
('bx_timeline_attach_link_add', 'controls', 2147483647, 1, 3),
('bx_timeline_attach_link_add', 'do_submit', 2147483647, 1, 4),
('bx_timeline_attach_link_add', 'do_cancel', 2147483647, 1, 5);
-- COMMENTS
INSERT INTO `sys_objects_cmts` (`Name`, `Module`, `Table`, `CharsPostMin`, `CharsPostMax`, `CharsDisplayMax`, `Html`, `PerView`, `PerViewReplies`, `BrowseType`, `IsBrowseSwitch`, `PostFormPosition`, `NumberOfLevels`, `IsDisplaySwitch`, `IsRatable`, `ViewingThreshold`, `IsOn`, `RootStylePrefix`, `BaseUrl`, `ObjectVote`, `TriggerTable`, `TriggerFieldId`, `TriggerFieldAuthor`, `TriggerFieldTitle`, `TriggerFieldComments`, `ClassName`, `ClassFile`) VALUES
('bx_timeline', 'bx_timeline', 'bx_timeline_comments', 1, 5000, 1000, 3, 5, 3, 'tail', 1, 'bottom', 1, 1, 1, -3, 1, 'cmt', 'page.php?i=item&id={object_id}', '', 'bx_timeline_events', 'id', 'object_id', 'title', 'comments', '', '');
-- VIEWS
INSERT INTO `sys_objects_view` (`name`, `table_track`, `period`, `is_on`, `trigger_table`, `trigger_field_id`, `trigger_field_author`, `trigger_field_count`, `class_name`, `class_file`) VALUES
('bx_timeline', 'bx_timeline_views_track', '86400', '1', 'bx_timeline_events', 'id', 'object_id', 'views', '', '');
-- VOTES
INSERT INTO `sys_objects_vote`(`Name`, `TableMain`, `TableTrack`, `PostTimeout`, `MinValue`, `MaxValue`, `IsUndo`, `IsOn`, `TriggerTable`, `TriggerFieldId`, `TriggerFieldAuthor`, `TriggerFieldRate`, `TriggerFieldRateCount`, `ClassName`, `ClassFile`) VALUES
('bx_timeline', 'bx_timeline_votes', 'bx_timeline_votes_track', '604800', '1', '1', '0', '1', 'bx_timeline_events', 'id', 'object_id', 'rate', 'votes', 'BxTimelineVoteLikes', 'modules/boonex/timeline/classes/BxTimelineVoteLikes.php'),
('bx_timeline_reactions', 'bx_timeline_reactions', 'bx_timeline_reactions_track', '604800', '1', '1', '1', '1', 'bx_timeline_events', 'id', 'object_id', 'rrate', 'rvotes', 'BxTemplVoteReactions', '');
-- SCORES
INSERT INTO `sys_objects_score` (`name`, `module`, `table_main`, `table_track`, `post_timeout`, `is_on`, `trigger_table`, `trigger_field_id`, `trigger_field_author`, `trigger_field_score`, `trigger_field_cup`, `trigger_field_cdown`, `class_name`, `class_file`) VALUES
('bx_timeline', 'bx_timeline', 'bx_timeline_scores', 'bx_timeline_scores_track', '604800', '0', 'bx_timeline_events', 'id', 'object_id', 'score', 'sc_up', 'sc_down', '', '');
-- REPORTS
INSERT INTO `sys_objects_report` (`name`, `module`, `table_main`, `table_track`, `is_on`, `base_url`, `trigger_table`, `trigger_field_id`, `trigger_field_author`, `trigger_field_count`, `class_name`, `class_file`) VALUES
('bx_timeline', 'bx_timeline', 'bx_timeline_reports', 'bx_timeline_reports_track', '1', 'page.php?i=item&id={object_id}', 'bx_timeline_events', 'id', 'owner_id', 'reports', 'BxTimelineReport', 'modules/boonex/timeline/classes/BxTimelineReport.php');
-- CONTENT INFO
INSERT INTO `sys_objects_content_info` (`name`, `title`, `alert_unit`, `alert_action_add`, `alert_action_update`, `alert_action_delete`, `class_name`, `class_file`) VALUES
('bx_timeline', '_bx_timeline', 'bx_timeline', 'post_common', '', 'delete', '', ''),
('bx_timeline_cmts', '_bx_timeline_cmts', 'bx_timeline', 'commentPost', 'commentUpdated', 'commentRemoved', 'BxDolContentInfoCmts', '');
-- STUDIO PAGE & WIDGET
INSERT INTO `sys_std_pages`(`index`, `name`, `header`, `caption`, `icon`) VALUES
(3, 'bx_timeline', '_bx_timeline', '_bx_timeline', 'bx_timeline@modules/boonex/timeline/|std-icon.svg');
SET @iPageId = LAST_INSERT_ID();
SET @iParentPageId = (SELECT `id` FROM `sys_std_pages` WHERE `name` = 'home');
SET @iParentPageOrder = (SELECT MAX(`order`) FROM `sys_std_pages_widgets` WHERE `page_id` = @iParentPageId);
INSERT INTO `sys_std_widgets` (`page_id`, `module`, `type`, `url`, `click`, `icon`, `caption`, `cnt_notices`, `cnt_actions`) VALUES
(@iPageId, 'bx_timeline', 'extensions', '{url_studio}module.php?name=bx_timeline', '', 'bx_timeline@modules/boonex/timeline/|std-icon.svg', '_bx_timeline', '', 'a:4:{s:6:"module";s:6:"system";s:6:"method";s:11:"get_actions";s:6:"params";a:0:{}s:5:"class";s:18:"TemplStudioModules";}');
INSERT INTO `sys_std_pages_widgets` (`page_id`, `widget_id`, `order`) VALUES
(@iParentPageId, LAST_INSERT_ID(), IF(ISNULL(@iParentPageOrder), 1, @iParentPageOrder + 1));
| {
"content_hash": "af5f50a5e5483f75b39918eae3f4ccfa",
"timestamp": "",
"source": "github",
"line_count": 531,
"max_line_length": 474,
"avg_line_length": 57.36158192090395,
"alnum_prop": 0.6389572868446108,
"repo_name": "boonex/trident",
"id": "6679ed316999d3a693b6c5943fca522c7c370105",
"size": "30459",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/boonex/timeline/install/sql/install.sql",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1763"
},
{
"name": "CSS",
"bytes": "1481231"
},
{
"name": "HTML",
"bytes": "690596"
},
{
"name": "JavaScript",
"bytes": "4916309"
},
{
"name": "PHP",
"bytes": "28451148"
},
{
"name": "Shell",
"bytes": "1265"
}
],
"symlink_target": ""
} |
package edu.isi.karma.kr2rml.template;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import edu.isi.karma.kr2rml.formatter.KR2RMLColumnNameFormatter;
import edu.isi.karma.kr2rml.formatter.KR2RMLColumnNameFormatterFactory;
import edu.isi.karma.rep.HNode;
import edu.isi.karma.rep.RepFactory;
import edu.isi.karma.rep.metadata.WorksheetProperties.SourceTypes;
public class TemplateTermSet {
private final List<TemplateTerm> termSet;
public TemplateTermSet() {
termSet = new LinkedList<TemplateTerm>();
}
public void addTemplateTermToSet(TemplateTerm term) {
this.termSet.add(term);
}
public List<TemplateTerm> getAllTerms() {
return this.termSet;
}
public List<ColumnTemplateTerm> getAllColumnNameTermElements() {
List<ColumnTemplateTerm> cnList = new ArrayList<ColumnTemplateTerm>();
for (TemplateTerm term:termSet) {
if (term instanceof ColumnTemplateTerm) {
cnList.add((ColumnTemplateTerm)term);
}
}
return cnList;
}
public TemplateTermSet clear() {
termSet.clear();
return this;
}
@Override
public String toString() {
StringBuilder str = new StringBuilder();
for (TemplateTerm term:termSet) {
if (term instanceof StringTemplateTerm)
str.append("<" + term.getTemplateTermValue() + ">");
else if (term instanceof ColumnTemplateTerm)
str.append("<ColumnHNodeId:" + term.getTemplateTermValue() + ">");
}
return str.toString();
}
public boolean isEmpty() {
return termSet.size() == 0;
}
public String getR2rmlTemplateString(RepFactory factory) {
//TODO fix this
return getR2rmlTemplateString(factory, KR2RMLColumnNameFormatterFactory.getFormatter(SourceTypes.CSV));
}
public String getR2rmlTemplateString(RepFactory factory, KR2RMLColumnNameFormatter formatter) {
StringBuilder str = new StringBuilder();
for (TemplateTerm term:termSet) {
if (term instanceof StringTemplateTerm) {
str.append(term.getTemplateTermValue());
} else if (term instanceof ColumnTemplateTerm) {
HNode hNode = factory.getHNode(term.getTemplateTermValue());
if (hNode != null) {
String colNameStr = "";
try {
JSONArray colNameArr = hNode.getJSONArrayRepresentation(factory);
if (colNameArr.length() == 1) {
colNameStr = (String)
(((JSONObject)colNameArr.get(0)).get("columnName"));
} else {
JSONArray colNames = new JSONArray();
for (int i=0; i<colNameArr.length();i++) {
colNames.put((String)
(((JSONObject)colNameArr.get(i)).get("columnName")));
}
colNameStr = colNames.toString();
}
str.append("{" + formatter.getFormattedColumnName(colNameStr) + "}");
} catch (JSONException e) {
continue;
}
}
else {
str.append("{" + formatter.getFormattedColumnName(term.getTemplateTermValue()) + "}");
}
}
}
return str.toString();
}
public String getColumnNameR2RMLRepresentation(RepFactory factory)
{
return getColumnNameR2RMLRepresentation(factory, KR2RMLColumnNameFormatterFactory.getFormatter(SourceTypes.CSV));
}
public String getColumnNameR2RMLRepresentation(RepFactory factory, KR2RMLColumnNameFormatter formatter) {
StringBuilder str = new StringBuilder();
for (TemplateTerm term:termSet) {
if (term instanceof StringTemplateTerm) {
str.append(term.getTemplateTermValue());
} else if (term instanceof ColumnTemplateTerm) {
HNode hNode = factory.getHNode(term.getTemplateTermValue());
if (hNode != null) {
String colNameStr = "";
try {
JSONArray colNameArr = hNode.getJSONArrayRepresentation(factory);
if (colNameArr.length() == 1) {
colNameStr = (String)
(((JSONObject)colNameArr.get(0)).get("columnName"));
} else {
JSONArray colNames = new JSONArray();
for (int i=0; i<colNameArr.length();i++) {
colNames.put((String)
(((JSONObject)colNameArr.get(i)).get("columnName")));
}
colNameStr = colNames.toString();
}
str.append(formatter.getFormattedColumnName(colNameStr));
} catch (JSONException e) {
continue;
}
}
else {
str.append(formatter.getFormattedColumnName(term.getTemplateTermValue()));
}
}
}
return str.toString();
}
public boolean isSingleUriString() {
if (termSet.size() == 1 && termSet.get(0) instanceof StringTemplateTerm)
return ((StringTemplateTerm)termSet.get(0)).hasFullUri();
return false;
}
public boolean isSingleColumnTerm() {
if (termSet.size() == 1 && termSet.get(0) instanceof ColumnTemplateTerm)
return true;
return false;
}
} | {
"content_hash": "216983052f08dbe3a57ac71081cf1790",
"timestamp": "",
"source": "github",
"line_count": 156,
"max_line_length": 115,
"avg_line_length": 30.121794871794872,
"alnum_prop": 0.6967439880825708,
"repo_name": "tushart91/study-usc",
"id": "0d5a976ac6178ee25490ee7a6abf31bd25f3b642",
"size": "5761",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "Information Integration/Homework/HW8/Web-Karma-master/karma-common/src/main/java/edu/isi/karma/kr2rml/template/TemplateTermSet.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "175970"
},
{
"name": "HTML",
"bytes": "4552572"
},
{
"name": "Java",
"bytes": "4721453"
},
{
"name": "JavaScript",
"bytes": "933366"
},
{
"name": "Makefile",
"bytes": "575"
},
{
"name": "Python",
"bytes": "1094563"
},
{
"name": "TeX",
"bytes": "17749"
},
{
"name": "Web Ontology Language",
"bytes": "6560"
}
],
"symlink_target": ""
} |
<?php
namespace AdminEspindola\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
abstract class Request extends FormRequest
{
//
public function authorize()
{
return true;
}
}
| {
"content_hash": "ee48ef1e1641e7e04659301b290adba5",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 43,
"avg_line_length": 15.214285714285714,
"alnum_prop": 0.6901408450704225,
"repo_name": "Junior-Shyko/admin",
"id": "83cf1e686d8f54361bec2f57df505d3cc88085c6",
"size": "213",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/Http/Requests/Request.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1014"
},
{
"name": "CSS",
"bytes": "59351"
},
{
"name": "HTML",
"bytes": "4115136"
},
{
"name": "JavaScript",
"bytes": "2340956"
},
{
"name": "PHP",
"bytes": "422291"
}
],
"symlink_target": ""
} |
/* Written by Paul Rubin, phr@ocf.berkeley.edu
and David MacKenzie, djm@gnu.ai.mit.edu. */
#include <config.h>
#include <stdio.h>
#include <getopt.h>
#include <sys/types.h>
/* Get mbstate_t, mbrtowc(), wcwidth(). */
#if HAVE_WCHAR_H
# include <wchar.h>
#endif
/* Get iswprint(), iswspace(). */
#if HAVE_WCTYPE_H
# include <wctype.h>
#endif
#if !defined iswprint && !HAVE_ISWPRINT
# define iswprint(wc) 1
#endif
#if !defined iswspace && !HAVE_ISWSPACE
# define iswspace(wc) \
((wc) == (unsigned char) (wc) && ISSPACE ((unsigned char) (wc)))
#endif
/* Include this after wctype.h so that we `#undef' ISPRINT
(from Solaris's euc.h, from widec.h, from wctype.h) before
redefining and using it. */
#include "system.h"
#include "closeout.h"
#include "error.h"
#include "inttostr.h"
#include "safe-read.h"
/* Some systems, like BeOS, have multibyte encodings but lack mbstate_t. */
#if HAVE_MBRTOWC && defined mbstate_t
# define mbrtowc(pwc, s, n, ps) (mbrtowc) (pwc, s, n, 0)
#endif
#ifndef HAVE_DECL_WCWIDTH
"this configure-time declaration test was not run"
#endif
#if !HAVE_DECL_WCWIDTH
extern int wcwidth ();
#endif
/* If wcwidth() doesn't exist, assume all printable characters have
width 1. */
#if !defined wcwidth && !HAVE_WCWIDTH
# define wcwidth(wc) ((wc) == 0 ? 0 : iswprint (wc) ? 1 : -1)
#endif
/* The official name of this program (e.g., no `g' prefix). */
#define PROGRAM_NAME "wc"
#define AUTHORS N_ ("Paul Rubin and David MacKenzie")
/* Size of atomic reads. */
#define BUFFER_SIZE (16 * 1024)
/* The name this program was run with. */
char *program_name;
/* Cumulative number of lines, words, chars and bytes in all files so far.
max_line_length is the maximum over all files processed so far. */
static uintmax_t total_lines;
static uintmax_t total_words;
static uintmax_t total_chars;
static uintmax_t total_bytes;
static uintmax_t max_line_length;
/* Which counts to print. */
static int print_lines, print_words, print_chars, print_bytes;
static int print_linelength;
/* Nonzero if we have ever read the standard input. */
static int have_read_stdin;
/* The error code to return to the system. */
static int exit_status;
/* If nonzero, do not line up columns but instead separate numbers by
a single space as specified in Single Unix Specification and POSIX. */
static int posixly_correct;
static struct option const longopts[] =
{
{"bytes", no_argument, NULL, 'c'},
{"chars", no_argument, NULL, 'm'},
{"lines", no_argument, NULL, 'l'},
{"words", no_argument, NULL, 'w'},
{"max-line-length", no_argument, NULL, 'L'},
{GETOPT_HELP_OPTION_DECL},
{GETOPT_VERSION_OPTION_DECL},
{NULL, 0, NULL, 0}
};
void
usage (int status)
{
if (status != 0)
fprintf (stderr, _("Try `%s --help' for more information.\n"),
program_name);
else
{
printf (_("\
Usage: %s [OPTION]... [FILE]...\n\
"),
program_name);
fputs (_("\
Print byte, word, and newline counts for each FILE, and a total line if\n\
more than one FILE is specified. With no FILE, or when FILE is -,\n\
read standard input.\n\
-c, --bytes print the byte counts\n\
-m, --chars print the character counts\n\
-l, --lines print the newline counts\n\
"), stdout);
fputs (_("\
-L, --max-line-length print the length of the longest line\n\
-w, --words print the word counts\n\
"), stdout);
fputs (HELP_OPTION_DESCRIPTION, stdout);
fputs (VERSION_OPTION_DESCRIPTION, stdout);
printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
}
exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
}
static void
write_counts (uintmax_t lines,
uintmax_t words,
uintmax_t chars,
uintmax_t bytes,
uintmax_t linelength,
const char *file)
{
char buf[INT_BUFSIZE_BOUND (uintmax_t)];
char const *space = "";
char const *format_int = (posixly_correct ? "%s" : "%7s");
char const *format_sp_int = (posixly_correct ? "%s%s" : "%s%7s");
if (print_lines)
{
printf (format_int, umaxtostr (lines, buf));
space = " ";
}
if (print_words)
{
printf (format_sp_int, space, umaxtostr (words, buf));
space = " ";
}
if (print_chars)
{
printf (format_sp_int, space, umaxtostr (chars, buf));
space = " ";
}
if (print_bytes)
{
printf (format_sp_int, space, umaxtostr (bytes, buf));
space = " ";
}
if (print_linelength)
{
printf (format_sp_int, space, umaxtostr (linelength, buf));
}
if (*file)
printf (" %s", file);
putchar ('\n');
}
static void
wc (int fd, const char *file)
{
char buf[BUFFER_SIZE + 1];
size_t bytes_read;
uintmax_t lines, words, chars, bytes, linelength;
int count_bytes, count_chars, count_complicated;
lines = words = chars = bytes = linelength = 0;
/* If in the current locale, chars are equivalent to bytes, we prefer
counting bytes, because that's easier. */
#if HAVE_MBRTOWC && (MB_LEN_MAX > 1)
if (MB_CUR_MAX > 1)
{
count_bytes = print_bytes;
count_chars = print_chars;
}
else
#endif
{
count_bytes = print_bytes + print_chars;
count_chars = 0;
}
count_complicated = print_words + print_linelength;
/* We need binary input, since `wc' relies on `lseek' and byte counts. */
SET_BINARY (fd);
/* When counting only bytes, save some line- and word-counting
overhead. If FD is a `regular' Unix file, using lseek is enough
to get its `size' in bytes. Otherwise, read blocks of BUFFER_SIZE
bytes at a time until EOF. Note that the `size' (number of bytes)
that wc reports is smaller than stats.st_size when the file is not
positioned at its beginning. That's why the lseek calls below are
necessary. For example the command
`(dd ibs=99k skip=1 count=0; ./wc -c) < /etc/group'
should make wc report `0' bytes. */
if (count_bytes && !count_chars && !print_lines && !count_complicated)
{
off_t current_pos, end_pos;
struct stat stats;
if (fstat (fd, &stats) == 0 && S_ISREG (stats.st_mode)
&& (current_pos = lseek (fd, (off_t) 0, SEEK_CUR)) != -1
&& (end_pos = lseek (fd, (off_t) 0, SEEK_END)) != -1)
{
off_t diff;
/* Be careful here. The current position may actually be
beyond the end of the file. As in the example above. */
bytes = (diff = end_pos - current_pos) < 0 ? 0 : diff;
}
else
{
while ((bytes_read = safe_read (fd, buf, BUFFER_SIZE)) > 0)
{
if (bytes_read == SAFE_READ_ERROR)
{
error (0, errno, "%s", file);
exit_status = 1;
break;
}
bytes += bytes_read;
}
}
}
else if (!count_chars && !count_complicated)
{
/* Use a separate loop when counting only lines or lines and bytes --
but not chars or words. */
while ((bytes_read = safe_read (fd, buf, BUFFER_SIZE)) > 0)
{
register char *p = buf;
if (bytes_read == SAFE_READ_ERROR)
{
error (0, errno, "%s", file);
exit_status = 1;
break;
}
while ((p = memchr (p, '\n', (buf + bytes_read) - p)))
{
++p;
++lines;
}
bytes += bytes_read;
}
}
#if HAVE_MBRTOWC && (MB_LEN_MAX > 1)
# define SUPPORT_OLD_MBRTOWC 1
else if (MB_CUR_MAX > 1)
{
int in_word = 0;
uintmax_t linepos = 0;
mbstate_t state;
uintmax_t last_error_line = 0;
int last_error_errno = 0;
# if SUPPORT_OLD_MBRTOWC
/* Back-up the state before each multibyte character conversion and
move the last incomplete character of the buffer to the front
of the buffer. This is needed because we don't know whether
the `mbrtowc' function updates the state when it returns -2, -
this is the ISO C 99 and glibc-2.2 behaviour - or not - amended
ANSI C, glibc-2.1 and Solaris 2.7 behaviour. We don't have an
autoconf test for this, yet. */
size_t prev = 0; /* number of bytes carried over from previous round */
# else
const size_t prev = 0;
# endif
memset (&state, 0, sizeof (mbstate_t));
while ((bytes_read = safe_read (fd, buf + prev, BUFFER_SIZE - prev)) > 0)
{
const char *p;
# if SUPPORT_OLD_MBRTOWC
mbstate_t backup_state;
# endif
if (bytes_read == SAFE_READ_ERROR)
{
error (0, errno, "%s", file);
exit_status = 1;
break;
}
bytes += bytes_read;
p = buf;
bytes_read += prev;
do
{
wchar_t wide_char;
size_t n;
# if SUPPORT_OLD_MBRTOWC
backup_state = state;
# endif
n = mbrtowc (&wide_char, p, bytes_read, &state);
if (n == (size_t) -2)
{
# if SUPPORT_OLD_MBRTOWC
state = backup_state;
# endif
break;
}
if (n == (size_t) -1)
{
/* Signal repeated errors only once per line. */
if (!(lines + 1 == last_error_line
&& errno == last_error_errno))
{
char line_number_buf[INT_BUFSIZE_BOUND (uintmax_t)];
last_error_line = lines + 1;
last_error_errno = errno;
error (0, errno, "%s:%s", file,
umaxtostr (last_error_line, line_number_buf));
}
p++;
bytes_read--;
}
else
{
if (n == 0)
{
wide_char = 0;
n = 1;
}
p += n;
bytes_read -= n;
chars++;
switch (wide_char)
{
case '\n':
lines++;
/* Fall through. */
case '\r':
case '\f':
if (linepos > linelength)
linelength = linepos;
linepos = 0;
goto mb_word_separator;
case '\t':
linepos += 8 - (linepos % 8);
goto mb_word_separator;
case ' ':
linepos++;
/* Fall through. */
case '\v':
mb_word_separator:
if (in_word)
{
in_word = 0;
words++;
}
break;
default:
if (iswprint (wide_char))
{
int width = wcwidth (wide_char);
if (width > 0)
linepos += width;
if (iswspace (wide_char))
goto mb_word_separator;
in_word = 1;
}
break;
}
}
}
while (bytes_read > 0);
# if SUPPORT_OLD_MBRTOWC
if (bytes_read > 0)
{
if (bytes_read == BUFFER_SIZE)
{
/* Encountered a very long redundant shift sequence. */
p++;
bytes_read--;
}
memmove (buf, p, bytes_read);
}
prev = bytes_read;
# endif
}
if (linepos > linelength)
linelength = linepos;
if (in_word)
words++;
}
#endif
else
{
int in_word = 0;
uintmax_t linepos = 0;
while ((bytes_read = safe_read (fd, buf, BUFFER_SIZE)) > 0)
{
const char *p = buf;
if (bytes_read == SAFE_READ_ERROR)
{
error (0, errno, "%s", file);
exit_status = 1;
break;
}
bytes += bytes_read;
do
{
switch (*p++)
{
case '\n':
lines++;
/* Fall through. */
case '\r':
case '\f':
if (linepos > linelength)
linelength = linepos;
linepos = 0;
goto word_separator;
case '\t':
linepos += 8 - (linepos % 8);
goto word_separator;
case ' ':
linepos++;
/* Fall through. */
case '\v':
word_separator:
if (in_word)
{
in_word = 0;
words++;
}
break;
default:
if (ISPRINT ((unsigned char) p[-1]))
{
linepos++;
if (ISSPACE ((unsigned char) p[-1]))
goto word_separator;
in_word = 1;
}
break;
}
}
while (--bytes_read);
}
if (linepos > linelength)
linelength = linepos;
if (in_word)
words++;
}
if (count_chars < print_chars)
chars = bytes;
write_counts (lines, words, chars, bytes, linelength, file);
total_lines += lines;
total_words += words;
total_chars += chars;
total_bytes += bytes;
if (linelength > max_line_length)
max_line_length = linelength;
}
static void
wc_file (const char *file)
{
if (STREQ (file, "-"))
{
have_read_stdin = 1;
wc (0, file);
}
else
{
int fd = open (file, O_RDONLY);
if (fd == -1)
{
error (0, errno, "%s", file);
exit_status = 1;
return;
}
wc (fd, file);
if (close (fd))
{
error (0, errno, "%s", file);
exit_status = 1;
}
}
}
int
main (int argc, char **argv)
{
int optc;
int nfiles;
program_name = argv[0];
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
atexit (close_stdout);
exit_status = 0;
posixly_correct = (getenv ("POSIXLY_CORRECT") != NULL);
print_lines = print_words = print_chars = print_bytes = print_linelength = 0;
total_lines = total_words = total_chars = total_bytes = max_line_length = 0;
while ((optc = getopt_long (argc, argv, "clLmw", longopts, NULL)) != -1)
switch (optc)
{
case 0:
break;
case 'c':
print_bytes = 1;
break;
case 'm':
print_chars = 1;
break;
case 'l':
print_lines = 1;
break;
case 'w':
print_words = 1;
break;
case 'L':
print_linelength = 1;
break;
case_GETOPT_HELP_CHAR;
case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
default:
usage (EXIT_FAILURE);
}
if (print_lines + print_words + print_chars + print_bytes + print_linelength
== 0)
print_lines = print_words = print_bytes = 1;
nfiles = argc - optind;
if (nfiles == 0)
{
have_read_stdin = 1;
wc (0, "");
}
else
{
for (; optind < argc; ++optind)
wc_file (argv[optind]);
if (nfiles > 1)
write_counts (total_lines, total_words, total_chars, total_bytes,
max_line_length, _("total"));
}
if (have_read_stdin && close (STDIN_FILENO) != 0)
error (EXIT_FAILURE, errno, "-");
exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
}
| {
"content_hash": "1a28609a5db171435d452b643e699a77",
"timestamp": "",
"source": "github",
"line_count": 584,
"max_line_length": 79,
"avg_line_length": 23.43321917808219,
"alnum_prop": 0.5763975155279503,
"repo_name": "amritkrs/Linux-Shell-in-C",
"id": "733d32d85e5a8f36748aa54c34897b3750d6c406",
"size": "14511",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Project/Real_code/gnu/coreutils-5.0/src/wc.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1027060"
},
{
"name": "C++",
"bytes": "792"
},
{
"name": "Makefile",
"bytes": "1011"
},
{
"name": "Roff",
"bytes": "781"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace SolidEdgeCommunity.Reader.Native
{
public class PropertySet : IList<Property>, ICollection<Property>
{
private STATPROPSETSTG _stat;
internal string _name = String.Empty;
private List<Property> _properties = new List<Property>();
internal PropertySet(STATPROPSETSTG stat, Property[] properties)
{
if (properties == null) throw new ArgumentNullException("properties");
_stat = stat;
_properties.AddRange(properties);
}
public Property this[uint propertyId]
{
get
{
return this.Where(x => x.PropertyId.Equals(propertyId)).FirstOrDefault();
}
}
public Property this[string name]
{
get
{
return this[name, StringComparison.Ordinal];
}
}
public Property this[string name, StringComparison comparisonType]
{
get
{
return this.Where(x => x.Name != null).Where(x => x.Name.Equals(name, comparisonType)).FirstOrDefault();
}
}
internal static PropertySet FromIPropertyStorage(IPropertyStorage propertyStorage)
{
if (propertyStorage == null) throw new ArgumentNullException("propertyStorage");
HRESULT hr = HRESULT.E_FAIL;
PropertySet propertySet = null;
STATPROPSETSTG stat;
propertyStorage.Stat(out stat);
IEnumSTATPROPSTG enumerator = null;
List<Property> properties = new List<Property>();
try
{
if (NativeMethods.Succeeded(hr = propertyStorage.Enum(out enumerator)))
{
STATPROPSTG[] sps = new STATPROPSTG[] { default(STATPROPSTG) };
uint fetched = 0;
while ((enumerator.Next(1, sps, out fetched) == HRESULT.S_OK) && (fetched == 1))
{
string name;
PROPVARIANT propvar = default(PROPVARIANT);
try
{
propertyStorage.GetPropertyName(sps[0].propid, out name);
sps[0].lpwstrName = name;
propertyStorage.GetProperty(sps[0].propid, out propvar);
properties.Add(new Property(sps[0], propvar.Value));
}
catch
{
}
finally
{
propvar.Clear();
}
}
}
}
catch
{
}
finally
{
if (enumerator != null)
{
enumerator.FinalRelease();
}
}
Type type = System.Reflection.Assembly.GetExecutingAssembly().GetPropertySetType(stat.fmtid);
if (type == null)
{
// In this case, we did not find a strongly typed property set.
type = typeof(PropertySet);
}
propertySet = PropertySet.InvokeInternalConstructor(type, stat, properties.ToArray());
propertySet.Name = type.GetPropertySetName();
return propertySet;
}
internal static PropertySet InvokeInternalConstructor(Type type, STATPROPSETSTG stat, Property[] properties)
{
Type[] types = new[] { typeof(STATPROPSETSTG), typeof(Property[]) };
ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, types, null);
if (ctor != null)
{
return (PropertySet)ctor.Invoke(new object[] { stat, properties });
}
else
{
throw new System.Reflection.TargetException(String.Format("Unable for find appropriate constructor for type '{0}'", type.FullName));
}
}
internal T GetPropertyValue<T>(PIDDSI propid)
{
return GetPropertyValue<T>((uint)propid);
}
internal T GetPropertyValue<T>(PIDSI propid)
{
return GetPropertyValue<T>((uint)propid);
}
internal T GetPropertyValue<T>(uint propid)
{
return (T)Convert.ChangeType(GetPropertyValue(propid), typeof(T));
}
internal DateTime? GetPropertyValueAsDateTime(PIDSI propid)
{
return GetPropertyValueAsDateTime((uint)propid);
}
internal DateTime? GetPropertyValueAsDateTime(uint propid)
{
DateTime? dt = null;
object value = GetPropertyValue(propid);
if (value is DateTime)
{
dt = (DateTime)value;
}
return dt;
}
internal object GetPropertyValue(uint propid)
{
Property property = _properties.FirstOrDefault(x => x.PropertyId == propid);
if (property != null)
{
return property.Value;
}
return null;
}
public Guid FormatId { get { return _stat.fmtid; } }
public string Name
{
get { return _name; }
internal set { _name = value; }
}
public override string ToString()
{
if (String.IsNullOrWhiteSpace(_name) == false)
{
return _name;
}
return _stat.fmtid.ToString("B");
}
#region System.Collections.Generic.IList
int IList<Property>.IndexOf(Property item)
{
return _properties.IndexOf(item);
}
void IList<Property>.Insert(int index, Property item)
{
throw new NotSupportedException();
}
void IList<Property>.RemoveAt(int index)
{
throw new NotSupportedException();
}
public Property this[int index]
{
get
{
return _properties[index];
}
set
{
throw new NotSupportedException();
}
}
#endregion
#region System.Collections.Generic.ICollection<T>
void ICollection<Property>.Add(Property item)
{
throw new NotSupportedException();
}
void ICollection<Property>.Clear()
{
throw new NotSupportedException();
}
bool ICollection<Property>.Contains(Property item)
{
return _properties.Contains(item);
}
void ICollection<Property>.CopyTo(Property[] array, int arrayIndex)
{
_properties.CopyTo(array, arrayIndex);
}
public int Count
{
get { return _properties.Count; }
}
public bool IsReadOnly
{
get { return true; }
}
bool ICollection<Property>.Remove(Property item)
{
throw new NotSupportedException();
}
#endregion
#region System.Collections.Generic.IEnumerable<T>
public IEnumerator<Property> GetEnumerator()
{
return _properties.GetEnumerator();
}
#endregion
#region System.Collections.IEnumerator
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _properties.GetEnumerator();
}
#endregion
}
[PropertySet(FMTID.UserDefinedProperties, "Custom")]
public class CustomPropertySet : PropertySet
{
internal CustomPropertySet(STATPROPSETSTG stat, Property[] properties)
: base(stat, properties)
{
}
}
[PropertySet(FMTID.DocSummaryInformation, "DocumentSummaryInformation")]
public class DocumentSummaryInformationPropertySet : PropertySet
{
internal DocumentSummaryInformationPropertySet(STATPROPSETSTG stat, Property[] properties)
: base(stat, properties)
{
}
// Remarked out properties are also excluded via the Solid Edge API.
public int ByteCount { get { return GetPropertyValue<int>(PIDDSI.BYTECOUNT); } }
public string Category { get { return GetPropertyValue<string>(PIDDSI.CATEGORY); } }
public string Company { get { return GetPropertyValue<string>(PIDDSI.COMPANY); } }
public int HiddenObjects { get { return GetPropertyValue<int>(PIDDSI.HIDDENCOUNT); } }
public int Lines { get { return GetPropertyValue<int>(PIDDSI.LINECOUNT); } }
public string Manager { get { return GetPropertyValue<string>(PIDDSI.MANAGER); } }
public int MultimediaClips { get { return GetPropertyValue<int>(PIDDSI.MMCLIPCOUNT); } }
//public bool LinksUpToDate { get { return (bool?)GetProperty<bool>(PIDDSI.LINKSDIRTY); } }
public int Notes { get { return GetPropertyValue<int>(PIDDSI.NOTECOUNT); } }
public int Paragraphs { get { return GetPropertyValue<int>(PIDDSI.PARCOUNT); } }
public string PresentationFormat { get { return GetPropertyValue<string>(PIDDSI.PRESFORMAT); } }
//public bool ScaleCrop { get { return GetProperty<bool>(PIDDSI.SCALE); } }
public int Slides { get { return GetPropertyValue<int>(PIDDSI.SLIDECOUNT); } }
}
[PropertySet(FMTID.SummaryInformation, "SummaryInformation")]
public class SummaryInformationPropertySet : PropertySet
{
internal SummaryInformationPropertySet(STATPROPSETSTG stat, Property[] properties)
: base(stat, properties)
{
}
// Remarked out properties are also excluded via the Solid Edge API.
public string ApplicationName { get { return GetPropertyValue<string>(PIDSI.APPNAME); } }
public string Author { get { return GetPropertyValue<string>(PIDSI.AUTHOR); } }
public string Comments { get { return GetPropertyValue<string>(PIDSI.COMMENTS); } }
public DateTime? CreatedDate { get { return GetPropertyValueAsDateTime(PIDSI.CREATE_DTM); } }
public string Keywords { get { return GetPropertyValue<string>(PIDSI.KEYWORDS); } }
public string LastAuthor { get { return GetPropertyValue<string>(PIDSI.LASTAUTHOR); } }
public DateTime? LastPrintDate { get { return GetPropertyValueAsDateTime(PIDSI.LASTPRINTED); } }
public DateTime? LastSavedDate { get { return GetPropertyValueAsDateTime(PIDSI.LASTSAVE_DTM); } }
public int NumberOfPages { get { return GetPropertyValue<int>(PIDSI.PAGECOUNT); } }
public int NumberOfWords { get { return GetPropertyValue<int>(PIDSI.WORDCOUNT); } }
public int NumberOfCharacters { get { return GetPropertyValue<int>(PIDSI.CHARCOUNT); } }
public string RevisionNumber { get { return GetPropertyValue<string>(PIDSI.REVNUMBER); } }
public string Subject { get { return GetPropertyValue<string>(PIDSI.SUBJECT); } }
public string Template { get { return GetPropertyValue<string>(PIDSI.TEMPLATE); } }
//public object Thumbnail { get { return GetProperty<object>(PIDSI.THUMBNAIL); } }
public string Title { get { return GetPropertyValue<string>(PIDSI.TITLE); } }
public DateTime? TotalEditingTime { get { return GetPropertyValueAsDateTime(PIDSI.EDITTIME); } }
public int Security { get { return GetPropertyValue<int>(PIDSI.DOC_SECURITY); } }
}
}
| {
"content_hash": "3481daf2cf84327e61530f751d9a8be0",
"timestamp": "",
"source": "github",
"line_count": 343,
"max_line_length": 148,
"avg_line_length": 34.268221574344025,
"alnum_prop": 0.5702739492938574,
"repo_name": "SolidEdgeCommunity/SolidEdge.Community.Reader",
"id": "76d64fab80bcf2211b52151f995f1a911507f3a2",
"size": "11756",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/SolidEdge.Community.Reader/Native/PropertySet.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "201"
},
{
"name": "C#",
"bytes": "198361"
}
],
"symlink_target": ""
} |
package consulo.gwt.javascript.lang.parsing;
import javax.annotation.Nonnull;
import consulo.javascript.lang.parsing.JavaScriptParser;
import consulo.javascript.lang.parsing.JavaScriptParsingContext;
/**
* @author VISTALL
* @since 28.01.2016
*/
public class GwtJavaScriptParser extends JavaScriptParser
{
@Nonnull
@Override
public JavaScriptParsingContext createParsingContext()
{
return new GwtJavaScriptParsingContext();
}
}
| {
"content_hash": "3fac28975572e17424f196ccf85b3162",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 64,
"avg_line_length": 21,
"alnum_prop": 0.8027210884353742,
"repo_name": "consulo/consulo-google-gwt",
"id": "c328d402b065b82411370c330701204cd2400a9b",
"size": "1036",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gwt-javascript-impl/src/main/java/consulo/gwt/javascript/lang/parsing/GwtJavaScriptParser.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "10351"
},
{
"name": "Java",
"bytes": "455929"
}
],
"symlink_target": ""
} |
package pin
import (
"encoding/json"
"errors"
"fmt"
"sync"
ds "github.com/djbarber/ipfs-hack/Godeps/_workspace/src/github.com/jbenet/go-datastore"
nsds "github.com/djbarber/ipfs-hack/Godeps/_workspace/src/github.com/jbenet/go-datastore/namespace"
context "github.com/djbarber/ipfs-hack/Godeps/_workspace/src/golang.org/x/net/context"
key "github.com/djbarber/ipfs-hack/blocks/key"
"github.com/djbarber/ipfs-hack/blocks/set"
mdag "github.com/djbarber/ipfs-hack/merkledag"
logging "github.com/djbarber/ipfs-hack/vendor/go-log-v1.0.0"
)
var log = logging.Logger("pin")
var recursePinDatastoreKey = ds.NewKey("/local/pins/recursive/keys")
var directPinDatastoreKey = ds.NewKey("/local/pins/direct/keys")
var indirectPinDatastoreKey = ds.NewKey("/local/pins/indirect/keys")
type PinMode int
const (
Recursive PinMode = iota
Direct
Indirect
NotPinned
)
type Pinner interface {
IsPinned(key.Key) bool
Pin(context.Context, *mdag.Node, bool) error
Unpin(context.Context, key.Key, bool) error
Flush() error
GetManual() ManualPinner
DirectKeys() []key.Key
IndirectKeys() map[key.Key]int
RecursiveKeys() []key.Key
}
// ManualPinner is for manually editing the pin structure
// Use with care! If used improperly, garbage collection
// may not be successful
type ManualPinner interface {
PinWithMode(key.Key, PinMode)
RemovePinWithMode(key.Key, PinMode)
Pinner
}
// pinner implements the Pinner interface
type pinner struct {
lock sync.RWMutex
recursePin set.BlockSet
directPin set.BlockSet
indirPin *indirectPin
dserv mdag.DAGService
dstore ds.ThreadSafeDatastore
}
// NewPinner creates a new pinner using the given datastore as a backend
func NewPinner(dstore ds.ThreadSafeDatastore, serv mdag.DAGService) Pinner {
// Load set from given datastore...
rcds := nsds.Wrap(dstore, recursePinDatastoreKey)
rcset := set.NewDBWrapperSet(rcds, set.NewSimpleBlockSet())
dirds := nsds.Wrap(dstore, directPinDatastoreKey)
dirset := set.NewDBWrapperSet(dirds, set.NewSimpleBlockSet())
nsdstore := nsds.Wrap(dstore, indirectPinDatastoreKey)
return &pinner{
recursePin: rcset,
directPin: dirset,
indirPin: NewIndirectPin(nsdstore),
dserv: serv,
dstore: dstore,
}
}
// Pin the given node, optionally recursive
func (p *pinner) Pin(ctx context.Context, node *mdag.Node, recurse bool) error {
p.lock.Lock()
defer p.lock.Unlock()
k, err := node.Key()
if err != nil {
return err
}
if recurse {
if p.recursePin.HasKey(k) {
return nil
}
if p.directPin.HasKey(k) {
p.directPin.RemoveBlock(k)
}
err := p.pinLinks(ctx, node)
if err != nil {
return err
}
p.recursePin.AddBlock(k)
} else {
if _, err := p.dserv.Get(ctx, k); err != nil {
return err
}
if p.recursePin.HasKey(k) {
return fmt.Errorf("%s already pinned recursively", k.B58String())
}
p.directPin.AddBlock(k)
}
return nil
}
// Unpin a given key
func (p *pinner) Unpin(ctx context.Context, k key.Key, recursive bool) error {
p.lock.Lock()
defer p.lock.Unlock()
if p.recursePin.HasKey(k) {
if recursive {
p.recursePin.RemoveBlock(k)
node, err := p.dserv.Get(ctx, k)
if err != nil {
return err
}
return p.unpinLinks(ctx, node)
} else {
return fmt.Errorf("%s is pinned recursively", k)
}
} else if p.directPin.HasKey(k) {
p.directPin.RemoveBlock(k)
return nil
} else if p.indirPin.HasKey(k) {
return fmt.Errorf("%s is pinned indirectly. indirect pins cannot be removed directly", k)
} else {
return fmt.Errorf("%s is not pinned", k)
}
}
func (p *pinner) unpinLinks(ctx context.Context, node *mdag.Node) error {
for _, l := range node.Links {
node, err := l.GetNode(ctx, p.dserv)
if err != nil {
return err
}
k, err := node.Key()
if err != nil {
return err
}
p.indirPin.Decrement(k)
err = p.unpinLinks(ctx, node)
if err != nil {
return err
}
}
return nil
}
func (p *pinner) pinIndirectRecurse(ctx context.Context, node *mdag.Node) error {
k, err := node.Key()
if err != nil {
return err
}
p.indirPin.Increment(k)
return p.pinLinks(ctx, node)
}
func (p *pinner) pinLinks(ctx context.Context, node *mdag.Node) error {
for _, ng := range p.dserv.GetDAG(ctx, node) {
subnode, err := ng.Get(ctx)
if err != nil {
// TODO: Maybe just log and continue?
return err
}
err = p.pinIndirectRecurse(ctx, subnode)
if err != nil {
return err
}
}
return nil
}
// IsPinned returns whether or not the given key is pinned
func (p *pinner) IsPinned(key key.Key) bool {
p.lock.RLock()
defer p.lock.RUnlock()
return p.recursePin.HasKey(key) ||
p.directPin.HasKey(key) ||
p.indirPin.HasKey(key)
}
func (p *pinner) RemovePinWithMode(key key.Key, mode PinMode) {
p.lock.Lock()
defer p.lock.Unlock()
switch mode {
case Direct:
p.directPin.RemoveBlock(key)
case Indirect:
p.indirPin.Decrement(key)
case Recursive:
p.recursePin.RemoveBlock(key)
default:
// programmer error, panic OK
panic("unrecognized pin type")
}
}
// LoadPinner loads a pinner and its keysets from the given datastore
func LoadPinner(d ds.ThreadSafeDatastore, dserv mdag.DAGService) (Pinner, error) {
p := new(pinner)
{ // load recursive set
var recurseKeys []key.Key
if err := loadSet(d, recursePinDatastoreKey, &recurseKeys); err != nil {
return nil, err
}
p.recursePin = set.SimpleSetFromKeys(recurseKeys)
}
{ // load direct set
var directKeys []key.Key
if err := loadSet(d, directPinDatastoreKey, &directKeys); err != nil {
return nil, err
}
p.directPin = set.SimpleSetFromKeys(directKeys)
}
{ // load indirect set
var err error
p.indirPin, err = loadIndirPin(d, indirectPinDatastoreKey)
if err != nil {
return nil, err
}
}
// assign services
p.dserv = dserv
p.dstore = d
return p, nil
}
// DirectKeys returns a slice containing the directly pinned keys
func (p *pinner) DirectKeys() []key.Key {
return p.directPin.GetKeys()
}
// IndirectKeys returns a slice containing the indirectly pinned keys
func (p *pinner) IndirectKeys() map[key.Key]int {
return p.indirPin.GetRefs()
}
// RecursiveKeys returns a slice containing the recursively pinned keys
func (p *pinner) RecursiveKeys() []key.Key {
return p.recursePin.GetKeys()
}
// Flush encodes and writes pinner keysets to the datastore
func (p *pinner) Flush() error {
p.lock.Lock()
defer p.lock.Unlock()
err := storeSet(p.dstore, directPinDatastoreKey, p.directPin.GetKeys())
if err != nil {
return err
}
err = storeSet(p.dstore, recursePinDatastoreKey, p.recursePin.GetKeys())
if err != nil {
return err
}
err = storeIndirPin(p.dstore, indirectPinDatastoreKey, p.indirPin)
if err != nil {
return err
}
return nil
}
// helpers to marshal / unmarshal a pin set
func storeSet(d ds.Datastore, k ds.Key, val interface{}) error {
buf, err := json.Marshal(val)
if err != nil {
return err
}
return d.Put(k, buf)
}
func loadSet(d ds.Datastore, k ds.Key, val interface{}) error {
buf, err := d.Get(k)
if err != nil {
return err
}
bf, ok := buf.([]byte)
if !ok {
return errors.New("invalid pin set value in datastore")
}
return json.Unmarshal(bf, val)
}
// PinWithMode is a method on ManualPinners, allowing the user to have fine
// grained control over pin counts
func (p *pinner) PinWithMode(k key.Key, mode PinMode) {
p.lock.Lock()
defer p.lock.Unlock()
switch mode {
case Recursive:
p.recursePin.AddBlock(k)
case Direct:
p.directPin.AddBlock(k)
case Indirect:
p.indirPin.Increment(k)
}
}
func (p *pinner) GetManual() ManualPinner {
return p
}
| {
"content_hash": "c839a38673296f10e9d90dc6bdcf3db2",
"timestamp": "",
"source": "github",
"line_count": 330,
"max_line_length": 100,
"avg_line_length": 22.90909090909091,
"alnum_prop": 0.6964285714285714,
"repo_name": "djbarber/ipfs-hack",
"id": "3296cc7e95078cfaf7baba6b4a88f15f3596a7b4",
"size": "7679",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pin/pin.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "1480160"
},
{
"name": "Makefile",
"bytes": "8865"
},
{
"name": "Protocol Buffer",
"bytes": "5788"
},
{
"name": "PureBasic",
"bytes": "29"
},
{
"name": "Python",
"bytes": "788"
},
{
"name": "Shell",
"bytes": "117870"
}
],
"symlink_target": ""
} |
[](https://travis-ci.org/sstur/nodeftpd)
- [Introduction](#introduction)
- [Usage](#usage)
- [FtpServer options:](#ftpserver-options)
- [host (string) - IP Address](#host-string---ip-address)
- [options (object) - Configuration](#options-object---configuration)
- [Path Configurations](#path-configurations)
- [File/handling Configurations](#filehandling-configurations)
- [Connectivity settings](#connectivity-settings)
- [File System Abstraction](#filesystem-abstraction)
## Introduction
This is a simple but very configurable FTP server. Notable features include:
* Abstracts out the `fs` module, so you can use any implementation,
even on a per-user basis. This makes it possible for each user to have
his/her own virtual file system, isolated from that of the system or other
users.
* Provides hooks for handling authentication, content modification, etc.
* Supports TLS with explicit AUTH.
## Installation
npm install ftpd
## Usage
See example code in `test.js`
### FtpServer options:
#### host (string) - IP Address
host is a string representation of the IP address clients use to connect to the FTP server. It's imperative that this actually reflects the remote IP the clients use to access the server, as this IP will be used in the establishment of PASV data connections. If this IP is not the one clients use to connect, you will see some strange behavior from the client side (hangs).
#### options (object) - Configuration
See `test.js` for a simple example. `FtpServer` accepts the following options:
##### Path Configurations
Both these need to be set - there are no defaults.
- `getInitialCwd`: Gets the initial working directory for the user. Called after user is authenticated.
This path is relative to the root directory. The user may escape their initial cwd.
- **Pattern**: `function(username, [callback(err, path)])`
- **Arguments**:
- username (string): the username to get CWD for
- callback (function, optional):
- **Examples**:
- Simplest usage, no callback, just return:
```js
getInitialCwd: function(connection) {
return "/" + connection.username;
}
```
- Usage with callback:
```js
getInitialCwd: function(connection, callback) {
var userDir = '/' + connection.username;
fs.exists(userDir, function(exists) {
if (exists) {
callback(null, userDir);
} else {
fs.mkDir(userDir, function(err) {
callback(err, userDir);
});
}
});
}
// If the directory exists, callback immediately with that directory
// If not, create the directory and callback possible error + directory
```
- Typical cases where you would want/need the callback involve retrieving configurations from external datasources and suchlike.
- `getRoot`: Gets the root directory for the user. This directory has the path '/' from the point of view of the user.
The user is not able to escape this directory.
- **Pattern**: `function(connection, [callback(err, rootPath)])`
- **Arguments**:
- connection (object): the connection for which to get root
- callback (function, optional):
- **Examples**:
```js
getRoot: function() {
return process.cwd();
}
// The users will now enter at the '/' level, which is the directory passed to getInitialCwd.
```
- Usage with callback:
```js
getRoot: function(connection, callback) {
var rootPath = process.cwd() + '/' + connection.username;
fs.exists(rootPath, function(exists) {
if (exists) {
callback(null, rootPath);
} else {
fs.mkDir(userDir, function(err) {
if (err) {
callback(null, '/'); // default to root
} else {
callback(err, rootPath);
}
});
}
});
}
// If the subdir exists, callback immediately with relative path to that directory
// If not, create the directory, and callback relative path to the directory
// Stupidly, instead of failing, we apparently want 'worst case' scenario to allow relative root.
```
- Typical cases where you would want/need the callback involve retrieving configurations from external datasources and suchlike.
- Additionally, you may want to provide emulation of a path, for instance /users/(username)/ftproot.
##### File/handling Configurations
- `useWriteFile`: _(default: false)_
- If set to `true`, then files which the client uploads are buffered in memory and then written to disk using `writeFile`.
- If `false`, files are written using writeStream.
- `useReadFile`: _(default: false)_
- If set to `true`, then files which the client downloads are slurped using 'readFile'.
- If `false`, files are read using readStream.
- `uploadMaxSlurpSize`: _(default: unlimited)_
- Determines the maximum file size (in bytes) for which uploads are buffered in memory before being written to disk.
- Has an effect only if `useWriteFile` is set to `true`.
- If `uploadMaxSlurpSize` is not set, then there is no limit on buffer size.
- `maxStatsAtOnce`: _(default: 5)_
- The maximum number of concurrent calls to `fs.stat` which will be
made when processing a `LIST` request.
- `filenameSortFunc`: _(default: `localeCompare`)_
- A function which can be used as the argument of an array's `sort` method. Used to sort filenames for directory listings.
See [https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort] for more info.
- `filenameSortMap`: _(default: `function (x) { return x.toUpperCase() }`)_
- A function which is applied to each filename before sorting.
- If set to `false`, filenames are unaltered.
- `dontSortFilenames`: _(default: false)_
- If this is set, then filenames are not sorted in responses to the `LIST` and `NLST` commands.
- `noWildcards`: _(default: false)_
- If set to `true`, then `LIST` and `NLST` treat the characters `?` and `*` as literals instead of as wildcards.
##### Connectivity settings
- `tlsOptions`: _(default: undefined)_
- If this is set, the server will allow explicit TLS authentication.
- Value should be a dictionary which is suitable as the `options` argument of `tls.createServer`.
- `tlsOnly`: _(default: false)_
- If this is set to `true`, and `tlsOptions` is also set, then the server will not allow logins over non-secure connections.
- `allowUnauthorizedTls`: ?? I obviously set this to true when tlsOnly is on -someone needs to update this.
- `pasvPortRangeStart`: _(default: random?)_
- Integer, specifies the lower-bound port (min port) for creating PASV connections
- `pasvPortRangeEnd`: _(default: random?)_
- Integer, specifies the upper-bound port (max port) for creating PASV connections
## Filesystem Abstraction
Filesystem abstraction makes it possible to
create an FTP server which interacts directly with a database rather than the
actual filesystem.
The server raises a `command:pass` event which is given `pass`, `success` and
`failure` arguments. On successful login, `success` should be called with a
username argument. It may also optionally be given a second argument, which
should be an object providing an implementation of the API for Node's `fs`
module.
The following must be implemented:
- `unlink`
- `readdir`
- `mkdir`
- `open`
- `close`
- `rmdir`
- `rename`
- `stat` →
- specific object properties: `{ mode, isDirectory(), size, mtime }`
- if `useWriteFile` option is not set or is false
- `createWriteStream`: _Returns a writable stream, requiring:_
- events: 'open', 'error', 'close'
- functions: 'write'
- if `useWriteFile` option is set to 'true'
- `writeFile`
- if `useReadFile` option is not set or is false
- `createReadStream`: _Returns a readable stream, requiring:_
- events: 'error', 'data', 'end'
- functions: 'destroy'
- if `useReadFile` option is set to 'true'
- `readFile`
`FtpServer` has `listen` and `close` methods which behave as expected. It
emits `close` and `error` events.
| {
"content_hash": "6f690a3f7b89f4a4471e23823c7d5aed",
"timestamp": "",
"source": "github",
"line_count": 205,
"max_line_length": 375,
"avg_line_length": 43.02439024390244,
"alnum_prop": 0.6417233560090703,
"repo_name": "phillipgreenii/nodeftpd",
"id": "af5d1195eda95a82d529fde070ce6b61f0bb79c1",
"size": "8874",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "76168"
}
],
"symlink_target": ""
} |
package goryachev.common.util.platform;
public class CPlatformLinux
extends CPlatformUnix
{
public CPlatformLinux()
{
}
}
| {
"content_hash": "dcfc98b5ffd6dac927422deb5ea740be",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 39,
"avg_line_length": 13.8,
"alnum_prop": 0.717391304347826,
"repo_name": "andy-goryachev/FindFiles",
"id": "163d0f60884b54edac7d054380f064e74bf0949a",
"size": "201",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/goryachev/common/util/platform/CPlatformLinux.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1156766"
}
],
"symlink_target": ""
} |
using MvvmCross.Core.ViewModels;
namespace RatingsSamples.ViewModels
{
public class RatingViewModel : MvxViewModel
{
public RatingViewModel()
{
Rating = 3;
}
private int rating;
private bool isReadOnly;
public int Rating
{
get { return rating; }
set { SetProperty(ref rating, value); }
}
public bool ReadOnly
{
get { return isReadOnly; }
set { SetProperty(ref isReadOnly, value); }
}
}
}
| {
"content_hash": "ce83f49ff6ced462cdfef840de79350d",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 55,
"avg_line_length": 20.48148148148148,
"alnum_prop": 0.5262206148282098,
"repo_name": "Johan-dutoit/MvvmCross.Plugins.Ratings",
"id": "b1ed8bbe33d4f8e6fb8dfcd3bc2ea3817c727b53",
"size": "555",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "RatingsSamples/RatingsSamples/RatingsSamples/ViewModels/RatingViewModel.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "42369"
},
{
"name": "Pascal",
"bytes": "446"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<title>Houzez HTML5 Template</title>
<!--Meta tags-->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="keywords" content="Houzez HTML5 Template">
<meta name="description" content="Houzez HTML5 Template">
<meta name="author" content="Favethemes">
<link rel="apple-touch-icon" sizes="144x144" href="images/favicons/apple-touch-icon.png">
<link rel="icon" type="image/png" href="images/favicons/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="images/favicons/favicon-16x16.png" sizes="16x16">
<link rel="manifest" href="images/favicons/manifest.json">
<link rel="mask-icon" href="images/favicons/safari-pinned-tab.svg" >
<meta name="theme-color" content="#ffffff">
<link href="css/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="css/bootstrap-select.css" rel="stylesheet" type="text/css" />
<link href="css/font-awesome.css" rel="stylesheet" type="text/css" />
<link href="css/owl.carousel.css" rel="stylesheet" type="text/css" />
<link href="css/slick.css" rel="stylesheet" type="text/css" />
<link href="css/slick-theme.css" rel="stylesheet" type="text/css" />
<link href="css/prettyPhoto.css" rel="stylesheet" type="text/css" />
<link href="css/jquery-ui.css" rel="stylesheet" type="text/css" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<button class="btn scrolltop-btn back-top"><i class="fa fa-angle-up"></i></button>
<div class="modal fade" id="pop-login" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<ul class="login-tabs">
<li class="active">Login</li>
<li>Register</li>
</ul>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><i class="fa fa-close"></i></button>
</div>
<div class="modal-body login-block">
<div class="tab-content">
<div class="tab-pane fade in active">
<div class="message">
<p class="error text-danger"><i class="fa fa-close"></i> You are not Logedin</p>
<p class="success text-success"><i class="fa fa-check"></i> You are not Logedin</p>
</div>
<form>
<div class="form-group field-group">
<div class="input-user input-icon">
<input type="text" placeholder="Username">
</div>
<div class="input-pass input-icon">
<input type="password" placeholder="Password">
</div>
</div>
<div class="forget-block clearfix">
<div class="form-group pull-left">
<div class="checkbox">
<label>
<input type="checkbox">
Remember me
</label>
</div>
</div>
<div class="form-group pull-right">
<a href="#" data-toggle="modal" data-dismiss="modal" data-target="#pop-reset-pass">I forgot username and password</a>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block">Login</button>
</form>
<hr>
<a href="#" class="btn btn-social btn-bg-facebook btn-block"><i class="fa fa-facebook"></i> login with facebook</a>
<a href="#" class="btn btn-social btn-bg-linkedin btn-block"><i class="fa fa-linkedin"></i> login with linkedin</a>
<a href="#" class="btn btn-social btn-bg-google-plus btn-block"><i class="fa fa-google-plus"></i> login with Google</a>
</div>
<div class="tab-pane fade">
<form>
<div class="form-group field-group">
<div class="input-user input-icon">
<input type="text" placeholder="Username">
</div>
<div class="input-email input-icon">
<input type="email" placeholder="Email">
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox">
I agree with your <a href="#">Terms & Conditions</a>.
</label>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block">Register</button>
</form>
<hr>
<a href="#" class="btn btn-social btn-bg-facebook btn-block"><i class="fa fa-facebook"></i> login with facebook</a>
<a href="#" class="btn btn-social btn-bg-linkedin btn-block"><i class="fa fa-linkedin"></i> login with linkedin</a>
<a href="#" class="btn btn-social btn-bg-google-plus btn-block"><i class="fa fa-google-plus"></i> login with Google</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="pop-reset-pass" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<ul class="login-tabs">
<li class="active">Reset Password</li>
</ul>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><i class="fa fa-close"></i></button>
</div>
<div class="modal-body">
<p>Please enter your username or email address. You will receive a link to create a new password via email.</p>
<form>
<div class="form-group">
<div class="input-user input-icon">
<input placeholder="Enter your username or email" class="form-control">
</div>
</div>
<button class="btn btn-primary btn-block">Get new password</button>
</form>
</div>
</div>
</div>
</div>
<!--start header section header v1-->
<header id="header-section" class="header-section-4 header-main nav-left hidden-sm hidden-xs" data-sticky="1">
<div class="container">
<div class="header-left">
<div class="logo">
<a href="index.html">
<img src="images/houzez-logo-color.png" alt="logo">
</a>
</div>
<nav class="navi main-nav">
<ul>
<li><a href="#">Home</a>
<ul class="sub-menu">
<li>
<a href="#">Map</a>
<ul class="sub-menu">
<li><a href="home-map.html">Map Standard</a></li>
<li><a href="home-map-fullscreen.html">Map Fullscreen</a></li>
</ul>
</li>
<li>
<a href="#">Parallax</a>
<ul class="sub-menu">
<li><a href="home-parallax.html">Parallax Standard</a></li>
<li><a href="home-parallax-fullscreen.html">Parallax Fullscreen</a></li>
<li><a href="home-parallax-autofix.html">Parallax Auto Fix</a></li>
</ul>
</li>
<li>
<a href="#">Video</a>
<ul class="sub-menu">
<li><a href="home-video.html">Video Standard</a></li>
<li><a href="home-video-fullscreen.html">Video Fullscreen</a></li>
</ul>
</li>
<li>
<a href="#">Sliders</a>
<ul class="sub-menu">
<li><a href="home-property-slider.html">Property Slider</a></li>
</ul>
</li>
<li>
<a href="#">Splash</a>
<ul class="sub-menu">
<li><a href="splash-video.html">Video Fullscreen</a></li>
<li><a href="splash-slider.html">Slider Fullscreen</a></li>
<li><a href="splash-image.html">Image Fullscreen</a></li>
<li><a href="home-splash.html">Home With Splash</a></li>
<li><a href="splash-half.html">Half</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#">Listing</a>
<ul class="sub-menu">
<li><a href="properties-list.html">List View</a>
<ul class="sub-menu">
<li><a href="properties-list.html">List View Standard</a></li>
<li><a href="properties-list-fullwidth.html">List View Fullwidth</a></li>
<li><a href="properties-list-compare.html">List View Compare Panel</a></li>
<li><a href="properties-list-save-search.html">List View Save Search</a></li>
</ul>
</li>
<li>
<a href="properties-list-style-2.html">List View Style 2</a>
<ul class="sub-menu">
<li><a href="properties-list-style-2.html">List View Standard Style 2</a></li>
<li><a href="properties-list-style-2-fullwidth.html">List View Fullwidth Style 2</a></li>
</ul>
</li>
<li><a href="properties-grid.html">Grid View</a>
<ul class="sub-menu">
<li><a href="properties-grid.html">Grid View Standard</a></li>
<li><a href="properties-grid-fullwidth.html">Grid View Fullwidth</a></li>
</ul>
</li>
<li><a href="properties-grid-style-2.html">Grid View Style 2</a>
<ul class="sub-menu">
<li><a href="properties-grid-style-2.html">Grid View Standard Style 2</a></li>
<li><a href="properties-grid-style-2-fullwidth.html">Grid View Fullwidth Style 2</a></li>
</ul>
</li>
<li><a href="#">Map</a>
<ul class="sub-menu">
<li><a href="map-listing.html">Half Map</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#">Property</a>
<ul class="sub-menu">
<li><a href="property-detail.html">Single Property v1</a></li>
<li><a href="property-detail-v2.html">Single Property v2</a></li>
<li><a href="property-detail-v3.html">Single Property v3</a></li>
<li><a href="property-detail-landing-page.html">Property Landing Page</a></li>
<li><a href="property-detail-full-width-gallery.html">Property Full Width Gallery</a></li>
<li><a href="property-detail-tabs.html">Single Property Tabs v1</a></li>
<li><a href="property-detail-tabs-vertical.html">Single Property Tabs v2</a></li>
<li><a href="property-detail-multi-properties.html">Multi Units / Sub listing</a></li>
<li><a href="property-nav-on-scroll.html">Property Nav On Scroll</a></li>
</ul>
</li>
<li class="houzez-megamenu"><a href="#">Pages</a>
<ul class="sub-menu">
<li>
<a href="#">Column 1</a>
<ul class="sub-menu">
<li><a href="agent-list.html">All Agents</a></li>
<li><a href="agent-detail.html">Agent Profile</a></li>
<li><a href="agency-list.html">All Agencies</a></li>
<li><a href="company-profile.html">Company Profile</a></li>
<li><a href="compare-properties.html">Compare Properties</a></li>
<li><a href="landing-page.html">Landing Page</a></li>
<li><a href="map-full-search.html">Map Full Screen</a></li>
</ul>
</li>
<li>
<a href="#">Column 2</a>
<ul class="sub-menu">
<li><a href="about-us.html">About Houzez</a></li>
<li><a href="contact-us.html">Contact us</a></li>
<li><a href="login.html">Login Page</a></li>
<li><a href="register.html">Register Page</a></li>
<li><a href="forget-password.html">Forget Password Page</a></li>
<li><a href="typography.html">Typography</a></li>
</ul>
</li>
<li>
<a href="#">Column 3</a>
<ul class="sub-menu">
<li><a href="faqs.html">FAQs</a></li>
<li><a href="simple-page.html">Simple Page</a></li>
<li><a href="404.html">404 Page</a></li>
<li><a href="headers.html">Houzez Headers</a></li>
<li><a href="footer.html">Houzez Footers</a></li>
<li><a href="widgets.html">Houzez Widgets</a></li>
</ul>
</li>
<li>
<a href="#">Column 4</a>
<ul class="sub-menu">
<li><a href="search-bars.html">Houzez Search Bars</a></li>
<li><a href="add-new-property.html">Create Listing Page</a></li>
<li><a href="listing-select-package.html">Select Packages Page</a></li>
<li><a href="listing-payment.html">Payment Page</a></li>
<li><a href="listing-done.html">Listing Done Page</a></li>
<li><a href="blog.html">Blog</a></li>
</ul>
</li>
<li>
<a href="#">Column 5</a>
<ul class="sub-menu">
<li><a href="blog-detail.html">Blog detail</a></li>
<li><a href="my-account.html">My Account</a></li>
<li><a href="my-properties.html">My Properties</a></li>
<li><a href="my-favourite-properties.html">My Favourite Properties</a></li>
<li><a href="my-saved-search.html">My Saved Searches</a></li>
<li><a href="my-invoices.html">My Invoices</a></li>
</ul>
</li>
</ul>
</li>
<li class="houzez-megamenu"><a href="#">Modules</a>
<ul class="sub-menu">
<li>
<a href="#"> Column 1 </a>
<ul class="sub-menu">
<li><a href="module-advanced-search.html">Advanced Search</a></li>
<li><a href="module-property-grids.html">Property Grids</a></li>
<li><a href="module-property-carousel-v1.html">Property Carousel v1</a></li>
<li><a href="module-property-carousel-v2.html">Property Carousel v2</a></li>
</ul>
</li>
<li>
<a href="#"> Column 2 </a>
<ul class="sub-menu">
<li><a href="module-property-cards.html">Property Cards Module</a></li>
<li><a href="module-property-by-id.html">Property by ID</a></li>
<li><a href="module-taxonomy-grids.html">Taxonomy Grids</a></li>
<li><a href="module-taxonomy-tabs.html">Taxonomy Tabs</a></li>
</ul>
</li>
<li>
<a href="#"> Column 3 </a>
<ul class="sub-menu">
<li><a href="module-testimonials.html">Testimonials</a></li>
<li><a href="module-membership-packages.html">Membership Packages</a></li>
<li><a href="module-agents.html">Agents</a></li>
<li><a href="module-team.html">Team</a></li>
</ul>
</li>
<li>
<a href="#"> Column 4 </a>
<ul class="sub-menu">
<li><a href="module-partners.html">Partners</a></li>
<li><a href="module-text-with-icons.html">Text with icons</a></li>
<li><a href="module-blog-post-carousels.html">Blog Post Carousels</a></li>
<li><a href="module-blog-post-grids.html">Blog Post Grids</a></li>
<li><a href="blog-masonry.html">Blog Post Masonry</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</div>
<div class="header-right">
<div class="user">
<a href="#" data-toggle="modal" data-target="#pop-login">Sign In / Register</a>
<a href="add-new-property.html" class="btn btn-default">Create Listing</a>
</div>
</div>
</div>
</header>
<div class="header-mobile visible-sm visible-xs">
<div class="container">
<!--start mobile nav-->
<div class="mobile-nav">
<span class="nav-trigger"><i class="fa fa-navicon"></i></span>
<div class="nav-dropdown main-nav-dropdown"></div>
</div>
<!--end mobile nav-->
<div class="header-logo">
<a href="index.html"><img src="images/logo-houzez-white.png" alt="logo"></a>
</div>
<div class="header-user">
<ul class="account-action">
<li>
<span class="user-icon"><i class="fa fa-user"></i></span>
<div class="account-dropdown">
<ul>
<li> <a href="add-new-property.html"> <i class="fa fa-plus-circle"></i>Creat Listing</a></li>
<li> <a href="#" data-toggle="modal" data-target="#pop-login"> <i class="fa fa-user"></i> Log in / Register </a></li>
</ul>
</div>
</li>
</ul>
</div>
</div>
</div>
<!--end header section header v1-->
<!--start advanced search section-->
<section class="advanced-search advance-search-header">
<div class="container">
<div class="row">
<div class="col-sm-12">
<form>
<div class="form-group search-long">
<div class="search">
<div class="input-search input-icon">
<input class="form-control" type="text" placeholder="Search for a place to stay?">
</div>
<select name="location" class="selectpicker bs-select-hidden" data-live-search="false" data-live-search-style="begins">
<option value="">All Cities</option>
<option value="chicago"> Chicago</option>
<option value="los-angeles"> Los Angeles</option>
<option value="miami"> Miami</option>
<option value="new-york"> New York</option>
</select>
<select name="area" class="selectpicker bs-select-hidden" data-live-search="false" data-live-search-style="begins">
<option value="">All Areas</option>
<option value="beverly-hills"> Beverly Hills</option>
<option value="brickell"> Brickell</option>
<option value="brickyard"> Brickyard</option>
<option value="bronx"> Bronx</option>
<option value="brooklyn"> Brooklyn</option>
<option value="coconut-grove"> Coconut Grove</option>
<option value="downtown"> Downtown</option>
<option value="eagle-rock"> Eagle Rock</option>
<option value="englewood"> Englewood</option>
<option value="hermosa"> Hermosa</option>
<option value="hollywood"> Hollywood</option>
<option value="lincoln-park"> Lincoln Park</option>
<option value="manhattan"> Manhattan</option>
<option value="midtown"> Midtown</option>
<option value="queens"> Queens</option>
<option value="westwood"> Westwood</option>
<option value="wynwood"> Wynwood</option>
</select>
<div class="advance-btn-holder">
<button class="advance-btn btn" type="button"><i class="fa fa-gear"></i> Advanced</button>
</div>
</div>
<div class="search-btn">
<button class="btn btn-secondary">Go</button>
</div>
</div>
<div class="advance-fields">
<div class="row">
<div class="col-sm-3 col-xs-6">
<div class="form-group">
<select class="selectpicker" data-live-search="true" data-live-search-style="begins" title="Status">
<option>Status 1</option>
<option>Status 2</option>
<option>Status 3</option>
<option>Status 4</option>
<option>Status 5</option>
</select>
</div>
</div>
<div class="col-sm-3 col-xs-6">
<div class="form-group">
<select class="selectpicker" data-live-search="true" data-live-search-style="begins" title="Property Type">
<option>Property Type 1</option>
<option>Property Type 2</option>
<option>Property Type 3</option>
<option>Property Type 4</option>
<option>Property Type 5</option>
</select>
</div>
</div>
<div class="col-sm-3 col-xs-6">
<div class="form-group">
<select class="selectpicker" data-live-search="true" data-live-search-style="begins" title="Beds">
<option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option>
</select>
</div>
</div>
<div class="col-sm-3 col-xs-6">
<div class="form-group">
<select class="selectpicker" data-live-search="true" data-live-search-style="begins" title="Baths">
<option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option>
</select>
</div>
</div>
<div class="col-sm-3 col-xs-6">
<div class="form-group">
<select class="selectpicker" data-live-search="true" data-live-search-style="begins" title="Min Areas (Sqft)">
<option>$100</option>
<option>$100</option>
<option>$100</option>
<option>$100</option>
<option>$100</option>
</select>
</div>
</div>
<div class="col-sm-3 col-xs-6">
<div class="form-group">
<select class="selectpicker" data-live-search="true" data-live-search-style="begins" title="Max Areas (Sqft)">
<option>$100</option>
<option>$100</option>
<option>$100</option>
<option>$100</option>
<option>$100</option>
</select>
</div>
</div>
<div class="col-sm-6 col-xs-6">
<div class="range-advanced-main">
<div class="range-text">
<input type="text" class="min-price-range-hidden range-input" readonly >
<input type="text" class="max-price-range-hidden range-input" readonly >
<p><span class="range-title">Price Range:</span> from <span class="min-price-range"></span> to <span class="max-price-range"></span></p>
</div>
<div class="range-wrap">
<div class="price-range-advanced"></div>
</div>
</div>
</div>
<div class="col-sm-12 col-xs-12 features-list">
<label class="advance-trigger text-uppercase title"><i class="fa fa-plus-square"></i> Other Features </label>
<div class="clearfix"></div>
<div class="field-expand">
<label class="checkbox-inline">
<input type="checkbox" value="option1"> Feature
</label>
<label class="checkbox-inline">
<input type="checkbox" value="option2"> Feature
</label>
<label class="checkbox-inline">
<input type="checkbox" value="option3"> Feature
</label>
<label class="checkbox-inline">
<input type="checkbox" value="option1"> Feature
</label>
<label class="checkbox-inline">
<input type="checkbox" value="option2"> Feature
</label>
<label class="checkbox-inline">
<input type="checkbox" value="option3"> Feature
</label>
<label class="checkbox-inline">
<input type="checkbox" value="option1"> Feature
</label>
<label class="checkbox-inline">
<input type="checkbox" value="option2"> Feature
</label>
<label class="checkbox-inline">
<input type="checkbox" value="option3"> Feature
</label>
<label class="checkbox-inline">
<input type="checkbox" value="option1"> Feature
</label>
<label class="checkbox-inline">
<input type="checkbox" value="option2"> Feature
</label>
<label class="checkbox-inline">
<input type="checkbox" value="option3"> Feature
</label>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
<!--end advanced search section-->
<!--start advanced search section-->
<section class="advanced-search-mobile visible-xs visible-sm">
<div class="container">
<div class="row">
<div class="col-sm-12">
<form>
<div class="single-search-wrap">
<div class="single-search-inner advance-btn">
<button class="table-cell text-left" type="button"><i class="fa fa-gear"></i></button>
</div>
<div class="single-search-inner single-search">
<input type="text" class="form-control table-cell" name="search" placeholder="Search">
</div>
<div class="single-search-inner single-seach-btn">
<button class="table-cell text-right" type="submit"><i class="fa fa-search"></i></button>
</div>
</div>
<div class="advance-fields">
<div class="row">
<div class="col-sm-6 col-xs-12">
<div class="form-group">
<select class="selectpicker" data-live-search="false" data-live-search-style="begins" title="All Cities">
<option>City 1</option>
<option>City 2</option>
<option>City 3</option>
<option>City 4</option>
<option>City 5</option>
</select>
</div>
</div>
<div class="col-sm-6 col-xs-12">
<div class="form-group">
<select class="selectpicker" data-live-search="false" data-live-search-style="begins" title="All Areas">
<option>Area 1</option>
<option>Area 2</option>
<option>Area 3</option>
<option>Area 4</option>
<option>Area 5</option>
</select>
</div>
</div>
<div class="col-sm-6 col-xs-12">
<div class="form-group">
<select class="selectpicker" data-live-search="false" data-live-search-style="begins" title="All Status">
<option>Status 1</option>
<option>Status 2</option>
<option>Status 3</option>
<option>Status 4</option>
<option>Status 5</option>
</select>
</div>
</div>
<div class="col-sm-6 col-xs-12">
<div class="form-group">
<select class="selectpicker" data-live-search="false" data-live-search-style="begins" title="All Types">
<option>Type 1</option>
<option>Type 2</option>
<option>Type 3</option>
<option>Type 4</option>
<option>Type 5</option>
</select>
</div>
</div>
<div class="col-sm-6 col-xs-6">
<div class="form-group">
<div class="input-group">
<span class="input-group-btn">
<button type="button" class="btn btn-number" disabled="disabled" data-type="minus" data-field="count_beds">
<i class="fa fa-minus"></i>
</button>
</span>
<input type="text" name="count_beds" class="form-control input-number" value="1" data-min="1" data-max="10" placeholder="Beds">
<span class="input-group-btn">
<button type="button" class="btn btn-number" data-type="plus" data-field="count_beds">
<i class="fa fa-plus"></i>
</button>
</span>
</div>
</div>
</div>
<div class="col-sm-6 col-xs-6">
<div class="form-group">
<div class="input-group">
<span class="input-group-btn">
<button type="button" class="btn btn-number" disabled="disabled" data-type="minus" data-field="count_baths">
<i class="fa fa-minus"></i>
</button>
</span>
<input type="text" name="count_baths" class="form-control input-number" value="1" data-min="1" data-max="10" placeholder="Baths">
<span class="input-group-btn">
<button type="button" class="btn btn-number" data-type="plus" data-field="count_baths">
<i class="fa fa-plus"></i>
</button>
</span>
</div>
</div>
</div>
<div class="col-sm-6 col-xs-6">
<div class="form-group">
<input type="text" class="form-control" value="" name="min-area" placeholder="Min Area (sqft)">
</div>
</div>
<div class="col-sm-6 col-xs-6">
<div class="form-group">
<input type="text" class="form-control" value="" name="max-area" placeholder="Max Area (sqft)">
</div>
</div>
<div class="col-sm-12 col-xs-12">
<div class="range-advanced-main">
<div class="range-text">
<input type="text" class="min-price-range-hidden range-input" readonly >
<input type="text" class="max-price-range-hidden range-input" readonly >
<p><span class="range-title">Price Range:</span> from <span class="min-price-range"></span> to <span class="max-price-range"></span></p>
</div>
<div class="range-wrap">
<div class="price-range-advanced"></div>
</div>
</div>
</div>
<div class="col-sm-12 col-xs-12">
<label class="advance-trigger"><i class="fa fa-plus-square"></i> Other Features </label>
</div>
<div class="col-sm-12 col-xs-12 features-list ">
<div class="field-expand">
<label class="checkbox-inline">
<input type="checkbox" value="option1"> Feature
</label>
<label class="checkbox-inline">
<input type="checkbox" value="option2"> Feature
</label>
<label class="checkbox-inline">
<input type="checkbox" value="option3"> Feature
</label>
<label class="checkbox-inline">
<input type="checkbox" value="option1"> Feature
</label>
<label class="checkbox-inline">
<input type="checkbox" value="option2"> Feature
</label>
<label class="checkbox-inline">
<input type="checkbox" value="option3"> Feature
</label>
<label class="checkbox-inline">
<input type="checkbox" value="option1"> Feature
</label>
<label class="checkbox-inline">
<input type="checkbox" value="option2"> Feature
</label>
<label class="checkbox-inline">
<input type="checkbox" value="option3"> Feature
</label>
<label class="checkbox-inline">
<input type="checkbox" value="option1"> Feature
</label>
<label class="checkbox-inline">
<input type="checkbox" value="option2"> Feature
</label>
<label class="checkbox-inline">
<input type="checkbox" value="option3"> Feature
</label>
</div>
</div>
<div class="col-sm-12 col-xs-12">
<button type="submit" class="btn btn-secondary btn-block"><i class="fa fa-search pull-left"></i> Search</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
<!--end advanced search section-->
<!--start section page body-->
<section id="section-body">
<!--start detail top-->
<div class="detail-top detail-top-grid no-margin">
<div class="container">
<div class="row">
<div class="col-sm-12 col-xs-12">
<div class="header-detail table-list">
<div class="header-left">
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-home"></i></a></li>
<li><a href="#">Library</a></li>
<li class="active">Data</li>
</ol>
<h1>
Oceanfront Villa With Pool
<span class="label-wrap hidden-sm hidden-xs">
<span class="label label-primary">For Sale</span>
<span class="label label-danger">Sold</span>
</span>
</h1>
<address class="property-address">7601 East Treasure Drive, Miami Beach, FL 33141</address>
</div>
<div class="header-right">
<ul class="actions">
<li class="share-btn">
<div class="share_tooltip tooltip_left fade">
<a href="#" onclick="window.open(this.href, 'mywin','left=50,top=50,width=600,height=350,toolbar=0'); return false;"><i class="fa fa-facebook"></i></a>
<a href="#" onclick="if(!document.getElementById('td_social_networks_buttons')){window.open(this.href, 'mywin','left=50,top=50,width=600,height=350,toolbar=0'); return false;}"><i class="fa fa-twitter"></i></a>
<a href="#" onclick="window.open(this.href, 'mywin','left=50,top=50,width=600,height=350,toolbar=0'); return false;"><i class="fa fa-pinterest"></i></a>
<a href="#" onclick="window.open(this.href, 'mywin','left=50,top=50,width=600,height=350,toolbar=0'); return false;"><i class="fa fa-linkedin"></i></a>
<a href="#" onclick="window.open(this.href, 'mywin','left=50,top=50,width=600,height=350,toolbar=0'); return false;"><i class="fa fa-google-plus"></i></a>
<a href="#"><i class="fa fa-envelope"></i></a>
</div>
<span data-placement="right" data-toggle="tooltip" data-original-title="share"><i class="fa fa-share-alt"></i></span>
</li>
<li>
<span><i class="fa fa-heart-o"></i></span>
</li>
</ul>
<span class="item-price">$575,000</span>
<span class="item-sub-price">$21,000/mo</span>
</div>
</div>
</div>
</div>
</div>
</div>
<!--end detail top-->
<!--start detail content-->
<section class="section-detail-content">
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-8 col-sm-12 col-xs-12 container-contentbar">
<div class="detail-bar">
<div class="detail-media detail-top-slideshow">
<div class="tab-content">
<div id="gallery" class="tab-pane fade in active">
<span class="label-wrap visible-sm visible-xs">
<span class="label label-primary">For Sale</span>
<span class="label label-danger">Sold</span>
</span>
<div class="slideshow">
<div class="slideshow-main">
<div class="slide">
<div>
<img src="http://placehold.it/810x430" width="810" height="430" alt="Slide show">
</div>
<div>
<img src="http://placehold.it/810x430" width="810" height="430" alt="Slide show">
</div>
<div>
<img src="http://placehold.it/810x430" width="810" height="430" alt="Slide show">
</div>
<div>
<img src="http://placehold.it/810x430" width="810" height="430" alt="Slide show">
</div>
</div>
</div>
<div class="slideshow-nav-main">
<div class="slideshow-nav">
<div>
<img src="http://placehold.it/100x70" width="100" height="70" alt="Slide show thumb">
</div>
<div>
<img src="http://placehold.it/100x70" width="100" height="70" alt="Slide show thumb">
</div>
<div>
<img src="http://placehold.it/100x70" width="100" height="70" alt="Slide show thumb">
</div>
<div>
<img src="http://placehold.it/100x70" width="100" height="70" alt="Slide show thumb">
</div>
</div>
</div>
</div>
</div>
<div id="map" class="tab-pane fade"></div>
<div id="street-map" class="tab-pane fade"></div>
</div>
<div class="media-tabs">
<ul class="media-tabs-list">
<li class="popup-trigger" data-placement="bottom" data-toggle="tooltip" data-original-title="View Photos">
<a href="#gallery" data-toggle="tab">
<i class="fa fa-camera"></i>
</a>
</li>
<li data-placement="bottom" data-toggle="tooltip" data-original-title="Map View">
<a href="#map" data-toggle="tab">
<i class="fa fa-map"></i>
</a>
</li>
<li data-placement="bottom" data-toggle="tooltip" data-original-title="Street View">
<a href="#street-map" data-toggle="tab">
<i class="fa fa-street-view"></i>
</a>
</li>
</ul>
<ul class="actions">
<li class="share-btn">
<div class="share_tooltip tooltip_left fade">
<a href="#" onclick="window.open(this.href, 'mywin','left=50,top=50,width=600,height=350,toolbar=0'); return false;"><i class="fa fa-facebook"></i></a>
<a href="#" onclick="if(!document.getElementById('td_social_networks_buttons')){window.open(this.href, 'mywin','left=50,top=50,width=600,height=350,toolbar=0'); return false;}"><i class="fa fa-twitter"></i></a>
<a href="#" onclick="window.open(this.href, 'mywin','left=50,top=50,width=600,height=350,toolbar=0'); return false;"><i class="fa fa-pinterest"></i></a>
<a href="#" onclick="window.open(this.href, 'mywin','left=50,top=50,width=600,height=350,toolbar=0'); return false;"><i class="fa fa-linkedin"></i></a>
<a href="#" onclick="window.open(this.href, 'mywin','left=50,top=50,width=600,height=350,toolbar=0'); return false;"><i class="fa fa-google-plus"></i></a>
<a href="#"><i class="fa fa-envelope"></i></a>
</div>
<span data-placement="right" data-toggle="tooltip" data-original-title="share"><i class="fa fa-share-alt"></i></span>
</li>
<li>
<span><i class="fa fa-heart-o"></i></span>
</li>
</ul>
</div>
</div>
<div class="property-description detail-block">
<div class="detail-title">
<h2 class="title-left">Description</h2>
<div class="title-right">
<a href="#">Flag this listing <i class="fa fa-flag"></i></a>
</div>
</div>
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, condimentum feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. </p>
<p>Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. </p>
</div>
<div class="detail-address detail-block">
<div class="detail-title">
<h2 class="title-left">Address</h2>
<div class="title-right">
<a href="#">Open on Google Maps <i class="fa fa-map-marker"></i></a>
</div>
</div>
<ul class="list-three-col">
<li><strong>Address:</strong> 7601 East Treasure Drive</li>
<li><strong>City:</strong> Miami Beach</li>
<li><strong>State/Country:</strong> Florida</li>
<li><strong>Zip:</strong> 33139</li>
<li><strong>Country:</strong> United States</li>
<li><strong>Neighbourhood:</strong> Miami</li>
</ul>
</div>
<div class="detail-list detail-block">
<div class="detail-title">
<h2 class="title-left">Detail</h2>
<div class="title-right">
<p>Information last updated on 11/29/2015 12:00 AM</p>
</div>
</div>
<div class="alert alert-info">
<ul class="list-three-col">
<li><strong>Property ID:</strong> HZ33</li>
<li><strong>Price:</strong> $670,000</li>
<li><strong>Property Size:</strong> 1200 Sq Ft</li>
<li><strong>Bedrooms:</strong> 4</li>
<li><strong>Bathrooms:</strong> 2</li>
<li><strong>Garage:</strong> 1</li>
<li><strong>Garage Size:</strong> 200 SqFt</li>
<li><strong>Year Built:</strong> 2016-01-09</li>
</ul>
</div>
<div class="detail-title-inner">
<h4 class="title-inner">Additional details</h4>
</div>
<ul class="list-three-col">
<li><strong>Deposit:</strong> 20%</li>
<li><strong>Pool Size:</strong> 300 Sqft</li>
<li><strong>Last remodel year:</strong> 1987</li>
<li><strong>Amenities:</strong> Clubhouse</li>
<li><strong>Additional Rooms::</strong> Guest Bath</li>
<li><strong>Equipment:</strong> Grill - Gas</li>
</ul>
</div>
<div class="detail-features detail-block">
<div class="detail-title">
<h2 class="title-left">Features</h2>
</div>
<ul class="list-three-col list-features">
<li><a href="#"><i class="fa fa-check"></i>Air Conditioning</a></li>
<li><a href="#"><i class="fa fa-check"></i>Barbeque</a></li>
<li><a href="#"><i class="fa fa-check"></i>Dryer</a></li>
<li><a href="#"><i class="fa fa-check"></i>Gym</a></li>
<li><a href="#"><i class="fa fa-check"></i>Laundry</a></li>
<li><a href="#"><i class="fa fa-check"></i>Lawn</a></li>
<li><a href="#"><i class="fa fa-check"></i>Microwave</a></li>
<li><a href="#"><i class="fa fa-check"></i>Outdoor Shower</a></li>
<li><a href="#"><i class="fa fa-check"></i>Refrigerator</a></li>
<li><a href="#"><i class="fa fa-check"></i>Sauna</a></li>
<li><a href="#"><i class="fa fa-check"></i>Swimming Pool</a></li>
<li><a href="#"><i class="fa fa-check"></i>TV Cable</a></li>
<li><a href="#"><i class="fa fa-check"></i>Washer</a></li>
<li><a href="#"><i class="fa fa-check"></i>WiFi</a></li>
<li><a href="#"><i class="fa fa-check"></i>Window Coverings</a></li>
</ul>
</div>
<div class="property-plans detail-block">
<div class="detail-title">
<h2 class="title-left">Floor plans</h2>
</div>
<div class="accord-block">
<div class="accord-tab">
<h3>Floor Plan A</h3>
<ul>
<li>Size: <strong>1,234 sqft</strong></li>
<li>Beds: <strong>4</strong></li>
<li>Baths: <strong>3</strong></li>
<li>Price: <strong>$1,200/mo</strong></li>
</ul>
<div class="expand-icon active"></div>
</div>
<div class="accord-content" style="display: block">
<img src="images/floor-image.png" alt="img" width="400" height="436">
</div>
<div class="accord-tab">
<h3>Floor Plan B</h3>
<ul>
<li>Size: <strong>1,234 sqft</strong></li>
<li>Beds: <strong>4</strong></li>
<li>Baths: <strong>3</strong></li>
<li>Price: <strong>$1,200/mo</strong></li>
</ul>
<div class="expand-icon"></div>
</div>
<div class="accord-content">
<img src="images/floor-image.png" alt="img" width="400" height="436">
</div>
<div class="accord-tab">
<h3>Floor Plan C</h3>
<ul>
<li>Size: <strong>1,234 sqft</strong></li>
<li>Beds: <strong>4</strong></li>
<li>Baths: <strong>3</strong></li>
<li>Price: <strong>$1,200/mo</strong></li>
</ul>
<div class="expand-icon"></div>
</div>
<div class="accord-content">
<img src="images/floor-image.png" alt="img" width="400" height="436">
</div>
</div>
<div class="detail-title-inner">
<h4 class="title-inner">Property Documents</h4>
</div>
<ul class="document-list">
<li>
<div class="pull-left">
<i class="fa fa-file-o"></i> Property plan PDF
</div>
<div class="pull-right">
<a href="#">DOWNLOAD</a>
</div>
</li>
<li>
<div class="pull-left">
<i class="fa fa-file-o"></i> Brochure PDF
</div>
<div class="pull-right">
<a href="#">DOWNLOAD</a>
</div>
</li>
</ul>
</div>
<div class="property-video detail-block">
<div class="detail-title">
<h2 class="title-left">Video</h2>
</div>
<div class="video-block">
<a href="https://www.youtube.com/watch?v=QK66RK7ogKU" data-fancy="property_video" title="YouTube demo">
<span class="play-icon"><img src="images/icons/video-play-icon.png" alt="YouTube demo" width="70" height="50"></span>
<img src="http://placehold.it/750x388" alt="thumb" class="video-thumb">
</a>
</div>
</div>
<div class="detail-contact detail-block">
<div class="detail-title">
<h2 class="title-left">Contact info</h2>
<div class="title-right"><strong><a href="#">View my listing</a></strong></div>
</div>
<div class="media agent-media">
<div class="media-left">
<a href="#">
<img src="http://placehold.it/74x74" class="media-object" alt="image" width="74" height="74">
</a>
</div>
<div class="media-body">
<h4 class="media-heading">CONTACT AGENT</h4>
<ul>
<li><i class="fa fa-user"></i> Kenneth Phllips</li>
<li>
<span><i class="fa fa-phone"></i> (987) 654 3210</span>
<span><i class="fa fa-mobile"></i> (987) 654 3210</span>
<span><a href="#"><i class="fa fa-skype"></i> kenneth.phllips</a></span>
</li>
<li>
<span><a href="#"><i class="fa fa-facebook-square"></i> Facebook</a></span>
<span><a href="#"><i class="fa fa-twitter-square"></i> Twitter</a></span>
<span><a href="#"><i class="fa fa-linkedin-square"></i> Linkedin</a></span>
<span><a href="#"><i class="fa fa-instagram"></i> Linkedin</a></span>
<span><a href="#"><i class="fa fa-pinterest-square"></i> Linkedin</a></span>
<span><a href="#"><i class="fa fa-globe"></i> Linkedin</a></span>
</li>
</ul>
</div>
</div>
<div class="detail-title-inner">
<h4 class="title-inner">Inquire about this propertys</h4>
</div>
<form>
<div class="row">
<div class="col-sm-4 col-xs-12">
<div class="form-group">
<input class="form-control" placeholder="Your Name" type="text">
</div>
</div>
<div class="col-sm-4 col-xs-12">
<div class="form-group">
<input class="form-control" placeholder="Phone" type="text">
</div>
</div>
<div class="col-sm-4 col-xs-12">
<div class="form-group">
<input class="form-control" placeholder="Email" type="email">
</div>
</div>
<div class="col-sm-12 col-xs-12">
<div class="form-group">
<textarea class="form-control" rows="5" placeholder="Location"></textarea>
</div>
</div>
</div>
<button class="btn btn-secondary">Request info</button>
</form>
</div>
<div class="next-prev-block clearfix">
<div class="prev-box pull-left">
<div class="media">
<div class="media-left">
<a href="#">
<img src="http://placehold.it/99x99" class="media-object" alt="image" width="99" height="99">
</a>
</div>
<div class="media-body media-middle">
<h3 class="media-heading"><a href="#"><i class="fa fa-angle-left"></i> PREVIOUS PROPERTY</a></h3>
<h4>Villa For Sale</h4>
</div>
</div>
</div>
<div class="next-box pull-right">
<div class="media">
<div class="media-body media-middle text-right">
<h3 class="media-heading"><a href="#">PREVIOUS PROPERTY <i class="fa fa-angle-right"></i></a></h3>
<h4>Villa For Sale</h4>
</div>
<div class="media-right">
<a href="#">
<img src="http://placehold.it/99x99" class="media-object" alt="image" width="99" height="99">
</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 col-md-offset-0 col-sm-offset-3 container-sidebar">
<aside id="sidebar">
<div class="widget widget-download">
<div class="widget-top">
<h3 class="widget-title">Documents</h3>
</div>
<div class="widget-body">
<ul>
<li>
<div class="pull-left">
Property plan PDF
</div>
<div class="pull-right">
<a href="#">DOWNLOAD</a>
</div>
</li>
<li>
<div class="pull-left">
Brochure PDF
</div>
<div class="pull-right">
<a href="#">DOWNLOAD</a>
</div>
</li>
</ul>
</div>
</div>
<div class="widget widget-recommend">
<div class="widget-top">
<h3 class="widget-title">We recommend</h3>
</div>
<div class="widget-body">
<div class="media">
<div class="media-left">
<figure class="item-thumb">
<a class="hover-effect" href="#">
<img alt="thumb" src="http://placehold.it/100x75" width="100" height="75">
</a>
</figure>
</div>
<div class="media-body">
<h3 class="media-heading"><a href="#">Apartment Oceanview</a></h3>
<h4>$350,000</h4>
<div class="amenities">
<p>3 beds • 2 baths • 1,238 sqft</p>
<p>Single Family Home</p>
</div>
</div>
</div>
<div class="media">
<div class="media-left">
<figure class="item-thumb">
<a class="hover-effect" href="#">
<img alt="thumb" src="http://placehold.it/100x75" width="100" height="75">
</a>
</figure>
</div>
<div class="media-body">
<h3 class="media-heading"><a href="#">Apartment Oceanview</a></h3>
<h4>$350,000</h4>
<div class="amenities">
<p>3 beds • 2 baths • 1,238 sqft</p>
<p>Single Family Home</p>
</div>
</div>
</div>
<div class="media">
<div class="media-left">
<figure class="item-thumb">
<a class="hover-effect" href="#">
<img alt="thumb" src="http://placehold.it/100x75" width="100" height="75">
</a>
</figure>
</div>
<div class="media-body">
<h3 class="media-heading"><a href="#">Apartment Oceanview</a></h3>
<h4>$350,000</h4>
<div class="amenities">
<p>3 beds • 2 baths • 1,238 sqft</p>
<p>Single Family Home</p>
</div>
</div>
</div>
</div>
</div>
<div class="widget widget-rated">
<div class="widget-top">
<h3 class="widget-title">Most Rated Properties</h3>
</div>
<div class="widget-body">
<div class="media">
<div class="media-left">
<figure class="item-thumb">
<a class="hover-effect" href="#">
<img alt="thumb" src="http://placehold.it/100x75" width="100" height="75">
</a>
</figure>
</div>
<div class="media-body">
<h3 class="media-heading"><a href="#">Apartment Oceanview</a></h3>
<div class="rating">
<span class="star-text-left">$350,000</span><span data-title="Average Rate: 4.67 / 5" class="bottom-ratings tip"><span class="fa fa-star-o"></span><span class="fa fa-star-o"></span><span class="fa fa-star-o"></span><span class="fa fa-star-o"></span><span class="fa fa-star-o"></span><span style="width: 70%" class="top-ratings"><span class="fa fa-star"></span><span class="fa fa-star"></span><span class="fa fa-star"></span><span class="fa fa-star"></span><span class="fa fa-star"></span></span></span>
</div>
<div class="amenities">
<p>3 beds • 2 baths • 1,238 sqft</p>
<p>Single Family Home</p>
</div>
</div>
</div>
<div class="media">
<div class="media-left">
<figure class="item-thumb">
<a class="hover-effect" href="#">
<img alt="thumb" src="http://placehold.it/100x75" width="100" height="75">
</a>
</figure>
</div>
<div class="media-body">
<h3 class="media-heading"><a href="#">Apartment Oceanview</a></h3>
<div class="rating">
<span class="star-text-left">$350,000</span><span data-title="Average Rate: 4.67 / 5" class="bottom-ratings tip"><span class="fa fa-star-o"></span><span class="fa fa-star-o"></span><span class="fa fa-star-o"></span><span class="fa fa-star-o"></span><span class="fa fa-star-o"></span><span style="width: 70%" class="top-ratings"><span class="fa fa-star"></span><span class="fa fa-star"></span><span class="fa fa-star"></span><span class="fa fa-star"></span><span class="fa fa-star"></span></span></span>
</div>
<div class="amenities">
<p>3 beds • 2 baths • 1,238 sqft</p>
<p>Single Family Home</p>
</div>
</div>
</div>
<div class="media">
<div class="media-left">
<figure class="item-thumb">
<a class="hover-effect" href="#">
<img alt="thumb" src="http://placehold.it/100x75" width="100" height="75">
</a>
</figure>
</div>
<div class="media-body">
<h3 class="media-heading"><a href="#">Apartment Oceanview</a></h3>
<div class="rating">
<span class="star-text-left">$350,000</span><span data-title="Average Rate: 4.67 / 5" class="bottom-ratings tip"><span class="fa fa-star-o"></span><span class="fa fa-star-o"></span><span class="fa fa-star-o"></span><span class="fa fa-star-o"></span><span class="fa fa-star-o"></span><span style="width: 70%" class="top-ratings"><span class="fa fa-star"></span><span class="fa fa-star"></span><span class="fa fa-star"></span><span class="fa fa-star"></span><span class="fa fa-star"></span></span></span>
</div>
<div class="amenities">
<p>3 beds • 2 baths • 1,238 sqft</p>
<p>Single Family Home</p>
</div>
</div>
</div>
</div>
</div>
<div class="widget widget-categories">
<div class="widget-top">
<h3 class="widget-title">Property Categories</h3>
</div>
<div class="widget-body">
<ul>
<li><a href="">Apartment</a> <span class="cat-count">(30)</span></li>
<li><a href="">Condo</a> <span class="cat-count">(30)</span></li>
<li><a href="">Single Family Home</a> <span class="cat-count">(30)</span></li>
<li><a href="">Villa</a> <span class="cat-count">(30)</span></li>
<li><a href="">Studio</a> <span class="cat-count">(30)</span></li>
</ul>
</div>
</div>
<div class="widget widget-pages">
<div class="widget-top">
<h3 class="widget-title">Pages</h3>
</div>
<ul>
<li><a href="#">Home</a>
<ul class="children">
<li><a href="#">Clearing Floats</a></li>
<li><a href="#">Page Image Alignment</a></li>
</ul>
</li>
<li><a href="#">About Houzez</a></li>
<li><a href="#">Our Agents</a></li>
<li><a href="#">Create Listing</a></li>
<li><a href="#">Faq</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
<div class="widget widget_archive">
<div class="widget-top">
<h3 class="widget-title">Archives</h3></div>
<ul>
<li><a href="#">March 2016</a> (10)</li>
<li><a href="#">January 2016</a> (1)</li>
<li><a href="#">January 2013</a> (5)</li>
<li><a href="#">March 2012</a> (5)</li>
</ul>
</div>
<div class="widget widget_meta">
<div class="widget-top">
<h3 class="widget-title">Meta</h3>
</div>
<ul>
<li><a href="#">Site Admin</a></li>
<li><a href="#">Log out</a></li>
<li><a href="#">Entries <abbr title="Really Simple Syndication">RSS</abbr></a></li>
<li><a href="#">Comments <abbr title="Really Simple Syndication">RSS</abbr></a></li>
</ul>
</div>
<div class="widget widget-reviews">
<div class="widget-top">
<h3 class="widget-title">Latest Reviews</h3>
</div>
<div class="widget-body">
<div class="media">
<div class="media-left">
<a href="#">
<img class="media-object img-circle" src="http://placehold.it/50x50" alt="Thumb" width="50" height="50">
</a>
</div>
<div class="media-body">
<h3 class="media-heading"><a href="#">Property title</a></h3>
<div class="rating">
<span class="bottom-ratings"><span class="fa fa-star-o"></span><span class="fa fa-star-o"></span><span class="fa fa-star-o"></span><span class="fa fa-star-o"></span><span class="fa fa-star-o"></span><span style="width: 70%" class="top-ratings"><span class="fa fa-star"></span><span class="fa fa-star"></span><span class="fa fa-star"></span><span class="fa fa-star"></span><span class="fa fa-star"></span></span></span>
</div>
<p>Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Etiam
risus tortor, accumsan at nisi et,
</p>
</div>
</div>
<div class="media">
<div class="media-left">
<a href="#">
<img class="media-object img-circle" src="http://placehold.it/50x50" alt="Thumb" width="50" height="50">
</a>
</div>
<div class="media-body">
<h3 class="media-heading"><a href="#">Property title</a></h3>
<div class="rating">
<span class="bottom-ratings"><span class="fa fa-star-o"></span><span class="fa fa-star-o"></span><span class="fa fa-star-o"></span><span class="fa fa-star-o"></span><span class="fa fa-star-o"></span><span style="width: 70%" class="top-ratings"><span class="fa fa-star"></span><span class="fa fa-star"></span><span class="fa fa-star"></span><span class="fa fa-star"></span><span class="fa fa-star"></span></span></span>
</div>
<p>Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Etiam
risus tortor, accumsan at nisi et,
</p>
</div>
</div>
</div>
</div>
</aside>
</div>
</div>
</div>
</section>
<!--end detail content-->
</section>
<!--end section page body-->
<div id="lightbox-popup-main" class="fade">
<div class="lightbox-popup">
<div class="popup-inner">
<div class="lightbox-left">
<div class="lightbox-header">
<div class="header-title">
<p>
<span>
<img src="images/logo-houzez-white.png" width="86" height="13" alt="logo">
</span>
<span class="hidden-xs">
Oceanfront Villa With Pool - 7601 East Treasure Drive, Miami Beach, FL 33141
</span>
</p>
</div>
<div class="header-actions">
<ul class="actions">
<li class="share-btn">
<div class="share_tooltip tooltip_left fade">
<a href="#" onclick="window.open(this.href, 'mywin','left=50,top=50,width=600,height=350,toolbar=0'); return false;"><i class="fa fa-facebook"></i></a>
<a href="#" onclick="if(!document.getElementById('td_social_networks_buttons')){window.open(this.href, 'mywin','left=50,top=50,width=600,height=350,toolbar=0'); return false;}"><i class="fa fa-twitter"></i></a>
<a href="#" onclick="window.open(this.href, 'mywin','left=50,top=50,width=600,height=350,toolbar=0'); return false;"><i class="fa fa-pinterest"></i></a>
<a href="#" onclick="window.open(this.href, 'mywin','left=50,top=50,width=600,height=350,toolbar=0'); return false;"><i class="fa fa-linkedin"></i></a>
<a href="#" onclick="window.open(this.href, 'mywin','left=50,top=50,width=600,height=350,toolbar=0'); return false;"><i class="fa fa-google-plus"></i></a>
<a href="#"><i class="fa fa-envelope"></i></a>
</div>
<span><i class="fa fa-share-alt"></i></span>
</li>
<li>
<span><i class="fa fa-heart-o"></i></span>
</li>
<li class="lightbox-expand visible-xs compress">
<span><i class="fa fa-envelope-o"></i></span>
</li>
<li class="lightbox-close">
<span><i class="fa fa-close"></i></span>
</li>
</ul>
</div>
</div>
<div class="gallery-area">
<div class="slider-placeholder">
<div class="loader-inner">
<span class="fa fa-spin fa-spinner"></span> Loading Slider...
</div>
</div>
<div class="expand-icon lightbox-expand hidden-xs"></div>
<div class="gallery-inner">
<div class="lightbox-slide slide-animated">
<div>
<img src="http://placehold.it/1044x525" alt="Lightbox Slider" width="1044" height="525">
</div>
<div>
<img src="http://placehold.it/1044x525" alt="Lightbox Slider" width="1044" height="525">
</div>
<div>
<img src="http://placehold.it/1044x525" alt="Lightbox Slider" width="1044" height="525">
</div>
<div>
<img src="http://placehold.it/1044x525" alt="Lightbox Slider" width="1044" height="525">
</div>
<div>
<img src="http://placehold.it/1044x525" alt="Lightbox Slider" width="1044" height="525">
</div>
<div>
<img src="http://placehold.it/1044x525" alt="Lightbox Slider" width="1044" height="525">
</div>
</div>
</div>
<div class="lightbox-slide-nav visible-xs">
<button class="lightbox-arrow-left lightbox-arrow"><i class="fa fa-angle-left"></i></button>
<p class="lightbox-nav-title">Luxury apartment bay view</p>
<button class="lightbox-arrow-right lightbox-arrow"><i class="fa fa-angle-right"></i></button>
</div>
</div>
</div>
<div class="lightbox-right fade in">
<div class="lightbox-header hidden-xs">
<div class="header-title">
<p>$575,000 or $21,000/mo</p>
</div>
<div class="header-actions">
<ul class="actions">
<li class="lightbox-close">
<span><i class="fa fa-close"></i></span>
</li>
</ul>
</div>
</div>
<div class="agent-area">
<div class="form-small">
<div class="agent-media-head">
<h4 class="head-left">Contact info</h4>
<a href="" class="head-right">View my listing</a>
</div>
<div class="media agent-media">
<div class="media-left">
<a href="#">
<img width="100" height="100" alt="image" class="media-object" src="http://placehold.it/100x100">
</a>
</div>
<div class="media-body">
<dl>
<dt>CONTACT AGENT</dt>
<dd><i class="fa fa-user"></i> Brittany Watkins</dd>
<dd><i class="fa fa-phone"></i> 321 456 9874</dd>
</dl>
<ul class="profile-social">
<li><a class="btn-facebook" href="#" target="_blank"><i class="fa fa-facebook-square"></i></a></li>
<li><a class="btn-twitter" href="#" target="_blank"><i class="fa fa-twitter-square"></i></a></li>
<li><a class="btn-linkedin" href="#" target="_blank"><i class="fa fa-linkedin-square"></i></a></li>
<li><a class="btn-google-plus" href="#" target="_blank"><i class="fa fa-google-plus-square"></i></a></li>
</ul>
</div>
</div>
<h4 class="form-small-title"> Inquire about this property </h4>
<form>
<div class="form-group">
<input type="text" placeholder="Your Name" class="form-control">
</div>
<div class="form-group">
<input type="text" placeholder="Phone" class="form-control">
</div>
<div class="form-group">
<input type="email" placeholder="Email" class="form-control">
</div>
<div class="form-group">
<textarea placeholder="Location" rows="2" class="form-control"></textarea>
</div>
<button class="btn btn-secondary btn-block">Request info</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<!--start footer section-->
<footer class="footer-v2">
<div class="footer">
<div class="container">
<div class="row">
<div class="col-sm-3">
<div class="footer-widget widget-about">
<div class="widget-top">
<h3 class="widget-title">About Site</h3>
</div>
<div class="widget-body">
<p>Houzez is a premium WordPress theme for real estate where modern aesthetics are combined with tasteful simplicity.</p>
<p class="read"><a href="about-us.html">Read more <i class="fa fa-caret-right"></i></a></p>
</div>
</div>
</div>
<div class="col-sm-3">
<div class="footer-widget widget-contact">
<div class="widget-top">
<h3 class="widget-title">Contact Us</h3>
</div>
<div class="widget-body">
<ul class="list-unstyled">
<li><i class="fa fa-location-arrow"></i> 121 King Street, Melbourne VIC 3000</li>
<li><i class="fa fa-phone"></i> +1 (877) 987 3487</li>
<li><i class="fa fa-envelope-o"></i> <a href="#">info@housez.com</a></li>
</ul>
<p class="read"><a href="contact-us.html">Contact us <i class="fa fa-caret-right"></i></a></p>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="footer-widget widget-newsletter">
<div class="widget-top">
<h3 class="widget-title">Newsletter Subscribe</h3>
</div>
<div class="widget-body">
<form>
<div class="table-list">
<div class="form-group table-cell">
<div class="input-email input-icon">
<input class="form-control" placeholder="Enter your email">
</div>
</div>
<div class="table-cell">
<button class="btn btn-primary">Submit</button>
</div>
</div>
</form>
<p>Houzez is a premium WordPress theme for real estate agents.<br>Don’t forget to fullow us on:</p>
<ul class="social">
<li>
<a href="#" class="btn-facebook"><i class="fa fa-facebook-square"></i></a>
</li>
<li>
<a href="#" class="btn-twitter"><i class="fa fa-twitter-square"></i></a>
</li>
<li>
<a href="#" class="btn-google-plus"><i class="fa fa-google-plus-square"></i></a>
</li>
<li>
<a href="#" class="btn-linkedin"><i class="fa fa-linkedin-square"></i></a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="footer-bottom">
<div class="container">
<div class="row">
<div class="col-md-3 col-sm-3">
<div class="footer-col">
<p>Houzez - All rights reserved</p>
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="footer-col">
<div class="navi">
<ul id="footer-menu" class="">
<li><a href="privacy.html">Privacy</a></li>
<li><a href="terms-and-conditions.html">Terms and Conditions</a></li>
<li><a href="contact-us.html">Contact</a></li>
</ul>
</div>
</div>
</div>
<div class="col-md-3 col-sm-3">
<div class="footer-col foot-social">
<p>
Follow us
<a target="_blank" class="btn-facebook" href="https://facebook.com/Favethemes"><i class="fa fa-facebook-square"></i></a>
<a target="_blank" class="btn-twitter" href="https://twitter.com/favethemes"><i class="fa fa-twitter-square"></i></a>
<a target="_blank" class="btn-linkedin" href="http://linkedin.com"><i class="fa fa-linkedin-square"></i></a>
<a target="_blank" class="btn-google-plus" href="http://google.com"><i class="fa fa-google-plus-square"></i></a>
<a target="_blank" class="btn-instagram" href="http://instagram.com"><i class="fa fa-instagram"></i></a>
</p>
</div>
</div>
</div>
</div>
</div>
</footer>
<!--end footer section-->
<!--Start Scripts-->
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB0N5pbJN10Y1oYFRd0MJ_v2g8W2QT74JE&callback=initMap"></script>
<script type="text/javascript" src="js/modernizr.custom.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/slick.min.js"></script>
<script type="text/javascript" src="js/owl.carousel.min.js"></script>
<script type="text/javascript" src="js/jquery.prettyPhoto.js"></script>
<script type="text/javascript" src="js/jquery.matchHeight-min.js"></script>
<script type="text/javascript" src="js/bootstrap-select.js"></script>
<script type="text/javascript" src="js/jquery-ui.js"></script>
<script type="text/javascript" src="js/masonry.pkgd.min.js"></script>
<script type="text/javascript" src="js/jquery.nicescroll.js"></script>
<script type="text/javascript" src="js/custom.js"></script>
<script type="text/javascript">
var map = null;
var panorama = null;
var fenway = new google.maps.LatLng(25.762449, -80.188872);
var mapOptions = {
center: fenway,
zoom: 12
};
var panoramaOptions = {
position: fenway,
pov: {
heading: 34,
pitch: 10
}
};
var tabsHeight = function() {
//jQuery(".detail-media .tab-content").css('min-height',jQuery("#gallery").innerHeight());
jQuery("#map,#street-map").css('min-height',jQuery(".detail-media #gallery").innerHeight());
};
jQuery(window).on('load',function(){
tabsHeight();
});
jQuery(window).on('resize',function(){
tabsHeight();
});
function initialize() {
map = new google.maps.Map(document.getElementById('map'), mapOptions);
panorama = new google.maps.StreetViewPanorama(document.getElementById('street-map'), panoramaOptions);
map.setStreetView(panorama);
}
jQuery('a[href="#gallery"]').on('shown.bs.tab', function (e) {
var main_slider = $('.slide');
var nav_slider = $('.slideshow-nav');
main_slider.slick("unslick");
nav_slider.slick("unslick");
main_slider.slick({
speed: 500,
autoplay: false,
autoplaySpeed: 4000,
slidesToShow: 1,
slidesToScroll: 1,
arrows: true,
//fade: true,
accessibility: true,
asNavFor: '.slideshow-nav'
});
nav_slider.slick({
speed: 500,
autoplay: false,
autoplaySpeed: 4000,
slidesToShow: 10,
slidesToScroll: 1,
asNavFor: '.slide',
arrows: false,
dots: false,
centerMode: true,
focusOnSelect: true,
responsive: [
{
breakpoint: 991,
settings:{
slidesToShow: 8
}
},
{
breakpoint: 767,
settings:{
slidesToShow: 4
}
}
]
});
});
jQuery('a[href="#map"]').on('shown.bs.tab', function (e) {
var center = panorama.getPosition();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
jQuery('a[href="#street-map"]').on('shown.bs.tab', function (e) {
fenway = panorama.getPosition();
panoramaOptions.position = fenway;
panorama = new google.maps.StreetViewPanorama(document.getElementById('street-map'), panoramaOptions);
map.setStreetView(panorama);
});
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</body>
</html> | {
"content_hash": "8436253562acfdbff2fceeb80852c24e",
"timestamp": "",
"source": "github",
"line_count": 1740,
"max_line_length": 550,
"avg_line_length": 64.1867816091954,
"alnum_prop": 0.3434301831042665,
"repo_name": "lucianoiw/imobler",
"id": "317b57e4559484a0c38b2b1ae390fcec7f8dbb89",
"size": "111711",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_apoio/houzez-html/property-detail-v3.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "32356"
},
{
"name": "ApacheConf",
"bytes": "833"
},
{
"name": "CSS",
"bytes": "17955583"
},
{
"name": "HTML",
"bytes": "21901185"
},
{
"name": "JavaScript",
"bytes": "9536597"
},
{
"name": "PHP",
"bytes": "2344167"
},
{
"name": "Ruby",
"bytes": "1829"
},
{
"name": "Shell",
"bytes": "2980"
},
{
"name": "TypeScript",
"bytes": "4696"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "7077daa2c046d3addad34b61908cf5a1",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "3244b2dfae39ef723707989c1d438183570bc089",
"size": "187",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Galium/Galium hystricocarpum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
Bank Project
## License
This project is licensed under the MIT license. For more information see `LICENSE.md`.
| {
"content_hash": "eed6d82e74b7e33ab90cbf8a25426adc",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 86,
"avg_line_length": 22.6,
"alnum_prop": 0.7699115044247787,
"repo_name": "rodrigoTrespalacios/project-bank",
"id": "33bda3800e9f0949c3d5796e063279906b01dc7f",
"size": "113",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1526"
},
{
"name": "CSS",
"bytes": "120"
},
{
"name": "HTML",
"bytes": "9196"
},
{
"name": "JavaScript",
"bytes": "76362"
}
],
"symlink_target": ""
} |
<component name="libraryTable">
<library name="support-media-compat-24.2.1">
<CLASSES>
<root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/support-media-compat/24.2.1/res" />
<root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/support-media-compat/24.2.1/jars/libs/internal_impl-24.2.1.jar!/" />
<root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/support-media-compat/24.2.1/jars/classes.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://E:/sdk1122-lite/extras/android/m2repository/com/android/support/support-media-compat/24.2.1/support-media-compat-24.2.1-sources.jar!/" />
</SOURCES>
</library>
</component> | {
"content_hash": "e2ef4edf0438e4f537045831e0b19178",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 162,
"avg_line_length": 59.84615384615385,
"alnum_prop": 0.7005141388174807,
"repo_name": "sunxiao123/coolweather",
"id": "54a821e8b8e1a950102bfb7402e545bf50aa00b5",
"size": "778",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/libraries/support_media_compat_24_2_1.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "37126"
}
],
"symlink_target": ""
} |
FactoryGirl.define do
factory :menu do
name "Dinner"
association :merchant
trait :with_items do
after(:create) do |menu|
create_list(:menu_item, 20, menu: menu)
end
end
end
end
| {
"content_hash": "9c878fb5933e1b33cfad80620f5a4c46",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 47,
"avg_line_length": 18.166666666666668,
"alnum_prop": 0.6146788990825688,
"repo_name": "enova/level_up_exercises",
"id": "9147ed934273dced2a0ce405cb23e9788fb8624c",
"size": "218",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "find_me_a_sandwich/factories/menus.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1616"
},
{
"name": "CoffeeScript",
"bytes": "633"
},
{
"name": "Cucumber",
"bytes": "1525"
},
{
"name": "HTML",
"bytes": "33346"
},
{
"name": "JavaScript",
"bytes": "1317"
},
{
"name": "Ruby",
"bytes": "153694"
}
],
"symlink_target": ""
} |
from .test_database import *
from .test_settings import *
| {
"content_hash": "5ae9acbdfa3e4a72caaa2f66227dd67a",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 28,
"avg_line_length": 29,
"alnum_prop": 0.7586206896551724,
"repo_name": "msincenselee/vnpy",
"id": "c5776fc1da34522acc7a18e46fba4db62c4fd538",
"size": "58",
"binary": false,
"copies": "2",
"ref": "refs/heads/vnpy2",
"path": "tests/trader/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "751"
},
{
"name": "C",
"bytes": "2862615"
},
{
"name": "C++",
"bytes": "14985812"
},
{
"name": "Cython",
"bytes": "42495"
},
{
"name": "Python",
"bytes": "12716181"
},
{
"name": "Shell",
"bytes": "17068"
}
],
"symlink_target": ""
} |
package com.navercorp.pinpoint.hbase.schema.reader.xml;
import com.navercorp.pinpoint.hbase.schema.reader.HbaseSchemaParseException;
import com.navercorp.pinpoint.hbase.schema.reader.HbaseSchemaReader;
import com.navercorp.pinpoint.hbase.schema.reader.core.ChangeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.ResourceUtils;
import org.xml.sax.InputSource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.List;
/**
* @author HyunGil Jeong
*/
public class XmlHbaseSchemaReader implements HbaseSchemaReader {
public static final String DEFAULT_HBASE_SCHEMA_PATH = "classpath:hbase-schema/hbase-schema.xml";
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final ResourceLoader resourceLoader = new FileSystemResourceLoader();
private final XmlHbaseSchemaParser xmlHbaseSchemaParser = new XmlHbaseSchemaParser();
/**
* Loads change sets from the hbase schema xml file from the default path - {@value DEFAULT_HBASE_SCHEMA_PATH}.
*
* @return list of change sets loaded
* @throws HbaseSchemaParseException if there was a problem reading or parsing from the schema xml file
*/
@Override
public List<ChangeSet> loadChangeSets() {
return loadChangeSets(DEFAULT_HBASE_SCHEMA_PATH);
}
/**
* Loads change sets from the hbase schema xml file at the given path.
*
* @param path path to hbase schema xml file
* @return list of change sets loaded
* @throws HbaseSchemaParseException if there was a problem reading or parsing from the schema xml file
*/
@Override
public List<ChangeSet> loadChangeSets(String path) {
Resource resource = resourceLoader.getResource(path);
XmlParseContext xmlParseContext = new XmlParseContext(resource);
try {
loadChangeSets(xmlParseContext);
} catch (HbaseSchemaParseException e) {
logger.error("Error loading change sets from {}", xmlParseContext.getResource(), e);
throw e;
} catch (Exception e) {
logger.error("Error loading change sets from {}", xmlParseContext.getResource(), e);
throw new HbaseSchemaParseException("Error loading change sets from " + xmlParseContext.getResource(), e);
}
return xmlParseContext.getChangeSets();
}
private void loadChangeSets(XmlParseContext xmlParseContext) throws IOException {
Resource resource = xmlParseContext.getResource();
XmlHbaseSchemaParseResult parseResult = readHbaseSchema(resource);
for (String includeFile : parseResult.getIncludeFiles()) {
Resource includeResource = createResource(resource, includeFile);
xmlParseContext.setResource(includeResource);
loadChangeSets(xmlParseContext);
}
xmlParseContext.addChangeSets(parseResult.getChangeSets());
}
private Resource createResource(Resource currentResource, String path) throws IOException {
if (isAbsolutePath(path)) {
return resourceLoader.getResource(path);
}
return currentResource.createRelative(path);
}
private XmlHbaseSchemaParseResult readHbaseSchema(Resource resource) throws IOException {
try (InputStream inputStream = resource.getInputStream()) {
InputSource inputSource = new InputSource(inputStream);
return xmlHbaseSchemaParser.parseSchema(inputSource);
}
}
private boolean isAbsolutePath(String path) {
if (path.startsWith("/") || path.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) {
return true;
}
try {
return ResourceUtils.toURI(path).isAbsolute();
} catch (URISyntaxException e) {
// conversion failed, assume relative
return false;
}
}
}
| {
"content_hash": "3e78f7e65af809856ea2a7fc75f6a225",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 118,
"avg_line_length": 39.36538461538461,
"alnum_prop": 0.7090864680019541,
"repo_name": "suraj-raturi/pinpoint",
"id": "e181da64a3fa5fa75c6242652043d0ff37bdfb13",
"size": "4688",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "hbase/hbase-schema/src/main/java/com/navercorp/pinpoint/hbase/schema/reader/xml/XmlHbaseSchemaReader.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "22853"
},
{
"name": "CSS",
"bytes": "133944"
},
{
"name": "CoffeeScript",
"bytes": "10124"
},
{
"name": "Groovy",
"bytes": "1423"
},
{
"name": "HTML",
"bytes": "473809"
},
{
"name": "Java",
"bytes": "8699243"
},
{
"name": "JavaScript",
"bytes": "2277035"
},
{
"name": "Makefile",
"bytes": "5246"
},
{
"name": "PLSQL",
"bytes": "4156"
},
{
"name": "Python",
"bytes": "3523"
},
{
"name": "Ruby",
"bytes": "943"
},
{
"name": "Shell",
"bytes": "30663"
},
{
"name": "Thrift",
"bytes": "7543"
}
],
"symlink_target": ""
} |
package shedar.mods.ic2.nuclearcontrol.blocks.subblocks;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IIcon;
import shedar.mods.ic2.nuclearcontrol.IC2NuclearControl;
import shedar.mods.ic2.nuclearcontrol.containers.ContainerAverageCounter;
import shedar.mods.ic2.nuclearcontrol.gui.GuiAverageCounter;
import shedar.mods.ic2.nuclearcontrol.tileentities.TileEntityAverageCounter;
import shedar.mods.ic2.nuclearcontrol.utils.BlockDamages;
public class AverageCounter extends Subblock {
private static final int DAMAGE = BlockDamages.DAMAGE_AVERAGE_COUNTER;
private static final float[] BOUNDS = { 0, 0, 0, 1, 1, 1 };
public static final byte I_INPUT = 0;
public static final byte I_OUTPUT = 1;
private static final byte[][] mapping = {
{ I_OUTPUT, I_INPUT, I_OUTPUT, I_OUTPUT, I_OUTPUT, I_OUTPUT },
{ I_INPUT, I_OUTPUT, I_OUTPUT, I_OUTPUT, I_OUTPUT, I_OUTPUT },
{ I_OUTPUT, I_OUTPUT, I_OUTPUT, I_INPUT, I_OUTPUT, I_OUTPUT },
{ I_OUTPUT, I_OUTPUT, I_INPUT, I_OUTPUT, I_OUTPUT, I_OUTPUT },
{ I_OUTPUT, I_OUTPUT, I_OUTPUT, I_OUTPUT, I_OUTPUT, I_INPUT },
{ I_OUTPUT, I_OUTPUT, I_OUTPUT, I_OUTPUT, I_INPUT, I_OUTPUT } };
private IIcon[] icons = new IIcon[2];
public AverageCounter() {
super(DAMAGE, "tile.blockAverageCounter");
}
@Override
public TileEntity getTileEntity() {
TileEntity instance = IC2NuclearControl.instance.crossRF.getAverageCounter();
if (instance == null)
instance = new TileEntityAverageCounter();
//TileEntity instance = new TileEntityAverageCounter();
return instance;
}
@Override
public boolean isSolidBlockRequired() {
return false;
}
@Override
public boolean hasGui() {
return true;
}
@Override
public float[] getBlockBounds(TileEntity tileEntity) {
return BOUNDS;
}
@Override
public Container getServerGuiElement(TileEntity tileEntity,
EntityPlayer player) {
return new ContainerAverageCounter(player,
(TileEntityAverageCounter) tileEntity);
}
@Override
public Object getClientGuiElement(TileEntity tileEntity, EntityPlayer player) {
ContainerAverageCounter containerAverageCounter = new ContainerAverageCounter(
player, (TileEntityAverageCounter) tileEntity);
return new GuiAverageCounter(containerAverageCounter);
}
@Override
public IIcon getIcon(int index) {
return icons[index];
}
@Override
protected byte[][] getMapping() {
return mapping;
}
@Override
public void registerIcons(IIconRegister iconRegister) {
icons[I_INPUT] = iconRegister
.registerIcon("nuclearcontrol:averageCounter/input");
icons[I_OUTPUT] = iconRegister
.registerIcon("nuclearcontrol:averageCounter/output");
}
}
| {
"content_hash": "a4be9eb385611a322500190c02ae6faa",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 80,
"avg_line_length": 31.47826086956522,
"alnum_prop": 0.7327348066298343,
"repo_name": "Chocohead/Nuclear-Control",
"id": "91bafb5a312a51ff7e78578fa37317a551b2c369",
"size": "2896",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "src/main/java/shedar/mods/ic2/nuclearcontrol/blocks/subblocks/AverageCounter.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "628896"
}
],
"symlink_target": ""
} |
/**
* Library methods for server tasks
*
* @author Nikhil Modak
*/
'use strict';
var path = require('path');
module.exports = function (gulp, gutil) {
var serverConfig = {};
var serverConfigPath = gutil.env.serverConfig || 'server.conf.json';
var defaults = {
serverUrl: undefined,
pluginToken: undefined,
community: undefined,
strictMode: false,
dryRun: false,
allowStudioOverrides: false,
toolVersion: '1.0.0',
verbose: false,
force: false,
pluginPoints: [],
sdkOutputDir: undefined,
coreOutputDir: 'coreplugin',
configDir: 'configs',
useLocalCompile: false,
localSkinCompileVersion: 'v2-lia16.6',
localSkinCompileSkin: 'responsive_peak',
localSkinCompileFeature: 'responsivepeak',
localSkinCompileDest: '.tmp/lia/styles',
localServerDir: '.tmp/lia',
localServerPort: 9000,
useResponsiveConfigsFromServer: false,
skipTemplateValidation: false,
//Hack to copy files to plugin - until sandbox is fully supported.
sandboxPluginDir: undefined,
pluginReloadUrl: '/t5/api/plugin'
};
try {
serverConfig = gutil.env.useServerDefaults ? {} : require(path.join(process.cwd(), serverConfigPath));
} catch (err) {
process.exitCode = 1;
throw new Error('Error reading server.conf.json at [' +
path.join(process.cwd(), serverConfigPath) +
']. Please use template.server.conf.json to create server.conf.json.');
}
Object.keys(defaults).forEach(function (key) {
if (!serverConfig.hasOwnProperty(key) || serverConfig[key] === undefined) {
serverConfig[key] = defaults[key];
}
});
var serverApi = {};
Object.keys(serverConfig).forEach(function (key) {
serverApi[key] = function () {
return serverConfig[key];
};
});
serverApi.pluginUploadProtocol = function() {
var serverUrl = serverApi.serverUrl();
if (serverUrl && serverUrl.indexOf('http://') > -1) {
return 'http';
}
return 'https';
};
return serverApi;
};
| {
"content_hash": "40971f94f4ab1070dbc0454367267df3",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 106,
"avg_line_length": 26.181818181818183,
"alnum_prop": 0.660218253968254,
"repo_name": "lithiumtech/lithium-sdk",
"id": "e02645017b2236664a5d020e21f318706afd933a",
"size": "2016",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "lib/server.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "60"
},
{
"name": "JavaScript",
"bytes": "280092"
},
{
"name": "SCSS",
"bytes": "292892"
}
],
"symlink_target": ""
} |
#pragma once
namespace Chrysalis
{
/** An object identifier used where a globally unique identifier is required. Id's need to be generated by a
specialised factory class that is capable of encapsulating all the rules for making a useful Id with minimal
or no chance of clashes. This needs to be OS agnostic are memory sensible.
The ID is tightly packed into a single 64 bit unsigned integer value. With 0 representing the highest order
bit (will this work on big endian machines?), the bits are laid out as follows. Do not rely on this for a sort
order, since clocks may not be correctly synced between systems. Don't be tempted to directly twiddle with
the bits, use the accessors provided instead.
0-31 : Number of seconds since Unix epoch.
32-49 : An instance ID that is unique for every running instance of this code. These need to be unique
and should be carefully assigned on a as-needed basis.
50-63 : A random component. Each second a new starting point is generated, and it increments with each
Id generated during that second. This forces a hard limit on the number of Ids that can be generated
in a single second. Currently this limit is 16,384. /
*/
typedef uint64_t ObjectId;
/** A factory class needed to properly construct valid ObjectIds. The class is dependant on
having a valid instanceId prior to instantiation.
It is recommended that you create an instance of this factory for every entity class where you think
you will need to create more the hard limit of ObjectId's / second. Currently, this limit is 16,384.
*/
class CObjectIdFactory
{
public:
/** The number of bits allocated to store seconds since epoch. */
static const int SecondsSinceEpochBits {32};
/** The number of bits allocated to store the instance identifier. */
static const int InstanceIdBits {18};
/** The number of bits allocated to store the random variant bits. */
static const int RandomVariantBits {14};
/** Identifier for the maximum instance. */
static const uint32 MaxInstanceId {(1 << InstanceIdBits) - 1};
/** The maximum random variant. */
static const uint32 MaxRandomVariant {(1 << RandomVariantBits) - 1};
/** Magic number to signify an invalid ID. */
static const ObjectId InvalidId {0};
/**
Constructor.
\param instanceId Identifier for the instance.
*/
CObjectIdFactory(uint32 instanceId);
/**
Makes a request to the factory to create a new valid ObjectId.
Only the factory should be allowed to construct these, since it has all the information needed to ensure the key is
generated correctly.
\return The new object identifier.
*/
ObjectId CreateObjectId();
/**
Gets seconds since epoch.
\return The seconds since epoch.
*/
uint32 GetSecondsSinceEpoch(ObjectId objectId);
/**
Gets instance identifier.
\return The instance identifier.
*/
uint32 GetInstanceId(ObjectId objectId);
/**
Gets random variant.
\return The random variant.
*/
uint32 GetRandomVariant(ObjectId objectId);
private:
uint32 m_instanceId;
uint32 m_randomVariant;
uint32 m_lastRandomVariantSeed;
int32 m_secondsSinceEpoch;
// DO NOT IMPLEMENT.
CObjectIdFactory();
};
} | {
"content_hash": "c4dfa1d3f67363051d7d143fb7b220ad",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 116,
"avg_line_length": 29.723809523809525,
"alnum_prop": 0.7600128164049984,
"repo_name": "ivanhawkes/Chrysalis",
"id": "e89f00d5cfc8fff2bb0833d9186f8fcba4dffe2a",
"size": "3121",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/ChrysalisCore/ObjectID/ObjectId.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Ada",
"bytes": "10806"
},
{
"name": "Batchfile",
"bytes": "557"
},
{
"name": "C",
"bytes": "7963"
},
{
"name": "C++",
"bytes": "947400"
},
{
"name": "CMake",
"bytes": "22061"
},
{
"name": "Mathematica",
"bytes": "3107"
},
{
"name": "Roff",
"bytes": "647"
}
],
"symlink_target": ""
} |
package com.esri.samples.display_layer_view_state;
/**
* Wrapper required for launching a JavaFX 11 app through Gradle or from a jar.
*/
public class DisplayLayerViewStateLauncher {
public static void main(String[] args) {
DisplayLayerViewStateSample.main(args);
}
}
| {
"content_hash": "46a0f43a4c1c98572e749ab3efe77154",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 78,
"avg_line_length": 25.272727272727273,
"alnum_prop": 0.7517985611510791,
"repo_name": "Esri/arcgis-runtime-samples-java",
"id": "02192b61d8e3091f22fbe5a05f63e37acd3369bc",
"size": "278",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "map_view/display-layer-view-state/src/main/java/com/esri/samples/display_layer_view_state/DisplayLayerViewStateLauncher.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "28447"
},
{
"name": "Java",
"bytes": "1787508"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_51) on Sun Apr 20 22:36:38 SAST 2014 -->
<title>ForeignKey</title>
<meta name="date" content="2014-04-20">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ForeignKey";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ForeignKey.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li><a href="../../../../../../za/co/neilson/sqlite/orm/annotations/Nullable.html" title="annotation in za.co.neilson.sqlite.orm.annotations"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?za/co/neilson/sqlite/orm/annotations/ForeignKey.html" target="_top">Frames</a></li>
<li><a href="ForeignKey.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#annotation_type_required_element_summary">Required</a> | </li>
<li><a href="#annotation_type_optional_element_summary">Optional</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#annotation_type_element_detail">Element</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">za.co.neilson.sqlite.orm.annotations</div>
<h2 title="Annotation Type ForeignKey" class="title">Annotation Type ForeignKey</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>@Target(value=FIELD)
@Retention(value=RUNTIME)
public @interface <span class="strong">ForeignKey</span></pre>
<div class="block"><p>
Designates an ObjectModel property as a foreign key reference to another
ObjectModel. The foreign key must reference the primary key of the foreign
table using the <b>table</b> and <b>column</b> parameters.
</p>
<p>
By convention, the table name will be the same as the referenced Type's name and the column name will
be the same as the name of the Field referenced.
</p>
<p>
Where a normal Field references the the primary key of the foreign
table a one-to-one relationship is formed.
</p>
<p>
If the field decorated with the foreign key attribute is also the primary key of
the table, a one-to-one relationship is formed.
</p></div>
<dl><dt><span class="strong">Since:</span></dt>
<dd>0.1</dd>
<dt><span class="strong">Version:</span></dt>
<dd>0.1</dd>
<dt><span class="strong">Author:</span></dt>
<dd><a href="http://www.neilson.co.za">Sheldon Neilson</a></dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== ANNOTATION TYPE REQUIRED MEMBER SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="annotation_type_required_element_summary">
<!-- -->
</a>
<h3>Required Element Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Required Element Summary table, listing required elements, and an explanation">
<caption><span>Required Elements</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Required Element and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../../../za/co/neilson/sqlite/orm/annotations/ForeignKey.html#column()">column</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../../../za/co/neilson/sqlite/orm/annotations/ForeignKey.html#table()">table</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- =========== ANNOTATION TYPE OPTIONAL MEMBER SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="annotation_type_optional_element_summary">
<!-- -->
</a>
<h3>Optional Element Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Optional Element Summary table, listing optional elements, and an explanation">
<caption><span>Optional Elements</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Optional Element and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../../../za/co/neilson/sqlite/orm/annotations/ForeignKey.html#childReference()">childReference</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../../../za/co/neilson/sqlite/orm/annotations/ForeignKey.html#parentReference()">parentReference</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ ANNOTATION TYPE MEMBER DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="annotation_type_element_detail">
<!-- -->
</a>
<h3>Element Detail</h3>
<a name="table()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>table</h4>
<pre>public abstract java.lang.String table</pre>
</li>
</ul>
<a name="column()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>column</h4>
<pre>public abstract java.lang.String column</pre>
</li>
</ul>
<a name="childReference()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>childReference</h4>
<pre>public abstract java.lang.String childReference</pre>
<dl>
<dt>Default:</dt>
<dd>""</dd>
</dl>
</li>
</ul>
<a name="parentReference()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>parentReference</h4>
<pre>public abstract java.lang.String parentReference</pre>
<dl>
<dt>Default:</dt>
<dd>""</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ForeignKey.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li><a href="../../../../../../za/co/neilson/sqlite/orm/annotations/Nullable.html" title="annotation in za.co.neilson.sqlite.orm.annotations"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?za/co/neilson/sqlite/orm/annotations/ForeignKey.html" target="_top">Frames</a></li>
<li><a href="ForeignKey.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#annotation_type_required_element_summary">Required</a> | </li>
<li><a href="#annotation_type_optional_element_summary">Optional</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#annotation_type_element_detail">Element</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "516ecef5b95594a530ffcf758acaefc3",
"timestamp": "",
"source": "github",
"line_count": 285,
"max_line_length": 189,
"avg_line_length": 33.863157894736844,
"alnum_prop": 0.637446896694643,
"repo_name": "SheldonNeilson/SQLite-Database-Model",
"id": "c120b6a652950597d1afaecd6bb1005ab57edd54",
"size": "9651",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SQLite Database Model JDBC/doc/za/co/neilson/sqlite/orm/annotations/ForeignKey.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "33417"
},
{
"name": "Java",
"bytes": "460272"
}
],
"symlink_target": ""
} |
import fs from 'fs';
import path from 'path';
import injectDecorator from './inject-decorator';
describe('inject-decorator', () => {
describe('positive - ts - csf', () => {
it('includes storySource parameter in the default exported object', () => {
const mockFilePath = './__mocks__/inject-decorator.ts.csf.txt';
const source = fs.readFileSync(mockFilePath, 'utf-8');
const result = injectDecorator(source, path.resolve(__dirname, mockFilePath), {
parser: 'typescript',
});
expect(result.source).toMatchSnapshot();
expect(result.source).toEqual(
expect.stringContaining(
'export default {parameters: {"storySource":{"source":"import React from'
)
);
});
});
describe('injectStoryParameters - ts - csf', () => {
it('includes storySource parameter in the default exported object', () => {
const mockFilePath = './__mocks__/inject-parameters.ts.csf.txt';
const source = fs.readFileSync(mockFilePath, 'utf-8');
const result = injectDecorator(source, path.resolve(__dirname, mockFilePath), {
injectStoryParameters: true,
parser: 'typescript',
});
expect(result.source).toMatchSnapshot();
});
});
});
| {
"content_hash": "b580e72e7daac2d07328f8cb4c86cd03",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 85,
"avg_line_length": 35.57142857142857,
"alnum_prop": 0.629718875502008,
"repo_name": "storybooks/react-storybook",
"id": "c26acb5cb834d2a000176c53372e0589c3e5d34b",
"size": "1245",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "lib/source-loader/src/abstract-syntax-tree/inject-decorator.csf.test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9157"
},
{
"name": "HTML",
"bytes": "5560"
},
{
"name": "JavaScript",
"bytes": "325573"
},
{
"name": "Shell",
"bytes": "7563"
},
{
"name": "TypeScript",
"bytes": "2617"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<context:annotation-config />
<context:spring-configured />
<tx:jta-transaction-manager />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder">
<constructor-arg value="MD5"/>
</bean>
<bean id="notificationTemplateMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="a.vincelli@gmail.com"/>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:it/av/youeat/web/YoueatApplication"/>
<property name="fallbackToSystemLocale" value="true" />
<property name="cacheSeconds" value="-1"/>
</bean>
<bean id="javaMailSender" class="it.av.youeat.web.util.MockJavaMailSender" >
<!-- <property name="host" value="127.0.0.1"/> -->
</bean>
<bean id="mailService" class="it.av.youeat.service.system.MailServiceImpl" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="youeatPersistence" />
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"/>
</bean>
<!-- <bean id="entityManagerFactoryStaticData" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="staticDataPersistance" />
<property name="persistenceXmlLocation" value="classpath:META-INF/persistenceStaticData.xml"></property>
</bean> -->
<!--
PostProcessors to perform resource injection according to the JPA specification
(@PersistenceContext, @PersistenceUnit).
-->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<!-- turn on @Required annotation checks -->
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
<!--
PostProcessors to perform exception translation on @Repository classes (from native
exceptions such as JPA PersistenceExceptions to Spring's DataAccessException hierarchy).
-->
<!-- Transaction manager for a single JPA EntityManagerFactory (alternative to JTA) -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="nestedTransactionAllowed" value="false"></property>
</bean>
<!-- <bean id="wicketApplication" class="it.av.youeat.web.YouetApplicationMock">
<property name="applicationURL" value="http://www.youeat.org"/>
</bean> -->
<bean id="eaterService" class="it.av.youeat.service.impl.EaterServiceHibernate" />
<bean id="commentService" class="it.av.youeat.service.impl.CommentServiceHibernate"/>
<bean id="eaterProfileService" class="it.av.youeat.service.impl.EaterProfileServiceHibernate"/>
<bean id="activityService" class="it.av.youeat.service.impl.ActivityServiceHibernate" />
<bean id="activityRistoranteService" class="it.av.youeat.service.impl.ActivityRistoranteServiceHibernate" />
<bean id="tagService" class="it.av.youeat.service.impl.TagServiceHibernate" />
<bean id="ristoranteRevisionService" class="it.av.youeat.service.impl.RistoranteRevisionServiceHibernate"/>
<bean id="rateRistoranteService" class="it.av.youeat.service.impl.RateRistoranteServiceHibernate"/>
<bean id="ristoranteService" class="it.av.youeat.service.impl.RistoranteServiceHibernate" />
<bean id="ristorantePositionService" class="it.av.youeat.service.impl.RistorantePositionServiceHibernate"/>
<!--<bean id="jcrRistoranteService" class="it.av.youeat.service.impl.JcrRistoranteServiceJackrabbit">
<property name="jcrMappingtemplate" ref="jcrMappingTemplateGeneric" />
<property name="basePath" value="/ristoranti" />
</bean>-->
<bean id="eaterRelationService" class="it.av.youeat.service.impl.EaterRelationServiceHibernate" />
<bean id="activityRelationService" class="it.av.youeat.service.impl.ActivityRelationServiceHibernate" />
<bean id="dataRistoranteService" class="it.av.youeat.service.impl.DataRistoranteServiceHibernate" />
<bean id="countryRegionService" class="it.av.youeat.service.impl.CountryRegionServiceHibernate" />
<bean id="countryService" class="it.av.youeat.service.impl.CountryServiceHibernate" />
<bean id="cityService" class="it.av.youeat.service.impl.CityServiceHibernate" />
<bean id="languageService" class="it.av.youeat.service.impl.LanguageServiceHibernate" />
<bean id="messageService" class="it.av.youeat.service.impl.MessageServiceHibernate" />
<bean id="dialogService" class="it.av.youeat.service.impl.DialogServiceHibernate" />
<bean id="ristorantePictureHibernate" class="it.av.youeat.service.impl.RistorantePictureHibernate" />
<bean id="userDetailsService" class="it.av.youeat.web.security.UserDetailsServiceImpl" scope="prototype">
<property name="service" ref="eaterService" />
</bean>
<bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userDetailsService" />
<property name="passwordEncoder" ref="passwordEncoder" />
<property name="saltSource">
<bean id="saltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource">
<property name="userPropertyToUse" value="passwordSalt"></property>
</bean>
</property>
</bean>
<bean id="facebookAuthenticationProvider" class="it.av.youeat.web.security.FacebookAuthenticationProvider"/>
<bean id="authenticationProvider" class="it.av.youeat.web.security.AuthenticationProvider">
<constructor-arg ref="daoAuthenticationProvider" />
<constructor-arg ref="facebookAuthenticationProvider" />
</bean>
<bean id="serverGeocoder" class="it.av.youeat.util.ServerGeocoder">
<constructor-arg value="ABQIAAAAEpqZyWLxrLSc1icxiiTLyBRjFP5Ion2TodTauLHyn40LiCPQaRSoBSldN1pDUDTAPEK5AlXpouSLuA"></constructor-arg>
</bean>
<bean id="periodUtil" class="it.av.youeat.util.PeriodUtil"/>
<bean id="templateUtil" class="it.av.youeat.util.TemplateUtil"/>
<bean id="socialServiceFacebook" class="it.av.youeat.service.impl.SocialServiceFacebook">
<property name="apiKey" value=""/>
<property name="secret" value=""/>
<property name="applicationID" value=""/>
</bean>
<bean id="prepareMessage" class="it.av.youeat.service.support.PrepareMessage"/>
<bean id="faceBookAuthHandler" class="it.av.youeat.web.security.FaceBookAuthHandler">
<property name="apiKey" value=""/>
<property name="secret" value=""/>
</bean>
<bean id="googleSitemapGenerator" class="it.av.youeat.web.xml.GoogleSitemapGenerator">
<property name="baseURL" value="http://www.youeat.org"></property>
</bean>
<bean id="youetGeneratorURL" class="it.av.youeat.web.url.YouetGeneratorURL">
<property name="baseURL" value="http://www.youeat.org"></property>
</bean>
<bean id="atomGenerator" class="it.av.youeat.web.xml.AtomGenerator"/>
<bean id="jaxbObjectMapper" class="it.av.youeat.web.rest.JaxbObjectMapper" />
<bean id="mappingJacksonJsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="objectMapper" ref="jaxbObjectMapper"/>
</bean>
</beans> | {
"content_hash": "649b571d84c95ba1aa270d743d3b1dae",
"timestamp": "",
"source": "github",
"line_count": 180,
"max_line_length": 132,
"avg_line_length": 47.605555555555554,
"alnum_prop": 0.7418601937215544,
"repo_name": "alessandro-vincelli/youeat",
"id": "3a5dac678eba92de854a0b8a90010ddb8c6a5c2b",
"size": "8569",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/resources/test-application-context.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "24773"
},
{
"name": "HTML",
"bytes": "96548"
},
{
"name": "Java",
"bytes": "1025564"
},
{
"name": "JavaScript",
"bytes": "948"
}
],
"symlink_target": ""
} |
<h3>Place your static files here</h3>
| {
"content_hash": "f5c6e627b686506790bf46cd4401e946",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 37,
"avg_line_length": 38,
"alnum_prop": 0.7368421052631579,
"repo_name": "beeman/complex-node-deployment",
"id": "a74b96618e1eae39c771353618c48cb1b7dd2d81",
"size": "38",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "static/public/readme.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "59"
},
{
"name": "JavaScript",
"bytes": "3580"
}
],
"symlink_target": ""
} |
import { NgModule, ErrorHandler } from '@angular/core';
import { HttpModule, Http } from '@angular/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { Storage, IonicStorageModule } from '@ionic/storage';
import { Angular2SocialLoginModule } from 'angular2-social-auth';
let providers = {
"google": {
"clientId": "278476534761-mav7dltvekh7vt8n2osvmjcuqb5k0e8n.apps.googleusercontent.com"
},
"facebook": {
"clientId": "551001138392957",
"apiVersion": "v2.5"
}
};
import { AppComponent } from './app.component';
import { SignInPage } from './pages/signin/signin';
import { SignUpPage } from './pages/signup/signup';
import { TutorialPage } from './pages/tutorial/tutorial';
import { WelcomePage } from './pages/welcome/welcome';
import { SupportPage } from './pages/support/support';
import { EventListPage } from './pages/event-list/event-list';
import { AboutPage } from './pages/about/about';
import { PopoverPage } from './pages/about-popover/about-popover';
import { EventCreatePage } from './pages/event-create/event-create';
import { CategoryDetailPage } from './pages/category-detail/category-detail';
import { CategoryListPage } from './pages/category-list/category-list';
import { MapPage } from './pages/map/map';
import { SettingsPage } from './pages/settings/settings';
import { EventTabsPage } from './pages/event-tabs/event-tabs';
import { Auth, Categories, Events, Settings, WebFacebook, WebGooglePlus } from './providers';
import { Camera } from '@ionic-native/camera';
import { GoogleMaps } from '@ionic-native/google-maps';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { GooglePlus } from '@ionic-native/google-plus';
import { Facebook } from '@ionic-native/facebook';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { ApolloModule } from 'apollo-angular';
import { provideClient } from './providers/client';
// The translate loader needs to know where to load i18n files
// in Ionic's static asset pipeline.
export function HttpLoaderFactory(http: Http) {
return new TranslateHttpLoader(http, 'assets/i18n/', '.json');
}
export function provideSettings(storage: Storage) {
/**
* The Settings provider takes a set of default settings for your app.
*
* You can add new settings options at any time. Once the settings are saved,
* these values will not overwrite the saved values (this can be done manually if desired).
*/
return new Settings(storage, {
option1: true,
option2: 'Ionitron J. Framework',
option3: '3',
option4: 'Hello'
});
}
/**
* The Pages array lists all of the pages we want to use in our app.
* We then take these pages and inject them into our NgModule so Angular
* can find them. As you add and remove pages, make sure to keep this list up to date.
*/
let pages = [
AppComponent,
SignInPage,
SignUpPage,
TutorialPage,
WelcomePage,
SupportPage,
EventListPage,
EventTabsPage,
EventCreatePage,
AboutPage,
PopoverPage,
CategoryDetailPage,
MapPage,
SettingsPage,
CategoryListPage
];
export function declarations() {
return pages;
}
export function entryComponents() {
return pages;
}
@NgModule({
imports: [
IonicModule.forRoot(AppComponent),
HttpModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [Http]
}
}),
BrowserAnimationsModule,
Angular2SocialLoginModule,
IonicStorageModule.forRoot(),
// Define the default ApolloClient
ApolloModule.withClient(provideClient)
],
declarations: declarations(),
entryComponents: entryComponents(),
bootstrap: [IonicApp],
providers: [
Auth,
Categories,
Events,
Camera,
GoogleMaps,
SplashScreen,
StatusBar,
{ provide: Facebook, useClass: build.target === 'cordova' ? Facebook : WebFacebook },
{ provide: GooglePlus, useClass: build.target === 'cordova' ? GooglePlus : WebGooglePlus },
{ provide: Settings, useFactory: provideSettings, deps: [Storage] },
// Keep this to enable Ionic's runtime error handling during development
{ provide: ErrorHandler, useClass: IonicErrorHandler }
]
})
export class AppModule { }
Angular2SocialLoginModule.loadProvidersScripts(providers);
| {
"content_hash": "942add6b941d1e9c8eec980617627555",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 95,
"avg_line_length": 32.364285714285714,
"alnum_prop": 0.7152946369454867,
"repo_name": "Iulian-Stan/angular4-ionic3-webpack2",
"id": "ea278186ea293d4f0c342ef91519c122763ab5ec",
"size": "4531",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/app.module.ts",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "13485"
},
{
"name": "HTML",
"bytes": "15680"
},
{
"name": "JavaScript",
"bytes": "6329"
},
{
"name": "TypeScript",
"bytes": "45784"
}
],
"symlink_target": ""
} |
<?php
namespace app;
//Load app autoloader
require_once __DIR__ . '/autoload.php';
//Load environment config
require_once __DIR__ . '/config/config_dev.inc.php';
require_once __DIR__ . '/config/config_demo.inc.php';
require_once __DIR__ . '/config/config_prod.inc.php';
require_once __DIR__ . '/filters.php';
//Load routes
foreach (glob(__DIR__ . "/routes/*.php") as $filename)
{
require $filename;
}
//EOF | {
"content_hash": "0e3781b9e339ed9d88f83f7ad64da54c",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 54,
"avg_line_length": 19.80952380952381,
"alnum_prop": 0.6490384615384616,
"repo_name": "GregDesplaces/classe-1914",
"id": "b4e67c3df9e1be86b375d35bfa141d8fd53f46e1",
"size": "416",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/bootstrap.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "312"
},
{
"name": "CSS",
"bytes": "162196"
},
{
"name": "CoffeeScript",
"bytes": "288644"
},
{
"name": "HTML",
"bytes": "54170"
},
{
"name": "JavaScript",
"bytes": "12279"
},
{
"name": "Makefile",
"bytes": "108"
},
{
"name": "PHP",
"bytes": "44160"
}
],
"symlink_target": ""
} |
// LzmaDecoder.cpp
#include "StdAfx.h"
#include "../../../C/Alloc.h"
#include "../Common/StreamUtils.h"
#include "LzmaDecoder.h"
static HRESULT SResToHRESULT(SRes res)
{
switch(res)
{
case SZ_OK: return S_OK;
case SZ_ERROR_MEM: return E_OUTOFMEMORY;
case SZ_ERROR_PARAM: return E_INVALIDARG;
case SZ_ERROR_UNSUPPORTED: return E_NOTIMPL;
case SZ_ERROR_DATA: return S_FALSE;
}
return E_FAIL;
}
namespace NCompress {
namespace NLzma {
CDecoder::CDecoder(): _inBuf(0), _propsWereSet(false), _outSizeDefined(false),
_inBufSize(1 << 20),
_outBufSize(1 << 22),
FinishStream(false)
{
_inSizeProcessed = 0;
_inPos = _inSize = 0;
LzmaDec_Construct(&_state);
}
static void *SzAlloc(void *p, size_t size) { p = p; return MyAlloc(size); }
static void SzFree(void *p, void *address) { p = p; MyFree(address); }
static ISzAlloc g_Alloc = { SzAlloc, SzFree };
CDecoder::~CDecoder()
{
LzmaDec_Free(&_state, &g_Alloc);
MyFree(_inBuf);
}
STDMETHODIMP CDecoder::SetInBufSize(UInt32 , UInt32 size) { _inBufSize = size; return S_OK; }
STDMETHODIMP CDecoder::SetOutBufSize(UInt32 , UInt32 size) { _outBufSize = size; return S_OK; }
HRESULT CDecoder::CreateInputBuffer()
{
if (_inBuf == 0 || _inBufSize != _inBufSizeAllocated)
{
MyFree(_inBuf);
_inBuf = (Byte *)MyAlloc(_inBufSize);
if (_inBuf == 0)
return E_OUTOFMEMORY;
_inBufSizeAllocated = _inBufSize;
}
return S_OK;
}
STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *prop, UInt32 size)
{
RINOK(SResToHRESULT(LzmaDec_Allocate(&_state, prop, size, &g_Alloc)));
_propsWereSet = true;
return CreateInputBuffer();
}
void CDecoder::SetOutStreamSizeResume(const UInt64 *outSize)
{
_outSizeDefined = (outSize != NULL);
if (_outSizeDefined)
_outSize = *outSize;
_outSizeProcessed = 0;
_wrPos = 0;
LzmaDec_Init(&_state);
}
STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize)
{
_inSizeProcessed = 0;
_inPos = _inSize = 0;
SetOutStreamSizeResume(outSize);
return S_OK;
}
HRESULT CDecoder::CodeSpec(ISequentialInStream *inStream, ISequentialOutStream *outStream, ICompressProgressInfo *progress)
{
if (_inBuf == 0 || !_propsWereSet)
return S_FALSE;
UInt64 startInProgress = _inSizeProcessed;
SizeT next = (_state.dicBufSize - _state.dicPos < _outBufSize) ? _state.dicBufSize : (_state.dicPos + _outBufSize);
for (;;)
{
if (_inPos == _inSize)
{
_inPos = _inSize = 0;
RINOK(inStream->Read(_inBuf, _inBufSizeAllocated, &_inSize));
}
SizeT dicPos = _state.dicPos;
SizeT curSize = next - dicPos;
ELzmaFinishMode finishMode = LZMA_FINISH_ANY;
if (_outSizeDefined)
{
const UInt64 rem = _outSize - _outSizeProcessed;
if (rem <= curSize)
{
curSize = (SizeT)rem;
if (FinishStream)
finishMode = LZMA_FINISH_END;
}
}
SizeT inSizeProcessed = _inSize - _inPos;
ELzmaStatus status;
SRes res = LzmaDec_DecodeToDic(&_state, dicPos + curSize, _inBuf + _inPos, &inSizeProcessed, finishMode, &status);
_inPos += (UInt32)inSizeProcessed;
_inSizeProcessed += inSizeProcessed;
SizeT outSizeProcessed = _state.dicPos - dicPos;
_outSizeProcessed += outSizeProcessed;
bool finished = (inSizeProcessed == 0 && outSizeProcessed == 0);
bool stopDecoding = (_outSizeDefined && _outSizeProcessed >= _outSize);
if (res != 0 || _state.dicPos == next || finished || stopDecoding)
{
HRESULT res2 = WriteStream(outStream, _state.dic + _wrPos, _state.dicPos - _wrPos);
_wrPos = _state.dicPos;
if (_state.dicPos == _state.dicBufSize)
{
_state.dicPos = 0;
_wrPos = 0;
}
next = (_state.dicBufSize - _state.dicPos < _outBufSize) ? _state.dicBufSize : (_state.dicPos + _outBufSize);
if (res != 0)
return S_FALSE;
RINOK(res2);
if (stopDecoding)
return S_OK;
if (finished)
return (status == LZMA_STATUS_FINISHED_WITH_MARK ? S_OK : S_FALSE);
}
if (progress)
{
UInt64 inSize = _inSizeProcessed - startInProgress;
RINOK(progress->SetRatioInfo(&inSize, &_outSizeProcessed));
}
}
}
STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress)
{
if (_inBuf == 0)
return E_INVALIDARG;
SetOutStreamSize(outSize);
return CodeSpec(inStream, outStream, progress);
}
#ifndef NO_READ_FROM_CODER
STDMETHODIMP CDecoder::SetInStream(ISequentialInStream *inStream) { _inStream = inStream; return S_OK; }
STDMETHODIMP CDecoder::ReleaseInStream() { _inStream.Release(); return S_OK; }
STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize)
{
if (processedSize)
*processedSize = 0;
do
{
if (_inPos == _inSize)
{
_inPos = _inSize = 0;
RINOK(_inStream->Read(_inBuf, _inBufSizeAllocated, &_inSize));
}
{
SizeT inProcessed = _inSize - _inPos;
if (_outSizeDefined)
{
const UInt64 rem = _outSize - _outSizeProcessed;
if (rem < size)
size = (UInt32)rem;
}
SizeT outProcessed = size;
ELzmaStatus status;
SRes res = LzmaDec_DecodeToBuf(&_state, (Byte *)data, &outProcessed,
_inBuf + _inPos, &inProcessed, LZMA_FINISH_ANY, &status);
_inPos += (UInt32)inProcessed;
_inSizeProcessed += inProcessed;
_outSizeProcessed += outProcessed;
size -= (UInt32)outProcessed;
data = (Byte *)data + outProcessed;
if (processedSize)
*processedSize += (UInt32)outProcessed;
RINOK(SResToHRESULT(res));
if (inProcessed == 0 && outProcessed == 0)
return S_OK;
}
}
while (size != 0);
return S_OK;
}
HRESULT CDecoder::CodeResume(ISequentialOutStream *outStream, const UInt64 *outSize, ICompressProgressInfo *progress)
{
SetOutStreamSizeResume(outSize);
return CodeSpec(_inStream, outStream, progress);
}
HRESULT CDecoder::ReadFromInputStream(void *data, UInt32 size, UInt32 *processedSize)
{
RINOK(CreateInputBuffer());
if (processedSize)
*processedSize = 0;
while (size > 0)
{
if (_inPos == _inSize)
{
_inPos = _inSize = 0;
RINOK(_inStream->Read(_inBuf, _inBufSizeAllocated, &_inSize));
if (_inSize == 0)
break;
}
{
UInt32 curSize = _inSize - _inPos;
if (curSize > size)
curSize = size;
memcpy(data, _inBuf + _inPos, curSize);
_inPos += curSize;
_inSizeProcessed += curSize;
size -= curSize;
data = (Byte *)data + curSize;
if (processedSize)
*processedSize += curSize;
}
}
return S_OK;
}
#endif
}}
| {
"content_hash": "ba70451611a2e640893b6c0370adfce1",
"timestamp": "",
"source": "github",
"line_count": 252,
"max_line_length": 123,
"avg_line_length": 27.738095238095237,
"alnum_prop": 0.6163090128755365,
"repo_name": "indashnet/InDashNet.Open.UN2000",
"id": "9f15fdb86b66973b3623a43a296afc4defcf0f66",
"size": "6990",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "android/external/lzma/CPP/7zip/Compress/LzmaDecoder.cpp",
"mode": "33261",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
from libcrypto import hamming_distance
from libcrypto import split_blocks
from libcrypto import xor
from libcrypto import freq_score
from base64 import b64decode
from operator import itemgetter
def main():
file64 = ""
for line in open("../assets/inputS1C6.txt","r"):
file64 += line.rstrip()
file = bytearray(b64decode(file64))
distances = []
for keysize in range(2,40):
dist = 0
sample_size = 10
for ctr in range(0, sample_size):
b1 = bytearray(file[(keysize*ctr):(keysize*(ctr+1))])
b2 = bytearray(file[(keysize*(ctr+1)):(keysize*(ctr+2))])
dist += hamming_distance(b1, b2) / float(keysize)
dist /= sample_size
distances.append([keysize, dist])
distances = sorted(distances,key=itemgetter(1))[:1]
print("Possible Solutions...\n")
for key in distances:
passphrase = ""
key = key[0]
blocks = split_blocks(key,file)
transposed_blocks = []
for idx in range(0,key):
tblock = bytearray()
for block in blocks:
try:
tblock.append(block[idx])
except IndexError:
pass
transposed_blocks.append(tblock)
for block in transposed_blocks:
bytekeys = []
for i in range(1,int("ff",16)):
xor_bytes = xor(bytearray(bytes({i})),block)
try:
xor_string = xor_bytes.decode("ascii")
bytekeys.append([i,xor_string,freq_score(xor_string)])
except UnicodeDecodeError:
next
bytekeys.sort(key=lambda x: x[2], reverse=True)
bkey = bytekeys[:1][0]
passphrase += chr(bkey[0])
print("Key:{0}\n".format(passphrase))
print(xor(bytearray(passphrase.encode()),bytearray(file)).decode())
if __name__ == "__main__":
main() | {
"content_hash": "d549a0e516dd81ccda91eff4cceeb45f",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 75,
"avg_line_length": 28.014285714285716,
"alnum_prop": 0.5471698113207547,
"repo_name": "BKreisel/MatasanoCrypto",
"id": "f7018c8e09cd0883cd4c4b032d2a2a08d23843ea",
"size": "1961",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Set1/challenge6.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "8852"
}
],
"symlink_target": ""
} |
@implementation HtmlElement_Dd
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if ( self )
{
self.layer.masksToBounds = NO;
}
return self;
}
- (void)dealloc
{
}
- (void)html_applyDom:(SamuraiHtmlDomNode *)dom
{
[super html_applyDom:dom];
}
- (void)html_applyStyle:(SamuraiHtmlStyle *)style
{
[super html_applyStyle:style];
}
- (void)html_applyFrame:(CGRect)newFrame
{
[super html_applyFrame:newFrame];
}
@end
// ----------------------------------
// Unit test
// ----------------------------------
#pragma mark -
#if __SAMURAI_TESTING__
TEST_CASE( UI, HtmlElement_Dd )
DESCRIBE( before )
{
}
DESCRIBE( after )
{
}
TEST_CASE_END
#endif // #if __SAMURAI_TESTING__
#endif // #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)
#import "_pragma_pop.h"
| {
"content_hash": "dd8d5ad683ebc778a7f66c1fbb8e38d8",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 59,
"avg_line_length": 13.724137931034482,
"alnum_prop": 0.6118090452261307,
"repo_name": "cyndibaby905/samurai-native",
"id": "382c265b1ba047f4da808c402900976c46ea8898",
"size": "2562",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "samurai-framework/samurai-ui/extension-html/element/HtmlElement_Dd.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "35712"
},
{
"name": "CSS",
"bytes": "87901"
},
{
"name": "Groff",
"bytes": "857"
},
{
"name": "HTML",
"bytes": "3708176"
},
{
"name": "JavaScript",
"bytes": "22922"
},
{
"name": "Objective-C",
"bytes": "2516266"
}
],
"symlink_target": ""
} |
title: Configuring Custom Multifactor Authentication
url: /multifactor-authentication/custom
description: Examples for configuring custom MFA implementations.
---
# Configuring Custom MFA
You may configure [rules](/rules) for custom MFA processes, which allow you to define the conditions that will trigger additional authentication challenges, such as changes in geographic location or logins from unrecognized devices.
## Implementing Contextual MFA
The exact requirements for configuring Contextual MFA will vary. Below are sample snippets you might consider using as you customize your specific solution.
### Change the frequency of authentication requests
By default, Auth0 asks the user for MFA once per month. You can change this setting by changing the `ignoreCookie` field to `true`:
```JS
function (user, context, callback) {
if (conditionIsMet()){
context.multifactor = {
ignoreCookie: true,
provider: 'google-authenticator'
};
}
callback(null, user, context);
}
```
### Access from an extranet
You can have Auth0 request MFA from users whose requests originate from outside the corporate network:
```JS
function (user, context, callback) {
if (IsExtranet()) {
context.multifactor = {
ignoreCookie: true,
provider: 'google-authenticator'
};
}
callback(null, user, context);
function IsExtranet() {
return !rangeCheck.inRange(context.request.ip, '10.0.0.0/8');
}
}
```
### Access from a different device or location
If the user makes a request from an IP address that Auth0 has not already associated with them, you can configure Auth0 to request MFA.
```JS
function (user, context, callback) {
var deviceFingerPrint = getDeviceFingerPrint();
if (user.lastLoginDeviceFingerPrint !== deviceFingerPrint) {
user.persistent.lasLoginDeviceFingerPrint = deviceFingerPrint;
context.multifactor = {
ignoreCookie: true,
provider: 'google-authenticator'
};
}
callback(null, user, context);
function getDeviceFingerPrint() {
var shasum = crypto.createHash('sha1');
shasum.update(context.request.userAgent);
shasum.update(context.request.ip);
return shasum.digest('hex');
}
}
```
## Use a Custom MFA Service
If you are using an MFA provider that does not have Auth0 built-in support or if you are using a service you have created, you can use the [redirect](/protocols#redirect-protocol-in-rules) protocol for the integration.
By using the redirect protocol, you interrupt the authentication transaction and redirect the user to a specified URL where they are asked for MFA. If authentication is successful, Auth0 will continue processing the request.
Some MFA options you can implement using the redirect protocol include:
* A one-time code sent via SMS
* A personally identifying question (e.g. about the user's parents, childhood friends, etc.)
* Integration with specialized providers, such as those that require hardware tokens
To use the redirect protocol, edit the `URL` field:
```JS
function (user, context, callback) {
if (condition() && context.protocol !== 'redirect-callback'){
context.redirect = {
url: 'https://your_custom_mfa'
};
}
if (context.protocol === 'redirect-callback'){
//TODO: handle the result of the MFA step
}
callback(null, user, context);
}
```
## Additional Notes
MFA does not work with the [Resource Owner](/protocols#oauth-resource-owner-password-credentials-grant) endpoint.
If you are using MFA for database connections that use [Popup Mode](https://github.com/auth0/auth0.js#popup-mode), set `sso` to `true` when defining the options in [auth0.js](https://github.com/auth0/auth0.js#sso) or [Lock](/libraries/lock). If you fail to do this, users will be able to log in without MFA.
If you are using MFA after an authentication with one or more social providers, you may need to use your own application `ID` and `Secret` in the connection to the provider's site in place of the default Auth0 development credentials. For instructions on how to get the credentials for each social provider, select your particular from the list at: [Identity Providers](/identityproviders).
| {
"content_hash": "ec0215dc14670bbfdbdc87fe895149b7",
"timestamp": "",
"source": "github",
"line_count": 123,
"max_line_length": 390,
"avg_line_length": 34.03252032520325,
"alnum_prop": 0.7427138079311992,
"repo_name": "Catografix/docs",
"id": "17c63728fe8d9bace67f1ee68fc4b692fb2c8a03",
"size": "4190",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "articles/multifactor-authentication/custom/custom-landing.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "GCC Machine Description",
"bytes": "16850"
},
{
"name": "HTML",
"bytes": "7108"
},
{
"name": "JavaScript",
"bytes": "2037"
},
{
"name": "Shell",
"bytes": "396"
}
],
"symlink_target": ""
} |
require "spec_helper"
describe Docks::Tags::Base do
subject { Docks::Tags::Base.instance }
it "has no synonyms by default" do
expect(subject.synonyms).to eq []
end
it "is multiline by default" do
expect(subject.multiline?).to be true
end
it "allows only one tag per block by default" do
expect(subject.multiple_allowed?).to be false
end
it "can be included in parse results" do
expect(subject.parseable?).to be true
end
end
| {
"content_hash": "94c2bc816d5b13831800407e84e7ceed",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 50,
"avg_line_length": 22.047619047619047,
"alnum_prop": 0.6976241900647948,
"repo_name": "lemonmade/docks",
"id": "460df98c94eeeb3b77f91062ec9ed1a9f59e2d43",
"size": "463",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spec/lib/tags/base_tag_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12089"
},
{
"name": "CoffeeScript",
"bytes": "4520"
},
{
"name": "HTML",
"bytes": "132"
},
{
"name": "JavaScript",
"bytes": "4648"
},
{
"name": "Ruby",
"bytes": "547019"
}
],
"symlink_target": ""
} |
if (p) delete p; \
p = 0;
struct SampleInfo {
Alembic::AbcCoreAbstract::index_t floorIndex;
Alembic::AbcCoreAbstract::index_t ceilIndex;
double alpha;
};
#ifndef uint64_t
typedef boost::uint64_t uint64_t;
#endif
template <class Key, class Data>
class MRUCache {
private:
struct MRUCacheEntry {
Key key;
Data data;
Abc::uint64_t lastAccess;
};
std::vector<MRUCacheEntry> entries;
Abc::uint64_t nextAccess;
int maxEntries;
public:
MRUCache(int _maxEntries = 2) : maxEntries(_maxEntries), nextAccess(0) {}
bool contains(Key const& key) const
{
for (int i = 0; i < entries.size(); i++) {
if (entries[i].key == key) {
return true;
}
}
return false;
}
void touch(Key const& key)
{
for (int i = 0; i < entries.size(); i++) {
if (entries[i].key == key) {
entries[i].lastAccess = nextAccess;
nextAccess++;
}
}
}
Data& get(Key const& key)
{
for (int i = 0; i < entries.size(); i++) {
if (entries[i].key == key) {
entries[i].lastAccess = nextAccess;
return entries[i].data;
}
}
}
void insert(Key const& key, Data& data)
{
if (entries.size() >= maxEntries) {
int oldestIndex = -1;
uint64_t oldestLastAccess;
for (int i = 0; i < entries.size(); i++) {
uint64_t lastAccess = entries[i].lastAccess;
if (oldestIndex == -1 || lastAccess < oldestLastAccess) {
oldestLastAccess = lastAccess;
oldestIndex = i;
}
}
if (oldestIndex >= 0) {
entries.erase(entries.begin() + oldestIndex);
}
}
MRUCacheEntry entry;
entry.key = key;
entry.data = data;
entry.lastAccess = nextAccess;
entries.push_back(entry);
nextAccess++;
}
void clear(void)
{
this->nextAccess = 0;
this->entries.clear();
}
};
std::string getExporterName(std::string const& shortName);
std::string getExporterFileName(std::string const& fileName);
AbcArchiveCache* getArchiveCache(std::string const& path,
CommonProgressBar* pBar = 0);
AbcObjectCache* getObjectCacheFromArchive(std::string const& path,
std::string const& identifier);
Alembic::Abc::IArchive* getArchiveFromID(std::string const& path);
std::string addArchive(Alembic::Abc::IArchive* archive);
void deleteArchive(std::string const& path);
void deleteAllArchives();
Alembic::Abc::IObject getObjectFromArchive(std::string const& path,
std::string const& identifier);
std::string resolvePath(std::string const& path);
std::string resolvePath_Internal(
std::string const& path); // must be defined in binding applications.
// ref counting
bool archiveExists(std::string const& path);
int addRefArchive(std::string const& path);
int decRefArchive(std::string const& path); // IMPORTANT: be extremely careful!
// doesn't delete if the refCount
// is zero. This is a Maya fix for
// a very specific case.
int delRefArchive(std::string const& path);
int getRefArchive(std::string const& path);
void getPaths(std::vector<std::string>& paths);
bool parseTrailingNumber(std::string const& text,
std::string const& requiredPrefix, int& number);
bool validate_filename_location(const char* filename);
typedef std::map<std::string, std::string> stringMap;
typedef std::map<std::string, std::string>::iterator stringMapIt;
typedef std::pair<std::string, std::string> stringPair;
// sortable math objects
class SortableV3f : public Alembic::Abc::V3f {
public:
SortableV3f() { x = y = z = 0.0f; }
SortableV3f(const Alembic::Abc::V3f& other)
{
x = other.x;
y = other.y;
z = other.z;
}
bool operator<(const SortableV3f& other) const
{
if (other.x != x) return other.x > x;
if (other.y != y) return other.y > y;
return other.z > z;
}
bool operator>(const SortableV3f& other) const
{
if (other.x != x) return other.x < x;
if (other.y != y) return other.y < y;
return other.z < z;
}
bool operator==(const SortableV3f& other) const
{
if (other.x != x) return false;
if (other.y != y) return false;
return other.z == z;
}
};
class SortableV2f : public Alembic::Abc::V2f {
public:
SortableV2f() { x = y = 0.0f; }
SortableV2f(const Alembic::Abc::V2f& other)
{
x = other.x;
y = other.y;
}
bool operator<(const SortableV2f& other) const
{
if (other.x != x) return other.x > x;
return other.y > y;
}
bool operator>(const SortableV2f& other) const
{
if (other.x != x) return other.x < x;
return other.y < y;
}
bool operator==(const SortableV2f& other) const
{
if (other.x != x) return false;
return other.y == y;
}
};
Imath::M33d extractRotation(Imath::M44d& m);
SampleInfo getSampleInfo(double iFrame,
Alembic::AbcCoreAbstract::TimeSamplingPtr iTime,
size_t numSamps);
Alembic::Abc::ICompoundProperty getCompoundFromObject(
Alembic::Abc::IObject& object);
Alembic::Abc::TimeSamplingPtr getTimeSamplingFromObject(
Alembic::Abc::IObject& object);
Alembic::Abc::TimeSamplingPtr getTimeSamplingFromObject(
Alembic::Abc::OObject* object);
size_t getNumSamplesFromObject(Alembic::Abc::IObject& object);
size_t getNumSamplesFromObject(Alembic::Abc::OObject* object);
bool isObjectConstant(Alembic::Abc::IObject& object);
struct BasicSchemaData {
enum SCHEMA_TYPE {
__XFORM,
__POLYMESH,
__CURVES,
__NUPATCH,
__POINTS,
__SUBDIV,
__CAMERA,
__FACESET
};
SCHEMA_TYPE type;
bool isConstant;
size_t nbSamples;
};
bool getBasicSchemaDataFromObject(Alembic::Abc::IObject& object,
BasicSchemaData& bsd);
float getTimeOffsetFromObject(Alembic::Abc::IObject& object,
SampleInfo const& sampleInfo);
template <typename SCHEMA>
float getTimeOffsetFromSchema(SCHEMA& schema, SampleInfo const& sampleInfo)
{
Alembic::Abc::TimeSamplingPtr timeSampling = schema.getTimeSampling();
if (timeSampling.get() == NULL) {
return 0;
}
else {
return (float)((timeSampling->getSampleTime(sampleInfo.ceilIndex) -
timeSampling->getSampleTime(sampleInfo.floorIndex)) *
sampleInfo.alpha);
}
}
std::string getModelName(const std::string& identifier);
std::string removeXfoSuffix(const std::string& importName);
template <class OBJTYPE, class DATATYPE>
bool getArbGeomParamPropertyAlembic(
OBJTYPE obj, std::string name,
Alembic::Abc::ITypedArrayProperty<DATATYPE>& pOut)
{
if (!obj.valid() || !obj.getSchema().valid()) {
return false;
}
// look for name with period on it.
std::string nameWithDotPrefix = std::string(".") + name;
if (obj.getSchema().getPropertyHeader(nameWithDotPrefix) != NULL) {
Alembic::Abc::ITypedArrayProperty<DATATYPE> prop =
Alembic::Abc::ITypedArrayProperty<DATATYPE>(obj.getSchema(),
nameWithDotPrefix);
if (prop.valid() && prop.getNumSamples() > 0) {
pOut = prop;
return true;
}
}
if (obj.getSchema().getArbGeomParams() != NULL) {
if (obj.getSchema().getArbGeomParams().getPropertyHeader(name) != NULL) {
Alembic::Abc::ITypedArrayProperty<DATATYPE> prop =
Alembic::Abc::ITypedArrayProperty<DATATYPE>(
obj.getSchema().getArbGeomParams(), name);
if (prop.valid() && prop.getNumSamples() > 0) {
pOut = prop;
return true;
}
}
if (obj.getSchema().getArbGeomParams().getPropertyHeader(
nameWithDotPrefix) != NULL) {
Alembic::Abc::ITypedArrayProperty<DATATYPE> prop =
Alembic::Abc::ITypedArrayProperty<DATATYPE>(
obj.getSchema().getArbGeomParams(), nameWithDotPrefix);
if (prop.valid() && prop.getNumSamples() > 0) {
pOut = prop;
return true;
}
}
}
return false;
}
template <class OBJTYPE, class DATATYPE>
bool getArbGeomParamPropertyAlembic_Permissive(
OBJTYPE obj, std::string name,
Alembic::Abc::ITypedArrayProperty<DATATYPE>& pOut)
{
if (!obj.valid() || !obj.getSchema().valid()) {
return false;
}
// look for name with period on it.
std::string nameWithDotPrefix = std::string(".") + name;
if (obj.getSchema().getPropertyHeader(nameWithDotPrefix) != NULL) {
Alembic::Abc::ITypedArrayProperty<DATATYPE> prop =
Alembic::Abc::ITypedArrayProperty<DATATYPE>(obj.getSchema(),
nameWithDotPrefix);
if (prop.valid()) {
pOut = prop;
return true;
}
}
if (obj.getSchema().getArbGeomParams() != NULL) {
if (obj.getSchema().getArbGeomParams().getPropertyHeader(name) != NULL) {
Alembic::Abc::ITypedArrayProperty<DATATYPE> prop =
Alembic::Abc::ITypedArrayProperty<DATATYPE>(
obj.getSchema().getArbGeomParams(), name);
if (prop.valid()) {
pOut = prop;
return true;
}
}
if (obj.getSchema().getArbGeomParams().getPropertyHeader(
nameWithDotPrefix) != NULL) {
Alembic::Abc::ITypedArrayProperty<DATATYPE> prop =
Alembic::Abc::ITypedArrayProperty<DATATYPE>(
obj.getSchema().getArbGeomParams(), nameWithDotPrefix);
if (prop.valid()) {
pOut = prop;
return true;
}
}
}
return false;
}
namespace NodeCategory {
enum type {
GEOMETRY, // probably should be called MERGEABLE
XFORM,
UNSUPPORTED
};
inline type get(Alembic::AbcGeom::IObject& iObj)
{
if (Alembic::AbcGeom::IPolyMesh::matches(iObj.getMetaData()) ||
Alembic::AbcGeom::ICamera::matches(iObj.getMetaData()) ||
Alembic::AbcGeom::IPoints::matches(iObj.getMetaData()) ||
Alembic::AbcGeom::ICurves::matches(iObj.getMetaData()) ||
Alembic::AbcGeom::ISubD::matches(iObj.getMetaData()) ||
Alembic::AbcGeom::INuPatch::matches(iObj.getMetaData()) ||
Alembic::AbcGeom::ILight::matches(iObj.getMetaData())) {
return GEOMETRY;
}
else if (Alembic::AbcGeom::IXform::matches(iObj.getMetaData())) {
return XFORM;
}
else {
return UNSUPPORTED;
}
}
};
void getMergeInfo(AbcArchiveCache* pArchiveCache, AbcObjectCache* pObjectCache,
bool& bCreateNullNode, int& nMergedGeomNodeIndex,
AbcObjectCache** ppMergedObjectCache);
int prescanAlembicHierarchy(AbcArchiveCache* pArchiveCache,
AbcObjectCache* pRootObjectCache,
std::vector<std::string>& nodes,
std::map<std::string, bool>& map,
bool bIncludeChildren = false);
template <class S>
struct cia_map_key {
Alembic::Abc::int32_t vid;
S data;
cia_map_key(const Alembic::Abc::int32_t& _vid, const S& _data)
: vid(_vid), data(_data)
{
}
bool operator<(const cia_map_key& other) const
{
if (vid == other.vid) return data < other.data;
return vid < other.vid;
}
};
// Alembic::Abc::N3f
// SortableV3f
template <class T, class S>
void createIndexedArray(
const std::vector<Alembic::Abc::int32_t>& faceIndicesVec,
const std::vector<T>& inputVec, std::vector<T>& outputVec,
std::vector<Alembic::Abc::uint32_t>& outputIndices)
{
std::map<cia_map_key<S>, size_t> normalMap;
outputIndices.resize(inputVec.size());
outputVec.clear();
// loop over all data
for (size_t i = 0; i < inputVec.size() && i < faceIndicesVec.size(); ++i) {
cia_map_key<S> mkey(faceIndicesVec[i], inputVec[i]);
if (normalMap.find(mkey) !=
normalMap
.end()) // the pair <vertexId, S> was found, let reuse it's index!
outputIndices[i] = (Alembic::Abc::uint32_t)normalMap.find(mkey)->second;
else {
const int map_size = (int)normalMap.size();
outputVec.push_back(inputVec[i]);
outputIndices[i] = map_size;
normalMap[mkey] = map_size;
}
}
}
namespace ObjectPrint {
enum option { PROPERTIES = 1, USER_PROPERTIES = 2, ARB_GEOM_PROPERTIES = 4 };
};
namespace AbcNodeUtils {
Abc::ICompoundProperty getUserProperties(const AbcG::IObject& iObj);
Abc::ICompoundProperty getUserProperties(const AbcG::IObject& iObj,
AbcA::TimeSamplingPtr& timeSampling,
int& nSamples);
Abc::ICompoundProperty getArbGeomParams(const AbcG::IObject& iObj);
char* getTypeStr(AbcA::PropertyType propType);
char* getPodStr(AbcA::PlainOldDataType pod);
void printCompoundProperty(Abc::ICompoundProperty prop);
void printObjectProperties(AbcG::IObject iObj, int options);
};
Abc::ICompoundProperty getArbGeomParams(const AbcG::IObject& iObj,
AbcA::TimeSamplingPtr& timeSampling,
int& nSamples);
Abc::FloatArraySamplePtr getKnotVector(AbcG::ICurves& obj);
Abc::UInt16ArraySamplePtr getCurveOrders(AbcG::ICurves& obj);
bool validateCurveData(Abc::P3fArraySamplePtr pCurvePos,
Abc::Int32ArraySamplePtr pCurveNbVertices,
Abc::UInt16ArraySamplePtr pOrders,
Abc::FloatArraySamplePtr pKnotVec, AbcG::CurveType type);
int getCurveOrder(int i, Abc::UInt16ArraySamplePtr pOrders,
AbcG::CurveType type);
AbcG::IVisibilityProperty getAbcVisibilityProperty(Abc::IObject shapeObj);
void clearIdentifierMap();
std::string getUniqueName(const std::string& identifier, std::string& name,
bool bValidate, bool& bRenamed);
#endif // __COMMON_UTILITIES_H
| {
"content_hash": "e00b14d06ac3b310c0861a9ec66644d6",
"timestamp": "",
"source": "github",
"line_count": 442,
"max_line_length": 80,
"avg_line_length": 31.235294117647058,
"alnum_prop": 0.6261770244821092,
"repo_name": "SqueezeStudioAnimation/ExocortexCrate",
"id": "6b1d0ba7589d64a863eee7135df09340fd94bc91",
"size": "13979",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Shared/CommonUtils/CommonUtilities.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AMPL",
"bytes": "469"
},
{
"name": "Ada",
"bytes": "89080"
},
{
"name": "Assembly",
"bytes": "137857"
},
{
"name": "Batchfile",
"bytes": "89522"
},
{
"name": "C",
"bytes": "14560191"
},
{
"name": "C#",
"bytes": "54011"
},
{
"name": "C++",
"bytes": "7375796"
},
{
"name": "CLIPS",
"bytes": "6933"
},
{
"name": "CMake",
"bytes": "279532"
},
{
"name": "CSS",
"bytes": "7532"
},
{
"name": "DIGITAL Command Language",
"bytes": "24911"
},
{
"name": "Fortran",
"bytes": "211556"
},
{
"name": "Groff",
"bytes": "4235"
},
{
"name": "HTML",
"bytes": "41160"
},
{
"name": "Lex",
"bytes": "6877"
},
{
"name": "M4",
"bytes": "20429"
},
{
"name": "MAXScript",
"bytes": "68273"
},
{
"name": "Makefile",
"bytes": "1036683"
},
{
"name": "Module Management System",
"bytes": "1545"
},
{
"name": "Objective-C",
"bytes": "36732"
},
{
"name": "Pascal",
"bytes": "61168"
},
{
"name": "Perl",
"bytes": "19814"
},
{
"name": "Python",
"bytes": "107954"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "Shell",
"bytes": "401729"
},
{
"name": "Yacc",
"bytes": "20428"
}
],
"symlink_target": ""
} |
object B {
inline def getInline: Int =
A.get
}
| {
"content_hash": "e1e15672d093bb1a442cfeb7063393a1",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 29,
"avg_line_length": 13.25,
"alnum_prop": 0.6037735849056604,
"repo_name": "lampepfl/dotty",
"id": "fc714b93b0a9c226747f173a90c046087e6d9d63",
"size": "53",
"binary": false,
"copies": "8",
"ref": "refs/heads/main",
"path": "sbt-test/source-dependencies/inline/changes/B1.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "836"
},
{
"name": "CSS",
"bytes": "136099"
},
{
"name": "HTML",
"bytes": "2829"
},
{
"name": "Java",
"bytes": "238326"
},
{
"name": "JavaScript",
"bytes": "153556"
},
{
"name": "Scala",
"bytes": "24095901"
},
{
"name": "Shell",
"bytes": "23566"
},
{
"name": "TypeScript",
"bytes": "8378"
}
],
"symlink_target": ""
} |
use ctypes::c_void;
use shared::d3d9::{IDirect3DDevice9Ex, IDirect3DSurface9};
use shared::d3d9types::{D3DCOLOR, D3DFORMAT, D3DPOOL};
use shared::guiddef::GUID;
use shared::minwindef::{BOOL, DWORD, FLOAT, INT, UINT};
use shared::windef::{RECT, SIZE};
use um::unknwnbase::{IUnknown, IUnknownVtbl};
use um::winnt::{HANDLE, HRESULT, ULONGLONG};
DEFINE_GUID!{IID_IDXVAHD_Device,
0x95f12dfd, 0xd77e, 0x49be, 0x81, 0x5f, 0x57, 0xd5, 0x79, 0x63, 0x4d, 0x6d}
DEFINE_GUID!{IID_IDXVAHD_VideoProcessor,
0x95f4edf4, 0x6e03, 0x4cd7, 0xbe, 0x1b, 0x30, 0x75, 0xd6, 0x65, 0xaa, 0x52}
ENUM!{enum DXVAHD_FRAME_FORMAT {
DXVAHD_FRAME_FORMAT_PROGRESSIVE = 0,
DXVAHD_FRAME_FORMAT_INTERLACED_TOP_FIELD_FIRST = 1,
DXVAHD_FRAME_FORMAT_INTERLACED_BOTTOM_FIELD_FIRST = 2,
}}
ENUM!{enum DXVAHD_DEVICE_USAGE {
DXVAHD_DEVICE_USAGE_PLAYBACK_NORMAL = 0,
DXVAHD_DEVICE_USAGE_OPTIMAL_SPEED = 1,
DXVAHD_DEVICE_USAGE_OPTIMAL_QUALITY = 2,
}}
ENUM!{enum DXVAHD_SURFACE_TYPE {
DXVAHD_SURFACE_TYPE_VIDEO_INPUT = 0,
DXVAHD_SURFACE_TYPE_VIDEO_INPUT_PRIVATE = 1,
DXVAHD_SURFACE_TYPE_VIDEO_OUTPUT = 2,
}}
ENUM!{enum DXVAHD_DEVICE_TYPE {
DXVAHD_DEVICE_TYPE_HARDWARE = 0,
DXVAHD_DEVICE_TYPE_SOFTWARE = 1,
DXVAHD_DEVICE_TYPE_REFERENCE = 2,
DXVAHD_DEVICE_TYPE_OTHER = 3,
}}
ENUM!{enum DXVAHD_DEVICE_CAPS {
DXVAHD_DEVICE_CAPS_LINEAR_SPACE = 0x1,
DXVAHD_DEVICE_CAPS_xvYCC = 0x2,
DXVAHD_DEVICE_CAPS_RGB_RANGE_CONVERSION = 0x4,
DXVAHD_DEVICE_CAPS_YCbCr_MATRIX_CONVERSION = 0x8,
}}
ENUM!{enum DXVAHD_FEATURE_CAPS {
DXVAHD_FEATURE_CAPS_ALPHA_FILL = 0x1,
DXVAHD_FEATURE_CAPS_CONSTRICTION = 0x2,
DXVAHD_FEATURE_CAPS_LUMA_KEY = 0x4,
DXVAHD_FEATURE_CAPS_ALPHA_PALETTE = 0x8,
}}
ENUM!{enum DXVAHD_FILTER_CAPS {
DXVAHD_FILTER_CAPS_BRIGHTNESS = 0x1,
DXVAHD_FILTER_CAPS_CONTRAST = 0x2,
DXVAHD_FILTER_CAPS_HUE = 0x4,
DXVAHD_FILTER_CAPS_SATURATION = 0x8,
DXVAHD_FILTER_CAPS_NOISE_REDUCTION = 0x10,
DXVAHD_FILTER_CAPS_EDGE_ENHANCEMENT = 0x20,
DXVAHD_FILTER_CAPS_ANAMORPHIC_SCALING = 0x40,
}}
ENUM!{enum DXVAHD_INPUT_FORMAT_CAPS {
DXVAHD_INPUT_FORMAT_CAPS_RGB_INTERLACED = 0x1,
DXVAHD_INPUT_FORMAT_CAPS_RGB_PROCAMP = 0x2,
DXVAHD_INPUT_FORMAT_CAPS_RGB_LUMA_KEY = 0x4,
DXVAHD_INPUT_FORMAT_CAPS_PALETTE_INTERLACED = 0x8,
}}
ENUM!{enum DXVAHD_PROCESSOR_CAPS {
DXVAHD_PROCESSOR_CAPS_DEINTERLACE_BLEND = 0x1,
DXVAHD_PROCESSOR_CAPS_DEINTERLACE_BOB = 0x2,
DXVAHD_PROCESSOR_CAPS_DEINTERLACE_ADAPTIVE = 0x4,
DXVAHD_PROCESSOR_CAPS_DEINTERLACE_MOTION_COMPENSATION = 0x8,
DXVAHD_PROCESSOR_CAPS_INVERSE_TELECINE = 0x10,
DXVAHD_PROCESSOR_CAPS_FRAME_RATE_CONVERSION = 0x20,
}}
ENUM!{enum DXVAHD_ITELECINE_CAPS {
DXVAHD_ITELECINE_CAPS_32 = 0x1,
DXVAHD_ITELECINE_CAPS_22 = 0x2,
DXVAHD_ITELECINE_CAPS_2224 = 0x4,
DXVAHD_ITELECINE_CAPS_2332 = 0x8,
DXVAHD_ITELECINE_CAPS_32322 = 0x10,
DXVAHD_ITELECINE_CAPS_55 = 0x20,
DXVAHD_ITELECINE_CAPS_64 = 0x40,
DXVAHD_ITELECINE_CAPS_87 = 0x80,
DXVAHD_ITELECINE_CAPS_222222222223 = 0x100,
DXVAHD_ITELECINE_CAPS_OTHER = 0x80000000,
}}
ENUM!{enum DXVAHD_FILTER {
DXVAHD_FILTER_BRIGHTNESS = 0,
DXVAHD_FILTER_CONTRAST = 1,
DXVAHD_FILTER_HUE = 2,
DXVAHD_FILTER_SATURATION = 3,
DXVAHD_FILTER_NOISE_REDUCTION = 4,
DXVAHD_FILTER_EDGE_ENHANCEMENT = 5,
DXVAHD_FILTER_ANAMORPHIC_SCALING = 6,
}}
ENUM!{enum DXVAHD_BLT_STATE {
DXVAHD_BLT_STATE_TARGET_RECT = 0,
DXVAHD_BLT_STATE_BACKGROUND_COLOR = 1,
DXVAHD_BLT_STATE_OUTPUT_COLOR_SPACE = 2,
DXVAHD_BLT_STATE_ALPHA_FILL = 3,
DXVAHD_BLT_STATE_CONSTRICTION = 4,
DXVAHD_BLT_STATE_PRIVATE = 1000,
}}
ENUM!{enum DXVAHD_ALPHA_FILL_MODE {
DXVAHD_ALPHA_FILL_MODE_OPAQUE = 0,
DXVAHD_ALPHA_FILL_MODE_BACKGROUND = 1,
DXVAHD_ALPHA_FILL_MODE_DESTINATION = 2,
DXVAHD_ALPHA_FILL_MODE_SOURCE_STREAM = 3,
}}
ENUM!{enum DXVAHD_STREAM_STATE {
DXVAHD_STREAM_STATE_D3DFORMAT = 0,
DXVAHD_STREAM_STATE_FRAME_FORMAT = 1,
DXVAHD_STREAM_STATE_INPUT_COLOR_SPACE = 2,
DXVAHD_STREAM_STATE_OUTPUT_RATE = 3,
DXVAHD_STREAM_STATE_SOURCE_RECT = 4,
DXVAHD_STREAM_STATE_DESTINATION_RECT = 5,
DXVAHD_STREAM_STATE_ALPHA = 6,
DXVAHD_STREAM_STATE_PALETTE = 7,
DXVAHD_STREAM_STATE_LUMA_KEY = 8,
DXVAHD_STREAM_STATE_ASPECT_RATIO = 9,
DXVAHD_STREAM_STATE_FILTER_BRIGHTNESS = 100,
DXVAHD_STREAM_STATE_FILTER_CONTRAST = 101,
DXVAHD_STREAM_STATE_FILTER_HUE = 102,
DXVAHD_STREAM_STATE_FILTER_SATURATION = 103,
DXVAHD_STREAM_STATE_FILTER_NOISE_REDUCTION = 104,
DXVAHD_STREAM_STATE_FILTER_EDGE_ENHANCEMENT = 105,
DXVAHD_STREAM_STATE_FILTER_ANAMORPHIC_SCALING = 106,
DXVAHD_STREAM_STATE_PRIVATE = 1000,
}}
ENUM!{enum DXVAHD_OUTPUT_RATE {
DXVAHD_OUTPUT_RATE_NORMAL = 0,
DXVAHD_OUTPUT_RATE_HALF = 1,
DXVAHD_OUTPUT_RATE_CUSTOM = 2,
}}
STRUCT!{struct DXVAHD_RATIONAL {
Numerator: UINT,
Denominator: UINT,
}}
STRUCT!{struct DXVAHD_COLOR_RGBA {
R: FLOAT,
G: FLOAT,
B: FLOAT,
A: FLOAT,
}}
STRUCT!{struct DXVAHD_COLOR_YCbCrA {
Y: FLOAT,
Cb: FLOAT,
Cr: FLOAT,
A: FLOAT,
}}
UNION!{union DXVAHD_COLOR {
[u32; 4],
RGB RGB_mut: DXVAHD_COLOR_RGBA,
YCbCr YCbCr_mut: DXVAHD_COLOR_YCbCrA,
}}
STRUCT!{struct DXVAHD_CONTENT_DESC {
InputFrameFormat: DXVAHD_FRAME_FORMAT,
InputFrameRate: DXVAHD_RATIONAL,
InputWidth: UINT,
InputHeight: UINT,
OutputFrameRate: DXVAHD_RATIONAL,
OutputWidth: UINT,
OutputHeight: UINT,
}}
STRUCT!{struct DXVAHD_VPDEVCAPS {
DeviceType: DXVAHD_DEVICE_TYPE,
DeviceCaps: UINT,
FeatureCaps: UINT,
FilterCaps: UINT,
InputFormatCaps: UINT,
InputPool: D3DPOOL,
OutputFormatCount: UINT,
InputFormatCount: UINT,
VideoProcessorCount: UINT,
MaxInputStreams: UINT,
MaxStreamStates: UINT,
}}
STRUCT!{struct DXVAHD_VPCAPS {
VPGuid: GUID,
PastFrames: UINT,
FutureFrames: UINT,
ProcessorCaps: UINT,
ITelecineCaps: UINT,
CustomRateCount: UINT,
}}
STRUCT!{struct DXVAHD_CUSTOM_RATE_DATA {
CustomRate: DXVAHD_RATIONAL,
OutputFrames: UINT,
InputInterlaced: BOOL,
InputFramesOrFields: UINT,
}}
STRUCT!{struct DXVAHD_FILTER_RANGE_DATA {
Minimum: INT,
Maximum: INT,
Default: INT,
Multiplier: FLOAT,
}}
STRUCT!{struct DXVAHD_BLT_STATE_TARGET_RECT_DATA {
Enable: BOOL,
TargetRect: RECT,
}}
STRUCT!{struct DXVAHD_BLT_STATE_BACKGROUND_COLOR_DATA {
YCbCr: BOOL,
BackgroundColor: DXVAHD_COLOR,
}}
STRUCT!{struct DXVAHD_BLT_STATE_OUTPUT_COLOR_SPACE_DATA {
Value: UINT,
}}
BITFIELD!{DXVAHD_BLT_STATE_OUTPUT_COLOR_SPACE_DATA Value: UINT [
Usage set_Usage[0..1],
RGB_Range set_RGB_Range[1..2],
YCbCr_Matrix set_YCbCr_Matrix[2..3],
YCbCr_xvYCC set_YCbCr_xvYCC[3..4],
Reserved set_Reserved[4..32],
]}
STRUCT!{struct DXVAHD_BLT_STATE_ALPHA_FILL_DATA {
Mode: DXVAHD_ALPHA_FILL_MODE,
StreamNumber: UINT,
}}
STRUCT!{struct DXVAHD_BLT_STATE_CONSTRICTION_DATA {
Enable: BOOL,
Size: SIZE,
}}
STRUCT!{struct DXVAHD_BLT_STATE_PRIVATE_DATA {
Guid: GUID,
DataSize: UINT,
pData: *mut c_void,
}}
STRUCT!{struct DXVAHD_STREAM_STATE_D3DFORMAT_DATA {
Format: D3DFORMAT,
}}
STRUCT!{struct DXVAHD_STREAM_STATE_FRAME_FORMAT_DATA {
FrameFormat: DXVAHD_FRAME_FORMAT,
}}
STRUCT!{struct DXVAHD_STREAM_STATE_INPUT_COLOR_SPACE_DATA {
Value: UINT,
}}
BITFIELD!{DXVAHD_STREAM_STATE_INPUT_COLOR_SPACE_DATA Value: UINT [
Type set_Type[0..1],
RGB_Range set_RGB_Range[1..2],
YCbCr_Matrix set_YCbCr_Matrix[2..3],
YCbCr_xvYCC set_YCbCr_xvYCC[3..4],
Reserved set_Reserved[4..32],
]}
STRUCT!{struct DXVAHD_STREAM_STATE_OUTPUT_RATE_DATA {
RepeatFrame: BOOL,
OutputRate: DXVAHD_OUTPUT_RATE,
CustomRate: DXVAHD_RATIONAL,
}}
STRUCT!{struct DXVAHD_STREAM_STATE_SOURCE_RECT_DATA {
Enable: BOOL,
SourceRect: RECT,
}}
STRUCT!{struct DXVAHD_STREAM_STATE_DESTINATION_RECT_DATA {
Enable: BOOL,
DestinationRect: RECT,
}}
STRUCT!{struct DXVAHD_STREAM_STATE_ALPHA_DATA {
Enable: BOOL,
Alpha: FLOAT,
}}
STRUCT!{struct DXVAHD_STREAM_STATE_PALETTE_DATA {
Count: UINT,
pEntries: *mut D3DCOLOR,
}}
STRUCT!{struct DXVAHD_STREAM_STATE_LUMA_KEY_DATA {
Enable: BOOL,
Lower: FLOAT,
Upper: FLOAT,
}}
STRUCT!{struct DXVAHD_STREAM_STATE_ASPECT_RATIO_DATA {
Enable: BOOL,
SourceAspectRatio: DXVAHD_RATIONAL,
DestinationAspectRatio: DXVAHD_RATIONAL,
}}
STRUCT!{struct DXVAHD_STREAM_STATE_FILTER_DATA {
Enable: BOOL,
Level: INT,
}}
STRUCT!{struct DXVAHD_STREAM_STATE_PRIVATE_DATA {
Guid: GUID,
DataSize: UINT,
pData: *mut c_void,
}}
STRUCT!{struct DXVAHD_STREAM_DATA {
Enable: BOOL,
OutputIndex: UINT,
InputFrameOrField: UINT,
PastFrames: UINT,
FutureFrames: UINT,
ppPastSurfaces: *mut *mut IDirect3DSurface9,
pInputSurface: *mut IDirect3DSurface9,
ppFutureSurfaces: *mut *mut IDirect3DSurface9,
}}
STRUCT!{struct DXVAHD_STREAM_STATE_PRIVATE_IVTC_DATA {
Enable: BOOL,
ITelecineFlags: UINT,
Frames: UINT,
InputField: UINT,
}}
RIDL!{#[uuid(0x95f12dfd, 0xd77e, 0x49be, 0x81, 0x5f, 0x57, 0xd5, 0x79, 0x63, 0x4d, 0x6d)]
interface IDXVAHD_Device(IDXVAHD_DeviceVtbl): IUnknown(IUnknownVtbl) {
fn CreateVideoSurface(
Width: UINT,
Height: UINT,
Format: D3DFORMAT,
Pool: D3DPOOL,
Usage: DWORD,
Type: DXVAHD_SURFACE_TYPE,
NumSurfaces: UINT,
ppSurfaces: *mut *mut IDirect3DSurface9,
pSharedHandle: *mut HANDLE,
) -> HRESULT,
fn GetVideoProcessorDeviceCaps(
pCaps: *mut DXVAHD_VPDEVCAPS,
) -> HRESULT,
fn GetVideoProcessorOutputFormats(
Count: UINT,
pFormats: *mut D3DFORMAT,
) -> HRESULT,
fn GetVideoProcessorInputFormats(
Count: UINT,
pFormats: *mut D3DFORMAT,
) -> HRESULT,
fn GetVideoProcessorCaps(
Count: UINT,
pCaps: *mut DXVAHD_VPCAPS,
) -> HRESULT,
fn GetVideoProcessorCustomRates(
pVPGuid: *const GUID,
Count: UINT,
pRates: *mut DXVAHD_CUSTOM_RATE_DATA,
) -> HRESULT,
fn GetVideoProcessorFilterRange(
Filter: DXVAHD_FILTER,
pRange: *mut DXVAHD_FILTER_RANGE_DATA,
) -> HRESULT,
fn CreateVideoProcessor(
pVPGuid: *const GUID,
ppVideoProcessor: *mut *mut IDXVAHD_VideoProcessor,
) -> HRESULT,
}}
RIDL!{#[uuid(0x95f4edf4, 0x6e03, 0x4cd7, 0xbe, 0x1b, 0x30, 0x75, 0xd6, 0x65, 0xaa, 0x52)]
interface IDXVAHD_VideoProcessor(IDXVAHD_VideoProcessorVtbl): IUnknown(IUnknownVtbl) {
fn SetVideoProcessBltState(
State: DXVAHD_BLT_STATE,
DataSize: UINT,
pData: *const c_void,
) -> HRESULT,
fn GetVideoProcessBltState(
State: DXVAHD_BLT_STATE,
DataSize: UINT,
pData: *mut c_void,
) -> HRESULT,
fn SetVideoProcessStreamState(
StreamNumber: UINT,
State: DXVAHD_STREAM_STATE,
DataSize: UINT,
pData: *const c_void,
) -> HRESULT,
fn GetVideoProcessStreamState(
StreamNumber: UINT,
State: DXVAHD_STREAM_STATE,
DataSize: UINT,
pData: *mut c_void,
) -> HRESULT,
fn VideoProcessBltHD(
pOutputSurface: *mut IDirect3DSurface9,
OutputFrame: UINT,
StreamCount: UINT,
pStreams: *const DXVAHD_STREAM_DATA,
) -> HRESULT,
}}
FN!{stdcall PDXVAHDSW_CreateDevice(
pD3DDevice: *mut IDirect3DDevice9Ex,
phDevice: *mut HANDLE,
) -> HRESULT}
FN!{stdcall PDXVAHDSW_ProposeVideoPrivateFormat(
hDevice: HANDLE,
pFormat: *mut D3DFORMAT,
) -> HRESULT}
FN!{stdcall PDXVAHDSW_GetVideoProcessorDeviceCaps(
hDevice: HANDLE,
pContentDesc: *const DXVAHD_CONTENT_DESC,
Usage: DXVAHD_DEVICE_USAGE,
pCaps: *mut DXVAHD_VPDEVCAPS,
) -> HRESULT}
FN!{stdcall PDXVAHDSW_GetVideoProcessorOutputFormats(
hDevice: HANDLE,
pContentDesc: *const DXVAHD_CONTENT_DESC,
Usage: DXVAHD_DEVICE_USAGE,
Count: UINT,
pFormats: *mut D3DFORMAT,
) -> HRESULT}
FN!{stdcall PDXVAHDSW_GetVideoProcessorInputFormats(
hDevice: HANDLE,
pContentDesc: *const DXVAHD_CONTENT_DESC,
Usage: DXVAHD_DEVICE_USAGE,
Count: UINT,
pFormats: *mut D3DFORMAT,
) -> HRESULT}
FN!{stdcall PDXVAHDSW_GetVideoProcessorCaps(
hDevice: HANDLE,
pContentDesc: *const DXVAHD_CONTENT_DESC,
Usage: DXVAHD_DEVICE_USAGE,
Count: UINT,
pCaps: *mut DXVAHD_VPCAPS,
) -> HRESULT}
FN!{stdcall PDXVAHDSW_GetVideoProcessorCustomRates(
hDevice: HANDLE,
pVPGuid: *const GUID,
Count: UINT,
pRates: *mut DXVAHD_CUSTOM_RATE_DATA,
) -> HRESULT}
FN!{stdcall PDXVAHDSW_GetVideoProcessorFilterRange(
hDevice: HANDLE,
Filter: DXVAHD_FILTER,
pRange: *mut DXVAHD_FILTER_RANGE_DATA,
) -> HRESULT}
FN!{stdcall PDXVAHDSW_DestroyDevice(
hDevice: HANDLE,
) -> HRESULT}
FN!{stdcall PDXVAHDSW_CreateVideoProcessor(
hDevice: HANDLE,
pVPGuid: *const GUID,
phVideoProcessor: *mut HANDLE,
) -> HRESULT}
FN!{stdcall PDXVAHDSW_SetVideoProcessBltState(
hVideoProcessor: HANDLE,
State: DXVAHD_BLT_STATE,
DataSize: UINT,
pData: *const c_void,
) -> HRESULT}
FN!{stdcall PDXVAHDSW_GetVideoProcessBltStatePrivate(
hVideoProcessor: HANDLE,
pData: *mut DXVAHD_BLT_STATE_PRIVATE_DATA,
) -> HRESULT}
FN!{stdcall PDXVAHDSW_SetVideoProcessStreamState(
hVideoProcessor: HANDLE,
StreamNumber: UINT,
State: DXVAHD_STREAM_STATE,
DataSize: UINT,
pData: *const c_void,
) -> HRESULT}
FN!{stdcall PDXVAHDSW_GetVideoProcessStreamStatePrivate(
hVideoProcessor: HANDLE,
StreamNumber: UINT,
pData: *mut DXVAHD_STREAM_STATE_PRIVATE_DATA,
) -> HRESULT}
FN!{stdcall PDXVAHDSW_VideoProcessBltHD(
hVideoProcessor: HANDLE,
pOutputSurface: *mut IDirect3DSurface9,
OutputFrame: UINT,
StreamCount: UINT,
pStreams: *const DXVAHD_STREAM_DATA,
) -> HRESULT}
FN!{stdcall PDXVAHDSW_DestroyVideoProcessor(
hVideoProcessor: HANDLE,
) -> HRESULT}
STRUCT!{struct DXVAHDSW_CALLBACKS {
CreateDevice: PDXVAHDSW_CreateDevice,
ProposeVideoPrivateFormat: PDXVAHDSW_ProposeVideoPrivateFormat,
GetVideoProcessorDeviceCaps: PDXVAHDSW_GetVideoProcessorDeviceCaps,
GetVideoProcessorOutputFormats: PDXVAHDSW_GetVideoProcessorOutputFormats,
GetVideoProcessorInputFormats: PDXVAHDSW_GetVideoProcessorInputFormats,
GetVideoProcessorCaps: PDXVAHDSW_GetVideoProcessorCaps,
GetVideoProcessorCustomRates: PDXVAHDSW_GetVideoProcessorCustomRates,
GetVideoProcessorFilterRange: PDXVAHDSW_GetVideoProcessorFilterRange,
DestroyDevice: PDXVAHDSW_DestroyDevice,
CreateVideoProcessor: PDXVAHDSW_CreateVideoProcessor,
SetVideoProcessBltState: PDXVAHDSW_SetVideoProcessBltState,
GetVideoProcessBltStatePrivate: PDXVAHDSW_GetVideoProcessBltStatePrivate,
SetVideoProcessStreamState: PDXVAHDSW_SetVideoProcessStreamState,
GetVideoProcessStreamStatePrivate: PDXVAHDSW_GetVideoProcessStreamStatePrivate,
VideoProcessBltHD: PDXVAHDSW_VideoProcessBltHD,
DestroyVideoProcessor: PDXVAHDSW_DestroyVideoProcessor,
}}
FN!{stdcall PDXVAHDSW_Plugin(
Size: UINT,
pCallbacks: *mut c_void,
) -> HRESULT}
DEFINE_GUID!{DXVAHDControlGuid,
0xa0386e75, 0xf70c, 0x464c, 0xa9, 0xce, 0x33, 0xc4, 0x4e, 0x09, 0x16, 0x23}
DEFINE_GUID!{DXVAHDETWGUID_CREATEVIDEOPROCESSOR,
0x681e3d1e, 0x5674, 0x4fb3, 0xa5, 0x03, 0x2f, 0x20, 0x55, 0xe9, 0x1f, 0x60}
DEFINE_GUID!{DXVAHDETWGUID_VIDEOPROCESSBLTSTATE,
0x76c94b5a, 0x193f, 0x4692, 0x94, 0x84, 0xa4, 0xd9, 0x99, 0xda, 0x81, 0xa8}
DEFINE_GUID!{DXVAHDETWGUID_VIDEOPROCESSSTREAMSTATE,
0x262c0b02, 0x209d, 0x47ed, 0x94, 0xd8, 0x82, 0xae, 0x02, 0xb8, 0x4a, 0xa7}
DEFINE_GUID!{DXVAHDETWGUID_VIDEOPROCESSBLTHD,
0xbef3d435, 0x78c7, 0x4de3, 0x97, 0x07, 0xcd, 0x1b, 0x08, 0x3b, 0x16, 0x0a}
DEFINE_GUID!{DXVAHDETWGUID_VIDEOPROCESSBLTHD_STREAM,
0x27ae473e, 0xa5fc, 0x4be5, 0xb4, 0xe3, 0xf2, 0x49, 0x94, 0xd3, 0xc4, 0x95}
DEFINE_GUID!{DXVAHDETWGUID_DESTROYVIDEOPROCESSOR,
0xf943f0a0, 0x3f16, 0x43e0, 0x80, 0x93, 0x10, 0x5a, 0x98, 0x6a, 0xa5, 0xf1}
STRUCT!{struct DXVAHDETW_CREATEVIDEOPROCESSOR {
pObject: ULONGLONG,
pD3D9Ex: ULONGLONG,
VPGuid: GUID,
}}
STRUCT!{struct DXVAHDETW_VIDEOPROCESSBLTSTATE {
pObject: ULONGLONG,
State: DXVAHD_BLT_STATE,
DataSize: UINT,
SetState: BOOL,
}}
STRUCT!{struct DXVAHDETW_VIDEOPROCESSSTREAMSTATE {
pObject: ULONGLONG,
StreamNumber: UINT,
State: DXVAHD_STREAM_STATE,
DataSize: UINT,
SetState: BOOL,
}}
STRUCT!{struct DXVAHDETW_VIDEOPROCESSBLTHD {
pObject: ULONGLONG,
pOutputSurface: ULONGLONG,
TargetRect: RECT,
OutputFormat: D3DFORMAT,
ColorSpace: UINT,
OutputFrame: UINT,
StreamCount: UINT,
Enter: BOOL,
}}
STRUCT!{struct DXVAHDETW_VIDEOPROCESSBLTHD_STREAM {
pObject: ULONGLONG,
pInputSurface: ULONGLONG,
SourceRect: RECT,
DestinationRect: RECT,
InputFormat: D3DFORMAT,
FrameFormat: DXVAHD_FRAME_FORMAT,
ColorSpace: UINT,
StreamNumber: UINT,
OutputIndex: UINT,
InputFrameOrField: UINT,
PastFrames: UINT,
FutureFrames: UINT,
}}
STRUCT!{struct DXVAHDETW_DESTROYVIDEOPROCESSOR {
pObject: ULONGLONG,
}}
extern "system" {
pub fn DXVAHD_CreateDevice(
pD3DDevice: *mut IDirect3DDevice9Ex,
pContentDesc: *const DXVAHD_CONTENT_DESC,
Usage: DXVAHD_DEVICE_USAGE,
pPlugin: PDXVAHDSW_Plugin,
ppDevice: *mut *mut IDXVAHD_Device,
) -> HRESULT;
}
FN!{stdcall PDXVAHD_CreateDevice(
pD3DDevice: *mut IDirect3DDevice9Ex,
pContentDesc: *const DXVAHD_CONTENT_DESC,
Usage: DXVAHD_DEVICE_USAGE,
pPlugin: PDXVAHDSW_Plugin,
ppDevice: *mut *mut IDXVAHD_Device,
) -> HRESULT}
| {
"content_hash": "ca0f94b93900dc7e732f9cfcffcf16df",
"timestamp": "",
"source": "github",
"line_count": 550,
"max_line_length": 89,
"avg_line_length": 32.04727272727273,
"alnum_prop": 0.7014637467377738,
"repo_name": "chromium/chromium",
"id": "755dfdc2326aa86a77f853df36ab704f1b3880b9",
"size": "17962",
"binary": false,
"copies": "17",
"ref": "refs/heads/main",
"path": "third_party/rust/winapi/v0_3/crate/src/um/dxvahd.rs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
Updating HTML pertains only to SVG icon. Icon from
[`carbon-elements`](https://github.com/IBM/carbon-elements) package is now used.
Vanilla markup should be migrated to one shown in
[carbondesignsystem.com](https://next.carbondesignsystem.com/components/code-snippet/code)
site. React and other framework variants should reflect the change
automatically.
### SCSS
No selector changes.
| {
"content_hash": "0761a35404bb9b3bf1f719759b88be18",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 90,
"avg_line_length": 38.7,
"alnum_prop": 0.7984496124031008,
"repo_name": "carbon-design-system/carbon-components",
"id": "b0cef670c463264132d2f47ba6c161324d531696",
"size": "397",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "packages/components/src/components/copy-button/migrate-to-10.x.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "552528"
},
{
"name": "HCL",
"bytes": "1049"
},
{
"name": "HTML",
"bytes": "226209"
},
{
"name": "JavaScript",
"bytes": "2220621"
},
{
"name": "Shell",
"bytes": "2502"
},
{
"name": "Vue",
"bytes": "2591"
}
],
"symlink_target": ""
} |
namespace SNES {
PPU ppu;
#include "mmio/mmio.cpp"
#include "window/window.cpp"
#include "cache/cache.cpp"
#include "background/background.cpp"
#include "sprite/sprite.cpp"
#include "screen/screen.cpp"
#include "serialization.cpp"
void PPU::step(unsigned clocks) {
clock += clocks;
}
void PPU::synchronize_cpu() {
if(CPU::Threaded == true) {
if(clock >= 0 && scheduler.sync != Scheduler::SynchronizeMode::All) co_switch(cpu.thread);
} else {
while(clock >= 0) cpu.enter();
}
}
void PPU::Enter() { ppu.enter(); }
void PPU::enter() {
while(true) {
if(scheduler.sync == Scheduler::SynchronizeMode::All) {
scheduler.exit(Scheduler::ExitReason::SynchronizeEvent);
}
scanline();
if(vcounter() < display.height && vcounter()) {
add_clocks(512);
render_scanline();
add_clocks(lineclocks() - 512);
} else {
add_clocks(lineclocks());
}
}
}
void PPU::add_clocks(unsigned clocks) {
tick(clocks);
step(clocks);
synchronize_cpu();
}
void PPU::render_scanline() {
if(display.framecounter) return; //skip this frame?
bg1.scanline();
bg2.scanline();
bg3.scanline();
bg4.scanline();
if(regs.display_disable) return screen.render_black();
screen.scanline();
bg1.render();
bg2.render();
bg3.render();
bg4.render();
sprite.render();
screen.render();
}
void PPU::scanline() {
display.width = !hires() ? 256 : 512;
display.height = !overscan() ? 225 : 240;
if(vcounter() == 0) frame();
if(vcounter() == display.height && regs.display_disable == false) sprite.address_reset();
}
void PPU::frame() {
sprite.frame();
system.frame();
display.interlace = regs.interlace;
display.overscan = regs.overscan;
display.framecounter = display.frameskip == 0 ? 0 : (display.framecounter + 1) % display.frameskip;
}
void PPU::enable() {
function<uint8 (unsigned)> read = { &PPU::mmio_read, (PPU*)&ppu };
function<void (unsigned, uint8)> write = { &PPU::mmio_write, (PPU*)&ppu };
bus.map(Bus::MapMode::Direct, 0x00, 0x3f, 0x2100, 0x213f, read, write);
bus.map(Bus::MapMode::Direct, 0x80, 0xbf, 0x2100, 0x213f, read, write);
}
void PPU::power() {
for(int i=0;i<128*1024;i++) vram[i] = 0;
for(int i=0;i<544;i++) oam[i] = 0;
for(int i=0;i<512;i++) cgram[i] = 0;
reset();
}
void PPU::reset() {
create(Enter, system.cpu_frequency());
PPUcounter::reset();
memset(surface, 0, 512 * 512 * sizeof(uint32));
mmio_reset();
display.interlace = false;
display.overscan = false;
}
void PPU::layer_enable(unsigned layer, unsigned priority, bool enable) {
switch(layer * 4 + priority) {
case 0: bg1.priority0_enable = enable; break;
case 1: bg1.priority1_enable = enable; break;
case 4: bg2.priority0_enable = enable; break;
case 5: bg2.priority1_enable = enable; break;
case 8: bg3.priority0_enable = enable; break;
case 9: bg3.priority1_enable = enable; break;
case 12: bg4.priority0_enable = enable; break;
case 13: bg4.priority1_enable = enable; break;
case 16: sprite.priority0_enable = enable; break;
case 17: sprite.priority1_enable = enable; break;
case 18: sprite.priority2_enable = enable; break;
case 19: sprite.priority3_enable = enable; break;
}
}
void PPU::set_frameskip(unsigned frameskip) {
display.frameskip = frameskip;
display.framecounter = 0;
}
PPU::PPU() :
cache(*this),
bg1(*this, Background::ID::BG1),
bg2(*this, Background::ID::BG2),
bg3(*this, Background::ID::BG3),
bg4(*this, Background::ID::BG4),
sprite(*this),
screen(*this),
vram(nullptr),
oam(nullptr),
cgram(nullptr)
{
surface = new uint32[512 * 512];
output = surface + 16 * 512;
display.width = 256;
display.height = 224;
display.frameskip = 0;
display.framecounter = 0;
}
PPU::~PPU() {
delete[] surface;
interface()->freeSharedMemory(vram);
interface()->freeSharedMemory(oam);
interface()->freeSharedMemory(cgram);
}
void PPU::initialize()
{
vram = (uint8*)interface()->allocSharedMemory("VRAM",128 * 1024);
oam = (uint8*)interface()->allocSharedMemory("OAM",544);
cgram = (uint8*)interface()->allocSharedMemory("CGRAM",512);
}
}
| {
"content_hash": "0d3396b4508fb9d2d43ba3cf17aeef48",
"timestamp": "",
"source": "github",
"line_count": 161,
"max_line_length": 101,
"avg_line_length": 25.565217391304348,
"alnum_prop": 0.6547619047619048,
"repo_name": "superusercode/RTC3",
"id": "dacdcd8c628aab97c05874037a622bc3ac5c4a88",
"size": "4158",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Real-Time Corruptor/BizHawk_RTC/libsnes/bsnes/snes/alt/ppu-performance/ppu.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "273687"
},
{
"name": "Batchfile",
"bytes": "18810"
},
{
"name": "C",
"bytes": "26790735"
},
{
"name": "C#",
"bytes": "13499009"
},
{
"name": "C++",
"bytes": "14428468"
},
{
"name": "CMake",
"bytes": "39873"
},
{
"name": "GLSL",
"bytes": "6610"
},
{
"name": "HTML",
"bytes": "420498"
},
{
"name": "Inno Setup",
"bytes": "3199"
},
{
"name": "Java",
"bytes": "13302"
},
{
"name": "Limbo",
"bytes": "15313"
},
{
"name": "Lua",
"bytes": "303246"
},
{
"name": "M4",
"bytes": "836"
},
{
"name": "Makefile",
"bytes": "147790"
},
{
"name": "NSIS",
"bytes": "3447"
},
{
"name": "Objective-C",
"bytes": "207179"
},
{
"name": "Perl",
"bytes": "78"
},
{
"name": "Python",
"bytes": "34858"
},
{
"name": "Roff",
"bytes": "5448"
},
{
"name": "Shell",
"bytes": "26787"
},
{
"name": "SourcePawn",
"bytes": "7395"
}
],
"symlink_target": ""
} |
namespace google {
namespace cloud {
namespace accessapproval_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
/// Define the gRPC status code semantics for retrying requests.
struct AccessApprovalRetryTraits {
static inline bool IsPermanentFailure(google::cloud::Status const& status) {
return status.code() != StatusCode::kOk &&
status.code() != StatusCode::kUnavailable;
}
};
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace accessapproval_internal
} // namespace cloud
} // namespace google
#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_ACCESSAPPROVAL_INTERNAL_ACCESS_APPROVAL_RETRY_TRAITS_H
| {
"content_hash": "aa007a4e9c3103eb90bab4593ee1e429",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 95,
"avg_line_length": 32.73684210526316,
"alnum_prop": 0.7540192926045016,
"repo_name": "googleapis/google-cloud-cpp",
"id": "95b7616916f13005f7e4a6760a92410f946c5c62",
"size": "1624",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "google/cloud/accessapproval/internal/access_approval_retry_traits.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "2387"
},
{
"name": "Batchfile",
"bytes": "3052"
},
{
"name": "C",
"bytes": "21004"
},
{
"name": "C++",
"bytes": "41174129"
},
{
"name": "CMake",
"bytes": "1350320"
},
{
"name": "Dockerfile",
"bytes": "111570"
},
{
"name": "Makefile",
"bytes": "138270"
},
{
"name": "PowerShell",
"bytes": "41266"
},
{
"name": "Python",
"bytes": "21338"
},
{
"name": "Shell",
"bytes": "249894"
},
{
"name": "Starlark",
"bytes": "722015"
}
],
"symlink_target": ""
} |
#pragma once
#include <stdint.h>
/* We need struct timeval */
#ifdef _WIN32
#include <winsock.h>
#else
#include <sys/time.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
/// A struct used in enumeration to give access to serial numbers, so you can
/// open a particular device by serial rather than depending on index. This
/// is most useful if you have more than one Kinect.
struct freenect2_device_attributes;
struct freenect2_device_attributes {
const char* camera_serial; /**< Serial number of this device's camera subdevice */
};
/// Enumeration of available resolutions.
/// Not all available resolutions are actually supported for all video formats.
/// Frame modes may not perfectly match resolutions.
typedef enum {
FREENECT2_RESOLUTION_512x424 = 0
FREENECT2_RESOLUTION_1920x1080 = 1
FREENECT2_RESOLUTION_DUMMY = 2147483647, /**< Dummy value to force enum to be 32 bits wide */
} freenect2_resolution;
/// Enumeration of video frame formats
typedef enum {
FREENECT2_VIDEO_RGB = 0, /**< Decompressed RGB mode */
FREENECT2_VIDEO_YUV = 0, /**< Decompressed YUV mode */
FREENECT2_VIDEO_RAW = 0, /**< Raw JPEG data mode */
FREENECT2_VIDEO_DUMMY = 2147483647, /**< Dummy value to force enum to be 32 bits wide */
} freenect2_video_format;
/// Enumeration of ir frame formats
typedef enum {
FREENECT2_IR_RAW = 5, /**< raw infrared data */
FREENECT2_IR_DUMMY = 2147483647, /**< Dummy value to force enum to be 32 bits wide */
} freenect2_ir_format;
/// Enumeration of depth frame formats
typedef enum {
FREENECT2_DEPTH_MM = 5, /**< depth to each pixel in mm, but left unaligned to RGB image */
FREENECT2_DEPTH_DUMMY = 2147483647, /**< Dummy value to force enum to be 32 bits wide */
} freenect2_depth_format;
/// Enumeration of flags to toggle features with freenect2_set_flag()
typedef enum {
// arbitrary bitfields to support flag combination
FREENECT2_MIRROR_DEPTH = 1 << 16,
FREENECT2_MIRROR_VIDEO = 1 << 17,
} freenect2_flag;
/// Possible values for setting each `freenect2_flag`
typedef enum {
FREENECT2_OFF = 0,
FREENECT2_ON = 1,
} freenect2_flag_value;
/// Structure to give information about the width, height, bitrate,
/// framerate, and buffer size of a frame in a particular mode, as
/// well as the total number of bytes needed to hold a single frame.
typedef struct {
uint32_t reserved; /**< unique ID used internally. The meaning of values may change without notice. Don't touch or depend on the contents of this field. We mean it. */
freenect2_resolution resolution; /**< Resolution this freenect2_frame_mode describes, should you want to find it again with freenect2_find_*_frame_mode(). */
union {
int32_t dummy;
freenect2_video_format video_format;
freenect2_ir_format ir_format;
freenect2_depth_format depth_format;
}; /**< The video or depth format that this freenect2_frame_mode describes. The caller should know which of video_format or depth_format to use, since they called freenect2_get_*_frame_mode() */
int32_t bytes; /**< Total buffer size in bytes to hold a single frame of data. Should be equivalent to width * height * (data_bits_per_pixel+padding_bits_per_pixel) / 8 */
int16_t width; /**< Width of the frame, in pixels */
int16_t height; /**< Height of the frame, in pixels */
int8_t data_bits_per_pixel; /**< Number of bits of information needed for each pixel */
int8_t padding_bits_per_pixel; /**< Number of bits of padding for alignment used for each pixel */
int8_t framerate; /**< Approximate expected frame rate, in Hz */
int8_t is_valid; /**< If 0, this freenect2_frame_mode is invalid and does not describe a supported mode. Otherwise, the frame_mode is valid. */
} freenect2_frame_mode;
struct _freenect2_context;
typedef struct _freenect2_context freenect2_context; /**< Holds information about the usb context. */
struct _freenect2_device;
typedef struct _freenect2_device freenect2_device; /**< Holds device information. */
// usb backend specific section
typedef void freenect2_usb_context; /**< Holds libusb-1.0 context */
//
/// If Win32, export all functions for DLL usage
#ifndef _WIN32
#define FREENECT2API /**< DLLExport information for windows, set to nothing on other platforms */
#else
/**< DLLExport information for windows, set to nothing on other platforms */
#ifdef __cplusplus
#define FREENECT2API extern "C" __declspec(dllexport)
#else
// this is required when building from a Win32 port of gcc without being
// forced to compile all of the library files (.c) with g++...
#define FREENECT2API __declspec(dllexport)
#endif
#endif
/// Enumeration of message logging levels
typedef enum {
FREENECT2_LOG_FATAL = 0, /**< Log for crashing/non-recoverable errors */
FREENECT2_LOG_ERROR, /**< Log for major errors */
FREENECT2_LOG_WARNING, /**< Log for warning messages */
FREENECT2_LOG_NOTICE, /**< Log for important messages */
FREENECT2_LOG_INFO, /**< Log for normal messages */
FREENECT2_LOG_DEBUG, /**< Log for useful development messages */
FREENECT2_LOG_SPEW, /**< Log for slightly less useful messages */
FREENECT2_LOG_FLOOD, /**< Log EVERYTHING. May slow performance. */
} freenect2_loglevel;
/**
* Initialize a freenect2 context and do any setup required for
* platform specific USB libraries.
*
* @param ctx Address of pointer to freenect2 context struct to allocate and initialize
* @param usb_ctx USB context to initialize. Can be NULL if not using multiple contexts.
*
* @return 0 on success, < 0 on error
*/
FREENECT2API int freenect2_init(freenect2_context **ctx, freenect2_usb_context *usb_ctx);
/**
* Closes the device if it is open, and frees the context
*
* @param ctx freenect2 context to close/free
*
* @return 0 on success
*/
FREENECT2API int freenect2_shutdown(freenect2_context *ctx);
/// Typedef for logging callback functions
typedef void (*freenect2_log_cb)(freenect2_context *dev, freenect2_loglevel level, const char *msg);
/**
* Set the log level for the specified freenect2 context
*
* @param ctx context to set log level for
* @param level log level to use (see freenect_loglevel enum)
*/
FREENECT2API void freenect2_set_log_level(freenect2_context *ctx, freenect2_loglevel level);
/**
* Callback for log messages (i.e. for rerouting to a file instead of
* stdout)
*
* @param ctx context to set log callback for
* @param cb callback function pointer
*/
FREENECT2API void freenect2_set_log_callback(freenect2_context *ctx, freenect2_log_cb cb);
/**
* Scans for kinect devices and returns the number of kinect devices currently connected to the
* system
*
* @param ctx Context to access device count through
*
* @return Number of devices connected, < 0 on error
*/
FREENECT2API int freenect2_num_devices(freenect2_context *ctx);
/**
* Gets the attributes of a kinect device at a given index.
*
* @param ctx Context to access device attributes through
* @param index Index of the kinect device
*
* @return Number of devices connected, < 0 on error
*/
FREENECT2API freenect2_device_attributes freenect2_get_device_attributes(freenect2_context *ctx, int index);
/**
* Opens a kinect device via a context. Index specifies the index of
* the device on the current state of the bus. Bus resets may cause
* indexes to shift.
*
* @param ctx Context to open device through
* @param dev Device structure to assign opened device to
* @param index Index of the device on the bus
*
* @return 0 on success, < 0 on error
*/
FREENECT2API int freenect2_open_device(freenect2_context *ctx, freenect2_device **dev, int index);
/**
* Opens a kinect device (via a context) associated with a particular camera
* subdevice serial number. This function will fail if no device with a
* matching serial number is found.
*
* @param ctx Context to open device through
* @param dev Device structure to assign opened device to
* @param camera_serial Null-terminated ASCII string containing the serial number of the camera subdevice in the device to open
*
* @return 0 on success, < 0 on error
*/
FREENECT2API int freenect2_open_device_by_camera_serial(freenect2_context *ctx, freenect2_device **dev, const char* camera_serial);
/**
* Closes a device that is currently open
*
* @param dev Device to close
*
* @return 0 on success
*/
FREENECT2API int freenect2_close_device(freenect2_device *dev);
/// Typedef for depth image received event callbacks
typedef void (*freenect2_depth_cb)(freenect2_device *dev, uint32_t timestamp, void *depth, void *user);
/// Typedef for ir image received event callbacks
typedef void (*freenect2_ir_cb)(freenect2_device *dev, uint32_t timestamp, void *ir, void *user);
/// Typedef for video image received event callbacks
typedef void (*freenect2_video_cb)(freenect2_device *dev, uint32_t timestamp, void *video, void *user);
/**
* Set callback for depth information received event
*
* @param dev Device to set callback for
* @param cb Function pointer for processing depth information
* @param user Pointer to user data
*/
FREENECT2API void freenect2_set_depth_callback(freenect2_device *dev, freenect2_depth_cb cb, void *user);
/**
* Set callback for ir information received event
*
* @param dev Device to set callback for
* @param cb Function pointer for processing depth information
* @param user Pointer to user data
*/
FREENECT2API void freenect2_set_ir_callback(freenect2_device *dev, freenect2_ir_cb cb, void *user);
/**
* Set callback for video information received event
*
* @param dev Device to set callback for
* @param cb Function pointer for processing video information
* @param user Pointer to user data
*/
FREENECT2API void freenect2_set_video_callback(freenect2_device *dev, freenect2_video_cb cb, void *user);
/**
* Start the depth information stream for a device.
*
* @param dev Device to start depth information stream for.
*
* @return 0 on success, < 0 on error
*/
FREENECT2API int freenect2_start_depth(freenect2_device *dev);
/**
* Start the ir information stream for a device.
*
* @param dev Device to start ir information stream for.
*
* @return 0 on success, < 0 on error
*/
FREENECT2API int freenect2_start_ir(freenect2_device *dev);
/**
* Start the video information stream for a device.
*
* @param dev Device to start video information stream for.
*
* @return 0 on success, < 0 on error
*/
FREENECT2API int freenect2_start_video(freenect2_device *dev);
/**
* Stop the depth information stream for a device
*
* @param dev Device to stop depth information stream on.
*
* @return 0 on success, < 0 on error
*/
FREENECT2API int freenect2_stop_depth(freenect2_device *dev);
/**
* Stop the ir information stream for a device
*
* @param dev Device to stop ir information stream on.
*
* @return 0 on success, < 0 on error
*/
FREENECT2API int freenect2_stop_ir(freenect2_device *dev);
/**
* Stop the video information stream for a device
*
* @param dev Device to stop video information stream on.
*
* @return 0 on success, < 0 on error
*/
FREENECT2API int freenect2_stop_video(freenect2_device *dev);
/**
* Get the number of video camera modes supported by the driver.
*
* @return Number of video modes supported by the driver
*/
FREENECT2API int freenect2_get_video_mode_count();
/**
* Get the frame descriptor of the nth supported video mode for the
* video camera.
*
* @param mode_num Which of the supported modes to return information about
*
* @return A freenect2_frame_mode describing the nth video mode
*/
FREENECT2API freenect2_frame_mode freenect2_get_video_mode(int mode_num);
/**
* Get the frame descriptor of the current video mode for the specified
* freenect device.
*
* @param dev Which device to return the currently-set video mode for
*
* @return A freenect2_frame_mode describing the current video mode of the specified device
*/
FREENECT2API freenect2_frame_mode freenect2_get_current_video_mode(freenect2_device *dev);
/**
* Convenience function to return a mode descriptor matching the
* specified resolution and video camera pixel format, if one exists.
*
* @param res Resolution desired
* @param fmt Pixel format desired
*
* @return A freenect2_frame_mode that matches the arguments specified, if such a valid mode exists; otherwise, an invalid freenect2_frame_mode.
*/
FREENECT2API freenect2_frame_mode freenect2_find_video_mode(freenect2_resolution res, freenect2_video_format fmt);
/**
* Sets the current video mode for the specified device. If the
* freenect2_frame_mode specified is not one provided by the driver
* e.g. from freenect2_get_video_mode() or freenect2_find_video_mode()
* then behavior is undefined. The current video mode cannot be
* changed while streaming is active.
*
* @param dev Device for which to set the video mode
* @param mode Frame mode to set
*
* @return 0 on success, < 0 if error
*/
FREENECT2API int freenect2_set_video_mode(freenect2_device* dev, freenect2_frame_mode mode);
/**
* Get the number of ir camera modes supported by the driver.
*
* @return Number of ir modes supported by the driver
*/
FREENECT2API int freenect2_get_ir_mode_count();
/**
* Get the frame descriptor of the nth supported ir mode for the
* ir camera.
*
* @param mode_num Which of the supported modes to return information about
*
* @return A freenect2_frame_mode describing the nth ir mode
*/
FREENECT2API freenect2_frame_mode freenect2_get_ir_mode(int mode_num);
/**
* Get the frame descriptor of the current ir mode for the specified
* freenect device.
*
* @param dev Which device to return the currently-set ir mode for
*
* @return A freenect2_frame_mode describing the ir video mode of the specified device
*/
FREENECT2API freenect2_frame_mode freenect2_get_current_ir_mode(freenect2_device *dev);
/**
* Convenience function to return a mode descriptor matching the
* specified resolution and ir camera pixel format, if one exists.
*
* @param res Resolution desired
* @param fmt Pixel format desired
*
* @return A freenect2_frame_mode that matches the arguments specified, if such a valid mode exists; otherwise, an invalid freenect2_frame_mode.
*/
FREENECT2API freenect2_frame_mode freenect2_find_ir_mode(freenect2_resolution res, freenect2_ir_format fmt);
/**
* Sets the current ir mode for the specified device. If the
* freenect2_frame_mode specified is not one provided by the driver
* e.g. from freenect2_get_ir_mode() or freenect2_find_ir_mode()
* then behavior is undefined. The current ir mode cannot be
* changed while streaming is active.
*
* @param dev Device for which to set the ir mode
* @param mode Frame mode to set
*
* @return 0 on success, < 0 if error
*/
FREENECT2API int freenect2_set_ir_mode(freenect2_device* dev, freenect2_frame_mode mode);
/**
* Get the number of depth camera modes supported by the driver.
*
* @return Number of depth modes supported by the driver
*/
FREENECT2API int freenect2_get_depth_mode_count();
/**
* Get the frame descriptor of the nth supported depth mode for the
* depth camera.
*
* @param mode_num Which of the supported modes to return information about
*
* @return A freenect2_frame_mode describing the nth depth mode
*/
FREENECT2API freenect2_frame_mode freenect2_get_depth_mode(int mode_num);
/**
* Get the frame descriptor of the current depth mode for the specified
* freenect2 device.
*
* @param dev Which device to return the currently-set depth mode for
*
* @return A freenect2_frame_mode describing the current depth mode of the specified device
*/
FREENECT2API freenect2_frame_mode freenect2_get_current_depth_mode(freenect2_device *dev);
/**
* Convenience function to return a mode descriptor matching the
* specified resolution and depth camera pixel format, if one exists.
*
* @param res Resolution desired
* @param fmt Pixel format desired
*
* @return A freenect2_frame_mode that matches the arguments specified, if such a valid mode exists; otherwise, an invalid freenect2_frame_mode.
*/
FREENECT2API freenect2_frame_mode freenect2_find_depth_mode(freenect2_resolution res, freenect2_depth_format fmt);
/**
* Sets the current depth mode for the specified device. The mode
* cannot be changed while streaming is active.
*
* @param dev Device for which to set the depth mode
* @param mode Frame mode to set
*
* @return 0 on success, < 0 if error
*/
FREENECT2API int freenect2_set_depth_mode(freenect2_device* dev, const freenect2_frame_mode mode);
/**
* Enables or disables the specified flag.
*
* @param flag Feature to set
* @param value `FREENECT2_OFF` or `FREENECT2_ON`
*
* @return 0 on success, < 0 if error
*/
FREENECT2API int freenect2_set_flag(freenect2_device *dev, freenect2_flag flag, freenect2_flag_value value);
#ifdef __cplusplus
}
#endif
| {
"content_hash": "8dc9617e6b72ac08eef5243d2a20a1a9",
"timestamp": "",
"source": "github",
"line_count": 474,
"max_line_length": 225,
"avg_line_length": 35.91772151898734,
"alnum_prop": 0.7241116005873716,
"repo_name": "mafua/ofxKinectTest",
"id": "ad0eafc356d5eb1fd3f27ecabcb342979f5b75e7",
"size": "18123",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "libs/libfreenect2/include/libfreenect2.h",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "169957"
},
{
"name": "C++",
"bytes": "160721"
},
{
"name": "GLSL",
"bytes": "15166"
},
{
"name": "Makefile",
"bytes": "382"
}
],
"symlink_target": ""
} |
{% extends "base.html" %}
{% block prerender %}
<link rel="prerender" href="/library">
{% endblock prerender %}
{% block maintitle %}
I18N_SPLASH_PAGE_TITLE
{% endblock maintitle %}
{% block header_js %}
{{ super() }}
<style>
html, body {
background-color: #f2f2ee;
}
</style>
{% endblock %}
{% block navbar_breadcrumb %}
{% endblock navbar_breadcrumb %}
{% block content %}
<div ng-controller="Splash">
<div class="oppia-splash-section-one text-center">
<h1 class="oppia-splash-h1" style="max-width: 800px; font-size: 2.3em; line-height: 1.5em; padding-bottom: 0.5em;">Tired of grading homework?</h1>
<div style="position: relative; left: -webkit-calc(-70px + 15%); left: -moz-calc(-70px + 15%); left: -o-calc(-70px + 15%); left: calc(-70px + 15%);">
<h2 style="max-width: 400px; color: #005c53; font-size: 1.6em; font-family: Capriola; line-height: 1.5em;">
Interactive explorations help students learn faster, and don't need grading.
</h2>
</div>
<div style="position: relative;">
<div style="padding-left: 200px;">
<div class="oppia-splash-background-icon-row">
<img ng-src="<[getStaticImageUrl('/splash/books.svg')]>" class="oppia-splash-books" style="margin-left: -250px; width: 500px; top: 95px;">
<img ng-src="<[getStaticSubjectImageUrl('Humor')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Combinatorics')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Cooking')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Government')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Architecture')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('History')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Microbiology')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Engineering')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Algorithms')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Economics')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Computing')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Reading')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Art')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Creativity')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Physics')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Language')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Arithmetic')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Chess')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Astronomy')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Religion')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Mathematics')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Philosophy')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Humor')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Combinatorics')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Cooking')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Government')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Architecture')]>" class="oppia-splash-background-icon">
</div>
<div class="oppia-splash-background-icon-row">
<img ng-src="<[getStaticSubjectImageUrl('Genetics')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Space')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Algebra')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Music')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Chemistry')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Poetry')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Puzzles')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Calculus')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Business')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Geography')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Biology')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Genetics')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Space')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Algebra')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Music')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Chemistry')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Poetry')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Puzzles')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Calculus')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Business')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Geography')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Biology')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Genetics')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Space')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Algebra')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Music')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Chemistry')]>" class="oppia-splash-background-icon">
</div>
<div class="oppia-splash-background-icon-row">
<img ng-src="<[getStaticSubjectImageUrl('Economics')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Algorithms')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Creativity')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Astronomy')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Chess')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Arithmetic')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Language')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Physics')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Combinatorics')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Humor')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Philosophy')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Mathematics')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Religion')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Cooking')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Engineering')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Microbiology')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('History')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Architecture')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Government')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Art')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Reading')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Computing')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Economics')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Algorithms')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Creativity')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Astronomy')]>" class="oppia-splash-background-icon">
<img ng-src="<[getStaticSubjectImageUrl('Chess')]>" class="oppia-splash-background-icon">
</div>
</div>
<div style="position: absolute; width: 100%;">
{% if not user_is_logged_in %}
<!-- User must complete the registration process. -->
<button type="button"
ng-click="onRedirectToLogin('/dashboard?mode=create')"
class="btn oppia-splash-button oppia-splash-button-create oppia-transition-200"
style="left: -webkit-calc(130px + 15%); left: -moz-calc(130px + 15%); left: -o-calc(130px + 15%); left: calc(130px + 15%); bottom: 210px; z-index: 10;"
translate="I18N_ACTION_CREATE_LESSON">
</button>
{% else %}
<button type="button"
ng-click="onClickCreateExplorationButton()"
class="btn oppia-splash-button oppia-splash-button-create oppia-transition-200"
style="left: -webkit-calc(130px + 15%); left: -moz-calc(130px + 15%); left: -o-calc(130px + 15%); left: calc(130px + 15%); bottom: 210px; z-index: 10;"
translate="I18N_ACTION_CREATE_LESSON">
</button>
{% endif %}
<button type="button" ng-click="onClickBrowseLibraryButton()"
class="btn oppia-splash-button oppia-splash-button-browse oppia-transition-200"
style="left: -webkit-calc(130px + 15%); left: -moz-calc(130px + 15%); left: -o-calc(130px + 15%); left: calc(130px + 15%); bottom: 150px; font-size: 0.93em; z-index: 10;"
translate="I18N_ACTION_BROWSE_LESSONS">
</button>
</div>
</div>
<div class="oppia-splash-h2-container">
<h2 class="oppia-splash-h2" style="padding-bottom: 30px; font-size: 1.6em; padding-top: 100px; max-width: 700px;">
</h2>
</div>
</div>
<div class="oppia-splash-section-two">
<div class="oppia-splash-section-two-content" style="padding-top: 0;">
<div class="oppia-splash-bullet" style="overflow: visible;">
<div class="oppia-splash-bullet-block oppia-splash-block-left-image">
<img ng-src="<[getStaticImageUrl('/splash/bullet1icon.svg')]>" class="oppia-splash-overlapping-image-1">
</div>
<div class="oppia-splash-bullet-block oppia-splash-block-right-text"
translate="I18N_SPLASH_FIRST_EXPLORATION_DESCRIPTION_ALTERNATE">
</div>
</div>
<div class="oppia-splash-bullet" style="clear: both;">
<div class="oppia-splash-bullet-block oppia-splash-block-right-image">
<img ng-src="<[getStaticImageUrl('/splash/bullet2icon.svg')]>">
</div>
<div class="oppia-splash-bullet-block oppia-splash-block-left-text"
translate="I18N_SPLASH_SECOND_EXPLORATION_DESCRIPTION">
</div>
</div>
<div class="oppia-splash-bullet">
<div class="oppia-splash-bullet-block oppia-splash-block-left-image">
<img ng-src="<[getStaticImageUrl('/splash/bullet3icon.svg')]>">
</div>
<div class="oppia-splash-bullet-block oppia-splash-block-right-text"
translate="I18N_SPLASH_THIRD_EXPLORATION_DESCRIPTION">
</div>
</div>
</div>
</div>
</div>
<style>
@media (min-width: 608px) {
.oppia-splash-overlapping-image-1 {
margin-top: -105px;
}
}
@media (max-width: 608px) {
.oppia-splash-overlapping-image-1 {
margin-top: -30px;
}
}
</style>
{% endblock %}
{% block footer %}
{% include 'footer.html' %}
{% endblock %}
{% block footer_js %}
{{ super() }}
<script src="{{TEMPLATE_DIR_PREFIX}}/pages/splash/Splash.js"></script>
{% endblock footer_js %}
| {
"content_hash": "5c0631d087b1f5865d2a8abafacd5a84",
"timestamp": "",
"source": "github",
"line_count": 222,
"max_line_length": 188,
"avg_line_length": 61.914414414414416,
"alnum_prop": 0.6343397599126955,
"repo_name": "MaximLich/oppia",
"id": "de3c36a3888817c10dad8590d01e0890d4457177",
"size": "13745",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "core/templates/dev/head/pages/splash/splash_ah1.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "88445"
},
{
"name": "HTML",
"bytes": "734882"
},
{
"name": "JavaScript",
"bytes": "2302526"
},
{
"name": "Python",
"bytes": "2599422"
},
{
"name": "Shell",
"bytes": "45916"
}
],
"symlink_target": ""
} |
package io.getlime.security.powerauth.lib.webflow.authentication.exception;
/**
* Invalid chosen method exception.
*
* @author Roman Strobl, roman.strobl@wultra.com
*/
public class AuthMethodNotAvailableException extends AuthStepException {
/**
* Constructor with message.
*
* @param message Error message.
*/
public AuthMethodNotAvailableException(String message) {
super(message, "operation.methodNotAvailable");
}
}
| {
"content_hash": "a82b7a3937acfbde5ed8b78b1093027d",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 75,
"avg_line_length": 22.285714285714285,
"alnum_prop": 0.7094017094017094,
"repo_name": "lime-company/powerauth-webflow",
"id": "1672660929e232c9dfabb555f7a7bd883fbf463d",
"size": "1234",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "powerauth-webflow-authentication/src/main/java/io/getlime/security/powerauth/lib/webflow/authentication/exception/AuthMethodNotAvailableException.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "12919"
},
{
"name": "HTML",
"bytes": "10042"
},
{
"name": "Java",
"bytes": "889385"
},
{
"name": "JavaScript",
"bytes": "120890"
}
],
"symlink_target": ""
} |
function dayct2
% dayct2: count number of gridpoint or region rainy days each year in specified seasonal window
% dayct2;
% Last revised: 11-26-01 to accomodate optionally mean-adjusted files
%
% Previously ran gridday1.m to get storage file (e.g., day1b.mat) with logical rainy-or-not daily
% tsm for gridpoints, and a daily tsm of fraction of gridpoints rainy. Now want to summarize data
% over season (e.g., summer). Question is how many rainy days each year in that season at each gridpoint.
% Another question is how many regionally rainy days each year, based on a threshold fraction of
% gridpoints rainy. And, total precip each season.
%
%*** INPUT
%
% No input args
% Prompted for infile produced by gridday1.m
% Prompted for name of outfile to hold results
%
%
%*** OUTPUT
%
% No output args
% Outfile of results has data on number of rainy days each year in the seasonal window, with
% associated data. See vlist stored with outfile for definitions
%
%*** REFERENCE -- NONE
%*** UW FUNCTIONS CALLED -- NONE
%*** TOOLBOXES NEEDED -- NONE
%
%*** NOTES
%
% Input daily tsm should be in the usual form. Year, month, day, "366"-day as cols 1-4. Time series for
% gridpoints, etc. as remaining cols.
%
% Output time series matrix is an annual time series matrix. Col 1 is the year, defined as the year of the
% ending day of the specified period. So if the season crosses from Dec into Jan, year is that of Jan.
% Example: [241 31] is previous year's Sept 1 (about) to Jan 31
% Remaining cols are the annual values of number of rainy days, or seasonal total precip
%
%
%*********************** NOTES ***********************************
%
% Template: dayct1.m
% Previously name rainy.m when developed for Connie Woodhouse rainy day analysis
%
% Daily ppt matrix X should contain 366 days for each year, with possibly
% fewer days in the first and last year. It is assumed that all missing
% data have been filled in beforehand. Day 60 (Feb 29) on non-leap years
% should have a missing-value code. It makes no difference to this function
% what the code is, because the code is replaced with zeros for the count
% of number of rainy days and the total rainfall over the day window.
%
% Be careful to consider the time coverage by valid daily data in choosing
% the analysis period YRS(2,:). For example, if valid daily data start in
% Jan 5, 1900 and end in Nov 28, 1993, the combination
% endday = [1 366], YRS = [1900 1993; 1900 1993]
% gives bogus values for years 1900 and 1993. If you want to have a day
% window 1-366 for this example, you can at best get an annual series
% for 1901-1993 (i.e., YRS=[1900 1993; 1901 1992]).
%
%
%****************** OUT ARGS ***********************************
%
% Y1 (mY1 x nY1) number of rainy days in day window (enddays)
% at each station in each year of the specified analysis period
% col 1: year
% col 2-nY1: values for each of nY1-1 stations
% rows: each row is a year
% Y2 (mY2 x nY2) like Y1, except total rainfall, in inches
%
%
%
% PLAN
%
%-- Prompt for specs
%-- Get input data file
%-- Flesh out daily matrix to begin Jan 1, end Dec 31
%-- Compute year information for the output day-windowed series
%-- Compute long-term daily mean of fraction of gridpoints rainy
%-- Compute n-rainy series for regional fraction-rainy data
%-- Compute n-rainy series for individual gridpoints
%-- Prepare output
%---- Prompt for whether using non-adjusted data or means-adjusted
kadj = menu('Choose',...
'Unadjusted daily ppt as input',...
'Adjusted (means-adjusted) daily ppt as input');
if kadj==1;
meanadj='No';
else;
meanadj='Yes';
end;
%---- Prompt for start and end day of season
prompt={'Enter start day','Enter end day'};
def={'183','244'};
dlgTitle='Starting and ending days of season';
lineNo=1;
answer=inputdlg(prompt,dlgTitle,lineNo,def);
endday=[str2num(answer{1}) str2num(answer{2})];
clear def dlgTitle lineNo answer
%---- Prompt for fraction of gridpoints wet to define regionally wet day
prompt={'Enter fraction'};
def={'.50'};
dlgTitle='Threshold fraction of gridpoints wet defining regionally wet day';
lineNo=1;
answer=inputdlg(prompt,dlgTitle,lineNo,def);
fract=[str2num(answer{1}) ];
clear def dlgTitle lineNo answer
%-- Get input data file
switch meanadj;
case 'No';
[file1,path1]=uigetfile('day?b.mat','Infile with gridpoint daily tsm of wet or not');
case 'Yes';
[file1,path1]=uigetfile('day?bx.mat','Infile with gridpoint daily tsm of wet or not');
otherwise;
end;
pf1=[path1 file1];
eval(['load ' pf1 ' G H pcrit U;']);
% G is daily tsm of wet or not for each gridpoint; gridpoint logical variables in cols 5-on
% H is cv of daily fraction of gridpoint wet; same row size as
% U is cv of daily total precip for the region, computed from griddpoint data by griddata1
%-- prompt for name of output file
switch meanadj;
case 'No';
deffn = ['day' file1(4) 'c.mat'];
case 'Yes';
deffn = ['day' file1(4) 'cx.mat'];
otherwise;
end;
[file2,path2]=uiputfile(deffn,'Outfile to hold summary number of rainy day data');
pf2=[path2 file2];
%-- Flesh out daily matrices G and U to begin Jan 1, end Dec 31
[mG,nG]=size(G);
daygo=G(1,4);
yrgo = G(1,1);
daysp=G(mG,4);
yrsp = G(mG,1);
mss = NaN;
if daygo~=1 ; % first row of G is not for Jan 1
daycv = (1:(daygo-1))'; % cv of days to splice at start of X
nadd = length(daycv);
yrcv = repmat(yrgo,ndd,1); % cv of duped first year
MSgo = repmat(NaN,nadd,(nG-4));
Ggo = [yrcv repmat(NaN,nadd,2) daycv MSgo];
G=[Ggo; G];
H=[repmat(NaN,nadd,1) ; H];
U=[repmat(NaN,nadd,1) ; U];
end
if daysp~=366 ; % last row of G is not for Dec 31
daycv = ((daysp+1):366)'; % cv of days to splice at end of G
nadd = length(daycv);
yrcv = repmat(yrsp,nadd,1); % cv of duped last year
MSsp = repmat(mxx,nadd,(nG-4));
Gsp = [yrcv daycv MSsp];
G=[G; Gsp];
H=[H; repmat(NaN,nadd,1)];
U=[U ; repmat(NaN,nadd,1) ];
end
% Check data consistency
% Compatible row size of X and YRS?
[mG,nG]=size(G);
if rem(mG,366)~=0;
error('row size of G should be even multiple of 366');
end;
%-- Compute year information for the output day-windowed series
year = G(:,1); % cv of years for input daily tsm
% Possible first year of day-windowed output, and first needed year
% of input data depend on whether day window crosses the calendar year
% boundary.
k1 = 0; % indicator for day window crossing year boundary
if endday(1) < endday(2); % day window does not cross calendar year boundary
first = year(1); % will need data from this year to form first year's grouping
goposs = year(1); % first possible year for day-window data
else; % crosses year boundary
first = year(1) - 1; % will need preceding years data
goposs = year(1) + 1; % earliest possible year for day-windowed series
k1 =1 ; % flag indicating that day window crosses year boundary
end;
spposs=max(year); % last possible year of day-windowed series
nyrs = spposs-goposs+1; % # of years of output series
yr = (goposs:spposs)'; % cv of output years
nstns = nG -4; % number of gridpoint series
%-- Compute long-term daily mean of fraction of gridpoints rainy
Hmn=repmat(NaN,366,2);
Hstd=repmat(NaN,366,2);
Hmn(:,1)=(1:366)';
Hstd(:,1)=(1:366)';
for i=1:366
L5=G(:,4)==i; % Select this day; H is same row-arrangement as G
HH1=H(L5);
hmn=nanmean(HH1);
Hmn(i,2)=hmn;
hstd=nanstd(HH1);
Hstd(i,2)=hstd;
end
%-- Compute long-term daily mean of total regional pcp
Umn=repmat(NaN,366,2);
Ustd=repmat(NaN,366,2);
Umn(:,1)=(1:366)';
Ustd(:,1)=(1:366)';
for i=1:366
L5=G(:,4)==i; % Select this day; H is same row-arrangement as G
UU1=U(L5);
umn=nanmean(UU1);
Umn(i,2)=umn;
ustd=nanstd(UU1);
Ustd(i,2)=ustd;
end
%-- Compute annual time series of fraction of gridpoints rainy in time window
%---- Compute number of days in day window, and form pointer to days
if k1==0; % not cross year boundary
L2 = G(:,4) >= endday(1) & G(:,4)<= endday(2);
L6 = Hmn(:,1) >= endday(1) & Hmn(:,1) <= endday(2);
ndays = endday(2) - endday(1) +1; % # days in day window
else
L2=(G(:,4)>=endday(1) & G(:,4)<=366) | (G(:,4)>=1 & G(:,4)<= endday(2));
L6=(Hmn(:,1)>=endday(1) & Hmn(:,1)<=366)|(Hmn(:,1)>=1 & Hmn(:,1)<= endday(2));
ndays = (366 - endday(1)+1) + endday(2);
end
% Make pointer to years of G needed for analysis period; depends on whether season crosses Dec 31, via first
L1 = G(:,1) >= first & G(:,1) <= spposs;
% allocate for time series & initialize
% F: col 1= year
% col 2 = number of days with fraction of gridpoints wet >= fract
% col 3 = average daily fraction of gridpoints wet
F=[yr repmat(NaN,nyrs,3)];
% Get needed rows of H , Hmn and Hstd,etc
H1 = H(L1 & L2,:);
Hmn1=Hmn(L6,2);
Hstd1=Hstd(L6,2);
U1 = U(L1 & L2,:);
Umn1=Umn(L6,2);
Ustd1=Ustd(L6,2);
% Truncate leading and trailing if window crosses year boundary;
if k1==1;
H1(1:endday(2),:)= [];
[mH1,nH1]=size(H1);
nout = 366 - endday(1) + 1; % # trailing days to drop off
nn = mH1 - nout;
H1=H1(1:nn,:);
U1(1:endday(2),:)= [];
[mU1,nU1]=size(U1);
nout = 366 - endday(1) + 1; % # trailing days to drop off
nn = mU1 - nout;
U1=U1(1:nn,:);
end
% H1, U1 should now have only the specified days in the day window
[mH1,nH1]=size(H1);
nr2 = ndays * (spposs-goposs + 1); % expected number of rows in H1
if nr2 ~= mH1
error('Row size of H1 incorrect')
end
%---- Compute number of valid (non-NaN) days each year in the endday window
Htemp= reshape(H1,ndays,nyrs);
nvalidH = (sum(~isnan(Htemp)))';
nvalidH=[yr nvalidH];
Utemp= reshape(U1,ndays,nyrs);
nvalidU = (sum(~isnan(Utemp)))';
nvalidU=[yr nvalidU];
%---- COMPUTE ANNUAL TIME SERIES OF NUMBER OF REGIONALLY WET DAYS IN SPECIFIED SEASONAL WINDOW
NH =[yr (sum(Htemp>fract))'];
Z = [yr (sum(Utemp))'];
%
% Recall a regionally wet day defined as fraction of gridpoints wet >= fract
% where a gridpoint/day is defined as wet if the median station P of stations in locus wet, and
% and a station is defined as wet if daily P>pcrit, as stored in input file day?b.mat
%
%--- OPERATE ON INDIVIDUAL GRIDPOINTS
%
% Recall that G is a logical daily tsm of rainy days at individual gridpoints. Cols 5-on hold
% the data for each gridpoint. See pf1 input file variable Gxy(Ireg,:) for the gridpoints, and
% Gstn{} for the stations for each gridpoint
%-- For each gridpoint, compute long-term fract of years wet, for each day of year
GF=repmat(NaN,366,nstns+1);
GN=repmat(NaN,366,nstns+1);
GF(:,1)=(1:366)';
GN(:,1)=(1:366)';
for i=1:366
L5=G(:,4)==i; % Select this day
GG1=G(L5,5:(nstns+4));
GF(i,(2:(nstns+1))) = nanmean(GG1);
% Compute number of valid (non-NaN) days, i.e., how many years the mean for that day is based on
GN (i,(2:nstns+1)) = sum(~isnan(GG1));
end;
% The annual tsm of gridpoint number of rainy days in window
% Get needed rows of G
G1 = G(L1 & L2,5:(nstns+4));
% Truncate leading and trailing if window crosses year boundary;
if k1==1;
G1(1:endday(2),:)= [];
[mG1,nG1]=size(G1);
nout = 366 - endday(1) + 1; % # trailing days to drop off
nn = mG1 - nout;
G1=G1(1:nn,:);
end
% G1 should now have only the specified days in the day window
[mG1,nG1]=size(G1);
nr2 = ndays * (spposs-goposs + 1); % expected number of rows in G1
if nr2 ~= mG1
error('Row size of G1 incorrect')
end
% Allocate & initialize for annual tsm of number of days wet at each gridpoint
% K: col 1= year
% col 2 = number of days wet at gridpoint 1, in order as Gxy(Ireg,:)
% col 3 = number ... gridpoint 2 ...
K=[yr repmat(NaN,nyrs,nstns)];
KN = [yr repmat(NaN,nyrs,nstns)]; % number of valid days (might be less than ndays) elements of K computed on
for n = 1:nstns ; % loop over gridpoints
x2 = G1(:,n); % get a gridpoint's daily data indicator of wet or not
x2 = reshape(x2,ndays,nyrs); % make into a matrix convenient for summing
K(:,n+1)=(nansum(x2))';
KN(:,n+1)= (sum(~isnan(x2)))';
end;
% SAVE OUTPUT
vlist = ['Produced by dayct2.m on ' pf1 ' with'];
vlist=char(vlist,[' pcrit = ' num2str(pcrit) ' : pre-set threshold (in) for wet day at each station']);
vlist=char(vlist,[' endday = ' int2str(endday) ' : start and end day of season']);
vlist=char(vlist,[' fract = ' num2str(fract) ' : critical fraction of gridpoints required wet']);
vlist=char(vlist,['Hmn long-term mean daily fraction of gridpoints wet']);
vlist=char(vlist,['Hstd ... standard dev of daily ....']);
vlist=char(vlist,['nvalidH= number of non-NaN days in seasonal window each year for input time series H']);
vlist=char(vlist,['NH = number of regionally rainy days in seasonal window each year']);
vlist=char(vlist,['GF= fraction of years in which each day of year was wet at each gridpoint (column)']);
vlist=char(vlist,['GN= sample size (number of valid years) on which fractions in GF computed']);
vlist=char(vlist,['K = annual tsm of number of days wet in seasonal window, by gridpoint']);
vlist=char(vlist,['KN = sample size (number of non-NaN days) on which sums in K computed']);
vlist=char(vlist,['Z = annual tsm of total regional precip in seasonal window']);
vlist=char(vlist,['Date produced = ' date]);
% vlist=char(vlist,
set1 = ' vlist endday pcrit fract Hmn Hstd nvalidH NH GF GN K KN Z';
eval(['save ' pf2 set1 ';'])
| {
"content_hash": "3cf144602a78daf5be26b743ecc518c8",
"timestamp": "",
"source": "github",
"line_count": 406,
"max_line_length": 109,
"avg_line_length": 32.76108374384236,
"alnum_prop": 0.6717540034583865,
"repo_name": "ltrr-arizona-edu/tree-ring-toolbox",
"id": "d0cc5730ed45e1232537acdd9d9a13742d0a68dd",
"size": "13301",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "daily/dayct2.m",
"mode": "33261",
"license": "bsd-2-clause",
"language": [
{
"name": "Erlang",
"bytes": "144"
},
{
"name": "FORTRAN",
"bytes": "13600"
},
{
"name": "JavaScript",
"bytes": "3201"
},
{
"name": "M",
"bytes": "795651"
},
{
"name": "Matlab",
"bytes": "3917725"
},
{
"name": "Objective-C",
"bytes": "16865"
},
{
"name": "Perl",
"bytes": "38239"
},
{
"name": "Python",
"bytes": "69"
},
{
"name": "Racket",
"bytes": "7224"
},
{
"name": "Shell",
"bytes": "7422"
}
],
"symlink_target": ""
} |
namespace ModuleZeroSampleProject.Authorization.Roles
{
public static class StaticRoleNames
{
public static class Host
{
public const string Admin = "Admin";
}
public static class Tenants
{
public const string Admin = "Admin";
}
}
} | {
"content_hash": "618e02e674b8259177145eda2b303bea",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 53,
"avg_line_length": 21.133333333333333,
"alnum_prop": 0.5709779179810726,
"repo_name": "aspnetboilerplate/questions-answers",
"id": "a17e981d8e4e8288e46fecbd8189cb2069bc1b0c",
"size": "317",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/ModuleZeroSampleProject.Core/Authorization/Roles/StaticRoleNames.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "118"
},
{
"name": "C#",
"bytes": "143506"
},
{
"name": "CSS",
"bytes": "91065"
},
{
"name": "HTML",
"bytes": "16282"
},
{
"name": "JavaScript",
"bytes": "13608"
}
],
"symlink_target": ""
} |
'use strict';
/* jshint ignore:start */
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
/* jshint ignore:end */
var _ = require('lodash'); /* jshint ignore:line */
var Holodeck = require('../../../../holodeck'); /* jshint ignore:line */
var Request = require(
'../../../../../../lib/http/request'); /* jshint ignore:line */
var Response = require(
'../../../../../../lib/http/response'); /* jshint ignore:line */
var RestException = require(
'../../../../../../lib/base/RestException'); /* jshint ignore:line */
var Twilio = require('../../../../../../lib'); /* jshint ignore:line */
var client;
var holodeck;
describe('Event', function() {
beforeEach(function() {
holodeck = new Holodeck();
client = new Twilio('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 'AUTHTOKEN', {
httpClient: holodeck
});
});
it('should generate valid fetch request',
function() {
holodeck.mock(new Response(500, '{}'));
var promise = client.taskrouter.v1.workspaces('WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.events('EVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch();
promise = promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
});
promise.done();
var solution = {
workspaceSid: 'WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
sid: 'EVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
};
var url = _.template('https://taskrouter.twilio.com/v1/Workspaces/<%= workspaceSid %>/Events/<%= sid %>')(solution);
holodeck.assertHasRequest(new Request({
method: 'GET',
url: url
}));
}
);
it('should generate valid fetch response',
function() {
var body = JSON.stringify({
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'actor_sid': 'WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'actor_type': 'workspace',
'actor_url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'description': 'Worker JustinWorker updated to Idle Activity',
'event_data': {
'worker_activity_name': 'Offline',
'worker_activity_sid': 'WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'worker_attributes': '{}',
'worker_name': 'JustinWorker',
'worker_sid': 'WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'worker_time_in_previous_activity': '26',
'workspace_name': 'WorkspaceName',
'workspace_sid': 'WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
},
'event_date': '2015-02-07T00:32:41Z',
'event_type': 'worker.activity',
'resource_sid': 'WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'resource_type': 'worker',
'resource_url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'sid': 'EVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'source': 'twilio',
'source_ip_address': '1.2.3.4',
'url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events/EVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
});
holodeck.mock(new Response(200, body));
var promise = client.taskrouter.v1.workspaces('WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.events('EVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch();
promise = promise.then(function(response) {
expect(response).toBeDefined();
}, function() {
throw new Error('failed');
});
promise.done();
}
);
it('should treat the first each arg as a callback',
function(done) {
var body = JSON.stringify({
'events': [
{
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'actor_sid': 'WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'actor_type': 'workspace',
'actor_url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'description': 'Worker JustinWorker updated to Idle Activity',
'event_data': {
'worker_activity_name': 'Offline',
'worker_activity_sid': 'WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'worker_attributes': '{}',
'worker_name': 'JustinWorker',
'worker_sid': 'WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'worker_time_in_previous_activity': '26',
'workspace_name': 'WorkspaceName',
'workspace_sid': 'WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
},
'event_date': '2015-02-07T00:32:41Z',
'event_type': 'worker.activity',
'resource_sid': 'WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'resource_type': 'worker',
'resource_url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'sid': 'EVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'source': 'twilio',
'source_ip_address': '1.2.3.4',
'url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events/EVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
}
],
'meta': {
'first_page_url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events?PageSize=50&Page=0',
'key': 'events',
'next_page_url': null,
'page': 0,
'page_size': 50,
'previous_page_url': null,
'url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events?PageSize=50&Page=0'
}
});
holodeck.mock(new Response(200, body));
client.taskrouter.v1.workspaces('WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.events.each(() => done());
}
);
it('should treat the second arg as a callback',
function(done) {
var body = JSON.stringify({
'events': [
{
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'actor_sid': 'WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'actor_type': 'workspace',
'actor_url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'description': 'Worker JustinWorker updated to Idle Activity',
'event_data': {
'worker_activity_name': 'Offline',
'worker_activity_sid': 'WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'worker_attributes': '{}',
'worker_name': 'JustinWorker',
'worker_sid': 'WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'worker_time_in_previous_activity': '26',
'workspace_name': 'WorkspaceName',
'workspace_sid': 'WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
},
'event_date': '2015-02-07T00:32:41Z',
'event_type': 'worker.activity',
'resource_sid': 'WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'resource_type': 'worker',
'resource_url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'sid': 'EVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'source': 'twilio',
'source_ip_address': '1.2.3.4',
'url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events/EVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
}
],
'meta': {
'first_page_url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events?PageSize=50&Page=0',
'key': 'events',
'next_page_url': null,
'page': 0,
'page_size': 50,
'previous_page_url': null,
'url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events?PageSize=50&Page=0'
}
});
holodeck.mock(new Response(200, body));
client.taskrouter.v1.workspaces('WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.events.each({pageSize: 20}, () => done());
holodeck.assertHasRequest(new Request({
method: 'GET',
url: 'https://taskrouter.twilio.com/v1/Workspaces/<%= workspaceSid %>/Events',
params: {PageSize: 20},
}));
}
);
it('should find the callback in the opts object',
function(done) {
var body = JSON.stringify({
'events': [
{
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'actor_sid': 'WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'actor_type': 'workspace',
'actor_url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'description': 'Worker JustinWorker updated to Idle Activity',
'event_data': {
'worker_activity_name': 'Offline',
'worker_activity_sid': 'WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'worker_attributes': '{}',
'worker_name': 'JustinWorker',
'worker_sid': 'WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'worker_time_in_previous_activity': '26',
'workspace_name': 'WorkspaceName',
'workspace_sid': 'WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
},
'event_date': '2015-02-07T00:32:41Z',
'event_type': 'worker.activity',
'resource_sid': 'WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'resource_type': 'worker',
'resource_url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'sid': 'EVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'source': 'twilio',
'source_ip_address': '1.2.3.4',
'url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events/EVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
}
],
'meta': {
'first_page_url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events?PageSize=50&Page=0',
'key': 'events',
'next_page_url': null,
'page': 0,
'page_size': 50,
'previous_page_url': null,
'url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events?PageSize=50&Page=0'
}
});
holodeck.mock(new Response(200, body));
client.taskrouter.v1.workspaces('WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.events.each({callback: () => done()}, () => fail('wrong callback!'));
}
);
it('should generate valid list request',
function() {
holodeck.mock(new Response(500, '{}'));
var promise = client.taskrouter.v1.workspaces('WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.events.list();
promise = promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
});
promise.done();
var solution = {workspaceSid: 'WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'};
var url = _.template('https://taskrouter.twilio.com/v1/Workspaces/<%= workspaceSid %>/Events')(solution);
holodeck.assertHasRequest(new Request({
method: 'GET',
url: url
}));
}
);
it('should generate valid read_full response',
function() {
var body = JSON.stringify({
'events': [
{
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'actor_sid': 'WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'actor_type': 'workspace',
'actor_url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'description': 'Worker JustinWorker updated to Idle Activity',
'event_data': {
'worker_activity_name': 'Offline',
'worker_activity_sid': 'WAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'worker_attributes': '{}',
'worker_name': 'JustinWorker',
'worker_sid': 'WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'worker_time_in_previous_activity': '26',
'workspace_name': 'WorkspaceName',
'workspace_sid': 'WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
},
'event_date': '2015-02-07T00:32:41Z',
'event_type': 'worker.activity',
'resource_sid': 'WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'resource_type': 'worker',
'resource_url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Workers/WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'sid': 'EVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'source': 'twilio',
'source_ip_address': '1.2.3.4',
'url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events/EVaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
}
],
'meta': {
'first_page_url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events?PageSize=50&Page=0',
'key': 'events',
'next_page_url': null,
'page': 0,
'page_size': 50,
'previous_page_url': null,
'url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events?PageSize=50&Page=0'
}
});
holodeck.mock(new Response(200, body));
var promise = client.taskrouter.v1.workspaces('WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.events.list();
promise = promise.then(function(response) {
expect(response).toBeDefined();
}, function() {
throw new Error('failed');
});
promise.done();
}
);
it('should generate valid read_empty response',
function() {
var body = JSON.stringify({
'events': [],
'meta': {
'first_page_url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events?PageSize=50&Page=0',
'key': 'events',
'next_page_url': null,
'page': 0,
'page_size': 50,
'previous_page_url': null,
'url': 'https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events?PageSize=50&Page=0'
}
});
holodeck.mock(new Response(200, body));
var promise = client.taskrouter.v1.workspaces('WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.events.list();
promise = promise.then(function(response) {
expect(response).toBeDefined();
}, function() {
throw new Error('failed');
});
promise.done();
}
);
});
| {
"content_hash": "18ba2f966ae91d01fbc92c6098411f49",
"timestamp": "",
"source": "github",
"line_count": 348,
"max_line_length": 158,
"avg_line_length": 45.46551724137931,
"alnum_prop": 0.5628239160662369,
"repo_name": "philnash/twilio-node",
"id": "68900e9fcfbd98a8cef2a99f0fd2b1fd297364bd",
"size": "15822",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/integration/rest/taskrouter/v1/workspace/event.spec.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "161"
},
{
"name": "JavaScript",
"bytes": "8949872"
},
{
"name": "Makefile",
"bytes": "872"
}
],
"symlink_target": ""
} |
package org.elasticsearch.client.sniff;
import com.carrotsearch.randomizedtesting.generators.RandomNumbers;
import com.carrotsearch.randomizedtesting.generators.RandomPicks;
import com.carrotsearch.randomizedtesting.generators.RandomStrings;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.apache.http.Consts;
import org.apache.http.HttpHost;
import org.apache.http.client.methods.HttpGet;
import org.elasticsearch.client.Node;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientTestCase;
import org.elasticsearch.mocksocket.MockHttpServer;
import org.junit.After;
import org.junit.Before;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
public class ElasticsearchNodesSnifferTests extends RestClientTestCase {
private int sniffRequestTimeout;
private ElasticsearchNodesSniffer.Scheme scheme;
private SniffResponse sniffResponse;
private HttpServer httpServer;
@Before
public void startHttpServer() throws IOException {
this.sniffRequestTimeout = RandomNumbers.randomIntBetween(getRandom(), 1000, 10000);
this.scheme = RandomPicks.randomFrom(getRandom(), ElasticsearchNodesSniffer.Scheme.values());
if (rarely()) {
this.sniffResponse = SniffResponse.buildFailure();
} else {
this.sniffResponse = buildSniffResponse(scheme);
}
this.httpServer = createHttpServer(sniffResponse, sniffRequestTimeout);
this.httpServer.start();
}
@After
public void stopHttpServer() throws IOException {
httpServer.stop(0);
}
public void testConstructorValidation() throws IOException {
try {
new ElasticsearchNodesSniffer(null, 1, ElasticsearchNodesSniffer.Scheme.HTTP);
fail("should have failed");
} catch(NullPointerException e) {
assertEquals("restClient cannot be null", e.getMessage());
}
HttpHost httpHost = new HttpHost(httpServer.getAddress().getHostString(), httpServer.getAddress().getPort());
try (RestClient restClient = RestClient.builder(httpHost).build()) {
try {
new ElasticsearchNodesSniffer(restClient, 1, null);
fail("should have failed");
} catch (NullPointerException e) {
assertEquals(e.getMessage(), "scheme cannot be null");
}
try {
new ElasticsearchNodesSniffer(restClient, RandomNumbers.randomIntBetween(getRandom(), Integer.MIN_VALUE, 0),
ElasticsearchNodesSniffer.Scheme.HTTP);
fail("should have failed");
} catch (IllegalArgumentException e) {
assertEquals(e.getMessage(), "sniffRequestTimeoutMillis must be greater than 0");
}
}
}
public void testSniffNodes() throws IOException {
HttpHost httpHost = new HttpHost(httpServer.getAddress().getHostString(), httpServer.getAddress().getPort());
try (RestClient restClient = RestClient.builder(httpHost).build()) {
ElasticsearchNodesSniffer sniffer = new ElasticsearchNodesSniffer(restClient, sniffRequestTimeout, scheme);
try {
List<Node> sniffedNodes = sniffer.sniff();
if (sniffResponse.isFailure) {
fail("sniffNodes should have failed");
}
assertEquals(sniffResponse.result, sniffedNodes);
} catch(ResponseException e) {
Response response = e.getResponse();
if (sniffResponse.isFailure) {
final String errorPrefix = "method [GET], host [" + httpHost + "], URI [/_nodes/http?timeout=" + sniffRequestTimeout
+ "ms], status line [HTTP/1.1";
assertThat(e.getMessage(), startsWith(errorPrefix));
assertThat(e.getMessage(), containsString(Integer.toString(sniffResponse.nodesInfoResponseCode)));
assertThat(response.getHost(), equalTo(httpHost));
assertThat(response.getStatusLine().getStatusCode(), equalTo(sniffResponse.nodesInfoResponseCode));
assertThat(response.getRequestLine().toString(),
equalTo("GET /_nodes/http?timeout=" + sniffRequestTimeout + "ms HTTP/1.1"));
} else {
fail("sniffNodes should have succeeded: " + response.getStatusLine());
}
}
}
}
private static HttpServer createHttpServer(final SniffResponse sniffResponse, final int sniffTimeoutMillis) throws IOException {
HttpServer httpServer = MockHttpServer.createHttp(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
httpServer.createContext("/_nodes/http", new ResponseHandler(sniffTimeoutMillis, sniffResponse));
return httpServer;
}
private static class ResponseHandler implements HttpHandler {
private final int sniffTimeoutMillis;
private final SniffResponse sniffResponse;
ResponseHandler(int sniffTimeoutMillis, SniffResponse sniffResponse) {
this.sniffTimeoutMillis = sniffTimeoutMillis;
this.sniffResponse = sniffResponse;
}
@Override
public void handle(HttpExchange httpExchange) throws IOException {
if (httpExchange.getRequestMethod().equals(HttpGet.METHOD_NAME)) {
if (httpExchange.getRequestURI().getRawQuery().equals("timeout=" + sniffTimeoutMillis + "ms")) {
String nodesInfoBody = sniffResponse.nodesInfoBody;
httpExchange.sendResponseHeaders(sniffResponse.nodesInfoResponseCode, nodesInfoBody.length());
try (OutputStream out = httpExchange.getResponseBody()) {
out.write(nodesInfoBody.getBytes(Consts.UTF_8));
return;
}
}
}
httpExchange.sendResponseHeaders(404, 0);
httpExchange.close();
}
}
private static SniffResponse buildSniffResponse(ElasticsearchNodesSniffer.Scheme scheme) throws IOException {
int numNodes = RandomNumbers.randomIntBetween(getRandom(), 1, 5);
List<Node> nodes = new ArrayList<>(numNodes);
JsonFactory jsonFactory = new JsonFactory();
StringWriter writer = new StringWriter();
JsonGenerator generator = jsonFactory.createGenerator(writer);
generator.writeStartObject();
if (getRandom().nextBoolean()) {
generator.writeStringField("cluster_name", "elasticsearch");
}
if (getRandom().nextBoolean()) {
generator.writeObjectFieldStart("bogus_object");
generator.writeEndObject();
}
generator.writeObjectFieldStart("nodes");
for (int i = 0; i < numNodes; i++) {
String nodeId = RandomStrings.randomAsciiOfLengthBetween(getRandom(), 5, 10);
String host = "host" + i;
int port = RandomNumbers.randomIntBetween(getRandom(), 9200, 9299);
HttpHost publishHost = new HttpHost(host, port, scheme.toString());
Set<HttpHost> boundHosts = new HashSet<>();
boundHosts.add(publishHost);
if (randomBoolean()) {
int bound = between(1, 5);
for (int b = 0; b < bound; b++) {
boundHosts.add(new HttpHost(host + b, port, scheme.toString()));
}
}
int numAttributes = between(0, 5);
Map<String, List<String>> attributes = new HashMap<>(numAttributes);
for (int j = 0; j < numAttributes; j++) {
int numValues = frequently() ? 1 : between(2, 5);
List<String> values = new ArrayList<>();
for (int v = 0; v < numValues; v++) {
values.add(j + "value" + v);
}
attributes.put("attr" + j, values);
}
final Set<String> nodeRoles = new TreeSet<>();
if (randomBoolean()) {
nodeRoles.add("master");
}
if (randomBoolean()) {
nodeRoles.add("data");
}
if (randomBoolean()) {
nodeRoles.add("data_content");
}
if (randomBoolean()) {
nodeRoles.add("data_hot");
}
if (randomBoolean()) {
nodeRoles.add("data_warm");
}
if (randomBoolean()) {
nodeRoles.add("data_cold");
}
if (randomBoolean()) {
nodeRoles.add("data_frozen");
}
if (randomBoolean()) {
nodeRoles.add("ingest");
}
Node node = new Node(publishHost, boundHosts, randomAsciiAlphanumOfLength(5),
randomAsciiAlphanumOfLength(5),
new Node.Roles(nodeRoles),
attributes);
generator.writeObjectFieldStart(nodeId);
if (getRandom().nextBoolean()) {
generator.writeObjectFieldStart("bogus_object");
generator.writeEndObject();
}
if (getRandom().nextBoolean()) {
generator.writeArrayFieldStart("bogus_array");
generator.writeStartObject();
generator.writeEndObject();
generator.writeEndArray();
}
boolean isHttpEnabled = rarely() == false;
if (isHttpEnabled) {
nodes.add(node);
generator.writeObjectFieldStart("http");
generator.writeArrayFieldStart("bound_address");
for (HttpHost bound : boundHosts) {
generator.writeString(bound.toHostString());
}
generator.writeEndArray();
if (getRandom().nextBoolean()) {
generator.writeObjectFieldStart("bogus_object");
generator.writeEndObject();
}
generator.writeStringField("publish_address", publishHost.toHostString());
if (getRandom().nextBoolean()) {
generator.writeNumberField("max_content_length_in_bytes", 104857600);
}
generator.writeEndObject();
}
List<String> roles = Arrays.asList(new String[]{"master", "data", "ingest",
"data_content", "data_hot", "data_warm", "data_cold", "data_frozen"});
Collections.shuffle(roles, getRandom());
generator.writeArrayFieldStart("roles");
for (String role : roles) {
if ("master".equals(role) && node.getRoles().isMasterEligible()) {
generator.writeString("master");
}
if ("data".equals(role) && node.getRoles().hasDataRole()) {
generator.writeString("data");
}
if ("data_content".equals(role) && node.getRoles().hasDataContentRole()) {
generator.writeString("data_content");
}
if ("data_hot".equals(role) && node.getRoles().hasDataHotRole()) {
generator.writeString("data_hot");
}
if ("data_warm".equals(role) && node.getRoles().hasDataWarmRole()) {
generator.writeString("data_warm");
}
if ("data_cold".equals(role) && node.getRoles().hasDataColdRole()) {
generator.writeString("data_cold");
}
if ("data_frozen".equals(role) && node.getRoles().hasDataFrozenRole()) {
generator.writeString("data_frozen");
}
if ("ingest".equals(role) && node.getRoles().isIngest()) {
generator.writeString("ingest");
}
}
generator.writeEndArray();
generator.writeFieldName("version");
generator.writeString(node.getVersion());
generator.writeFieldName("name");
generator.writeString(node.getName());
if (numAttributes > 0) {
generator.writeObjectFieldStart("attributes");
for (Map.Entry<String, List<String>> entry : attributes.entrySet()) {
if (entry.getValue().size() == 1) {
generator.writeStringField(entry.getKey(), entry.getValue().get(0));
} else {
for (int v = 0; v < entry.getValue().size(); v++) {
generator.writeStringField(entry.getKey() + "." + v, entry.getValue().get(v));
}
}
}
generator.writeEndObject();
}
generator.writeEndObject();
}
generator.writeEndObject();
generator.writeEndObject();
generator.close();
return SniffResponse.buildResponse(writer.toString(), nodes);
}
private static class SniffResponse {
private final String nodesInfoBody;
private final int nodesInfoResponseCode;
private final List<Node> result;
private final boolean isFailure;
SniffResponse(String nodesInfoBody, List<Node> result, boolean isFailure) {
this.nodesInfoBody = nodesInfoBody;
this.result = result;
this.isFailure = isFailure;
if (isFailure) {
this.nodesInfoResponseCode = randomErrorResponseCode();
} else {
this.nodesInfoResponseCode = 200;
}
}
static SniffResponse buildFailure() {
return new SniffResponse("", Collections.<Node>emptyList(), true);
}
static SniffResponse buildResponse(String nodesInfoBody, List<Node> nodes) {
return new SniffResponse(nodesInfoBody, nodes, false);
}
}
private static int randomErrorResponseCode() {
return RandomNumbers.randomIntBetween(getRandom(), 400, 599);
}
}
| {
"content_hash": "8fb61a1eb2f44b70e910243842f6338b",
"timestamp": "",
"source": "github",
"line_count": 347,
"max_line_length": 136,
"avg_line_length": 43.48991354466859,
"alnum_prop": 0.5912795706049964,
"repo_name": "robin13/elasticsearch",
"id": "ded1f5316f36983f0315b06fd691db5f005590c3",
"size": "15890",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "client/sniffer/src/test/java/org/elasticsearch/client/sniff/ElasticsearchNodesSnifferTests.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "11082"
},
{
"name": "Batchfile",
"bytes": "14049"
},
{
"name": "Emacs Lisp",
"bytes": "3341"
},
{
"name": "FreeMarker",
"bytes": "45"
},
{
"name": "Groovy",
"bytes": "315863"
},
{
"name": "HTML",
"bytes": "3399"
},
{
"name": "Java",
"bytes": "40107206"
},
{
"name": "Perl",
"bytes": "7271"
},
{
"name": "Python",
"bytes": "54437"
},
{
"name": "Shell",
"bytes": "108937"
}
],
"symlink_target": ""
} |
from __future__ import division
import copy
import random
import unittest
from itertools import imap, chain, izip
from vistrails.core.data_structures.queue import Queue
from vistrails.core.data_structures.stack import Stack
from vistrails.core.utils import all
################################################################################
# Graph
class GraphException(Exception):
pass
class GraphContainsCycles(GraphException):
def __init__(self, v1, v2):
self.back_edge = (v1, v2)
def __str__(self):
return ("Graph contains cycles: back edge %s encountered" %
(self.back_edge,))
class Graph(object):
"""Graph holds a graph with possible multiple edges. The
datastructures are all dictionary-based, so datatypes more general than ints
can be used. For example:
>>> g = Graph()
>>> g.add_vertex('foo')
>>> g.add_vertex('bar')
>>> g.add_edge('foo', 'bar', 'edge_foo')
>>> g.add_edge('foo', 'bar', 'edge_bar')
>>> g.add_edge('bar', 'foo', 'edge_back')
>>> g.out_degree('foo')
2
>>> g.out_degree('bar')
1
"""
##########################################################################
# Constructor
def __init__(self):
""" Graph() -> Graph
Initialize an empty graph and return nothing
"""
self.vertices = {}
self.adjacency_list = {}
self.inverse_adjacency_list = {}
@staticmethod
def map_vertices(graph, vertex_map=None, edge_map=None):
""" map_vertices(graph: Graph, vertex_map: dict): Graph
Creates a new graph that is a mapping of vertex ids through
vertex_map.
"""
result = Graph()
if vertex_map is None:
vertex_map = dict((v, v) for v in graph.vertices)
if edge_map is None:
edge_map = {}
for vfrom, lto in graph.adjacency_list.iteritems():
for (vto, eid) in lto:
edge_map[eid] = eid
result.vertices = dict((vertex_map[v], True) for v in graph.vertices)
for (vto, lto) in graph.adjacency_list.iteritems():
result.adjacency_list[vto] = [(vertex_map[to], edge_map[eid]) for (to, eid) in lto]
for (vto, lto) in graph.inverse_adjacency_list.iteritems():
result.inverse_adjacency_list[vto] = [(vertex_map[to], edge_map[eid]) for (to, eid) in lto]
return result
##########################################################################
# Accessors
def inverse(self):
"""inverse() -> Graph
Inverse all edge directions on the graph and return a Graph
"""
result = copy.copy(self)
t = result.adjacency_list
result.adjacency_list = result.inverse_adjacency_list
result.inverse_adjacency_list = t
return result
def inverse_immutable(self):
"""inverse_immutable() -> Graph
Fast version of inverse(), but requires that output not be
mutated (it shares with self.)
"""
result = Graph()
result.vertices = self.vertices
result.adjacency_list = self.inverse_adjacency_list
result.inverse_adjacency_list = self.adjacency_list
return result
def undirected_immutable(self):
"""undirected_immutable() -> Graph
Creates an undirected version of self. Notice that this
version should not be mutated because there is sharing in the
adjacency lists and the vertex map.
Additionally, if self wasn't acyclic, then
undirected_immutable() won't be simple.
"""
result = Graph()
result.vertices = self.vertices
result.adjacency_list = dict((k, (self.adjacency_list[k] +
self.inverse_adjacency_list[k]))
for k in self.vertices)
result.inverse_adjacency_list = result.adjacency_list
return result
def out_degree(self, froom):
""" out_degree(froom: id type) -> int
Compute the number of edges leaving 'froom' and return an int
Keyword arguments:
froom -- 'immutable' vertex id
"""
return len(self.adjacency_list[froom])
def in_degree(self, to):
""" in_degree(to: id type) -> int
Compute the number of edges entering 'to' and return an int
Keyword arguments:
to -- 'immutable' vertex id
"""
return len(self.inverse_adjacency_list[to])
def sinks(self):
""" sinks() -> list(id type)
Find all vertices whose out_degree is zero and return a list of ids
"""
return [idx for idx in self.vertices.keys() \
if self.out_degree(idx) == 0]
def sources(self):
""" sources() -> list(id type)
Find all vertices whose in_degree is zero and return a list of ids
"""
return [idx for idx in self.vertices.keys() if self.in_degree(idx) == 0]
def edges_to(self, id):
""" edges_to(id: id type) -> list(list)
Find edges entering a vertex id and return a list of tuples (id,id)
Keyword arguments:
id : 'immutable' vertex id
"""
return self.inverse_adjacency_list[id]
def edges_from(self, id):
""" edges_from(id: id type) -> list(list)
Find edges leaving a vertex id and return a list of tuples (id,id)
Keyword arguments:
id : 'immutable' vertex id
"""
return self.adjacency_list[id]
def get_edge(self, frm, to):
""" get_edge(frm, to) -> edge_id
Returns the id from the edge from->to."""
for (t, e_id) in self.edges_from(frm):
if t == to:
return e_id
def has_edge(self, frm, to):
""" has_edge(frm, to) -> bool
True if there exists an edge (frm, to)"""
for (t, _) in self.edges_from(frm):
if t == to:
return True
return False
##########################################################################
# Mutate graph
def add_vertex(self, id, data=None):
""" add_vertex(id: id type, data) -> None
Add a vertex to the graph if it is not already in the graph
and return nothing
Keyword arguments:
id -- vertex id
"""
if not id in self.vertices:
self.vertices[id] = data
self.adjacency_list[id] = []
self.inverse_adjacency_list[id] = []
def add_edge(self, froom, to, id=None):
""" add_edge(froom: id type, to: id type, id: id type) -> None
Add an edge from vertex 'froom' to vertex 'to' and return nothing
Keyword arguments:
froom -- 'immutable' origin vertex id
to -- 'immutable' destination vertex id
id -- 'immutable' edge id (default None)
"""
self.add_vertex(froom)
self.add_vertex(to)
self.adjacency_list[froom].append((to, id))
self.inverse_adjacency_list[to].append((froom, id))
def delete_vertex(self, id):
""" delete_vertex(id: id type) -> None
Remove a vertex from graph and return nothing
Keyword arguments:
-- id : 'immutable' vertex id
"""
for (origin, edge_id) in self.inverse_adjacency_list[id]:
t = (id, edge_id)
self.adjacency_list[origin].remove(t)
for (dest, edge_id) in self.adjacency_list[id]:
t = (id, edge_id)
self.inverse_adjacency_list[dest].remove(t)
del self.adjacency_list[id]
del self.inverse_adjacency_list[id]
del self.vertices[id]
class RenameVertexError(GraphException):
pass
def rename_vertex(self, old_vertex, new_vertex):
""" rename_vertex(old_vertex, new_vertex) -> None
renames old_vertex to new_vertex in the graph, updating the edges
appropriately. Should not be used to merge vertices, will raise
exception if new_vertex exists in graph.
"""
if not (old_vertex in self.vertices):
raise self.RenameVertexError("vertex '%s' does not exist" % old_vertex)
if new_vertex in self.vertices:
raise self.RenameVertexError("vertex '%s' already exists" % new_vertex)
self.add_vertex(new_vertex)
# the slice ([:]) is important for copying, since change_edge
# mutates the list we'll be traversing
for (v_from, e_id) in self.inverse_adjacency_list[old_vertex][:]:
self.change_edge(v_from, old_vertex, new_vertex, e_id, e_id)
self.adjacency_list[new_vertex] = self.adjacency_list[old_vertex]
del self.adjacency_list[old_vertex]
del self.vertices[old_vertex]
def change_edge(self, old_froom, old_to, new_to, old_id=None, new_id=None):
""" change_edge(old_froom: id, old_to: id, new_to: id,
old_id: id, new_id: id) -> None
Changes the destination of an edge in a graph **in place**
Keyword arguments:
old_froom -- 'immutable' origin vertex id
old_to -- 'immutable' destination vertex id
new_to -- 'immutable' destination vertex id
old_id -- 'immutable' edge id (default None)
new_id -- 'immutable' edge id (default None)
"""
if old_id is None:
efroom = self.adjacency_list[old_froom]
forward_idx = None
for i, edge in enumerate(efroom):
if edge[0] == old_to:
old_id = edge[1]
forward_idx = i
break
if forward_idx is None:
raise ValueError("No edge to %r" % old_to)
else:
forward_idx = self.adjacency_list[old_froom].index((old_to, old_id))
self.adjacency_list[old_froom][forward_idx] = ((new_to, new_id))
self.inverse_adjacency_list[old_to].remove((old_froom, old_id))
self.inverse_adjacency_list[new_to].append((old_froom, new_id))
def delete_edge(self, froom, to, id=None):
""" delete_edge(froom: id type, to: id type, id: id type) -> None
Remove an edge from graph and return nothing
Keyword arguments:
froom -- 'immutable' origin vertex id
to -- 'immutable' destination vertex id
id -- 'immutable' edge id
"""
if id is None:
efroom = self.adjacency_list[froom]
for edge in efroom:
if edge[0] == to:
id = edge[1]
break
if id is None:
raise GraphException("delete_edge didn't find edge (%s,%s)"%
(froom, to))
self.adjacency_list[froom].remove((to, id))
self.inverse_adjacency_list[to].remove((froom, id))
##########################################################################
# Graph algorithms
def closest_vertex(self, frm, target_list):
""" closest_vertex(frm, target_list) -> id Uses bfs-like
algorithm to find closest vertex to frm in target_list
"""
if frm in target_list:
return frm
target_list = set(target_list)
visited = set([frm])
parent = {}
q = Queue()
q.push(frm)
while 1:
try:
current = q.pop()
except q.EmptyQueue:
raise GraphException("no vertices reachable: %s %s" % (frm, list(target_list)))
efrom = self.edges_from(current)
for (to, eid) in efrom:
if to in target_list:
return to
if to not in visited:
parent[to] = current
q.push(to)
visited.add(to)
def bfs(self, frm):
""" bfs(frm:id type) -> dict(id type)
Perform Breadth-First-Search and return a dict of parent id
Keyword arguments:
frm -- 'immutable' vertex id
"""
visited = set([frm])
parent = {}
q = Queue()
q.push(frm)
while 1:
try:
current = q.pop()
except q.EmptyQueue:
break
efrom = self.edges_from(current)
for (to, eid) in efrom:
if to not in visited:
parent[to] = current
q.push(to)
visited.add(to)
return parent
# For legacy reasons, moved after 2.2.1
GraphContainsCycles = GraphContainsCycles
def dfs(self,
vertex_set=None,
raise_if_cyclic=False,
enter_vertex=None,
leave_vertex=None):
""" dfs(self,vertex_set=None,raise_if_cyclic=False,enter_vertex=None,
leave_vertex=None) -> (discovery, parent, finish)
Performs a depth-first search on a graph and returns three dictionaries with
relevant information. If vertex_set is not None, then it is used as
the list of ids to perform the DFS on.
See CLRS p. 541.
enter_vertex, when present, is called just before visiting a vertex
for the first time (and only once) with the vertex id as a parameter.
leave_vertex, when present, is called just after visiting a vertex
for the first time (and only once) with the vertex id as a parameter.
"""
if not vertex_set:
vertex_set = self.vertices
# Straight CLRS p.541
discovery = {} # d in CLRS
parents = {} # \pi in CLRS
finish = {} # f in CLRS
t = [0]
(enter, leave, back, other) = xrange(4)
# inspired by http://www.ics.uci.edu/~eppstein/PADS/DFS.py
def handle(v, w, edgetype):
t[0] += 1
if edgetype == enter:
discovery[v] = t[0]
if enter_vertex:
enter_vertex(w)
if v != w:
parents[w] = v
elif edgetype == leave:
finish[w] = t[0]
if leave_vertex:
leave_vertex(w)
elif edgetype == back and raise_if_cyclic:
raise GraphContainsCycles(v, w)
visited = set()
gray = set()
# helper function to build stack structure
def st(v): return (v, iter(self.adjacency_list[v]))
for vertex in vertex_set:
if vertex not in visited:
handle(vertex, vertex, enter)
visited.add(vertex)
stack = Stack()
stack.push(st(vertex))
gray.add(vertex)
while stack.size:
parent, children = stack.top()
try:
child, _ = children.next()
if child in visited:
handle(parent, child, (child in gray
and back
or other))
else:
handle(parent, child, enter)
visited.add(child)
stack.push(st(child))
gray.add(child)
except StopIteration:
gray.remove(parent)
stack.pop()
if stack.size:
handle(stack.top()[0], parent, leave)
handle(vertex, vertex, leave)
return discovery, parents, finish
class VertexHasNoParentError(GraphException):
def __init__(self, v):
Exception.__init__(self, v)
self._v = v
def __str__(self):
return ("called parent() on vertex '%s', which has no parent nodes"
% self._v)
def parent(self, v):
""" parent(v: id type) -> id type
Find the parent of vertex v and return an id
Keyword arguments:
v -- 'immutable' vertex id
raises VertexHasNoParentError is vertex has no parent
raises KeyError is vertex is not on graph
"""
l=self.inverse_adjacency_list[v]
if len(l):
(froom, a) = l[-1]
else:
raise self.VertexHasNoParentError(v)
return froom
def vertices_topological_sort(self,vertex_set=None):
""" vertices_topological_sort(self,vertex_set=None) ->
sequence(vertices) Returns a sequence of all vertices, so that
they are in topological sort order (every node traversed is
such that their parent nodes have already been
traversed). vertex_set is optionally a list of vertices on
which to perform the topological sort.
This is O(n log n) instead of the optimal O(n),
"""
(d, p, f) = self.dfs(vertex_set,raise_if_cyclic=True)
# Optimized these three lines into the last one
# lst = [(v, k) for (k,v) in f.iteritems()]
# lst.sort(reverse=True)
# return [v for (k, v) in lst]
return [k for (k, _) in sorted(f.iteritems(),
key=lambda x: (x[1], x[0]),
reverse=True)]
def topologically_contractible(self, subgraph):
"""topologically_contractible(subgraph) -> Boolean.
Returns true if contracting the subgraph to a single vertex
doesn't create cycles. This is equivalent to checking whether
a pipeline subgraph forms a legal abstraction."""
x = copy.copy(self)
conns_to_subgraph = self.connections_to_subgraph(subgraph)
conns_from_subgraph = self.connections_from_subgraph(subgraph)
for v in subgraph.vertices.iterkeys():
x.delete_vertex(v)
free_vertex = max(subgraph.vertices.iterkeys()) + 1
x.add_vertex(free_vertex)
for (edge_from, edge_to, edge_id) in conns_to_subgraph:
x.add_edge(free_vertex, edge_to)
for (edge_from, edge_to, edge_id) in conns_from_subgraph:
x.add_edge(edge_from, free_vertex)
try:
x.vertices_topological_sort()
return True
except GraphContainsCycles:
return False
##########################################################################
# Subgraphs
def subgraph(self, vertex_set):
""" subgraph(vertex_set) -> Graph.
Returns a subgraph of self containing all vertices and
connections between them."""
result = Graph()
vertex_set = set(vertex_set)
# add vertices
for vertex in vertex_set:
result.add_vertex(vertex)
# add edges
for vertex_from in vertex_set:
for (vertex_to, edge_id) in self.edges_from(vertex_from):
if vertex_to in vertex_set:
result.add_edge(vertex_from, vertex_to, edge_id)
return result
def connections_to_subgraph(self, subgraph):
"""connections_to_subgraph(subgraph) -> [(vert_from, vert_to, edge_id)]
Returns the list of all edges that connect to a vertex \in
subgraph. subgraph is assumed to be a subgraph of self"""
vertices_to_traverse = set(self.vertices.iterkeys())
subgraph_verts = set(subgraph.vertices.iterkeys())
vertices_to_traverse -= subgraph_verts
result = []
for v in vertices_to_traverse:
for e in self.adjacency_list[v]:
(v_to, e_id) = e
if v_to in subgraph_verts:
result.append((v, v_to, e_id))
return result
def connections_from_subgraph(self, subgraph):
"""connections_from_subgraph(subgraph) -> [(vert_from, vert_to, edge_id)]
Returns the list of all edges that connect from a vertex \in
subgraph to a vertex \not \in subgraph. subgraph is assumed to
be a subgraph of self"""
subgraph_verts = set(subgraph.vertices.iterkeys())
vertices_to_traverse = subgraph_verts
result = []
for v in vertices_to_traverse:
for e in self.adjacency_list[v]:
(v_to, e_id) = e
if v_to not in subgraph_verts:
result.append((v, v_to, e_id))
return result
##########################################################################
# Iterators
def iter_edges_from(self, vertex):
"""iter_edges_from(self, vertex) -> iterable
Returns an iterator over all edges in the form
(vertex, vert_to, edge_id)."""
def fn(edge):
(edge_to, edge_id) = edge
return (vertex, edge_to, edge_id)
return imap(fn, self.adjacency_list[vertex])
def iter_edges_to(self, vertex):
"""iter_edges_to(self, vertex) -> iterable
Returns an iterator over all edges in the form
(vertex, vert_to, edge_id)."""
def fn(edge):
(edge_from, edge_id) = edge
return (edge_from, vertex, edge_id)
return imap(fn, self.inverse_adjacency_list[vertex])
def iter_all_edges(self):
"""iter_all_edges() -> iterable
Returns an iterator over all edges in the graph in the form
(vert_from, vert_to, edge_id)."""
verts = self.iter_vertices()
edge_itors = imap(self.iter_edges_from, verts)
return chain(*[v for v in edge_itors])
def iter_vertices(self):
"""iter_vertices() -> iterable
Returns an iterator over all vertex ids of the graph."""
return self.vertices.iterkeys()
##########################################################################
# Special Python methods
def __str__(self):
""" __str__() -> str
Format the graph for serialization and return a string
"""
vs = self.vertices.keys()
vs.sort()
al = [(vfrom, vto, edgeid)
for vfrom, lto in self.adjacency_list.iteritems()
for vto, edgeid in lto]
al.sort()
return ("digraph G {\n"
+ ";".join([str(s) for s in vs])
+ ";\n"
+ "\n".join(["%s -> %s [label=\"%s\"];" % s for s in al])
+ "\n}")
def __repr__(self):
""" __repr__() -> str
Similar to __str__ to re-represent the graph and returns a string
"""
return self.__str__()
def __copy__(self):
""" __copy__() -> Graph
Make a copy of the graph and return a Graph
"""
cp = Graph()
cp.vertices = copy.copy(self.vertices)
cp.adjacency_list = dict((k, v[:]) for (k,v) in self.adjacency_list.iteritems())
cp.inverse_adjacency_list = dict((k, v[:]) for (k,v) in self.inverse_adjacency_list.iteritems())
return cp
def __eq__(self, other):
# Does not test isomorphism - vertices must be consistently labeled
# might be slow - don't use in tight code
if type(self) <> type(other):
return False
for v in self.vertices:
if not v in other.vertices:
return False
for vfrom, elist in self.adjacency_list.iteritems():
for vto, eid in elist:
if not other.get_edge(vfrom, vto) == eid:
return False
return True
def __ne__(self, other):
return not (self == other)
################################################################################
# Unit testing
class TestGraph(unittest.TestCase):
""" Class to test Graph
It tests vertex addition, the out_degree of a sink and in_degree of a
source consistencies.
"""
def make_complete(self, v):
"""returns a complete graph with v verts."""
g = Graph()
for x in xrange(v):
g.add_vertex(x)
for f in xrange(v):
for t in xrange(f+1, v):
g.add_edge(f, t, f * v + t)
return g
def make_linear(self, v, bw=False):
"""returns a linear graph with v verts. if bw=True, add
backward links."""
g = Graph()
for x in xrange(v):
g.add_vertex(x)
for x,y in izip(xrange(v-1), xrange(1, v)):
g.add_edge(x, y, x)
if bw:
g.add_edge(y, x, x + v)
return g
def get_default_graph(self):
g = Graph()
g.add_vertex(0)
g.add_vertex(1)
g.add_vertex(2)
g.add_vertex(3)
g.add_vertex(4)
g.add_edge(0,1,0)
g.add_edge(1,2,1)
g.add_edge(0,3,2)
g.add_edge(3,2,3)
g.add_edge(2,4,4)
return g
def test1(self):
"""Test adding edges and vertices"""
g = Graph()
g.add_vertex('0')
g.add_vertex('1')
g.add_vertex('2')
g.add_vertex('3')
g.add_edge('0', '1', 0)
g.add_edge('1', '2', 1)
g.add_edge('2', '3', 2)
parent = g.bfs('0')
self.assertEquals(parent['3'], '2')
self.assertEquals(parent['2'], '1')
self.assertEquals(parent['1'], '0')
def test2(self):
"""Test bread-first-search"""
g = self.get_default_graph()
p = g.bfs(0)
k = p.keys()
k.sort()
self.assertEquals(k, [1, 2, 3, 4])
inv = g.inverse()
p_inv = inv.bfs(4)
k2 = p_inv.keys()
k2.sort()
self.assertEquals(k2, [0, 1, 2, 3])
def test3(self):
"""Test sink and source degree consistency"""
g = Graph()
for i in xrange(100):
g.add_vertex(i)
for i in xrange(1000):
v1 = random.randint(0,99)
v2 = random.randint(0,99)
g.add_edge(v1, v2, i)
sinkResult = [None for i in g.sinks() if g.out_degree(i) == 0]
sourceResult = [None for i in g.sources() if g.in_degree(i) == 0]
if len(sinkResult) <> len(g.sinks()):
assert False
if len(sourceResult) <> len(g.sources()):
assert False
def test_remove_vertices(self):
g = self.make_linear(5)
g.delete_vertex(1)
g.delete_vertex(2)
def test_DFS(self):
"""Test DFS on graph."""
g = self.get_default_graph()
g.dfs()
def test_topological_sort(self):
"""Test toposort on graph."""
g = self.get_default_graph()
g.vertices_topological_sort()
g = self.make_linear(10)
r = g.vertices_topological_sort()
assert r == [0,1,2,3,4,5,6,7,8,9]
g = Graph()
g.add_vertex('a')
g.add_vertex('b')
g.add_vertex('c')
g.add_edge('a', 'b')
g.add_edge('b', 'c')
assert g.vertices_topological_sort() == ['a', 'b', 'c']
def test_limited_DFS(self):
"""Test DFS on graph using a limited set of starting vertices."""
g = self.get_default_graph()
g.dfs(vertex_set=[1])
g.dfs(vertex_set=[1,3])
g.dfs(vertex_set=[1,2])
def test_limited_topological_sort(self):
"""Test toposort on graph using a limited set of starting vertices."""
g = self.get_default_graph()
g.vertices_topological_sort(vertex_set=[1])
g.vertices_topological_sort(vertex_set=[1,3])
g.vertices_topological_sort(vertex_set=[1,2])
def test_print_empty_graph(self):
"""Test print on empty graph"""
g = Graph()
g.__str__()
def test_delete(self):
"""Tests consistency of data structure after deletion."""
g = Graph()
g.add_vertex(0)
g.add_vertex(1)
g.add_vertex(2)
g.add_edge(0, 1, 0)
g.add_edge(1, 2, 1)
g.delete_vertex(2)
self.assertEquals(g.adjacency_list[1], [])
def test_raising_DFS(self):
"""Tests if DFS with cycle-checking will raise exceptions."""
g = Graph()
g.add_vertex(0)
g.add_vertex(1)
g.add_vertex(2)
g.add_edge(0, 1)
g.add_edge(1, 2)
g.add_edge(2, 0)
with self.assertRaises(GraphContainsCycles):
g.dfs(raise_if_cyclic=True)
def test_call_inverse(self):
"""Test if calling inverse methods work."""
g = Graph()
g.add_vertex(0)
g.add_vertex(1)
g.add_vertex(2)
g.add_edge(0, 1)
g.add_edge(1, 2)
g.add_edge(2, 0)
g2 = g.inverse()
g3 = g.inverse_immutable()
def test_subgraph(self):
"""Test subgraph routines."""
g = self.make_complete(5)
sub = g.subgraph([0,1])
assert 0 in sub.vertices
assert 1 in sub.vertices
assert (1,1) in sub.adjacency_list[0]
assert (0,1) in sub.inverse_adjacency_list[1]
g = self.make_linear(3)
sub = g.subgraph([0, 2])
assert 0 in sub.vertices
assert 2 in sub.vertices
assert sub.adjacency_list[0] == []
assert sub.adjacency_list[2] == []
def test_connections_to_subgraph(self):
"""Test connections_to_subgraph."""
g = self.make_linear(5)
sub = g.subgraph([3])
assert len(g.connections_to_subgraph(sub)) == 1
g = self.make_linear(5, True)
sub = g.subgraph([3])
assert len(g.connections_to_subgraph(sub)) == 2
def test_connections_from_subgraph(self):
"""Test connections_from_subgraph."""
g = self.make_linear(5)
sub = g.subgraph([3])
assert len(g.connections_from_subgraph(sub)) == 1
g = self.make_linear(5, True)
sub = g.subgraph([3])
assert len(g.connections_from_subgraph(sub)) == 2
def test_topologically_contractible(self):
"""Test topologically_contractible."""
g = self.make_linear(5)
sub = g.subgraph([1, 2])
assert g.topologically_contractible(sub)
sub = g.subgraph([1, 3])
assert not g.topologically_contractible(sub)
g = Graph()
g.add_vertex(0)
g.add_vertex(1)
g.add_vertex(2)
g.add_vertex(3)
g.add_edge(0, 1)
g.add_edge(2, 3)
for i in xrange(1, 16):
s = []
for j in xrange(4):
if i & (1 << j): s.append(j)
assert g.topologically_contractible(g.subgraph(s))
def test_iter_vertices(self):
g = self.get_default_graph()
l = list(g.iter_vertices())
l.sort()
assert l == [0,1,2,3,4]
def test_iter_edges(self):
g = self.get_default_graph()
l = [v for v in g.iter_all_edges()]
l.sort()
assert l == [(0,1,0), (0,3,2), (1, 2, 1), (2, 4, 4), (3, 2, 3)]
def test_iter_edges_empty(self):
"""Test iterators on empty parts of the graph."""
g = Graph()
for a in g.iter_vertices():
assert False
g.add_vertex(0)
for a in g.iter_edges_from(0):
assert False
for a in g.iter_edges_to(0):
assert False
for a in g.iter_all_edges():
assert False
def test_get_edge_none(self):
g = Graph()
g.add_vertex(0)
g.add_vertex(1)
assert g.get_edge(0, 1) is None
def test_dfs_before(self):
g = self.make_linear(10)
inc = []
dec = []
def before(id): inc.append(id)
def after(id): dec.append(id)
g.dfs(enter_vertex=before,
leave_vertex=after)
assert inc == [0,1,2,3,4,5,6,7,8,9]
assert inc == list(reversed(dec))
assert all(a < b for a, b in izip(inc[:-1], inc[1:]))
assert all(a > b for a, b in izip(dec[:-1], dec[1:]))
def test_parent_source(self):
g = self.make_linear(10)
self.assertRaises(g.VertexHasNoParentError,
lambda: g.parent(0))
for i in xrange(1, 10):
assert g.parent(i) == i-1
def test_rename_vertex(self):
g = self.make_linear(10)
self.assertRaises(g.RenameVertexError,
lambda: g.rename_vertex(0, 1))
assert g.get_edge(0, 1) is not None
assert g.get_edge(0, 11) is None
g.rename_vertex(1, 11)
assert g.get_edge(0, 1) is None
assert g.get_edge(0, 11) is not None
g.rename_vertex(11, 1)
assert g.get_edge(0, 1) is not None
assert g.get_edge(0, 11) is None
def test_delete_get_edge(self):
g = self.make_linear(10)
self.assertRaises(GraphException, lambda: g.delete_edge(7, 9))
assert g.has_edge(7, 8)
g.delete_edge(7, 8)
assert not g.has_edge(7, 8)
def test_bfs(self):
g = self.make_linear(5)
lst = g.bfs(0).items()
lst.sort()
assert lst == [(1, 0), (2, 1), (3, 2), (4, 3)]
lst = g.bfs(2).items()
lst.sort()
assert lst == [(3, 2), (4, 3)]
def test_undirected(self):
g = self.make_linear(5).undirected_immutable()
lst = g.bfs(0).items()
lst.sort()
assert lst == [(1, 0), (2, 1), (3, 2), (4, 3)]
lst = g.bfs(2).items()
lst.sort()
assert lst == [(0, 1), (1, 2), (3, 2), (4, 3)]
def test_closest_vertex(self):
g = self.make_linear(10)
g.delete_edge(7, 8)
g = g.undirected_immutable()
self.assertRaises(GraphException, lambda: g.closest_vertex(1, [9]))
assert g.closest_vertex(3, [2, 6, 7]) == 2
assert g.closest_vertex(3, [2, 3, 6, 7]) == 3
# Test using dictionary as target_list
d1 = {2:True, 6:True, 7:False}
d2 = {2:True, 6:True, 7:False, 3:False}
d3 = {9:True}
self.assertRaises(GraphException, lambda: g.closest_vertex(1, d3))
assert g.closest_vertex(3, d1) == 2
assert g.closest_vertex(3, d2) == 3
def test_copy_not_share(self):
g = self.make_linear(10)
g2 = copy.copy(g)
for v in g.vertices:
assert id(g.adjacency_list[v]) <> id(g2.adjacency_list[v])
assert id(g.inverse_adjacency_list[v]) <> id(g2.inverse_adjacency_list[v])
def test_copy_works(self):
g = self.make_linear(10)
g2 = copy.copy(g)
for v in g.vertices:
assert v in g2.vertices
assert g2.adjacency_list[v] == g.adjacency_list[v]
assert g2.inverse_adjacency_list[v] == g.inverse_adjacency_list[v]
def test_equals(self):
g = self.make_linear(5)
assert copy.copy(g) == g
g2 = copy.copy(g)
g2.add_vertex(10)
assert g2 <> g
def test_map_vertices(self):
g = self.make_linear(5)
m = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4}
assert g == Graph.map_vertices(g, m)
m = {0: 5, 1: 6, 2: 7, 3: 8, 4: 9}
assert g <> Graph.map_vertices(g, m)
if __name__ == '__main__':
unittest.main()
| {
"content_hash": "384725532cb8fdd37113ee7a379af89b",
"timestamp": "",
"source": "github",
"line_count": 1042,
"max_line_length": 104,
"avg_line_length": 33.661228406909785,
"alnum_prop": 0.5229650748396294,
"repo_name": "hjanime/VisTrails",
"id": "6f0dd8e25d3a79e4ede35fb9f687c63b59933272",
"size": "36988",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vistrails/core/data_structures/graph.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1421"
},
{
"name": "Inno Setup",
"bytes": "19550"
},
{
"name": "Makefile",
"bytes": "768"
},
{
"name": "Mako",
"bytes": "66613"
},
{
"name": "PHP",
"bytes": "49302"
},
{
"name": "Python",
"bytes": "19803915"
},
{
"name": "R",
"bytes": "782836"
},
{
"name": "Ruby",
"bytes": "875"
},
{
"name": "Shell",
"bytes": "35024"
},
{
"name": "TeX",
"bytes": "145333"
},
{
"name": "XSLT",
"bytes": "1090"
}
],
"symlink_target": ""
} |
#ifndef ZEPHYR_INCLUDE_DRIVERS_PCIE_MSI_H_
#define ZEPHYR_INCLUDE_DRIVERS_PCIE_MSI_H_
#include <kernel.h>
#include <zephyr/types.h>
#include <stdbool.h>
#include <drivers/pcie/pcie.h>
#ifdef __cplusplus
extern "C" {
#endif
struct msix_vector {
uint32_t msg_addr;
uint32_t msg_up_addr;
uint32_t msg_data;
uint32_t vector_ctrl;
};
struct msi_vector {
pcie_bdf_t bdf;
arch_msi_vector_t arch;
#ifdef CONFIG_PCIE_MSI_X
struct msix_vector *msix_vector;
bool msix;
#endif /* CONFIG_PCIE_MSI_X */
};
typedef struct msi_vector msi_vector_t;
#ifdef CONFIG_PCIE_MSI_MULTI_VECTOR
/**
* @brief Allocate vector(s) for the endpoint MSI message(s)
*
* @param bdf the target PCI endpoint
* @param priority the MSI vectors base interrupt priority
* @param vectors an array for storing allocated MSI vectors
* @param n_vector the size of the MSI vectors array
*
* @return the number of allocated MSI vectors.
*/
extern uint8_t pcie_msi_vectors_allocate(pcie_bdf_t bdf,
unsigned int priority,
msi_vector_t *vectors,
uint8_t n_vector);
/**
* @brief Connect the MSI vector to the handler
*
* @param bdf the target PCI endpoint
* @param vector the MSI vector to connect
* @param routine Interrupt service routine
* @param parameter ISR parameter
* @param flags Arch-specific IRQ configuration flag
*
* @return True on success, false otherwise
*/
extern bool pcie_msi_vector_connect(pcie_bdf_t bdf,
msi_vector_t *vector,
void (*routine)(const void *parameter),
const void *parameter,
uint32_t flags);
#endif /* CONFIG_PCIE_MSI_MULTI_VECTOR */
/**
* @brief Compute the target address for an MSI posted write.
*
* This function is exported by the arch, board or SoC code.
*
* @param irq The IRQ we wish to trigger via MSI.
* @param vector The vector for which you want the address (or NULL)
* @return A (32-bit) value for the MSI MAP register.
*/
extern uint32_t pcie_msi_map(unsigned int irq,
msi_vector_t *vector);
/**
* @brief Compute the data for an MSI posted write.
*
* This function is exported by the arch, board or SoC code.
*
* @param irq The IRQ we wish to trigger via MSI.
* @param vector The vector for which you want the data (or NULL)
* @return A (16-bit) value for MSI MDR register.
*/
extern uint16_t pcie_msi_mdr(unsigned int irq,
msi_vector_t *vector);
/**
* @brief Configure the given PCI endpoint to generate MSIs.
*
* @param bdf the target PCI endpoint
* @param vectors an array of allocated vector(s)
* @param n_vector the size of the vector array
* @return true if the endpoint supports MSI, false otherwise.
*/
extern bool pcie_msi_enable(pcie_bdf_t bdf,
msi_vector_t *vectors,
uint8_t n_vector);
/*
* MSI capability IDs in the PCI configuration capability list.
*/
#define PCIE_MSI_CAP_ID 0x05U
#define PCIE_MSIX_CAP_ID 0x11U
/*
* The first word of the MSI capability is shared with the
* capability ID and list link. The high 16 bits are the MCR.
*/
#define PCIE_MSI_MCR 0U
#define PCIE_MSI_MCR_EN 0x00010000U /* enable MSI */
#define PCIE_MSI_MCR_MMC 0x000E0000U /* Multi Messages Capable mask */
#define PCIE_MSI_MCR_MMC_SHIFT 17
#define PCIE_MSI_MCR_MME 0x00700000U /* mask of # of enabled IRQs */
#define PCIE_MSI_MCR_MME_SHIFT 20
#define PCIE_MSI_MCR_64 0x00800000U /* 64-bit MSI */
/*
* The MAP follows the MCR. If PCIE_MSI_MCR_64, then the MAP
* is two words long. The MDR follows immediately after the MAP.
*/
#define PCIE_MSI_MAP0 1U
#define PCIE_MSI_MAP1_64 2U
#define PCIE_MSI_MDR_32 2U
#define PCIE_MSI_MDR_64 3U
/*
* As for MSI, he first word of the MSI-X capability is shared
* with the capability ID and list link. The high 16 bits are the MCR.
*/
#define PCIE_MSIX_MCR 0U
#define PCIE_MSIX_MCR_EN 0x80000000U /* Enable MSI-X */
#define PCIE_MSIX_MCR_FMASK 0x40000000U /* Function Mask */
#define PCIE_MSIX_MCR_TSIZE 0x07FF0000U /* Table size mask */
#define PCIE_MSIX_MCR_TSIZE_SHIFT 16
#define PCIE_MSIR_TABLE_ENTRY_SIZE 16
#define PCIE_MSIX_TR 1U
#define PCIE_MSIX_TR_BIR 0x00000007U /* BIR mask */
#define PCIE_MSIX_TR_OFFSET 0xFFFFFFF8U /* Offset mask */
#define PCIE_VTBL_MA 0U /* Msg Address offset */
#define PCIE_VTBL_MUA 4U /* Msg Upper Address offset */
#define PCIE_VTBL_MD 8U /* Msg Data offset */
#define PCIE_VTBL_VCTRL 12U /* Vector control offset */
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_DRIVERS_PCIE_MSI_H_ */
| {
"content_hash": "fe028eb3429c2a46684ac7ce152269dc",
"timestamp": "",
"source": "github",
"line_count": 163,
"max_line_length": 71,
"avg_line_length": 27.355828220858896,
"alnum_prop": 0.7006055169320475,
"repo_name": "nashif/zephyr",
"id": "31d6ff12311c4096b3fc97baa900fbd9c4ea651e",
"size": "4547",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "include/drivers/pcie/msi.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "411112"
},
{
"name": "BASIC",
"bytes": "592"
},
{
"name": "Batchfile",
"bytes": "110"
},
{
"name": "C",
"bytes": "29131455"
},
{
"name": "C++",
"bytes": "222578"
},
{
"name": "CMake",
"bytes": "828435"
},
{
"name": "EmberScript",
"bytes": "959"
},
{
"name": "Gherkin",
"bytes": "2014"
},
{
"name": "Haskell",
"bytes": "722"
},
{
"name": "Objective-C",
"bytes": "3377"
},
{
"name": "PLSQL",
"bytes": "303"
},
{
"name": "Perl",
"bytes": "214752"
},
{
"name": "Python",
"bytes": "1831845"
},
{
"name": "Shell",
"bytes": "92436"
},
{
"name": "SmPL",
"bytes": "36625"
},
{
"name": "Smalltalk",
"bytes": "1885"
},
{
"name": "Tcl",
"bytes": "5840"
},
{
"name": "Verilog",
"bytes": "6394"
}
],
"symlink_target": ""
} |
package models;
/**
*Classe que representa um status payload.
* @author Davi
*/
public class StatusPayload {
//Atributo
In status;
public StatusPayload(String text){
this.status = new In(text);
}
public StatusPayload(String text, String type){
this.status = new In(text, type);
}
class In{
String text;
String type;
public In(String text){
this.text = text;
}
public In(String text, String type){
this.text = text;
this.type = type;
}
}
} | {
"content_hash": "d38ce90aad16e2e83e8b248a84a18cb7",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 48,
"avg_line_length": 15.483870967741936,
"alnum_prop": 0.6583333333333333,
"repo_name": "dfcDavi/encapsulador",
"id": "a6cca833311c89740f0552a8ea53a1e0729ea06f",
"size": "480",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "encapsulador/src/models/StatusPayload.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "21903"
}
],
"symlink_target": ""
} |
FactoryGirl.define do
factory :user_artist do
user_id "MyString"
artist_id "MyString"
end
end
| {
"content_hash": "e470fc96261c91d7e79091e387f532c5",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 25,
"avg_line_length": 14.714285714285714,
"alnum_prop": 0.7184466019417476,
"repo_name": "bshap27/festy",
"id": "2994ad37fab74016dccd5d4301ec3cb6947259e5",
"size": "103",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/factories/user_artists.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2773"
},
{
"name": "HTML",
"bytes": "21855"
},
{
"name": "JavaScript",
"bytes": "1009"
},
{
"name": "Ruby",
"bytes": "86384"
}
],
"symlink_target": ""
} |
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| {
"content_hash": "ced12a9a586a8e85a0fd6822256d5bf8",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 60,
"avg_line_length": 16.857142857142858,
"alnum_prop": 0.7796610169491526,
"repo_name": "ocarol/LLDropDownMenu",
"id": "829e6bee1dacca50be1431515ac2c9b6bd328d7a",
"size": "281",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LLDropDownMenuDemo/LLDropDownMenuDemo/AppDelegate.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "41634"
}
],
"symlink_target": ""
} |
(function() {
'use strict';
angular
.module('minotaur')
.directive('minotaurTileMinimize', minotaurTileMinimize);
/** @ngInject */
function minotaurTileMinimize() {
var directive = {
restrict: 'EA',
template: '<i class="fa fa-angle-up"></i>Minimize',
link: function (scope, element) {
var tile = element.parents('.tile');
element.on('click', function(){
if (tile.hasClass('collapsed')) {
element[0].innerHTML = '<i class="fa fa-angle-up"></i>Minimize'
} else {
element[0].innerHTML = '<i class="fa fa-angle-down"></i>Expand'
}
tile.toggleClass('collapsed');
tile.children().not('.tile-header').slideToggle(150);
});
}
};
return directive;
}
})();
| {
"content_hash": "c343a00a6b7a5a87de4fb763e965da25",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 75,
"avg_line_length": 23.735294117647058,
"alnum_prop": 0.5464684014869888,
"repo_name": "benxander/caribbean.com",
"id": "b4c3646accb4a4a3f78f6988281813bed57e9c28",
"size": "807",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "shop/app/components/directives/minotaur-tile-minimize.directive.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7064104"
},
{
"name": "HTML",
"bytes": "459935"
},
{
"name": "Hack",
"bytes": "140704"
},
{
"name": "JavaScript",
"bytes": "3356928"
},
{
"name": "PHP",
"bytes": "2645234"
},
{
"name": "Shell",
"bytes": "4146"
}
],
"symlink_target": ""
} |
<?php
/**
* Extension to PHPUnit_Framework_AssertionFailedError to mark the special
* case of an incomplete test.
*
* @since Class available since Release 2.0.0
*/
class PHPUnit_Framework_IncompleteTestError extends PHPUnit_Framework_AssertionFailedError implements PHPUnit_Framework_IncompleteTest
{
}
| {
"content_hash": "b6581e6327af58570b4f2952d84e04d0",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 134,
"avg_line_length": 26.25,
"alnum_prop": 0.7777777777777778,
"repo_name": "Brother-Simon/yascmf",
"id": "cfa3819d14584eaa26c361b054ac2a2b36ad1425",
"size": "536",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "vendor/phpunit/phpunit/src/Framework/IncompleteTestError.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "780"
},
{
"name": "CSS",
"bytes": "62304"
},
{
"name": "HTML",
"bytes": "1701167"
},
{
"name": "Java",
"bytes": "14870"
},
{
"name": "JavaScript",
"bytes": "2712073"
},
{
"name": "PHP",
"bytes": "914725"
}
],
"symlink_target": ""
} |
export default {
schedule: 'Schedule Meeting',
prompt: 'Please authorize RingCentral to access your account information.'
};
| {
"content_hash": "133cbb1817968b22900993d964fe7de9",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 76,
"avg_line_length": 32.25,
"alnum_prop": 0.7596899224806202,
"repo_name": "u9520107/ringcentral-js-widget",
"id": "e71e9b612e45b0dc999858b154a4fdbe3c15fb21",
"size": "129",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/ringcentral-widgets/components/MeetingScheduleButton/i18n/en-US.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "90533"
},
{
"name": "HTML",
"bytes": "2967"
},
{
"name": "JavaScript",
"bytes": "433434"
},
{
"name": "Shell",
"bytes": "1001"
}
],
"symlink_target": ""
} |
package org.killbill.billing.invoice.optimizer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;
import javax.inject.Inject;
import org.joda.time.LocalDate;
import org.joda.time.Period;
import org.killbill.billing.callcontext.InternalCallContext;
import org.killbill.billing.catalog.api.BillingMode;
import org.killbill.billing.invoice.api.Invoice;
import org.killbill.billing.invoice.api.InvoiceItem;
import org.killbill.billing.invoice.api.InvoiceItemType;
import org.killbill.billing.invoice.dao.InvoiceDao;
import org.killbill.billing.invoice.dao.InvoiceModelDao;
import org.killbill.billing.invoice.model.DefaultInvoice;
import org.killbill.billing.junction.BillingEvent;
import org.killbill.billing.junction.BillingEventSet;
import org.killbill.billing.util.config.definition.InvoiceConfig;
import org.killbill.clock.Clock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
public class InvoiceOptimizerExp extends InvoiceOptimizerBase {
private static Logger logger = LoggerFactory.getLogger(InvoiceOptimizerExp.class);
@Inject
public InvoiceOptimizerExp(final InvoiceDao invoiceDao,
final Clock clock,
final InvoiceConfig invoiceConfig) {
super(invoiceDao, clock, invoiceConfig);
logger.info("Feature InvoiceOptimizer is ON");
}
@Override
public AccountInvoices getInvoices(final InternalCallContext callContext) {
final Period maxInvoiceLimit = invoiceConfig.getMaxInvoiceLimit(callContext);
final LocalDate fromDate = maxInvoiceLimit != null ? callContext.toLocalDate(clock.getUTCNow()).minus(maxInvoiceLimit) : null;
final List<Invoice> existingInvoices = new LinkedList<Invoice>();
final List<InvoiceModelDao> invoicesByAccount = invoiceDao.getInvoicesByAccount(false, fromDate, null, callContext);
for (final InvoiceModelDao invoiceModelDao : invoicesByAccount) {
existingInvoices.add(new DefaultInvoice(invoiceModelDao));
}
return new AccountInvoicesExp(fromDate, existingInvoices);
}
public static class AccountInvoicesExp extends AccountInvoices {
public AccountInvoicesExp(final LocalDate cutoffDate, final List<Invoice> invoices) {
super(cutoffDate, invoices);
}
public AccountInvoicesExp() {
super();
}
@Override
public void filterProposedItems(final List<InvoiceItem> proposedItems, final BillingEventSet eventSet, final InternalCallContext internalCallContext) {
if (cutoffDate != null) {
final Map<String, BillingMode> billingModes = new HashMap<>();
final Iterable<InvoiceItem> filtered = Iterables.filter(proposedItems, new Predicate<InvoiceItem>() {
@Override
public boolean apply(final InvoiceItem invoiceItem) {
if (invoiceItem.getInvoiceItemType() == InvoiceItemType.FIXED) {
return invoiceItem.getStartDate().compareTo(cutoffDate) >= 0;
}
Preconditions.checkState(invoiceItem.getInvoiceItemType() == InvoiceItemType.RECURRING, "Expected (proposed) item %s to be a RECURRING invoice item", invoiceItem);
// Extract Plan info associated with item by correlating with list of billing events
// From plan info, retrieve billing mode.
BillingMode billingMode = billingModes.get(invoiceItem.getPlanName());
if (billingMode == null) {
// Best effort logic to find the correct billing event ('be'):
// We could simplify and look for any 'be' whose Plan matches the one from the invoiceItem,
// but in unlikely scenarios where there are multiple Plans across catalog versions with different BillingMode,
// we could end up with the wrong billing event (and therefore billing mode). Therefore, the complexity.
// (all this because catalog is not available in this layer)
//
final Iterator<BillingEvent> it = ((NavigableSet<BillingEvent>) eventSet).descendingIterator();
while (it.hasNext()) {
final BillingEvent be = it.next();
if (!be.getSubscriptionId().equals(invoiceItem.getSubscriptionId()) /* wrong subscription ID */ ||
/* Not the correct plan */
!(be.getPlan() != null && be.getPlan().getName().equals(invoiceItem.getPlanName())) ||
/* Whether in-advance or in-arrear (what we are trying to find out), the 'be' we want is the one where ii.endDate >= be.effDt */
invoiceItem.getEndDate().compareTo(internalCallContext.toLocalDate(be.getEffectiveDate())) < 0) {
continue;
}
billingMode = be.getPlan().getRecurringBillingMode();
billingModes.put(invoiceItem.getPlanName(), billingMode);
break;
}
}
// Any cutoff date 't' will return invoices with all items where:
// - If IN_ADVANCE, all items where startDate >= t
// - If IN_ARREAR, all items where endDate >= t
final LocalDate startOrEndDate = (billingMode == BillingMode.IN_ADVANCE) ? invoiceItem.getStartDate() : invoiceItem.getEndDate();
return startOrEndDate.compareTo(cutoffDate) >= 0;
}
});
final List<InvoiceItem> filteredProposed = ImmutableList.copyOf(filtered);
proposedItems.clear();
proposedItems.addAll(filteredProposed);
}
}
}
}
| {
"content_hash": "68daf9ea05bb3c65d5e4822062873af1",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 187,
"avg_line_length": 51.576,
"alnum_prop": 0.6230805025593299,
"repo_name": "sbrossie/killbill",
"id": "3a255a597065f39cc15083a12519b9bd044ec050",
"size": "7134",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "invoice/src/main/java/org/killbill/billing/invoice/optimizer/InvoiceOptimizerExp.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "206958"
},
{
"name": "HTML",
"bytes": "21430"
},
{
"name": "Java",
"bytes": "10376015"
},
{
"name": "JavaScript",
"bytes": "272772"
},
{
"name": "PLpgSQL",
"bytes": "1423"
},
{
"name": "Ruby",
"bytes": "8940"
},
{
"name": "SQLPL",
"bytes": "8585"
},
{
"name": "Shell",
"bytes": "19608"
}
],
"symlink_target": ""
} |
import gitloc
import json
import requests
import unittest
class ParseUrlTests(unittest.TestCase):
def setUp(self):
gitloc.app.config['TESTING'] = True
self.app = gitloc.app.test_client()
def test_missing_url(self):
response = self.app.get('/repo')
json_response = json.loads(response.data.decode('utf-8'))
self.assertEqual(json_response, {'error': 'missing_parameters'})
def test_invalid_url(self):
response = self.app.get('/repo?url=github.com%2F404')
json_response = json.loads(response.data.decode('utf-8'))
self.assertEqual(json_response, {'error': 'invalid_url'})
class GetZipTests(unittest.TestCase):
def setUp(self):
gitloc.app.config['TESTING'] = True
self.app = gitloc.app.test_client()
def test_successful_download(self):
self.assertEqual(len(gitloc._get_zip('octocat', 'Hello-World')), 351)
def test_invalid_repo(self):
try:
gitloc._get_zip('fakeuser', 'fakerepo')
self.assertFail()
except requests.exceptions.HTTPError as e:
self.assertEqual(e.response.status_code, 404)
class GithubLocTests(unittest.TestCase):
def setUp(self):
gitloc.app.config['TESTING'] = True
self.app = gitloc.app.test_client()
def test_invalid_repo(self):
response = self.app.get('loc/github?owner=fakeowner&repo=fakerepo')
json_response = json.loads(response.data.decode('utf-8'))
self.assertEqual(json_response, {'error': 'invalid_repo'})
def test_missing_parameters(self):
response = self.app.get('loc/github?repo=fakerepo')
json_response = json.loads(response.data.decode('utf-8'))
self.assertEqual(json_response, {'error': 'missing_parameters'})
def test_loc(self):
response = self.app.get('loc/github?owner=octocat&repo=Spoon-Knife')
json_response = json.loads(response.data.decode('utf-8'))
self.assertCountEqual(
json_response["languages"].keys(),
['html', 'css']
)
if __name__ == '__main__':
unittest.main(warnings='ignore')
| {
"content_hash": "f040b71dbde83fb601c5f673353817f8",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 77,
"avg_line_length": 32.43939393939394,
"alnum_prop": 0.6352171882297991,
"repo_name": "chowdhurya/git-loc-server",
"id": "7308a036dfbd0b05bb76359d4a9c1aefe505fd7c",
"size": "2141",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "5006"
}
],
"symlink_target": ""
} |
<?php
namespace PhpGuard\Application\Linter;
use PhpGuard\Listen\Exception\RuntimeException;
class LinterException extends RuntimeException
{
/**
* @var LinterInterface $linter
*/
private $linter;
/**
* @param string|null $output
*/
public function __construct(LinterInterface $linter,$output)
{
$this->linter = $linter;
parent::__construct($output);
}
public function getFormattedOutput()
{
$format = '%s failed: <comment>%s</comment>';
$output = sprintf($format,$this->linter->getTitle(),$this->message);
return $output;
}
}
| {
"content_hash": "258217a08e2b1a261166e5aed626b3d1",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 76,
"avg_line_length": 19.71875,
"alnum_prop": 0.6133122028526149,
"repo_name": "phpguard/phpguard",
"id": "c039371208a9ad8de8f7afbfe6b61959df909a78",
"size": "857",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Linter/LinterException.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "228462"
}
],
"symlink_target": ""
} |
DOUBTFUL
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "a415bc086049d4ca9f68655efa5398a7",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "f3f9830be99291ff2705d139d4cb89d97ce29197",
"size": "211",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Rubus/Rubus amplifoliatus/Rubus amplifoliatus acerosus/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package javax.xml.soap;
import java.io.InputStream;
import java.io.Reader;
import java.util.Iterator;
import javax.activation.DataHandler;
/**
* A single attachment to a <code>SOAPMessage</code> object. A <code>SOAPMessage</code>
* object may contain zero, one, or many <code>AttachmentPart</code> objects.
* Each <code>AttachmentPart</code> object consists of two parts,
* application-specific content and associated MIME headers. The
* MIME headers consists of name/value pairs that can be used to
* identify and describe the content.
* <p>
* An <code>AttachmentPart</code> object must conform to certain standards.
* <OL>
* <LI>It must conform to <a href="http://www.ietf.org/rfc/rfc2045.txt">
* MIME [RFC2045] standards</a>
* <LI>It MUST contain content
* <LI>The header portion MUST include the following header:
* <UL>
* <LI><code>Content-Type</code><br>
* This header identifies the type of data in the content of an
* <code>AttachmentPart</code> object and MUST conform to [RFC2045].
* The following is an example of a Content-Type header:
* <PRE>
* Content-Type: application/xml
* </PRE>
* The following line of code, in which <code>ap</code> is an
* <code>AttachmentPart</code> object, sets the header shown in
* the previous example.
* <PRE>
* ap.setMimeHeader("Content-Type", "application/xml");
* </PRE>
* <p>
* </UL>
* </OL>
* <p>
* There are no restrictions on the content portion of an <code>
* AttachmentPart</code> object. The content may be anything from a
* simple plain text object to a complex XML document or image file.
*
* <p>
* An <code>AttachmentPart</code> object is created with the method
* <code>SOAPMessage.createAttachmentPart</code>. After setting its MIME headers,
* the <code>AttachmentPart</code> object is added to the message
* that created it with the method <code>SOAPMessage.addAttachmentPart</code>.
*
* <p>
* The following code fragment, in which <code>m</code> is a
* <code>SOAPMessage</code> object and <code>contentStringl</code> is a
* <code>String</code>, creates an instance of <code>AttachmentPart</code>,
* sets the <code>AttachmentPart</code> object with some content and
* header information, and adds the <code>AttachmentPart</code> object to
* the <code>SOAPMessage</code> object.
* <PRE>
* AttachmentPart ap1 = m.createAttachmentPart();
* ap1.setContent(contentString1, "text/plain");
* m.addAttachmentPart(ap1);
* </PRE>
*
*
* <p>
* The following code fragment creates and adds a second
* <code>AttachmentPart</code> instance to the same message. <code>jpegData</code>
* is a binary byte buffer representing the jpeg file.
* <PRE>
* AttachmentPart ap2 = m.createAttachmentPart();
* byte[] jpegData = ...;
* ap2.setContent(new ByteArrayInputStream(jpegData), "image/jpeg");
* m.addAttachmentPart(ap2);
* </PRE>
* <p>
* The <code>getContent</code> method retrieves the contents and header from
* an <code>AttachmentPart</code> object. Depending on the
* <code>DataContentHandler</code> objects present, the returned
* <code>Object</code> can either be a typed Java object corresponding
* to the MIME type or an <code>InputStream</code> object that contains the
* content as bytes.
* <PRE>
* String content1 = ap1.getContent();
* java.io.InputStream content2 = ap2.getContent();
* </PRE>
*
* The method <code>clearContent</code> removes all the content from an
* <code>AttachmentPart</code> object but does not affect its header information.
* <PRE>
* ap1.clearContent();
* </PRE>
*/
public abstract class AttachmentPart {
/**
* Returns the number of bytes in this <code>AttachmentPart</code>
* object.
*
* @return the size of this <code>AttachmentPart</code> object in bytes
* or -1 if the size cannot be determined
* @exception SOAPException if the content of this attachment is
* corrupted of if there was an exception while trying
* to determine the size.
*/
public abstract int getSize() throws SOAPException;
/**
* Clears out the content of this <code>AttachmentPart</code> object.
* The MIME header portion is left untouched.
*/
public abstract void clearContent();
/**
* Gets the content of this <code>AttachmentPart</code> object as a Java
* object. The type of the returned Java object depends on (1) the
* <code>DataContentHandler</code> object that is used to interpret the bytes
* and (2) the <code>Content-Type</code> given in the header.
* <p>
* For the MIME content types "text/plain", "text/html" and "text/xml", the
* <code>DataContentHandler</code> object does the conversions to and
* from the Java types corresponding to the MIME types.
* For other MIME types,the <code>DataContentHandler</code> object
* can return an <code>InputStream</code> object that contains the content data
* as raw bytes.
* <p>
* A SAAJ-compliant implementation must, as a minimum, return a
* <code>java.lang.String</code> object corresponding to any content
* stream with a <code>Content-Type</code> value of
* <code>text/plain</code>, a
* <code>javax.xml.transform.stream.StreamSource</code> object corresponding to a
* content stream with a <code>Content-Type</code> value of
* <code>text/xml</code>, a <code>java.awt.Image</code> object
* corresponding to a content stream with a
* <code>Content-Type</code> value of <code>image/gif</code> or
* <code>image/jpeg</code>. For those content types that an
* installed <code>DataContentHandler</code> object does not understand, the
* <code>DataContentHandler</code> object is required to return a
* <code>java.io.InputStream</code> object with the raw bytes.
*
* @return a Java object with the content of this <code>AttachmentPart</code>
* object
*
* @exception SOAPException if there is no content set into this
* <code>AttachmentPart</code> object or if there was a data
* transformation error
*/
public abstract Object getContent() throws SOAPException;
/**
* Gets the content of this <code>AttachmentPart</code> object as an
* InputStream as if a call had been made to <code>getContent</code> and no
* <code>DataContentHandler</code> had been registered for the
* <code>content-type</code> of this <code>AttachmentPart</code>.
*<p>
* Note that reading from the returned InputStream would result in consuming
* the data in the stream. It is the responsibility of the caller to reset
* the InputStream appropriately before calling a Subsequent API. If a copy
* of the raw attachment content is required then the {@link #getRawContentBytes} API
* should be used instead.
*
* @return an <code>InputStream</code> from which the raw data contained by
* the <code>AttachmentPart</code> can be accessed.
*
* @throws SOAPException if there is no content set into this
* <code>AttachmentPart</code> object or if there was a data
* transformation error.
*
* @since SAAJ 1.3
* @see #getRawContentBytes
*/
public abstract InputStream getRawContent() throws SOAPException;
/**
* Gets the content of this <code>AttachmentPart</code> object as a
* byte[] array as if a call had been made to <code>getContent</code> and no
* <code>DataContentHandler</code> had been registered for the
* <code>content-type</code> of this <code>AttachmentPart</code>.
*
* @return a <code>byte[]</code> array containing the raw data of the
* <code>AttachmentPart</code>.
*
* @throws SOAPException if there is no content set into this
* <code>AttachmentPart</code> object or if there was a data
* transformation error.
*
* @since SAAJ 1.3
*/
public abstract byte[] getRawContentBytes() throws SOAPException;
/**
* Returns an <code>InputStream</code> which can be used to obtain the
* content of <code>AttachmentPart</code> as Base64 encoded
* character data, this method would base64 encode the raw bytes
* of the attachment and return.
*
* @return an <code>InputStream</code> from which the Base64 encoded
* <code>AttachmentPart</code> can be read.
*
* @throws SOAPException if there is no content set into this
* <code>AttachmentPart</code> object or if there was a data
* transformation error.
*
* @since SAAJ 1.3
*/
public abstract InputStream getBase64Content() throws SOAPException;
/**
* Sets the content of this attachment part to that of the given
* <code>Object</code> and sets the value of the <code>Content-Type</code>
* header to the given type. The type of the
* <code>Object</code> should correspond to the value given for the
* <code>Content-Type</code>. This depends on the particular
* set of <code>DataContentHandler</code> objects in use.
*
*
* @param object the Java object that makes up the content for
* this attachment part
* @param contentType the MIME string that specifies the type of
* the content
*
* @exception IllegalArgumentException may be thrown if the contentType
* does not match the type of the content object, or if there
* was no <code>DataContentHandler</code> object for this
* content object
*
* @see #getContent
*/
public abstract void setContent(Object object, String contentType);
/**
* Sets the content of this attachment part to that contained by the
* <code>InputStream</code> <code>content</code> and sets the value of the
* <code>Content-Type</code> header to the value contained in
* <code>contentType</code>.
* <P>
* A subsequent call to getSize() may not be an exact measure
* of the content size.
*
* @param content the raw data to add to the attachment part
* @param contentType the value to set into the <code>Content-Type</code>
* header
*
* @exception SOAPException if an there is an error in setting the content
* @exception NullPointerException if <code>content</code> is null
* @since SAAJ 1.3
*/
public abstract void setRawContent(InputStream content, String contentType) throws SOAPException;
/**
* Sets the content of this attachment part to that contained by the
* <code>byte[]</code> array <code>content</code> and sets the value of the
* <code>Content-Type</code> header to the value contained in
* <code>contentType</code>.
*
* @param content the raw data to add to the attachment part
* @param contentType the value to set into the <code>Content-Type</code>
* header
* @param offset the offset in the byte array of the content
* @param len the number of bytes that form the content
*
* @exception SOAPException if an there is an error in setting the content
* or content is null
* @since SAAJ 1.3
*/
public abstract void setRawContentBytes(
byte[] content, int offset, int len, String contentType)
throws SOAPException;
/**
* Sets the content of this attachment part from the Base64 source
* <code>InputStream</code> and sets the value of the
* <code>Content-Type</code> header to the value contained in
* <code>contentType</code>, This method would first decode the base64
* input and write the resulting raw bytes to the attachment.
* <P>
* A subsequent call to getSize() may not be an exact measure
* of the content size.
*
* @param content the base64 encoded data to add to the attachment part
* @param contentType the value to set into the <code>Content-Type</code>
* header
*
* @exception SOAPException if an there is an error in setting the content
* @exception NullPointerException if <code>content</code> is null
*
* @since SAAJ 1.3
*/
public abstract void setBase64Content(
InputStream content, String contentType) throws SOAPException;
/**
* Gets the <code>DataHandler</code> object for this <code>AttachmentPart</code>
* object.
*
* @return the <code>DataHandler</code> object associated with this
* <code>AttachmentPart</code> object
*
* @exception SOAPException if there is no data in
* this <code>AttachmentPart</code> object
*/
public abstract DataHandler getDataHandler()
throws SOAPException;
/**
* Sets the given <code>DataHandler</code> object as the data handler
* for this <code>AttachmentPart</code> object. Typically, on an incoming
* message, the data handler is automatically set. When
* a message is being created and populated with content, the
* <code>setDataHandler</code> method can be used to get data from
* various data sources into the message.
*
* @param dataHandler the <code>DataHandler</code> object to be set
*
* @exception IllegalArgumentException if there was a problem with
* the specified <code>DataHandler</code> object
*/
public abstract void setDataHandler(DataHandler dataHandler);
/**
* Gets the value of the MIME header whose name is "Content-ID".
*
* @return a <code>String</code> giving the value of the
* "Content-ID" header or <code>null</code> if there
* is none
* @see #setContentId
*/
public String getContentId() {
String[] values = getMimeHeader("Content-ID");
if (values != null && values.length > 0)
return values[0];
return null;
}
/**
* Gets the value of the MIME header whose name is "Content-Location".
*
* @return a <code>String</code> giving the value of the
* "Content-Location" header or <code>null</code> if there
* is none
*/
public String getContentLocation() {
String[] values = getMimeHeader("Content-Location");
if (values != null && values.length > 0)
return values[0];
return null;
}
/**
* Gets the value of the MIME header whose name is "Content-Type".
*
* @return a <code>String</code> giving the value of the
* "Content-Type" header or <code>null</code> if there
* is none
*/
public String getContentType() {
String[] values = getMimeHeader("Content-Type");
if (values != null && values.length > 0)
return values[0];
return null;
}
/**
* Sets the MIME header whose name is "Content-ID" with the given value.
*
* @param contentId a <code>String</code> giving the value of the
* "Content-ID" header
*
* @exception IllegalArgumentException if there was a problem with
* the specified <code>contentId</code> value
* @see #getContentId
*/
public void setContentId(String contentId)
{
setMimeHeader("Content-ID", contentId);
}
/**
* Sets the MIME header whose name is "Content-Location" with the given value.
*
*
* @param contentLocation a <code>String</code> giving the value of the
* "Content-Location" header
* @exception IllegalArgumentException if there was a problem with
* the specified content location
*/
public void setContentLocation(String contentLocation)
{
setMimeHeader("Content-Location", contentLocation);
}
/**
* Sets the MIME header whose name is "Content-Type" with the given value.
*
* @param contentType a <code>String</code> giving the value of the
* "Content-Type" header
*
* @exception IllegalArgumentException if there was a problem with
* the specified content type
*/
public void setContentType(String contentType)
{
setMimeHeader("Content-Type", contentType);
}
/**
* Removes all MIME headers that match the given name.
*
* @param header the string name of the MIME header/s to
* be removed
*/
public abstract void removeMimeHeader(String header);
/**
* Removes all the MIME header entries.
*/
public abstract void removeAllMimeHeaders();
/**
* Gets all the values of the header identified by the given
* <code>String</code>.
*
* @param name the name of the header; example: "Content-Type"
* @return a <code>String</code> array giving the value for the
* specified header
* @see #setMimeHeader
*/
public abstract String[] getMimeHeader(String name);
/**
* Changes the first header entry that matches the given name
* to the given value, adding a new header if no existing header
* matches. This method also removes all matching headers but the first. <p>
*
* Note that RFC822 headers can only contain US-ASCII characters.
*
* @param name a <code>String</code> giving the name of the header
* for which to search
* @param value a <code>String</code> giving the value to be set for
* the header whose name matches the given name
*
* @exception IllegalArgumentException if there was a problem with
* the specified mime header name or value
*/
public abstract void setMimeHeader(String name, String value);
/**
* Adds a MIME header with the specified name and value to this
* <code>AttachmentPart</code> object.
* <p>
* Note that RFC822 headers can contain only US-ASCII characters.
*
* @param name a <code>String</code> giving the name of the header
* to be added
* @param value a <code>String</code> giving the value of the header
* to be added
*
* @exception IllegalArgumentException if there was a problem with
* the specified mime header name or value
*/
public abstract void addMimeHeader(String name, String value);
/**
* Retrieves all the headers for this <code>AttachmentPart</code> object
* as an iterator over the <code>MimeHeader</code> objects.
*
* @return an <code>Iterator</code> object with all of the Mime
* headers for this <code>AttachmentPart</code> object
*/
public abstract Iterator getAllMimeHeaders();
/**
* Retrieves all <code>MimeHeader</code> objects that match a name in
* the given array.
*
* @param names a <code>String</code> array with the name(s) of the
* MIME headers to be returned
* @return all of the MIME headers that match one of the names in the
* given array as an <code>Iterator</code> object
*/
public abstract Iterator getMatchingMimeHeaders(String[] names);
/**
* Retrieves all <code>MimeHeader</code> objects whose name does
* not match a name in the given array.
*
* @param names a <code>String</code> array with the name(s) of the
* MIME headers not to be returned
* @return all of the MIME headers in this <code>AttachmentPart</code> object
* except those that match one of the names in the
* given array. The nonmatching MIME headers are returned as an
* <code>Iterator</code> object.
*/
public abstract Iterator getNonMatchingMimeHeaders(String[] names);
}
| {
"content_hash": "c1376b46c80fcb1d7df6b623bf525eb9",
"timestamp": "",
"source": "github",
"line_count": 503,
"max_line_length": 101,
"avg_line_length": 39.51093439363817,
"alnum_prop": 0.6480326054141089,
"repo_name": "rokn/Count_Words_2015",
"id": "b1fabb0fa6144df3ea50d4b673fea9694ccdae2f",
"size": "21086",
"binary": false,
"copies": "24",
"ref": "refs/heads/master",
"path": "testing/openjdk2/jaxws/src/share/jaxws_classes/javax/xml/soap/AttachmentPart.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "61802"
},
{
"name": "Ruby",
"bytes": "18888605"
}
],
"symlink_target": ""
} |
/**
* @license Highcharts JS v8.0.0 (2019-12-10)
*
* (c) 2009-2019 Highsoft AS
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define('highcharts/themes/avocado', ['highcharts'], function (Highcharts) {
factory(Highcharts);
factory.Highcharts = Highcharts;
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
var _modules = Highcharts ? Highcharts._modules : {};
function _registerModule(obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
}
_registerModule(_modules, 'themes/avocado.js', [_modules['parts/Globals.js']], function (Highcharts) {
/* *
*
* (c) 2010-2019 Highsoft AS
*
* Author: Øystein Moseng
*
* License: www.highcharts.com/license
*
* Accessible high-contrast theme for Highcharts. Considers colorblindness and
* monochrome rendering.
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
Highcharts.theme = {
colors: ['#F3E796', '#95C471', '#35729E', '#251735'],
colorAxis: {
maxColor: '#05426E',
minColor: '#F3E796'
},
plotOptions: {
map: {
nullColor: '#FCFEFE'
}
},
navigator: {
maskFill: 'rgba(170, 205, 170, 0.5)',
series: {
color: '#95C471',
lineColor: '#35729E'
}
}
};
// Apply the theme
Highcharts.setOptions(Highcharts.theme);
});
_registerModule(_modules, 'masters/themes/avocado.src.js', [], function () {
});
})); | {
"content_hash": "fc4e103c368e754e5810342a2fedab27",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 106,
"avg_line_length": 30.380281690140844,
"alnum_prop": 0.4951321279554937,
"repo_name": "cdnjs/cdnjs",
"id": "248083f5a164b0e57a0fe265281a7506f3f35c4c",
"size": "2158",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ajax/libs/highcharts/8.0.0/themes/avocado.src.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
"""
Tests the Table class which contains metadata
"""
import sys
sys.path.append('code')
from pdftables import get_tables
from nose.tools import *
def test_it_includes_page_numbers():
"""
page_number is 1-indexed, as defined in the PDF format
table_number is 1-indexed
"""
fh = open('fixtures/sample_data/AnimalExampleTables.pdf', 'rb')
result = get_tables(fh)
assert_equals(result[0].total_pages, 4)
assert_equals(result[0].page_number, 2)
assert_equals(result[1].total_pages, 4)
assert_equals(result[1].page_number, 3)
assert_equals(result[2].total_pages, 4)
assert_equals(result[2].page_number, 4)
def test_it_includes_table_numbers():
fh = open('fixtures/sample_data/AnimalExampleTables.pdf', 'rb')
result = get_tables(fh)
assert_equals(result[0].table_number_on_page, 1)
assert_equals(result[0].total_tables_on_page, 1)
| {
"content_hash": "4e5ae24f549b5323f795c313b78c0a49",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 67,
"avg_line_length": 29.8,
"alnum_prop": 0.6901565995525727,
"repo_name": "pombredanne/pdftables",
"id": "3f6ebed16a414aa775c86fecb6c3fe0abdcc5033",
"size": "991",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/test_Table_class.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [],
"symlink_target": ""
} |
// Copyright (c) 2020-2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef FUJICOIN_TEST_UTIL_NET_H
#define FUJICOIN_TEST_UTIL_NET_H
#include <compat/compat.h>
#include <node/eviction.h>
#include <netaddress.h>
#include <net.h>
#include <util/sock.h>
#include <array>
#include <cassert>
#include <cstring>
#include <memory>
#include <string>
struct ConnmanTestMsg : public CConnman {
using CConnman::CConnman;
void SetPeerConnectTimeout(std::chrono::seconds timeout)
{
m_peer_connect_timeout = timeout;
}
void AddTestNode(CNode& node)
{
LOCK(m_nodes_mutex);
m_nodes.push_back(&node);
}
void ClearTestNodes()
{
LOCK(m_nodes_mutex);
for (CNode* node : m_nodes) {
delete node;
}
m_nodes.clear();
}
void Handshake(CNode& node,
bool successfully_connected,
ServiceFlags remote_services,
ServiceFlags local_services,
int32_t version,
bool relay_txs);
void ProcessMessagesOnce(CNode& node) { m_msgproc->ProcessMessages(&node, flagInterruptMsgProc); }
void NodeReceiveMsgBytes(CNode& node, Span<const uint8_t> msg_bytes, bool& complete) const;
bool ReceiveMsgFrom(CNode& node, CSerializedNetMsg& ser_msg) const;
};
constexpr ServiceFlags ALL_SERVICE_FLAGS[]{
NODE_NONE,
NODE_NETWORK,
NODE_BLOOM,
NODE_WITNESS,
NODE_COMPACT_FILTERS,
NODE_NETWORK_LIMITED,
};
constexpr NetPermissionFlags ALL_NET_PERMISSION_FLAGS[]{
NetPermissionFlags::None,
NetPermissionFlags::BloomFilter,
NetPermissionFlags::Relay,
NetPermissionFlags::ForceRelay,
NetPermissionFlags::NoBan,
NetPermissionFlags::Mempool,
NetPermissionFlags::Addr,
NetPermissionFlags::Download,
NetPermissionFlags::Implicit,
NetPermissionFlags::All,
};
constexpr ConnectionType ALL_CONNECTION_TYPES[]{
ConnectionType::INBOUND,
ConnectionType::OUTBOUND_FULL_RELAY,
ConnectionType::MANUAL,
ConnectionType::FEELER,
ConnectionType::BLOCK_RELAY,
ConnectionType::ADDR_FETCH,
};
constexpr auto ALL_NETWORKS = std::array{
Network::NET_UNROUTABLE,
Network::NET_IPV4,
Network::NET_IPV6,
Network::NET_ONION,
Network::NET_I2P,
Network::NET_CJDNS,
Network::NET_INTERNAL,
};
/**
* A mocked Sock alternative that returns a statically contained data upon read and succeeds
* and ignores all writes. The data to be returned is given to the constructor and when it is
* exhausted an EOF is returned by further reads.
*/
class StaticContentsSock : public Sock
{
public:
explicit StaticContentsSock(const std::string& contents) : m_contents{contents}, m_consumed{0}
{
// Just a dummy number that is not INVALID_SOCKET.
m_socket = INVALID_SOCKET - 1;
}
~StaticContentsSock() override { m_socket = INVALID_SOCKET; }
StaticContentsSock& operator=(Sock&& other) override
{
assert(false && "Move of Sock into MockSock not allowed.");
return *this;
}
ssize_t Send(const void*, size_t len, int) const override { return len; }
ssize_t Recv(void* buf, size_t len, int flags) const override
{
const size_t consume_bytes{std::min(len, m_contents.size() - m_consumed)};
std::memcpy(buf, m_contents.data() + m_consumed, consume_bytes);
if ((flags & MSG_PEEK) == 0) {
m_consumed += consume_bytes;
}
return consume_bytes;
}
int Connect(const sockaddr*, socklen_t) const override { return 0; }
int Bind(const sockaddr*, socklen_t) const override { return 0; }
int Listen(int) const override { return 0; }
std::unique_ptr<Sock> Accept(sockaddr* addr, socklen_t* addr_len) const override
{
if (addr != nullptr) {
// Pretend all connections come from 5.5.5.5:6789
memset(addr, 0x00, *addr_len);
const socklen_t write_len = static_cast<socklen_t>(sizeof(sockaddr_in));
if (*addr_len >= write_len) {
*addr_len = write_len;
sockaddr_in* addr_in = reinterpret_cast<sockaddr_in*>(addr);
addr_in->sin_family = AF_INET;
memset(&addr_in->sin_addr, 0x05, sizeof(addr_in->sin_addr));
addr_in->sin_port = htons(6789);
}
}
return std::make_unique<StaticContentsSock>("");
};
int GetSockOpt(int level, int opt_name, void* opt_val, socklen_t* opt_len) const override
{
std::memset(opt_val, 0x0, *opt_len);
return 0;
}
int SetSockOpt(int, int, const void*, socklen_t) const override { return 0; }
int GetSockName(sockaddr* name, socklen_t* name_len) const override
{
std::memset(name, 0x0, *name_len);
return 0;
}
bool Wait(std::chrono::milliseconds timeout,
Event requested,
Event* occurred = nullptr) const override
{
if (occurred != nullptr) {
*occurred = requested;
}
return true;
}
bool WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const override
{
for (auto& [sock, events] : events_per_sock) {
(void)sock;
events.occurred = events.requested;
}
return true;
}
private:
const std::string m_contents;
mutable size_t m_consumed;
};
std::vector<NodeEvictionCandidate> GetRandomNodeEvictionCandidates(int n_candidates, FastRandomContext& random_context);
#endif // FUJICOIN_TEST_UTIL_NET_H
| {
"content_hash": "a0915dd6b9ca4b5ae9295a2f725e2818",
"timestamp": "",
"source": "github",
"line_count": 194,
"max_line_length": 120,
"avg_line_length": 29.515463917525775,
"alnum_prop": 0.6355221795319594,
"repo_name": "fujicoin/fujicoin",
"id": "84d242e120aa000ad230976028e3546a036b6d26",
"size": "5726",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/util/net.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "28178"
},
{
"name": "Batchfile",
"bytes": "13"
},
{
"name": "C",
"bytes": "1226556"
},
{
"name": "C++",
"bytes": "10236550"
},
{
"name": "CMake",
"bytes": "29182"
},
{
"name": "Cap'n Proto",
"bytes": "1256"
},
{
"name": "Dockerfile",
"bytes": "1740"
},
{
"name": "HTML",
"bytes": "21833"
},
{
"name": "Java",
"bytes": "547"
},
{
"name": "M4",
"bytes": "221436"
},
{
"name": "Makefile",
"bytes": "147554"
},
{
"name": "Objective-C++",
"bytes": "5500"
},
{
"name": "Python",
"bytes": "2974091"
},
{
"name": "QMake",
"bytes": "438"
},
{
"name": "Sage",
"bytes": "58534"
},
{
"name": "Scheme",
"bytes": "26044"
},
{
"name": "Shell",
"bytes": "168383"
}
],
"symlink_target": ""
} |
FROM ppc64le/ubuntu
RUN apt-get update && apt-get -y install unzip \
xz-utils \
curl \
bc \
git \
wget \
locales \
language-pack-en \
python python-pip curl \
build-essential \
golang \
cpio \
gcc libc6 libc6-dev libssl-dev \
kmod \
genisoimage \
automake \
libtool \
make \
sudo \
pkg-config \
p7zip-full
# https://www.kernel.org/
ENV KERNEL_VERSION 4.4.16
# Fetch the kernel sources
RUN curl --retry 10 https://www.kernel.org/pub/linux/kernel/v${KERNEL_VERSION%%.*}.x/linux-$KERNEL_VERSION.tar.xz | tar -C / -xJ && \
mv /linux-$KERNEL_VERSION /linux-kernel
# http://aufs.sourceforge.net/
ENV AUFS_REPO https://github.com/sfjro/aufs4-standalone
ENV AUFS_BRANCH aufs4.4
ENV AUFS_COMMIT 45192fd8c7c447090b990953c62760dc18508dd7
# we use AUFS_COMMIT to get stronger repeatability guarantees
# Download AUFS and apply patches and files, then remove it
RUN git clone -b "$AUFS_BRANCH" "$AUFS_REPO" /aufs-standalone && \
cd /aufs-standalone && \
git checkout -q "$AUFS_COMMIT" && \
cd /linux-kernel && \
cp -r /aufs-standalone/Documentation /linux-kernel && \
cp -r /aufs-standalone/fs /linux-kernel && \
cp -r /aufs-standalone/include/uapi/linux/aufs_type.h /linux-kernel/include/uapi/linux/ && \
set -e && for patch in \
/aufs-standalone/aufs*-kbuild.patch \
/aufs-standalone/aufs*-base.patch \
/aufs-standalone/aufs*-mmap.patch \
/aufs-standalone/aufs*-standalone.patch \
/aufs-standalone/aufs*-loopback.patch \
; do \
patch -p1 < "$patch"; \
done
COPY config/kernel_config /linux-kernel/.config
RUN jobs=$(nproc); \
cd /linux-kernel && \
make -j ${jobs} oldconfig && \
make -j ${jobs} zImage && \
make -j ${jobs} modules
# The post kernel build process
ENV ROOTFS /rootfs
# Make the ROOTFS
RUN mkdir -p $ROOTFS
# Prepare the build directory (/tmp/iso)
#RUN mkdir -p /tmp/iso/boot
RUN mkdir /isoimage
COPY isoimage/ /isoimage/
RUN mkdir /docker-binaries
COPY docker-binaries/ /docker-binaries/
# Install the kernel modules in $ROOTFS
RUN cd /linux-kernel && \
make INSTALL_MOD_PATH=$ROOTFS modules_install firmware_install
# Remove useless kernel modules, based on unclejack/debian2docker
RUN cd $ROOTFS/lib/modules && \
rm -rf ./*/kernel/sound/* && \
rm -rf ./*/kernel/drivers/gpu/* && \
rm -rf ./*/kernel/drivers/infiniband/* && \
rm -rf ./*/kernel/drivers/isdn/* && \
rm -rf ./*/kernel/drivers/media/* && \
rm -rf ./*/kernel/drivers/staging/lustre/* && \
rm -rf ./*/kernel/drivers/staging/comedi/* && \
rm -rf ./*/kernel/fs/ocfs2/* && \
rm -rf ./*/kernel/net/bluetooth/* && \
rm -rf ./*/kernel/net/mac80211/* && \
rm -rf ./*/kernel/net/wireless/*
# Make sure the kernel headers are installed for aufs-util, and then build it
ENV AUFS_UTIL_REPO git://git.code.sf.net/p/aufs/aufs-util
ENV AUFS_UTIL_BRANCH aufs4.1
ENV AUFS_UTIL_COMMIT 12eff17c0de02bd36c89c45a28aa5dc6536ef956
RUN set -ex \
&& git clone -b "$AUFS_UTIL_BRANCH" "$AUFS_UTIL_REPO" /aufs-util \
&& git -C /aufs-util checkout --quiet "$AUFS_UTIL_COMMIT" \
&& make -C /linux-kernel headers_install INSTALL_HDR_PATH=/tmp/kheaders \
&& export CFLAGS='-I/tmp/kheaders/include' \
&& export CPPFLAGS="$CFLAGS" LDFLAGS="$CFLAGS" \
&& make -C /aufs-util \
&& make -C /aufs-util install DESTDIR="$ROOTFS" \
&& rm -r /tmp/kheaders
# Prepare the ISO directory with the kernel
RUN cp -v /linux-kernel/arch/powerpc/boot/zImage /isoimage/ppc/ppc64/
#remove kernel source after building
#RUN rm -rf /linux-kernel/
# build rootfs using buildroot
#https://buildroot.org/
ENV BUILDROOT_VERSION 2016.11.1
# Fetch the buildroot sources
RUN curl --retry 10 https://buildroot.org/downloads/buildroot-$BUILDROOT_VERSION.tar.gz | tar -C / -xz && \
mv /buildroot-$BUILDROOT_VERSION /buildroot
COPY config/buildroot-$BUILDROOT_VERSION.config /buildroot/.config
RUN jobs=$(nproc); \
cd /buildroot && \
make -j ${jobs} && \
cp -av /buildroot/output/images/rootfs.tar $ROOTFS/
RUN mkdir -p /scripts
COPY scripts/ /scripts/
#COPY rootfs/rootfs.tar $ROOTFS/
RUN cd /rootfs && \
tar -xvf rootfs.tar && \
rm -rf rootfs.tar && \
cp /scripts/init /rootfs/ && \
cp /scripts/S90automount /scripts/S91docker /scripts/docker /rootfs/etc/init.d/ && \
cp /scripts/autologin /scripts/sethostname /rootfs/usr/bin/ && \
cp /scripts/interfaces /rootfs/etc/network/ && \
cp /docker-binaries/* /rootfs/usr/bin/ && \
chmod 755 /rootfs/etc/sudoers && \
rm -f /rootfs/etc/os-release && \
rm -f /rootfs/etc/inittab && \
rm -f /rootfs/bin/login && \
rm -f /rootfs/etc/resolv.conf && \
cd /rootfs/bin && \
sudo ln -s busybox login
#remove unused kernel modules
RUN cd /rootfs/lib/modules/4.4.16/kernel/ && \
find . -type f | sort > /root/installed_modules.list && \
cp /scripts/kernel_modules.list /root/ && \
cd /root && \
sort kernel_modules.list -o kernel_modules.list && \
comm -13 kernel_modules.list installed_modules.list > /rootfs/lib/modules/4.4.16/kernel/rm_modules.list && \
cd /rootfs/lib/modules/4.4.16/kernel/ && \
xargs -a rm_modules.list rm
RUN cd /rootfs && \
cp /scripts/os-release /scripts/inittab /scripts/resolv.conf /rootfs/etc/ && \
rm -f /rootfs/rootfs.tar && \
cd /rootfs && \
sudo find . | cpio -oHnewc | gzip > /isoimage/ppc/ppc64/initramfs.gz
RUN mkdir -p /boot2docker_iso
RUN cd /isoimage/ && \
mkisofs -R -V "Docker" -sysid PPC -chrp-boot -U -no-desktop -allow-multidot -volset 4 -volset-size 1 -volset-seqno 1 -hfs-volid 4 -o ../boot2docker_iso/Boot2docker.iso . && \
ls -lh /rootfs/ && \
ls -lh /boot2docker_iso/
VOLUME /boot2docker_iso/
#CMD ["/bin/sh"]
CMD ["sh", "-c", "[ -t 1 ] && exec bash || exec cat /boot2docker_iso/Boot2docker.iso"]
| {
"content_hash": "e363d43df8eee66aea365c4cb335bb42",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 176,
"avg_line_length": 34.201117318435756,
"alnum_prop": 0.6277360339758249,
"repo_name": "power-dev-env/boot2docker",
"id": "67183725c3073bf6ba82145c11cca050d0b05312",
"size": "6122",
"binary": false,
"copies": "1",
"ref": "refs/heads/ppc64le_support",
"path": "build_scripts/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "146"
},
{
"name": "Shell",
"bytes": "54508"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
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("VersionOne.TestComplete.V1Connector")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("VersionOne")]
[assembly: AssemblyProduct("VersionOne.TestComplete.V1Connector")]
[assembly: AssemblyCopyright("Copyright © VersionOne 2011")]
[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("e6c3863e-7663-4b64-b59e-fb7d61bf6683")]
// 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": "25cac82f99c56be44449c6f4f4b5a54c",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 84,
"avg_line_length": 39.567567567567565,
"alnum_prop": 0.7534153005464481,
"repo_name": "versionone/VersionOne.Integration.TestComplete",
"id": "02482ddc868b8a11acb0bfb26b624c7a98b3bc50",
"size": "1467",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "VersionOne.TestComplete.V1Connector/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "43240"
},
{
"name": "C#",
"bytes": "53877"
},
{
"name": "C++",
"bytes": "80684"
},
{
"name": "Objective-C",
"bytes": "173"
}
],
"symlink_target": ""
} |
<ul class="dropdown-menu" role="menu">
<li>{!! link_to('lang/en', trans('menus.language-picker.langs.en')) !!}</li>
</ul> | {
"content_hash": "7417c0d6d87f5a65c30c3fb52d86ca3e",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 80,
"avg_line_length": 41.666666666666664,
"alnum_prop": 0.608,
"repo_name": "agenciamav/HorusWP",
"id": "44686874ec72904e0d64367e0a2660651d96d502",
"size": "125",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "resources/views/includes/partials/lang.blade.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "39551"
},
{
"name": "CSS",
"bytes": "121878"
},
{
"name": "JavaScript",
"bytes": "52412"
},
{
"name": "PHP",
"bytes": "512045"
}
],
"symlink_target": ""
} |
/* Desc: Link class
* Author: Nate Koenig
*/
#ifndef __LINK_HH__
#define __LINK_HH__
#include <map>
#include <vector>
#include <string>
#include "common/Event.hh"
#include "common/CommonTypes.hh"
#include "physics/LinkState.hh"
#include "physics/Entity.hh"
#include "physics/Inertial.hh"
#include "physics/Joint.hh"
namespace gazebo
{
namespace physics
{
class Model;
class Collision;
/// \addtogroup gazebo_physics
/// \{
/// \brief Link class
class Link : public Entity
{
/// \brief Constructor
public: Link(EntityPtr parent);
/// \brief Destructor
public: virtual ~Link();
/// \brief Load the body based on an SDF element
/// \param _sdf SDF parameters
public: virtual void Load(sdf::ElementPtr _sdf);
/// \brief Initialize the body
public: virtual void Init();
/// \brief Finalize the body
public: void Fini();
/// \brief Reset the link
public: void Reset();
/// \brief Update the parameters using new sdf values
public: virtual void UpdateParameters(sdf::ElementPtr _sdf);
/// \brief Update the body
public: virtual void Update();
/// \brief Set whether this body is enabled
public: virtual void SetEnabled(bool enable) const = 0;
/// \brief Get whether this body is enabled in the physics engine
public: virtual bool GetEnabled() const = 0;
/// \brief Set whether this entity has been selected by the user
/// through the gui
public: virtual bool SetSelected(bool s);
/// \brief Set whether gravity affects this body
public: virtual void SetGravityMode(bool mode) = 0;
/// \brief Get the gravity mode
public: virtual bool GetGravityMode() = 0;
/// \brief Set whether this body will collide with others in the model
public: virtual void SetSelfCollide(bool collide) = 0;
/// \brief Set the collide mode of the body
public: void SetCollideMode(const std::string &m);
/// \brief Get Self-Collision Flag, if this is true, this body will
/// collide with other bodies even if they share the same parent.
public: bool GetSelfCollide();
/// \brief Set the laser retro reflectiveness
public: void SetLaserRetro(float retro);
/// \brief Set the linear velocity of the body
public: virtual void SetLinearVel(const math::Vector3 &vel) = 0;
/// \brief Set the angular velocity of the body
public: virtual void SetAngularVel(const math::Vector3 &vel) = 0;
/// \brief Set the linear acceleration of the body
public: void SetLinearAccel(const math::Vector3 &accel);
/// \brief Set the angular acceleration of the body
public: void SetAngularAccel(const math::Vector3 &accel);
/// \brief Set the force applied to the body
public: virtual void SetForce(const math::Vector3 &_force) = 0;
/// \brief Set the torque applied to the body
public: virtual void SetTorque(const math::Vector3 &_force) = 0;
/// \brief Add a force to the body
public: virtual void AddForce(const math::Vector3 &_force) = 0;
/// \brief Add a force to the body, components are relative to the
/// body's own frame of reference.
public: virtual void AddRelativeForce(const math::Vector3 &_force) = 0;
/// \brief Add a force to the body using a global position
public: virtual void AddForceAtWorldPosition(const math::Vector3 &_force,
const math::Vector3 &_pos) = 0;
/// \brief Add a force to the body at position expressed to the body's
/// own frame of reference.
public: virtual void AddForceAtRelativePosition(
const math::Vector3 &_force,
const math::Vector3 &_relpos) = 0;
/// \brief Add a torque to the body
public: virtual void AddTorque(const math::Vector3 &_torque) = 0;
/// \brief Add a torque to the body, components are relative to the
/// body's own frame of reference.
public: virtual void AddRelativeTorque(const math::Vector3 &_torque) = 0;
/// \brief Get the linear velocity of the body
public: math::Vector3 GetRelativeLinearVel() const;
/// \brief Get the angular velocity of the body
public: math::Vector3 GetRelativeAngularVel() const;
/// \brief Get the linear acceleration of the body
public: math::Vector3 GetRelativeLinearAccel() const;
/// \brief Get the linear acceleration of the body in the world frame
public: math::Vector3 GetWorldLinearAccel() const;
/// \brief Get the angular acceleration of the body
public: math::Vector3 GetRelativeAngularAccel() const;
/// \brief Get the angular acceleration of the body in the world frame
public: math::Vector3 GetWorldAngularAccel() const;
/// \brief Get the force applied to the body
public: math::Vector3 GetRelativeForce() const;
/// \brief Get the force applied to the body in the world frame
public: virtual math::Vector3 GetWorldForce() const = 0;
/// \brief Get the torque applied to the body
public: math::Vector3 GetRelativeTorque() const;
/// \brief Get the torque applied to the body in the world frame
public: virtual math::Vector3 GetWorldTorque() const = 0;
/// \brief Get the model that this body belongs to
public: ModelPtr GetModel() const;
/// \brief Get the mass of the body
public: InertialPtr GetInertial() const { return this->inertial; }
/// \brief Set the mass of the body
public: void SetInertial(const InertialPtr &_inertial);
/// \brief Get a collision by id
/// \return Pointer to the collision
public: CollisionPtr GetCollisionById(unsigned int _id) const;
/// \brief accessor for collisions
public: CollisionPtr GetCollision(const std::string &name);
/// \brief accessor for collisions
public: CollisionPtr GetCollision(unsigned int _index) const;
/// \brief Get the size of the body
public: virtual math::Box GetBoundingBox() const;
/// \brief Set the linear damping factor
public: virtual void SetLinearDamping(double _damping) = 0;
/// \brief Set the angular damping factor
public: virtual void SetAngularDamping(double _damping) = 0;
/// \brief Get the linear damping factor
public: double GetLinearDamping() const;
/// \brief Get the angular damping factor
public: double GetAngularDamping() const;
/// \brief Set whether this body is in the kinematic state
public: virtual void SetKinematic(const bool &) {}
/// \brief Get whether this body is in the kinematic state
public: virtual bool GetKinematic() const {return false;}
/// \brief Get sensor count
public: unsigned int GetSensorCount() const;
/// \brief Get sensor name
public: std::string GetSensorName(unsigned int _i) const;
/// \brief Connect a to the add entity signal
public: template<typename T>
event::ConnectionPtr ConnectEnabled(T subscriber)
{ return enabledSignal.Connect(subscriber); }
public: void DisconnectEnabled(event::ConnectionPtr &c)
{ enabledSignal.Disconnect(c); }
/// \brief Fill a link message
/// \param _msg Message to fill
public: void FillLinkMsg(msgs::Link &_msg);
/// \brief Update parameters from a message
/// \param _msg Message to read
public: void ProcessMsg(const msgs::Link &_msg);
/// \brief Joints that have this Link as a parent Link
public: void AddChildJoint(JointPtr joint);
/// \brief Joints that have this Link as a child Link
public: void AddParentJoint(JointPtr joint);
/// \brief Attach a static model to this link
public: void AttachStaticModel(ModelPtr &_model,
const math::Pose &_offset);
/// \brief Detach a static model from this link
public: void DetachStaticModel(const std::string &_modelName);
/// \brief Detach all static models from this link
public: void DetachAllStaticModels();
public: virtual void OnPoseChange();
/// \brief Get the link state
public: LinkState GetState();
/// \brief Set the current link state
public: void SetState(const LinkState &_state);
/// \brief Update the mass matrix
public: virtual void UpdateMass() {}
/// \brief Update surface parameters
public: virtual void UpdateSurface() {}
/// Load a new collision helper function
/// \param _sdf SDF element used to load the collision
private: void LoadCollision(sdf::ElementPtr _sdf);
/// \brief Set the inertial properties based on the collision entities
private: void SetInertialFromCollisions();
protected: bool isStatic;
protected: InertialPtr inertial;
protected: std::vector<std::string> cgVisuals;
protected: std::vector<std::string> visuals;
protected: math::Vector3 linearAccel;
protected: math::Vector3 angularAccel;
private: event::EventT<void (bool)> enabledSignal;
private: event::ConnectionPtr showPhysicsConnection;
/// This flag is used to trigger the enabled
private: bool enabled;
protected: math::Pose newPose;
private: std::vector<std::string> sensors;
private: std::vector<JointPtr> parentJoints;
private: std::vector<JointPtr> childJoints;
private: std::vector<ModelPtr> attachedModels;
protected: std::vector<math::Pose> attachedModelsOffset;
};
/// \}
}
}
#endif
| {
"content_hash": "0faeb9ee126eaf636018d3675a98339e",
"timestamp": "",
"source": "github",
"line_count": 287,
"max_line_length": 79,
"avg_line_length": 33.88850174216028,
"alnum_prop": 0.652580711494962,
"repo_name": "nherment/gazebo",
"id": "570134965cb12d7d7d2ab91880dd0fd599791fef",
"size": "10338",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/physics/Link.hh",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
//
// XBActionRecordBaseModel.h
// jiazhangduan
//
// Created by 周旭斌 on 2016/11/18.
// Copyright © 2016年 周旭斌. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <MJExtension.h>
@interface XBActionRecordBaseModel : NSObject
/*Childid": "8",
"Childname": "小青",
"Childavator": "/upload/201611/18/201611181252142767.jpg",
"Actiontypes*/
@property (nonatomic, copy) NSString *Childid;
@property (nonatomic, copy) NSString *Childname;
@property (nonatomic, copy) NSString *Childavator;
@property (nonatomic, strong) NSArray *Actiontypes;
@end
| {
"content_hash": "6b3c3a9a5c98d85a877900d211f302f7",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 59,
"avg_line_length": 25.545454545454547,
"alnum_prop": 0.7313167259786477,
"repo_name": "bowenhx/DxTeacherNew",
"id": "0602f5b54d2fcc3ff53f228be360dc87d800162d",
"size": "581",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DxTeacher/HomeVC/model/XBActionRecordBaseModel.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "1140561"
},
{
"name": "Ruby",
"bytes": "211"
}
],
"symlink_target": ""
} |
package mv.model.mvsystem.in;
import java.io.IOException;
public class InStreamNada implements InStream {
public void open() { }
public void close() { }
public int read() { return -1; }
public void reset() throws IOException { }
}
| {
"content_hash": "f30693df829926bda803c53ebd6527a3",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 47,
"avg_line_length": 21,
"alnum_prop": 0.6706349206349206,
"repo_name": "hecoding/OOVM",
"id": "9e344d4c86b22e653e11748c36f313c4fd85e4fa",
"size": "252",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/mv/model/mvsystem/in/InStreamNada.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "116993"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.sandbox.tsa.fftarma.ArmaFft.filter2 — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/stylesheets/deprecation.css">
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="../_static/material.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/doctools.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.sandbox.tsa.fftarma.ArmaFft.from_coeffs" href="statsmodels.sandbox.tsa.fftarma.ArmaFft.from_coeffs.html" />
<link rel="prev" title="statsmodels.sandbox.tsa.fftarma.ArmaFft.filter" href="statsmodels.sandbox.tsa.fftarma.ArmaFft.filter.html" />
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.sandbox.tsa.fftarma.ArmaFft.filter2" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels v0.12.2</span>
<span class="md-header-nav__topic"> statsmodels.sandbox.tsa.fftarma.ArmaFft.filter2 </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="GET" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../_static/versions.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../tsa.html" class="md-tabs__link">Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a></li>
<li class="md-tabs__item"><a href="statsmodels.sandbox.tsa.fftarma.ArmaFft.html" class="md-tabs__link">statsmodels.sandbox.tsa.fftarma.ArmaFft</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels v0.12.2</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../tsa.html" class="md-nav__link">Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a>
</li>
<li class="md-nav__item">
<a href="../statespace.html" class="md-nav__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a>
</li>
<li class="md-nav__item">
<a href="../vector_ar.html" class="md-nav__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.sandbox.tsa.fftarma.ArmaFft.filter2.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<h1 id="generated-statsmodels-sandbox-tsa-fftarma-armafft-filter2--page-root">statsmodels.sandbox.tsa.fftarma.ArmaFft.filter2<a class="headerlink" href="#generated-statsmodels-sandbox-tsa-fftarma-armafft-filter2--page-root" title="Permalink to this headline">¶</a></h1>
<dl class="py method">
<dt id="statsmodels.sandbox.tsa.fftarma.ArmaFft.filter2">
<code class="sig-prename descclassname">ArmaFft.</code><code class="sig-name descname">filter2</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">x</span></em>, <em class="sig-param"><span class="n">pad</span><span class="o">=</span><span class="default_value">0</span></em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/sandbox/tsa/fftarma.html#ArmaFft.filter2"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.sandbox.tsa.fftarma.ArmaFft.filter2" title="Permalink to this definition">¶</a></dt>
<dd><p>filter a time series using fftconvolve3 with ARMA filter</p>
<p>padding of x currently works only if x is 1d
in example it produces same observations at beginning as lfilter even
without padding.</p>
<p>TODO: this returns 1 additional observation at the end</p>
</dd></dl>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.sandbox.tsa.fftarma.ArmaFft.filter.html" title="statsmodels.sandbox.tsa.fftarma.ArmaFft.filter"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.sandbox.tsa.fftarma.ArmaFft.filter </span>
</div>
</a>
<a href="statsmodels.sandbox.tsa.fftarma.ArmaFft.from_coeffs.html" title="statsmodels.sandbox.tsa.fftarma.ArmaFft.from_coeffs"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.sandbox.tsa.fftarma.ArmaFft.from_coeffs </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Feb 02, 2021.
<br/>
Created using
<a href="http://www.sphinx-doc.org/">Sphinx</a> 3.4.3.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html> | {
"content_hash": "b935f320837219221074bb1bbacb2377",
"timestamp": "",
"source": "github",
"line_count": 452,
"max_line_length": 999,
"avg_line_length": 40.1570796460177,
"alnum_prop": 0.6031072668172552,
"repo_name": "statsmodels/statsmodels.github.io",
"id": "4580f7d9660cfedd77a2685d786d4496bf4faaa1",
"size": "18155",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "v0.12.2/generated/statsmodels.sandbox.tsa.fftarma.ArmaFft.filter2.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.