text
stringlengths 2
1.04M
| meta
dict |
---|---|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>FST - Alice Lemoigne</title>
<meta name="description" content="Keep track of the statistics from Alice Lemoigne. Average heat score, heat wins, heat wins percentage, epic heats road to the final">
<meta name="author" content="">
<link rel="apple-touch-icon" sizes="57x57" href="/favicon/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/favicon/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/favicon/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/favicon/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/favicon/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/favicon/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/favicon/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/favicon/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="/favicon/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="/favicon/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<meta property="og:title" content="Fantasy Surfing tips"/>
<meta property="og:image" content="https://fantasysurfingtips.com/img/just_waves.png"/>
<meta property="og:description" content="See how great Alice Lemoigne is surfing this year"/>
<!-- Bootstrap Core CSS - Uses Bootswatch Flatly Theme: https://bootswatch.com/flatly/ -->
<link href="https://fantasysurfingtips.com/css/bootstrap.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="https://fantasysurfingtips.com/css/freelancer.css" rel="stylesheet">
<link href="https://cdn.datatables.net/plug-ins/1.10.7/integration/bootstrap/3/dataTables.bootstrap.css" rel="stylesheet" />
<!-- Custom Fonts -->
<link href="https://fantasysurfingtips.com/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
<script src="https://code.jquery.com/jquery-2.x-git.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ujs/1.2.1/rails.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<script src="https://www.w3schools.com/lib/w3data.js"></script>
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-2675412311042802",
enable_page_level_ads: true
});
</script>
</head>
<body>
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v2.6";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<!-- Navigation -->
<div w3-include-html="https://fantasysurfingtips.com/layout/header.html"></div>
<!-- Header -->
<div w3-include-html="https://fantasysurfingtips.com/layout/sponsor.html"></div>
<section >
<div class="container">
<div class="row">
<div class="col-sm-3 ">
<div class="col-sm-2 ">
</div>
<div class="col-sm-8 ">
<!-- <img src="http://fantasysurfingtips.com/img/surfers/alem.png" class="img-responsive" alt=""> -->
<h3 style="text-align:center;">Alice Lemoigne</h3>
<a href="https://twitter.com/share" class="" data-via="fansurfingtips"><i class="fa fa-twitter"></i> Share on Twitter</i></a> <br/>
<a class="fb-xfbml-parse-ignore" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Ffantasysurfingtips.com%2Fsurfers%2Falem&src=sdkpreparse"><i class="fa fa-facebook"></i> Share on Facebook</a>
</div>
<div class="col-sm-2 ">
</div>
</div>
<div class="col-sm-3 portfolio-item">
</div>
<div class="col-sm-3 portfolio-item">
<h6 style="text-align:center;">Avg Heat Score (FST DATA)</h6>
<h1 style="text-align:center;">3.4</h1>
</div>
</div>
<hr/>
<h4 style="text-align:center;" >Competitions</h4>
<hr/>
<h4 style="text-align:center;" >Heat Stats (FST data)</h4>
<div class="row">
<div class="col-sm-4 portfolio-item">
<h6 style="text-align:center;">Heats</h6>
<h2 style="text-align:center;">1</h2>
</div>
<div class="col-sm-4 portfolio-item">
<h6 style="text-align:center;">Heat wins</h6>
<h2 style="text-align:center;">0</h2>
</div>
<div class="col-sm-4 portfolio-item">
<h6 style="text-align:center;">HEAT WINS PERCENTAGE</h6>
<h2 style="text-align:center;">0.0%</h2>
</div>
</div>
<hr/>
<h4 style="text-align:center;">Avg Heat Score progression</h4>
<div id="avg_chart" style="height: 250px;"></div>
<hr/>
<h4 style="text-align:center;">Heat stats progression</h4>
<div id="heat_chart" style="height: 250px;"></div>
<hr/>
<style type="text/css">
.heats-all{
z-index: 3;
margin-left: 5px;
cursor: pointer;
}
</style>
<div class="container">
<div id="disqus_thread"></div>
<script>
/**
* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/
var disqus_config = function () {
this.page.url = "http://fantasysurfingtips.com/surfers/alem"; // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = '4609'; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = '//fantasysurfingtips.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>
</section>
<script type="text/javascript">
$('.heats-all').click(function(){
$('.heats-all-stat').css('display', 'none')
$('#'+$(this).attr('id')+'-stat').css('display', 'block')
});
$('.heats-2016').click(function(){
$('.heats-2016-stat').css('display', 'none')
$('#'+$(this).attr('id')+'-stat').css('display', 'block')
});
$('document').ready(function(){
new Morris.Line({
// ID of the element in which to draw the chart.
element: 'avg_chart',
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data: [{"year":"2014","avg":3.4,"avg_all":3.4}],
// The name of the data record attribute that contains x-values.
xkey: 'year',
// A list of names of data record attributes that contain y-values.
ykeys: ['avg', 'avg_all'],
// Labels for the ykeys -- will be displayed when you hover over the
// chart.
labels: ['Avg score in year', 'Avg score FST DATA']
});
new Morris.Bar({
// ID of the element in which to draw the chart.
element: 'heat_chart',
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data: [{"year":"2014","heats":1,"wins":0,"percs":"0.0%"}],
// The name of the data record attribute that contains x-values.
xkey: 'year',
// A list of names of data record attributes that contain y-values.
ykeys: ['heats', 'wins', 'percs'],
// Labels for the ykeys -- will be displayed when you hover over the
// chart.
labels: ['Heats surfed', 'Heats won', 'Winning percentage']
});
});
</script>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
<!-- Footer -->
<div w3-include-html="https://fantasysurfingtips.com/layout/footer.html"></div>
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-74337819-1', 'auto'); // Replace with your property ID.
ga('send', 'pageview');
</script>
<script>
w3IncludeHTML();
</script>
<!-- jQuery -->
<script src="https://fantasysurfingtips.com/js/jquery.js"></script>
<script src="https://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="https://fantasysurfingtips.com/js/bootstrap.min.js"></script>
<!-- Plugin JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<script src="https://fantasysurfingtips.com/js/classie.js"></script>
<script src="https://fantasysurfingtips.com/js/cbpAnimatedHeader.js"></script>
<!-- Contact Form JavaScript -->
<script src="https://fantasysurfingtips.com/js/jqBootstrapValidation.js"></script>
<script src="https://fantasysurfingtips.com/js/contact_me.js"></script>
<!-- Custom Theme JavaScript -->
<script src="https://fantasysurfingtips.com/js/freelancer.js"></script>
<script type="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script type="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "9c3c42d8c7bc45edfccd74004dd158d0",
"timestamp": "",
"source": "github",
"line_count": 286,
"max_line_length": 295,
"avg_line_length": 39.61188811188811,
"alnum_prop": 0.6303292435342925,
"repo_name": "chicofilho/fst",
"id": "6ec4e424c509e302eec35a8ebede55834505d231",
"size": "11329",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "surfers/wqs/alem.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "25157"
},
{
"name": "HTML",
"bytes": "114679577"
},
{
"name": "JavaScript",
"bytes": "43263"
},
{
"name": "PHP",
"bytes": "1097"
}
],
"symlink_target": ""
} |
package net.datenstrudel.bulbs.core.infrastructure.monitoring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.MetricReaderPublicMetrics;
import org.springframework.boot.actuate.endpoint.PublicMetrics;
import org.springframework.boot.actuate.metrics.repository.InMemoryMetricRepository;
import org.springframework.boot.actuate.metrics.repository.MetricRepository;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = {
"net.datenstrudel.bulbs.core.infrastructure.monitoring"
}, excludeFilters = @ComponentScan.Filter(Configuration.class))
public class MonitoringConfig {
@Autowired
ApplicationContext ctx;
@Bean
public MetricRepository metricRepository() {
return new InMemoryMetricRepository();
}
@Bean
public PublicMetrics threadPoolMetrics() {
return new PublicMetricsAggregator(
new ThreadPoolMetrics(ctx),
new MetricReaderPublicMetrics(metricRepository())
);
}
}
| {
"content_hash": "9aabb4b2b9cd89ce5d30b0ed733bd104",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 84,
"avg_line_length": 36.64705882352941,
"alnum_prop": 0.7929373996789727,
"repo_name": "datenstrudel/bulbs-core",
"id": "b05f34b1fe18c234d9bdc237f2fb3b77d6111c44",
"size": "1246",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/net/datenstrudel/bulbs/core/infrastructure/monitoring/MonitoringConfig.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "63831"
},
{
"name": "HTML",
"bytes": "80353"
},
{
"name": "Java",
"bytes": "752184"
},
{
"name": "JavaScript",
"bytes": "495628"
},
{
"name": "Puppet",
"bytes": "771"
}
],
"symlink_target": ""
} |
require File.expand_path('../../test_helper', File.dirname(__FILE__))
class PageDateTimeTest < ActiveSupport::TestCase
def test_initialize_tag
assert tag = CmsTag::PageDateTime.initialize_tag(cms_pages(:default), '{{ cms:page:content:datetime }}')
assert_equal 'content', tag.label
assert tag = CmsTag::PageDateTime.initialize_tag(cms_pages(:default), '{{cms:page:content:datetime}}')
assert_equal 'content', tag.label
assert tag = CmsTag::PageDateTime.initialize_tag(cms_pages(:default), '{{cms:page:dash-content:datetime}}')
assert_equal 'dash-content', tag.label
end
def test_initialize_tag_failure
[
'{{cms:page:content:not_datetime}}',
'{{cms:page:content}}',
'{{cms:not_page:content}}',
'{not_a_tag}'
].each do |tag_signature|
assert_nil CmsTag::PageDateTime.initialize_tag(cms_pages(:default), tag_signature)
end
end
def test_content_and_render
tag = CmsTag::PageDateTime.initialize_tag(cms_pages(:default), '{{cms:page:content:datetime}}')
assert tag.content.blank?
time = 2.days.ago
tag.content = time
assert_equal time, tag.content
assert_equal time.to_s, tag.render
end
end | {
"content_hash": "3217883760f8a5daf03a0140d99926bb",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 111,
"avg_line_length": 35.26470588235294,
"alnum_prop": 0.6738949124270225,
"repo_name": "lucysoft/lucy_cms",
"id": "3046e1471b2bec848291e3516a77edb78ea67d6c",
"size": "1199",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/unit/cms_tags/page_datetime_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "138754"
},
{
"name": "Ruby",
"bytes": "184889"
}
],
"symlink_target": ""
} |
package com.github.hi_fi.remotesikulilibrary.utils;
public class SikuliLogger {
public static void logImage(String imagePath) {
logHTML("<a href='"+imagePath+"' target='_blank'><img src='"+imagePath+"' style='width:80%; height: auto;'/></a>");
}
public static void logHTML(Object log) {
System.out.println("*HTML* "+log);
}
public static void logError(Object log) {
System.out.println("*ERROR* "+log);
}
public static void logDebug(Object log) {
if (Helper.isDebug()) {
System.out.println("*DEBUG* "+log);
}
}
public static void logTrace(Object log) {
if (Helper.isDebug()) {
System.out.println("*TRACE* "+log);
}
}
public static void log(Object log) {
System.out.println("*INFO* "+log);
}
}
| {
"content_hash": "3932d57bf813e134b5bb83152d596a74",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 117,
"avg_line_length": 24.09375,
"alnum_prop": 0.6264591439688716,
"repo_name": "Hi-Fi/remotesikulilibrary",
"id": "72c3fdb9066006e83f9dc581c194515ddb2ee6bc",
"size": "771",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/github/hi_fi/remotesikulilibrary/utils/SikuliLogger.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "61777"
},
{
"name": "RobotFramework",
"bytes": "10376"
}
],
"symlink_target": ""
} |
import {BaseContract} from "./BaseContract";
import {BaseConnection} from "./BaseConnection";
export class ForeignKey<T extends BaseContract> {
constructor(
private contract: BaseContract,
private connection: BaseConnection<BaseContract>,
private field: string,
private destType: new (...args: any[]) => T
) { /* */ }
public get id(): number {
return this.connection.getField(this.contract, this.field);
}
public fetch(): Promise<T> {
return this.connection.fetchOne<T>(this.contract, this.destType, this.field);
}
public set(item: T): Promise<void> {
return this.connection.setRelated(this.contract, item, this.field, this.destType);
}
}
| {
"content_hash": "8d731b911dfcb7483b89d58756b44863",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 84,
"avg_line_length": 28.91304347826087,
"alnum_prop": 0.7172932330827068,
"repo_name": "tanjentjs/ts-orm",
"id": "113f81191be7330def9ff9d407bba0b0ff24538d",
"size": "665",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "shared/ForeignKey.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "TypeScript",
"bytes": "36428"
}
],
"symlink_target": ""
} |
using testing::_;
using testing::Invoke;
namespace Router {
TEST(ShadowWriterImplTest, All) {
Upstream::MockClusterManager cm;
ShadowWriterImpl writer(cm);
// Success case
Http::MessagePtr message(new Http::RequestMessageImpl());
message->headers().insertHost().value(std::string("cluster1"));
EXPECT_CALL(cm, httpAsyncClientForCluster("foo")).WillOnce(ReturnRef(cm.async_client_));
Http::MockAsyncClientRequest request(&cm.async_client_);
Http::AsyncClient::Callbacks* callback;
EXPECT_CALL(cm.async_client_,
send_(_, _, Optional<std::chrono::milliseconds>(std::chrono::milliseconds(5))))
.WillOnce(
Invoke([&](Http::MessagePtr& inner_message, Http::AsyncClient::Callbacks& callbacks,
const Optional<std::chrono::milliseconds>&) -> Http::AsyncClient::Request* {
EXPECT_EQ(message, inner_message);
EXPECT_STREQ("cluster1-shadow", message->headers().Host()->value().c_str());
callback = &callbacks;
return &request;
}));
writer.shadow("foo", std::move(message), std::chrono::milliseconds(5));
Http::MessagePtr response(new Http::RequestMessageImpl());
callback->onSuccess(std::move(response));
// Failure case
message.reset(new Http::RequestMessageImpl());
message->headers().insertHost().value(std::string("cluster2"));
EXPECT_CALL(cm, httpAsyncClientForCluster("bar")).WillOnce(ReturnRef(cm.async_client_));
EXPECT_CALL(cm.async_client_,
send_(_, _, Optional<std::chrono::milliseconds>(std::chrono::milliseconds(10))))
.WillOnce(
Invoke([&](Http::MessagePtr& inner_message, Http::AsyncClient::Callbacks& callbacks,
const Optional<std::chrono::milliseconds>&) -> Http::AsyncClient::Request* {
EXPECT_EQ(message, inner_message);
EXPECT_STREQ("cluster2-shadow", message->headers().Host()->value().c_str());
callback = &callbacks;
return &request;
}));
writer.shadow("bar", std::move(message), std::chrono::milliseconds(10));
callback->onFailure(Http::AsyncClient::FailureReason::Reset);
}
} // Router
| {
"content_hash": "e6485c839f2ad6e5421430d87014ce59",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 97,
"avg_line_length": 44.10204081632653,
"alnum_prop": 0.6524757056918093,
"repo_name": "timperrett/envoy",
"id": "4c4fd353ba925ee7810d6bdd28cb3dd943489066",
"size": "2319",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/common/router/shadow_writer_impl_test.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "226"
},
{
"name": "C++",
"bytes": "2662234"
},
{
"name": "CMake",
"bytes": "20781"
},
{
"name": "Makefile",
"bytes": "3887"
},
{
"name": "Protocol Buffer",
"bytes": "6293"
},
{
"name": "Python",
"bytes": "187935"
},
{
"name": "Shell",
"bytes": "30686"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe OneOne do
it 'has a version number' do
expect(OneOne::VERSION).not_to be nil
end
end
| {
"content_hash": "2346664ea93cd2522d091ca11eb917f1",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 41,
"avg_line_length": 17.857142857142858,
"alnum_prop": 0.712,
"repo_name": "ConnorAtherton/one_one",
"id": "fd2eab218b7984394190b0a5a30da539f398ab6a",
"size": "125",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/one_one_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "15011"
},
{
"name": "Shell",
"bytes": "115"
}
],
"symlink_target": ""
} |
package io.datarouter.util;
import org.testng.Assert;
import org.testng.annotations.Test;
public class BooleanToolTests{
@Test
public void testNullSafeSame(){
Assert.assertEquals(BooleanTool.nullSafeSame(null, null), true);
Assert.assertEquals(BooleanTool.nullSafeSame(true, true), true);
Assert.assertEquals(BooleanTool.nullSafeSame(false, false), true);
Assert.assertEquals(BooleanTool.nullSafeSame(true, null), false);
Assert.assertEquals(BooleanTool.nullSafeSame(null, true), false);
Assert.assertEquals(BooleanTool.nullSafeSame(false, null), false);
Assert.assertEquals(BooleanTool.nullSafeSame(null, false), false);
}
}
| {
"content_hash": "48e961a199126acff0155b5551ed4a8a",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 68,
"avg_line_length": 32.4,
"alnum_prop": 0.7870370370370371,
"repo_name": "hotpads/datarouter",
"id": "f01c2c609f0c8aa07028df0ef7c0747fdad25c51",
"size": "1261",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "datarouter-util/src/test/java/io/datarouter/util/BooleanToolTests.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "9438"
},
{
"name": "Java",
"bytes": "8616487"
},
{
"name": "JavaScript",
"bytes": "639471"
}
],
"symlink_target": ""
} |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="UK Train Departure Boards"/>
<meta name="author" content="Peter Mount"/>
<link rel=canonical href=”https://departureboards.mobi/”/>
<link rel="icon" href="/fav/favicon.ico"/>
<link rel="stylesheet" href="https://area51.onl/css/bootstrap.min.css"/>
<title>UK Departure Boards</title>
</head>
<body>
<div id="root">
<h1>Loading departureboards</h1>
<p>Please wait</p>
</div>
</body>
</html>
| {
"content_hash": "0f1a96179a9db33fa1931379de4828b3",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 76,
"avg_line_length": 31.31578947368421,
"alnum_prop": 0.653781512605042,
"repo_name": "peter-mount/departureboards",
"id": "b2801f20a397c8498e4f77bd866204fb47b9d2e3",
"size": "599",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/index.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "15241"
},
{
"name": "Dockerfile",
"bytes": "1996"
},
{
"name": "HTML",
"bytes": "599"
},
{
"name": "JavaScript",
"bytes": "84398"
},
{
"name": "Shell",
"bytes": "76"
}
],
"symlink_target": ""
} |
namespace ui {
class ListSelectionModel;
}
namespace views {
class View;
class ViewTracker;
}
class Browser;
class KeyEventTracker;
class Tab;
class TabDragControllerTest;
class TabDragContext;
class TabSlotView;
class TabStripModel;
class WindowFinder;
// TabDragController is responsible for managing the tab dragging session. When
// the user presses the mouse on a tab a new TabDragController is created and
// Drag() is invoked as the mouse is dragged. If the mouse is dragged far enough
// TabDragController starts a drag session. The drag session is completed when
// EndDrag() is invoked (or the TabDragController is destroyed).
//
// While dragging within a tab strip TabDragController sets the bounds of the
// tabs (this is referred to as attached). When the user drags far enough such
// that the tabs should be moved out of the tab strip a new Browser is created
// and RunMoveLoop() is invoked on the Widget to drag the browser around. This
// is the default on aura.
class TabDragController : public views::WidgetObserver {
public:
// Indicates the event source that initiated the drag.
enum EventSource {
EVENT_SOURCE_MOUSE,
EVENT_SOURCE_TOUCH,
};
// Amount above or below the tabstrip the user has to drag before detaching.
static const int kTouchVerticalDetachMagnetism;
static const int kVerticalDetachMagnetism;
TabDragController();
TabDragController(const TabDragController&) = delete;
TabDragController& operator=(const TabDragController&) = delete;
~TabDragController() override;
// Initializes TabDragController to drag the views in |dragging_views|
// originating from |source_context|. |source_view| is the view that
// initiated the drag and is either a Tab or a TabGroupHeader contained in
// |dragging_views|. |mouse_offset| is the distance of the mouse pointer from
// the origin of the first view in |dragging_views| and |source_view_offset|
// the offset from |source_view|. |source_view_offset| is the horizontal
// offset of |mouse_offset| relative to |source_view|.
// |initial_selection_model| is the selection model before the drag started
// and is only non-empty if the original selection isn't the same as the
// dragging set.
void Init(TabDragContext* source_context,
TabSlotView* source_view,
const std::vector<TabSlotView*>& dragging_views,
const gfx::Point& mouse_offset,
int source_view_offset,
ui::ListSelectionModel initial_selection_model,
EventSource event_source);
// Returns true if there is a drag underway and the drag is attached to
// |tab_strip|.
// NOTE: this returns false if the TabDragController is in the process of
// finishing the drag.
static bool IsAttachedTo(const TabDragContext* tab_strip);
// Returns true if there is a drag underway.
static bool IsActive();
// Returns the pointer of |source_context_|.
static TabDragContext* GetSourceContext();
EventSource event_source() const { return event_source_; }
// See description above fields for details on these.
bool active() const { return current_state_ != DragState::kStopped; }
const TabDragContext* attached_context() const { return attached_context_; }
// Returns true if a drag started.
bool started_drag() const { return current_state_ != DragState::kNotStarted; }
// Returns true if mutating the TabStripModel.
bool is_mutating() const { return is_mutating_; }
// Returns true if we've detached from a tabstrip and are running a nested
// move message loop.
bool is_dragging_window() const {
return current_state_ == DragState::kDraggingWindow;
}
// Returns the tab group being dragged, if any. Will only return a value if
// the user is dragging a tab group header, not an individual tab or tabs from
// a group.
const absl::optional<tab_groups::TabGroupId>& group() const { return group_; }
// Returns true if currently dragging a tab with |contents|.
bool IsDraggingTab(content::WebContents* contents);
// Invoked to drag to the new location, in screen coordinates.
void Drag(const gfx::Point& point_in_screen);
// Complete the current drag session.
void EndDrag(EndDragReason reason);
// Set a callback to be called when the nested drag loop finishes.
void SetDragLoopDoneCallbackForTesting(base::OnceClosure callback);
private:
friend class TabDragControllerTest;
#if BUILDFLAG(IS_CHROMEOS_ASH)
class DeferredTargetTabstripObserver;
#endif
class SourceTabStripEmptinessTracker;
class DraggedTabsClosedTracker;
// Used to indicate the direction the mouse has moved when attached.
static const int kMovedMouseLeft = 1 << 0;
static const int kMovedMouseRight = 1 << 1;
enum class DragState {
// The drag has not yet started; the user has not dragged far enough to
// begin a session.
kNotStarted,
// The session is dragging a set of tabs within |attached_context_|.
kDraggingTabs,
// The session is dragging a window; |attached_context_| is that window's
// tabstrip.
kDraggingWindow,
// The session is waiting for the nested move loop to exit to transition
// to kDraggingTabs. Not used on all platforms.
kWaitingToDragTabs,
// The session is waiting for the nested move loop to exit to end the drag.
kWaitingToStop,
// The drag session has completed or been canceled.
kStopped
};
enum class Liveness {
ALIVE,
DELETED,
};
// Enumeration of the ways a drag session can end.
enum EndDragType {
// Drag session exited normally: the user released the mouse.
NORMAL,
// The drag session was canceled (alt-tab during drag, escape ...)
CANCELED,
// The tab (NavigationController) was destroyed during the drag.
TAB_DESTROYED
};
// Whether Detach() should release capture or not.
enum ReleaseCapture {
RELEASE_CAPTURE,
DONT_RELEASE_CAPTURE,
};
// Enumeration of the possible positions the detached tab may detach from.
enum DetachPosition {
DETACH_BEFORE,
DETACH_AFTER,
DETACH_ABOVE_OR_BELOW
};
// Specifies what should happen when a drag motion exits the tab strip region
// in an attempt to detach a tab.
enum DetachBehavior {
DETACHABLE,
NOT_DETACHABLE
};
// Indicates what should happen after invoking DragBrowserToNewTabStrip().
enum DragBrowserResultType {
// The caller should return immediately. This return value is used if a
// nested run loop was created or we're in a nested run loop and
// need to exit it.
DRAG_BROWSER_RESULT_STOP,
// The caller should continue.
DRAG_BROWSER_RESULT_CONTINUE,
};
// Stores the date associated with a single tab that is being dragged.
struct TabDragData {
TabDragData();
TabDragData(const TabDragData&) = delete;
TabDragData& operator=(const TabDragData&) = delete;
~TabDragData();
TabDragData(TabDragData&&);
// The WebContents being dragged.
raw_ptr<content::WebContents> contents;
// There is a brief period of time when a tab is being moved from one tab
// strip to another [after Detach but before Attach] that the TabDragData
// owns the WebContents.
std::unique_ptr<content::WebContents> owned_contents;
// This is the index of the tab in |source_context_| when the drag
// began. This is used to restore the previous state if the drag is aborted.
int source_model_index;
// If attached this is the view in |attached_context_|.
raw_ptr<TabSlotView> attached_view;
// Is the tab pinned?
bool pinned;
// Contains the information for the tab's group at the start of the drag.
struct TabGroupData {
tab_groups::TabGroupId group_id;
tab_groups::TabGroupVisualData group_visual_data;
};
// Stores the information of the group the tab is in, or nullopt if tab is
// not grouped.
absl::optional<TabGroupData> tab_group_data;
};
typedef std::vector<TabDragData> DragData;
// Sets |drag_data| from |view|. This also registers for necessary
// notifications and resets the delegate of the WebContents.
void InitDragData(TabSlotView* view, TabDragData* drag_data);
// Overriden from views::WidgetObserver:
void OnWidgetBoundsChanged(views::Widget* widget,
const gfx::Rect& new_bounds) override;
void OnWidgetDestroyed(views::Widget* widget) override;
// Forget the source tabstrip. It doesn't exist any more, so it doesn't
// make sense to insert dragged tabs back into it if the drag is reverted.
void OnSourceTabStripEmpty();
// A tab was closed in the active tabstrip. Clean up if we were dragging it.
void OnActiveStripWebContentsRemoved(content::WebContents* contents);
// The WebContents in a tab was replaced in the active tabstrip. Update our
// canonical reference if we were dragging that tab.
void OnActiveStripWebContentsReplaced(content::WebContents* previous,
content::WebContents* next);
// Initialize the offset used to calculate the position to create windows
// in |GetWindowCreatePoint|. This should only be invoked from |Init|.
void InitWindowCreatePoint();
// Returns the point where a detached window should be created given the
// current mouse position |origin|.
gfx::Point GetWindowCreatePoint(const gfx::Point& origin) const;
void UpdateDockInfo(const gfx::Point& point_in_screen);
// Saves focus in the window that the drag initiated from. Focus will be
// restored appropriately if the drag ends within this same window.
void SaveFocus();
// Restore focus to the View that had focus before the drag was started, if
// the drag ends within the same Window as it began.
void RestoreFocus();
// Tests whether |point_in_screen| is past a minimum elasticity threshold
// required to start a drag.
bool CanStartDrag(const gfx::Point& point_in_screen) const;
// Invoked once a drag has started to determine the appropriate context to
// drag to (which may be the currently attached one).
Liveness ContinueDragging(const gfx::Point& point_in_screen)
WARN_UNUSED_RESULT;
// Transitions dragging from |attached_context_| to |target_context|.
// |target_context| is NULL if the mouse is not over a valid tab strip. See
// DragBrowserResultType for details of the return type.
DragBrowserResultType DragBrowserToNewTabStrip(
TabDragContext* target_context,
const gfx::Point& point_in_screen);
// Handles dragging tabs while the tabs are attached. |just_attached| should
// be true iff this is the first call to MoveAttached after attaching.
void MoveAttached(const gfx::Point& point_in_screen, bool just_attached);
// Returns the compatible TabDragContext to drag to at the
// specified point (screen coordinates), or nullptr if there is none.
Liveness GetTargetTabStripForPoint(const gfx::Point& point_in_screen,
TabDragContext** tab_strip);
// Returns true if |context| contains the specified point in screen
// coordinates.
bool DoesTabStripContain(TabDragContext* context,
const gfx::Point& point_in_screen) const;
// Returns the DetachPosition given the specified location in screen
// coordinates.
DetachPosition GetDetachPosition(const gfx::Point& point_in_screen);
// Attach the dragged Tab to the specified TabDragContext. If
// |set_capture| is true, the newly attached context will have capture.
// This can only be used to pass ownership of |this| through |controller|.
// |controller| must be nullptr if |attached_context| already owns |this|.
void Attach(TabDragContext* attached_context,
const gfx::Point& point_in_screen,
std::unique_ptr<TabDragController> controller,
bool set_capture = true);
// Detach the dragged Tab from the current TabDragContext. Returns
// ownership of the owned controller, which must be |this|, if
// |attached_context_| currently owns a controller. Otherwise returns
// nullptr.
std::unique_ptr<TabDragController> Detach(ReleaseCapture release_capture);
// Detach from |attached_context_| and attach to |target_context| instead.
// See Detach/Attach for parameter documentation. Transfers ownership of
// |this| from |attached_context_| (which must own |this|) to
// |target_context|.
void DetachAndAttachToNewContext(ReleaseCapture release_capture,
TabDragContext* target_context,
const gfx::Point& point_in_screen,
bool set_capture = true);
// Detaches the tabs being dragged, creates a new Browser to contain them and
// runs a nested move loop.
void DetachIntoNewBrowserAndRunMoveLoop(const gfx::Point& point_in_screen);
// Runs a nested run loop that handles moving the current
// Browser. |drag_offset| is the offset from the window origin and is used in
// calculating the location of the window offset from the cursor while
// dragging.
void RunMoveLoop(const gfx::Vector2d& drag_offset);
// Retrieves the bounds of the dragged tabs relative to the attached
// TabDragContext. |tab_strip_point| is in the attached
// TabDragContext's coordinate system.
gfx::Rect GetDraggedViewTabStripBounds(const gfx::Point& tab_strip_point);
// Gets the position of the dragged tabs relative to the attached tab strip
// with the mirroring transform applied.
gfx::Point GetAttachedDragPoint(const gfx::Point& point_in_screen);
// Finds the TabSlotViews within the specified TabDragContext that
// corresponds to the WebContents of the dragged views. Also finds the group
// header if it is dragging. Returns an empty vector if not attached.
std::vector<TabSlotView*> GetViewsMatchingDraggedContents(
TabDragContext* context);
// Does the work for EndDrag(). If we actually started a drag and |how_end| is
// not TAB_DESTROYED then one of EndDrag() or RevertDrag() is invoked.
void EndDragImpl(EndDragType how_end);
// Called after the drag ends and |deferred_target_context_| is not nullptr.
void PerformDeferredAttach();
// Reverts a cancelled drag operation.
void RevertDrag();
// Reverts the tab at |drag_index| in |drag_data_|.
void RevertDragAt(size_t drag_index);
// Selects the dragged tabs in |model|. Does nothing if there are no longer
// any dragged contents (as happens when a WebContents is deleted out from
// under us).
void ResetSelection(TabStripModel* model);
// Restores |initial_selection_model_| to the |source_context_|.
void RestoreInitialSelection();
// Finishes a successful drag operation.
void CompleteDrag();
// Maximizes the attached window.
void MaximizeAttachedWindow();
// Hides the frame for the window that contains the TabDragContext
// the current drag session was initiated from.
void HideFrame();
void BringWindowUnderPointToFront(const gfx::Point& point_in_screen);
// Convenience for getting the TabDragData corresponding to the source view
// that the user started dragging.
TabDragData* source_view_drag_data() {
return &(drag_data_[source_view_index_]);
}
// Convenience for |source_view_drag_data()->contents|.
content::WebContents* source_dragged_contents() {
return source_view_drag_data()->contents;
}
// Returns the number of Tab views currently dragging.
// Excludes the TabGroupHeader view, if any.
int num_dragging_tabs() {
return header_drag_ ? drag_data_.size() - 1 : drag_data_.size();
}
// Returns the index of the first Tab, since the first dragging view may
// instead be a TabGroupHeader.
int first_tab_index() { return header_drag_ ? 1 : 0; }
// Returns the Widget of the currently attached TabDragContext's
// BrowserView.
views::Widget* GetAttachedBrowserWidget();
// Returns true if the tabs were originality one after the other in
// |source_context_|.
bool AreTabsConsecutive();
// Calculates and returns new bounds for the dragged browser window.
// Takes into consideration current and restore bounds of |source| tab strip
// preventing the dragged size from being too small. Positions the new bounds
// such that the tab that was dragged remains under the |point_in_screen|.
// Offsets |drag_bounds| if necessary when dragging to the right from the
// source browser.
gfx::Rect CalculateDraggedBrowserBounds(TabDragContext* source,
const gfx::Point& point_in_screen,
std::vector<gfx::Rect>* drag_bounds);
// Calculates and returns the dragged bounds for the non-maximize dragged
// browser window. Taks into consideration the initial drag offset so that
// the dragged tab remains under the |point_in_screen|.
gfx::Rect CalculateNonMaximizedDraggedBrowserBounds(
views::Widget* widget,
const gfx::Point& point_in_screen);
// Calculates scaled |drag_bounds| for dragged tabs and sets the tabs bounds.
// Layout of the tabstrip is performed and a new tabstrip width calculated.
// When |last_tabstrip_width| is larger than the new tabstrip width the tabs
// in the attached tabstrip are scaled and the attached browser is positioned
// such that the tab that was dragged remains under the |point_in_screen|.
// |drag_offset| is the offset of |point_in_screen| from the origin of the
// dragging browser window, and will be updated when this method ends up with
// changing the origin of the attached browser window.
void AdjustBrowserAndTabBoundsForDrag(int last_tabstrip_width,
const gfx::Point& point_in_screen,
gfx::Vector2d* drag_offset,
std::vector<gfx::Rect>* drag_bounds);
// Creates and returns a new Browser to handle the drag.
Browser* CreateBrowserForDrag(TabDragContext* source,
const gfx::Point& point_in_screen,
gfx::Vector2d* drag_offset,
std::vector<gfx::Rect>* drag_bounds);
// Returns the location of the cursor. This is either the location of the
// mouse or the location of the current touch point.
gfx::Point GetCursorScreenPoint();
// Returns the offset from the top left corner of the window to
// |point_in_screen|.
gfx::Vector2d GetWindowOffset(const gfx::Point& point_in_screen);
// Returns the NativeWindow in |window| at the specified point. If
// |exclude_dragged_view| is true, then the dragged view is not considered.
Liveness GetLocalProcessWindow(const gfx::Point& screen_point,
bool exclude_dragged_view,
gfx::NativeWindow* window) WARN_UNUSED_RESULT;
// Sets the dragging info for the current dragged context. On Chrome OS, the
// dragging info include two window properties: one is to indicate if the
// tab-dragging process starts/stops, and the other is to indicate which
// window initiates the dragging. This function is supposed to be called
// whenever the dragged tabs are attached to a new tabstrip.
void SetTabDraggingInfo();
// Clears the tab dragging info for the current dragged context. This
// function is supposed to be called whenever the dragged tabs are detached
// from the old context or the tab dragging is ended.
void ClearTabDraggingInfo();
// Sets |deferred_target_context_| and updates its corresponding window
// property. |location| is the location of the pointer when the deferred
// target is set.
void SetDeferredTargetTabstrip(TabDragContext* deferred_target_context);
DragState current_state_;
// Tests whether a drag can be attached to a |window|. Drags may be
// disallowed for reasons such as the target: does not support tabs, is
// showing a modal, has a different profile, is a different browser type
// (NORMAL vs APP).
bool CanAttachTo(gfx::NativeWindow window);
// Helper method for TabDragController::MoveAttached to update the tab group
// membership of selected tabs. UpdateGroupForDraggedTabs should be called
// after the tabs move in a drag so the first selected index is the target
// index of the move.
void UpdateGroupForDraggedTabs();
// Helper method for TabDragController::UpdateGroupForDraggedTabs to decide if
// a dragged tab should stay in the tab group. Returns absl::nullopt if the
// tab should not be in a group. Otherwise returns tab_groups::TabGroupId of
// the group the selected tabs should join.
absl::optional<tab_groups::TabGroupId> GetTabGroupForTargetIndex(
const std::vector<int>& selected);
EventSource event_source_;
// The TabDragContext the drag originated from. This is set to null
// if destroyed during the drag.
raw_ptr<TabDragContext> source_context_;
// The TabDragContext the dragged Tab is currently attached to, or
// null if the dragged Tab is detached.
raw_ptr<TabDragContext> attached_context_;
#if BUILDFLAG(IS_CHROMEOS_ASH)
// Observe the target TabDragContext to attach to after the drag
// ends. It's only possible to happen in Chrome OS tablet mode, if the dragged
// tabs are dragged over an overview window, we should wait until the drag
// ends to attach it.
std::unique_ptr<DeferredTargetTabstripObserver>
deferred_target_context_observer_;
#endif
// Whether capture can be released during the drag. When false, capture should
// not be released when transferring capture between widgets and when starting
// the move loop.
bool can_release_capture_;
// The position of the mouse (in screen coordinates) at the start of the drag
// operation. This is used to calculate minimum elasticity before a
// DraggedTabView is constructed.
gfx::Point start_point_in_screen_;
// This is the offset of the mouse from the top left of the first Tab where
// dragging began. This is used to ensure that the dragged view is always
// positioned at the correct location during the drag, and to ensure that the
// detached window is created at the right location.
gfx::Point mouse_offset_;
// Ratio of the x-coordinate of the |source_view_offset| to the width of the
// source view.
float offset_to_width_ratio_;
// A hint to use when positioning new windows created by detaching Tabs. This
// is the distance of the mouse from the top left of the dragged tab as if it
// were the distance of the mouse from the top left of the first tab in the
// attached TabDragContext from the top left of the window.
gfx::Point window_create_point_;
// Location of the first tab in the source tabstrip in screen coordinates.
// This is used to calculate |window_create_point_|.
gfx::Point first_source_tab_point_;
// Used to track the view that had focus in the window containing
// |source_view_|. This is saved so that focus can be restored properly when
// a drag begins and ends within this same window.
std::unique_ptr<views::ViewTracker> old_focused_view_tracker_;
// The horizontal position of the mouse cursor in screen coordinates at the
// time of the last re-order event.
int last_move_screen_loc_;
// Timer used to bring the window under the cursor to front. If the user
// stops moving the mouse for a brief time over a browser window, it is
// brought to front.
base::OneShotTimer bring_to_front_timer_;
DragData drag_data_;
// Index of the source view in |drag_data_|.
size_t source_view_index_;
// The attached views. Also found in |drag_data_|, but cached for convenience.
std::vector<TabSlotView*> attached_views_;
// Whether the drag originated from a group header.
bool header_drag_;
// The group that is being dragged. Only set if the drag originated from a
// group header, indicating that the entire group is being dragged together.
absl::optional<tab_groups::TabGroupId> group_;
// True until MoveAttached() is first invoked.
bool initial_move_;
// The selection model before the drag started. See comment above Init() for
// details.
ui::ListSelectionModel initial_selection_model_;
// The selection model of |attached_context_| before the tabs were attached.
ui::ListSelectionModel selection_model_before_attach_;
// Initial x-coordinates of the tabs when the drag started. Only used for
// touch mode.
std::vector<int> initial_tab_positions_;
// What should occur during ConinueDragging when a tab is attempted to be
// detached.
DetachBehavior detach_behavior_;
// Last location used in screen coordinates.
gfx::Point last_point_in_screen_;
// The following are needed when detaching into a browser
// (|detach_into_browser_| is true).
// True if |attached_context_| is in a browser specifically created for
// the drag.
bool is_dragging_new_browser_;
// True if |source_context_| was maximized before the drag.
bool was_source_maximized_;
// True if |source_context_| was in immersive fullscreen before the drag.
bool was_source_fullscreen_;
// True if the initial drag resulted in restoring the window (because it was
// maximized).
bool did_restore_window_;
// The TabDragContext to attach to after the move loop completes.
raw_ptr<TabDragContext> tab_strip_to_attach_to_after_exit_;
// Non-null for the duration of RunMoveLoop.
raw_ptr<views::Widget> move_loop_widget_;
// See description above getter.
bool is_mutating_;
// |attach_x_| and |attach_index_| are set to the x-coordinate of the mouse
// (in terms of the tabstrip) and the insertion index at the time tabs are
// dragged into a new browser (attached). They are used to ensure we don't
// shift the tabs around in the wrong direction. The two are only valid if
// |attach_index_| is not -1.
// See comment around use for more details.
int attach_x_;
int attach_index_;
// Called when the loop in RunMoveLoop finishes. Only for tests.
base::OnceClosure drag_loop_done_callback_;
std::unique_ptr<KeyEventTracker> key_event_tracker_;
std::unique_ptr<SourceTabStripEmptinessTracker>
source_context_emptiness_tracker_;
std::unique_ptr<DraggedTabsClosedTracker>
attached_context_tabs_closed_tracker_;
std::unique_ptr<WindowFinder> window_finder_;
base::ScopedObservation<views::Widget, views::WidgetObserver>
widget_observation_{this};
// True while RunMoveLoop() has been called on a widget.
bool in_move_loop_ = false;
base::WeakPtrFactory<TabDragController> weak_factory_{this};
};
#endif // CHROME_BROWSER_UI_VIEWS_TABS_TAB_DRAG_CONTROLLER_H_
| {
"content_hash": "47fceb37facc79fb60d0db1522f44b05",
"timestamp": "",
"source": "github",
"line_count": 658,
"max_line_length": 80,
"avg_line_length": 40.5531914893617,
"alnum_prop": 0.7157847399190527,
"repo_name": "ric2b/Vivaldi-browser",
"id": "c9a3eebc5a7cbe54a8e63797390b20796f236bf0",
"size": "27673",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chromium/chrome/browser/ui/views/tabs/tab_drag_controller.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
using ComputerAlgebra;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;
namespace Circuit
{
public class UnitCastException : InvalidCastException
{
public UnitCastException(Units From, Units To)
: base("Cannot convert quantity from '" + From.ToString() + "' to '" + To.ToString() + "'")
{ }
}
[TypeConverter("Circuit.QuantityConverter")]
public class Quantity : IEquatable<Quantity>, IFormattable
{
private Expression x = 0;
private Units units;
public Units Units { get { return units; } set { units = value; } }
public Quantity(Expression x, Units Units)
{
this.x = x;
this.units = Units;
}
public Quantity() { units = null; }
// Set the value of this quantity from another quantity, validating the units.
public bool Set(Quantity Value)
{
if (Value.Units != units && Value.Units != Units.None)
throw new UnitCastException(Value.Units, units);
if (!Equals(x, Value.x))
{
x = Value.x;
return true;
}
else
{
return false;
}
}
private static Expression ParsePrefix(ref string s)
{
s = s.TrimEnd();
if (s.Length < 2)
return 1;
if (Prefixes.TryGetValue(DeAliasPrefix(s[s.Length - 1].ToString()), out int prefix))
{
// Make sure this isn't just part of the word before the prefix.
if (char.IsDigit(s[s.Length - 2]) || char.IsWhiteSpace(s[s.Length - 2]))
{
s = s.Substring(0, s.Length - 1);
return ((Real)10) ^ prefix;
}
}
return 1;
}
public static Quantity Parse(string s, CultureInfo culture)
{
Expression prefix = ParsePrefix(ref s);
Units units = Units.None;
if (prefix.EqualsOne())
{
units = Units.Parse(ref s);
s = s.TrimEnd();
prefix = ParsePrefix(ref s);
}
return new Quantity(prefix * Expression.Parse(s, culture), units);
}
public static Quantity Parse(string s, Units ExpectedUnits)
{
Quantity m = Parse(s);
if (m.Units == Units.None)
m.Units = ExpectedUnits;
else if (m.Units != ExpectedUnits)
throw new UnitCastException(m.Units, ExpectedUnits);
return m;
}
public static Quantity Parse(string s) { return Parse(s, CultureInfo.InstalledUICulture); }
public static implicit operator Expression(Quantity x) { return x.x; }
public static implicit operator LazyExpression(Quantity x) { return new LazyExpression(x.x); }
public static explicit operator Real(Quantity x) { return (Real)x.x; }
public static explicit operator double(Quantity x) { return (double)x.x; }
// IEquatable interface.
public bool Equals(Quantity obj) { return this == obj; }
// object interface.
public override bool Equals(object obj) { return obj is Quantity quantity ? Equals(quantity) : base.Equals(obj); }
public override int GetHashCode() { return x.GetHashCode() ^ units.GetHashCode(); }
public override string ToString() { return ToString("G3", null); }
// IFormattable interface.
private static Dictionary<string, int> Prefixes = new Dictionary<string, int>()
{
{ "f", -15 },
{ "p", -12 },
{ "n", -9 },
{ "\u03BC", -6 },
{ "m", -3 },
{ "", 0 },
{ "k", 3 },
{ "M", 6 },
{ "G", 9 },
{ "T", 12 },
};
private static int MinPrefix = Prefixes.Values.Min();
private static int MaxPrefix = Prefixes.Values.Max();
private static string DeAliasPrefix(string Prefix)
{
switch (Prefix)
{
case "u": return "\u03BC";
default: return Prefix;
}
}
public string ToString(string format, IFormatProvider formatProvider) { return ToString(x, units, format, formatProvider); }
public static string ToString(Expression Value, Units Units, string format, IFormatProvider formatProvider)
{
StringBuilder SB = new StringBuilder();
Constant constant = Value as Constant;
if (constant != null)
{
if (format != null && format.StartsWith("+"))
{
if (constant.Value >= 0)
SB.Append("+");
format = format.Remove(0, 1);
}
// Find out how many digits the format has.
double round = 1.0;
for (int significant = 12; significant > 0; --significant)
{
round = 1.0 + 5 * Math.Pow(10.0, -significant);
if (double.Parse(round.ToString(format)) != 1.0)
break;
}
// Find the order of magnitude of the value.
Real order = Real.Log10(Real.Abs(constant.Value.IsNaN() ? 0 : constant.Value) * round);
if (order < -20) order = 0;
else if (order == Real.Infinity) order = 0;
int prefix = Math.Max(Math.Min((int)Real.Floor(order / 3) * 3, MaxPrefix), MinPrefix);
Value /= (((Real)10) ^ prefix);
SB.Append(Value.ToString(format, formatProvider));
SB.Append(" ");
SB.Append(Prefixes.Single(i => i.Value == prefix).Key);
}
else if (Value != null)
{
SB.Append(Convert.ToString((object)Value, formatProvider));
SB.Append(" ");
}
else
{
SB.Append("0");
SB.Append(" ");
}
SB.Append(Units);
return SB.ToString().Trim();
}
public static string ToString(Expression Value, Units Units, string Format) { return ToString(Value, Units, Format, null); }
public static string ToString(Expression Value, Units Units) { return ToString(Value, Units, "G3", null); }
}
}
| {
"content_hash": "bd3abcfb361e3d62e31233301d0609f1",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 132,
"avg_line_length": 35.494623655913976,
"alnum_prop": 0.5130263556498031,
"repo_name": "dsharlet/LiveSPICE",
"id": "5f5a2e0041c02323560702227b1a2d85a77fd95e",
"size": "6604",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Circuit/Utils/Quantity.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "588259"
},
{
"name": "Inno Setup",
"bytes": "1799"
}
],
"symlink_target": ""
} |
using Amazon.DynamoDBv2.DataModel;
using AspNetCore.Identity.DynamoDB.Converters;
using OpenIddict.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace AspNetCore.Identity.DynamoDB.OpenIddict.Models
{
[DynamoDBTable(Constants.DefaultTokenTableName)]
public class DynamoIdentityToken
{
public DynamoIdentityToken()
{
Id = Guid.NewGuid().ToString();
CreatedOn = DateTimeOffset.Now;
}
[DynamoDBHashKey]
public string Id { get; set; }
[DynamoDBProperty(typeof(DateTimeOffsetConverter))]
public DateTimeOffset CreatedOn { get; set; }
[DynamoDBGlobalSecondaryIndexHashKey("Subject-index")]
public string Subject { get; set; }
[DynamoDBGlobalSecondaryIndexHashKey("Application-index")]
public string Application { get; set; }
[DynamoDBGlobalSecondaryIndexHashKey("Authorization-index")]
public string Authorization { get; set; }
public string Type { get; set; }
}
}
| {
"content_hash": "355fcbe8de7b770fc649f8213d2e0bde",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 68,
"avg_line_length": 29.63888888888889,
"alnum_prop": 0.6710402999062793,
"repo_name": "cmsd2/oidc",
"id": "dd52f24898aa6855ff2ee330665e89619756aa20",
"size": "1069",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/AspNetCore.Identity.DynamoDB.OpenIddict/Models/DynamoIdentityToken.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "2047676"
},
{
"name": "CSS",
"bytes": "167769"
},
{
"name": "HTML",
"bytes": "13326"
},
{
"name": "JavaScript",
"bytes": "398948"
},
{
"name": "PowerShell",
"bytes": "182"
},
{
"name": "Shell",
"bytes": "1242"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>mathcomp-odd-order: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / extra-dev</a></li>
<li class="active"><a href="">8.11.dev / mathcomp-odd-order - 1.7.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
mathcomp-odd-order
<small>
1.7.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2019-11-29 00:21:18 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2019-11-29 00:21:18 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq 8.11.dev Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.05.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0 Official 4.05.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
name: "coq-mathcomp-odd-order"
version: "1.7.0"
maintainer: "Mathematical Components <[email protected]>"
homepage: "http://math-comp.github.io/math-comp/"
bug-reports: "Mathematical Components <[email protected]>"
license: "CeCILL-B"
build: [
[make "-j" "%{jobs}%"]
]
install: [ make "install" ]
remove: [
["sh" "-c" "rm -rf '%{lib}%/coq/user-contrib/mathcomp/odd_order'"]
]
depends: [
"ocaml"
"coq-mathcomp-algebra" {= "1.7.0"}
"coq-mathcomp-character" {= "1.7.0"}
"coq-mathcomp-field" {= "1.7.0"}
"coq-mathcomp-fingroup" {= "1.7.0"}
"coq-mathcomp-solvable" {= "1.7.0"}
"coq-mathcomp-ssreflect" {= "1.7.0"}
]
tags: [ "keyword:finite groups" "keyword:Feit Thompson theorem" "keyword:small scale reflection" "keyword:mathematical components" "keyword:odd order theorem" ]
authors: [ "Jeremy Avigad <>" "Andrea Asperti <>" "Stephane Le Roux <>" "Yves Bertot <>" "Laurence Rideau <>" "Enrico Tassi <>" "Ioana Pasca <>" "Georges Gonthier <>" "Sidi Ould Biha <>" "Cyril Cohen <>" "Francois Garillot <>" "Alexey Solovyev <>" "Russell O'Connor <>" "Laurent Théry <>" "Assia Mahboubi <>" ]
synopsis: "The formal proof of the Feit-Thompson theorem"
description: """
The formal proof of the Feit-Thompson theorem.
From mathcomp Require Import all_ssreflect all_fingroup all_solvable PFsection14.
Check Feit_Thompson.
: forall (gT : finGroupType) (G : {group gT}), odd #|G| -> solvable G
From mathcomp Require Import all_ssreflect all_fingroup
all_solvable stripped_odd_order_theorem.
Check stripped_Odd_Order.
: forall (T : Type) (mul : T -> T -> T) (one : T) (inv : T -> T)
(G : T -> Type) (n : natural),
group_axioms T mul one inv ->
group T mul one inv G ->
finite_of_order T G n -> odd n -> solvable_group T mul one inv G"""
url {
src:
"https://github.com/math-comp/odd-order/archive/mathcomp-odd-order.1.7.0.tar.gz"
checksum: "md5=e7a90d25223e257a604a8574a06a3e3c"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-mathcomp-odd-order.1.7.0 coq.8.11.dev</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.11.dev).
The following dependencies couldn't be met:
- coq-mathcomp-odd-order -> coq-mathcomp-ssreflect = 1.7.0 -> coq < 8.10~ -> ocaml < 4.05.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-mathcomp-odd-order.1.7.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "f5762dd7b30fdaf5f4297a25594efcca",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 554,
"avg_line_length": 45.854838709677416,
"alnum_prop": 0.5619650603822254,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "bd5cb156ff621900a6d43fcb7f1f5001296d41ed",
"size": "8555",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.04.2-2.0.5/extra-dev/8.11.dev/mathcomp-odd-order/1.7.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
maintainer "Opscode, Inc."
maintainer_email "[email protected]"
license "Apache 2.0"
description "Installs emacs"
version IO.read(File.join(File.dirname(__FILE__), 'VERSION'))
recipe "emacs", "Installs Emacs"
%w{ ubuntu debian redhat centos scientific fedora freebsd }.each do |os|
supports os
end
| {
"content_hash": "230fa4b494d03833a0bfbb6bb1927664",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 72,
"avg_line_length": 30.818181818181817,
"alnum_prop": 0.6755162241887905,
"repo_name": "yieldbot/ironfan-pantry",
"id": "1e5663152568ea02c2f338e23387b0bde4f57923",
"size": "339",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "cookbooks/emacs/metadata.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Gherkin",
"bytes": "2758"
},
{
"name": "Groovy",
"bytes": "1666"
},
{
"name": "HTML",
"bytes": "267071"
},
{
"name": "Perl",
"bytes": "8609"
},
{
"name": "Ruby",
"bytes": "1145463"
},
{
"name": "Shell",
"bytes": "126903"
}
],
"symlink_target": ""
} |
//
// select_reactor.hpp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_DETAIL_SELECT_REACTOR_HPP
#define BOOST_ASIO_DETAIL_SELECT_REACTOR_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/push_options.hpp>
#include <boost/asio/detail/socket_types.hpp> // Must come before posix_time.
#include <boost/asio/detail/push_options.hpp>
#include <cstddef>
#include <boost/config.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/shared_ptr.hpp>
#include <vector>
#include <boost/asio/detail/pop_options.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/detail/bind_handler.hpp>
#include <boost/asio/detail/fd_set_adapter.hpp>
#include <boost/asio/detail/mutex.hpp>
#include <boost/asio/detail/noncopyable.hpp>
#include <boost/asio/detail/reactor_op_queue.hpp>
#include <boost/asio/detail/select_interrupter.hpp>
#include <boost/asio/detail/select_reactor_fwd.hpp>
#include <boost/asio/detail/service_base.hpp>
#include <boost/asio/detail/signal_blocker.hpp>
#include <boost/asio/detail/socket_ops.hpp>
#include <boost/asio/detail/socket_types.hpp>
#include <boost/asio/detail/task_io_service.hpp>
#include <boost/asio/detail/thread.hpp>
#include <boost/asio/detail/timer_queue.hpp>
namespace boost {
namespace asio {
namespace detail {
template <bool Own_Thread>
class select_reactor
: public boost::asio::detail::service_base<select_reactor<Own_Thread> >
{
public:
// Per-descriptor data.
struct per_descriptor_data
{
};
// Constructor.
select_reactor(boost::asio::io_service& io_service)
: boost::asio::detail::service_base<
select_reactor<Own_Thread> >(io_service),
mutex_(),
select_in_progress_(false),
interrupter_(),
read_op_queue_(),
write_op_queue_(),
except_op_queue_(),
pending_cancellations_(),
stop_thread_(false),
thread_(0),
shutdown_(false)
{
if (Own_Thread)
{
boost::asio::detail::signal_blocker sb;
thread_ = new boost::asio::detail::thread(
bind_handler(&select_reactor::call_run_thread, this));
}
}
// Destructor.
~select_reactor()
{
shutdown_service();
}
// Destroy all user-defined handler objects owned by the service.
void shutdown_service()
{
boost::asio::detail::mutex::scoped_lock lock(mutex_);
shutdown_ = true;
stop_thread_ = true;
lock.unlock();
if (thread_)
{
interrupter_.interrupt();
thread_->join();
delete thread_;
thread_ = 0;
}
read_op_queue_.destroy_operations();
write_op_queue_.destroy_operations();
except_op_queue_.destroy_operations();
for (std::size_t i = 0; i < timer_queues_.size(); ++i)
timer_queues_[i]->destroy_timers();
timer_queues_.clear();
}
// Initialise the task, but only if the reactor is not in its own thread.
void init_task()
{
if (!Own_Thread)
{
typedef task_io_service<select_reactor<Own_Thread> > task_io_service_type;
use_service<task_io_service_type>(this->get_io_service()).init_task();
}
}
// Register a socket with the reactor. Returns 0 on success, system error
// code on failure.
int register_descriptor(socket_type, per_descriptor_data&)
{
return 0;
}
// Start a new read operation. The handler object will be invoked when the
// given descriptor is ready to be read, or an error has occurred.
template <typename Handler>
void start_read_op(socket_type descriptor, per_descriptor_data&,
Handler handler, bool /*allow_speculative_read*/ = true)
{
boost::asio::detail::mutex::scoped_lock lock(mutex_);
if (!shutdown_)
if (read_op_queue_.enqueue_operation(descriptor, handler))
interrupter_.interrupt();
}
// Start a new write operation. The handler object will be invoked when the
// given descriptor is ready to be written, or an error has occurred.
template <typename Handler>
void start_write_op(socket_type descriptor, per_descriptor_data&,
Handler handler, bool /*allow_speculative_write*/ = true)
{
boost::asio::detail::mutex::scoped_lock lock(mutex_);
if (!shutdown_)
if (write_op_queue_.enqueue_operation(descriptor, handler))
interrupter_.interrupt();
}
// Start a new exception operation. The handler object will be invoked when
// the given descriptor has exception information, or an error has occurred.
template <typename Handler>
void start_except_op(socket_type descriptor,
per_descriptor_data&, Handler handler)
{
boost::asio::detail::mutex::scoped_lock lock(mutex_);
if (!shutdown_)
if (except_op_queue_.enqueue_operation(descriptor, handler))
interrupter_.interrupt();
}
// Wrapper for connect handlers to enable the handler object to be placed
// in both the write and the except operation queues, but ensure that only
// one of the handlers is called.
template <typename Handler>
class connect_handler_wrapper
{
public:
connect_handler_wrapper(socket_type descriptor,
boost::shared_ptr<bool> completed,
select_reactor<Own_Thread>& reactor, Handler handler)
: descriptor_(descriptor),
completed_(completed),
reactor_(reactor),
handler_(handler)
{
}
bool perform(boost::system::error_code& ec,
std::size_t& bytes_transferred)
{
// Check whether one of the handlers has already been called. If it has,
// then we don't want to do anything in this handler.
if (*completed_)
{
completed_.reset(); // Indicate that this handler should not complete.
return true;
}
// Cancel the other reactor operation for the connection.
*completed_ = true;
reactor_.enqueue_cancel_ops_unlocked(descriptor_);
// Call the contained handler.
return handler_.perform(ec, bytes_transferred);
}
void complete(const boost::system::error_code& ec,
std::size_t bytes_transferred)
{
if (completed_.get())
handler_.complete(ec, bytes_transferred);
}
private:
socket_type descriptor_;
boost::shared_ptr<bool> completed_;
select_reactor<Own_Thread>& reactor_;
Handler handler_;
};
// Start new write and exception operations. The handler object will be
// invoked when the given descriptor is ready for writing or has exception
// information available, or an error has occurred. The handler will be called
// only once.
template <typename Handler>
void start_connect_op(socket_type descriptor,
per_descriptor_data&, Handler handler)
{
boost::asio::detail::mutex::scoped_lock lock(mutex_);
if (!shutdown_)
{
boost::shared_ptr<bool> completed(new bool(false));
connect_handler_wrapper<Handler> wrapped_handler(
descriptor, completed, *this, handler);
bool interrupt = write_op_queue_.enqueue_operation(
descriptor, wrapped_handler);
interrupt = except_op_queue_.enqueue_operation(
descriptor, wrapped_handler) || interrupt;
if (interrupt)
interrupter_.interrupt();
}
}
// Cancel all operations associated with the given descriptor. The
// handlers associated with the descriptor will be invoked with the
// operation_aborted error.
void cancel_ops(socket_type descriptor, per_descriptor_data&)
{
boost::asio::detail::mutex::scoped_lock lock(mutex_);
cancel_ops_unlocked(descriptor);
}
// Enqueue cancellation of all operations associated with the given
// descriptor. The handlers associated with the descriptor will be invoked
// with the operation_aborted error. This function does not acquire the
// select_reactor's mutex, and so should only be used when the reactor lock is
// already held.
void enqueue_cancel_ops_unlocked(socket_type descriptor)
{
pending_cancellations_.push_back(descriptor);
}
// Cancel any operations that are running against the descriptor and remove
// its registration from the reactor.
void close_descriptor(socket_type descriptor, per_descriptor_data&)
{
boost::asio::detail::mutex::scoped_lock lock(mutex_);
cancel_ops_unlocked(descriptor);
}
// Add a new timer queue to the reactor.
template <typename Time_Traits>
void add_timer_queue(timer_queue<Time_Traits>& timer_queue)
{
boost::asio::detail::mutex::scoped_lock lock(mutex_);
timer_queues_.push_back(&timer_queue);
}
// Remove a timer queue from the reactor.
template <typename Time_Traits>
void remove_timer_queue(timer_queue<Time_Traits>& timer_queue)
{
boost::asio::detail::mutex::scoped_lock lock(mutex_);
for (std::size_t i = 0; i < timer_queues_.size(); ++i)
{
if (timer_queues_[i] == &timer_queue)
{
timer_queues_.erase(timer_queues_.begin() + i);
return;
}
}
}
// Schedule a timer in the given timer queue to expire at the specified
// absolute time. The handler object will be invoked when the timer expires.
template <typename Time_Traits, typename Handler>
void schedule_timer(timer_queue<Time_Traits>& timer_queue,
const typename Time_Traits::time_type& time, Handler handler, void* token)
{
boost::asio::detail::mutex::scoped_lock lock(mutex_);
if (!shutdown_)
if (timer_queue.enqueue_timer(time, handler, token))
interrupter_.interrupt();
}
// Cancel the timer associated with the given token. Returns the number of
// handlers that have been posted or dispatched.
template <typename Time_Traits>
std::size_t cancel_timer(timer_queue<Time_Traits>& timer_queue, void* token)
{
boost::asio::detail::mutex::scoped_lock lock(mutex_);
std::size_t n = timer_queue.cancel_timer(token);
if (n > 0)
interrupter_.interrupt();
return n;
}
private:
friend class task_io_service<select_reactor<Own_Thread> >;
// Run select once until interrupted or events are ready to be dispatched.
void run(bool block)
{
boost::asio::detail::mutex::scoped_lock lock(mutex_);
// Dispatch any operation cancellations that were made while the select
// loop was not running.
read_op_queue_.perform_cancellations();
write_op_queue_.perform_cancellations();
except_op_queue_.perform_cancellations();
for (std::size_t i = 0; i < timer_queues_.size(); ++i)
timer_queues_[i]->dispatch_cancellations();
// Check if the thread is supposed to stop.
if (stop_thread_)
{
complete_operations_and_timers(lock);
return;
}
// We can return immediately if there's no work to do and the reactor is
// not supposed to block.
if (!block && read_op_queue_.empty() && write_op_queue_.empty()
&& except_op_queue_.empty() && all_timer_queues_are_empty())
{
complete_operations_and_timers(lock);
return;
}
// Set up the descriptor sets.
fd_set_adapter read_fds;
read_fds.set(interrupter_.read_descriptor());
read_op_queue_.get_descriptors(read_fds);
fd_set_adapter write_fds;
write_op_queue_.get_descriptors(write_fds);
fd_set_adapter except_fds;
except_op_queue_.get_descriptors(except_fds);
socket_type max_fd = read_fds.max_descriptor();
if (write_fds.max_descriptor() > max_fd)
max_fd = write_fds.max_descriptor();
if (except_fds.max_descriptor() > max_fd)
max_fd = except_fds.max_descriptor();
// Block on the select call without holding the lock so that new
// operations can be started while the call is executing.
timeval tv_buf = { 0, 0 };
timeval* tv = block ? get_timeout(tv_buf) : &tv_buf;
select_in_progress_ = true;
lock.unlock();
boost::system::error_code ec;
int retval = socket_ops::select(static_cast<int>(max_fd + 1),
read_fds, write_fds, except_fds, tv, ec);
lock.lock();
select_in_progress_ = false;
// Reset the interrupter.
if (retval > 0 && read_fds.is_set(interrupter_.read_descriptor()))
interrupter_.reset();
// Dispatch all ready operations.
if (retval > 0)
{
// Exception operations must be processed first to ensure that any
// out-of-band data is read before normal data.
except_op_queue_.perform_operations_for_descriptors(
except_fds, boost::system::error_code());
read_op_queue_.perform_operations_for_descriptors(
read_fds, boost::system::error_code());
write_op_queue_.perform_operations_for_descriptors(
write_fds, boost::system::error_code());
except_op_queue_.perform_cancellations();
read_op_queue_.perform_cancellations();
write_op_queue_.perform_cancellations();
}
for (std::size_t i = 0; i < timer_queues_.size(); ++i)
{
timer_queues_[i]->dispatch_timers();
timer_queues_[i]->dispatch_cancellations();
}
// Issue any pending cancellations.
for (size_t i = 0; i < pending_cancellations_.size(); ++i)
cancel_ops_unlocked(pending_cancellations_[i]);
pending_cancellations_.clear();
complete_operations_and_timers(lock);
}
// Run the select loop in the thread.
void run_thread()
{
boost::asio::detail::mutex::scoped_lock lock(mutex_);
while (!stop_thread_)
{
lock.unlock();
run(true);
lock.lock();
}
}
// Entry point for the select loop thread.
static void call_run_thread(select_reactor* reactor)
{
reactor->run_thread();
}
// Interrupt the select loop.
void interrupt()
{
interrupter_.interrupt();
}
// Check if all timer queues are empty.
bool all_timer_queues_are_empty() const
{
for (std::size_t i = 0; i < timer_queues_.size(); ++i)
if (!timer_queues_[i]->empty())
return false;
return true;
}
// Get the timeout value for the select call.
timeval* get_timeout(timeval& tv)
{
if (all_timer_queues_are_empty())
return 0;
// By default we will wait no longer than 5 minutes. This will ensure that
// any changes to the system clock are detected after no longer than this.
boost::posix_time::time_duration minimum_wait_duration
= boost::posix_time::minutes(5);
for (std::size_t i = 0; i < timer_queues_.size(); ++i)
{
boost::posix_time::time_duration wait_duration
= timer_queues_[i]->wait_duration();
if (wait_duration < minimum_wait_duration)
minimum_wait_duration = wait_duration;
}
if (minimum_wait_duration > boost::posix_time::time_duration())
{
tv.tv_sec = minimum_wait_duration.total_seconds();
tv.tv_usec = minimum_wait_duration.total_microseconds() % 1000000;
}
else
{
tv.tv_sec = 0;
tv.tv_usec = 0;
}
return &tv;
}
// Cancel all operations associated with the given descriptor. The do_cancel
// function of the handler objects will be invoked. This function does not
// acquire the select_reactor's mutex.
void cancel_ops_unlocked(socket_type descriptor)
{
bool interrupt = read_op_queue_.cancel_operations(descriptor);
interrupt = write_op_queue_.cancel_operations(descriptor) || interrupt;
interrupt = except_op_queue_.cancel_operations(descriptor) || interrupt;
if (interrupt)
interrupter_.interrupt();
}
// Clean up operations and timers. We must not hold the lock since the
// destructors may make calls back into this reactor. We make a copy of the
// vector of timer queues since the original may be modified while the lock
// is not held.
void complete_operations_and_timers(
boost::asio::detail::mutex::scoped_lock& lock)
{
timer_queues_for_cleanup_ = timer_queues_;
lock.unlock();
read_op_queue_.complete_operations();
write_op_queue_.complete_operations();
except_op_queue_.complete_operations();
for (std::size_t i = 0; i < timer_queues_for_cleanup_.size(); ++i)
timer_queues_for_cleanup_[i]->complete_timers();
}
// Mutex to protect access to internal data.
boost::asio::detail::mutex mutex_;
// Whether the select loop is currently running or not.
bool select_in_progress_;
// The interrupter is used to break a blocking select call.
select_interrupter interrupter_;
// The queue of read operations.
reactor_op_queue<socket_type> read_op_queue_;
// The queue of write operations.
reactor_op_queue<socket_type> write_op_queue_;
// The queue of exception operations.
reactor_op_queue<socket_type> except_op_queue_;
// The timer queues.
std::vector<timer_queue_base*> timer_queues_;
// A copy of the timer queues, used when cleaning up timers. The copy is
// stored as a class data member to avoid unnecessary memory allocation.
std::vector<timer_queue_base*> timer_queues_for_cleanup_;
// The descriptors that are pending cancellation.
std::vector<socket_type> pending_cancellations_;
// Does the reactor loop thread need to stop.
bool stop_thread_;
// The thread that is running the reactor loop.
boost::asio::detail::thread* thread_;
// Whether the service has been shut down.
bool shutdown_;
};
} // namespace detail
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#endif // BOOST_ASIO_DETAIL_SELECT_REACTOR_HPP
| {
"content_hash": "b272b2f7d1c2b5f4a61176c843273734",
"timestamp": "",
"source": "github",
"line_count": 543,
"max_line_length": 80,
"avg_line_length": 32.24309392265194,
"alnum_prop": 0.6675234178661184,
"repo_name": "shoerob/BumbleTales",
"id": "ba8b5d3ba568efe569b7b1b3b5a13592122fa181",
"size": "17508",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "ThirdParty/boost/asio/detail/select_reactor.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AGS Script",
"bytes": "26238"
},
{
"name": "Assembly",
"bytes": "261207"
},
{
"name": "Batchfile",
"bytes": "1748"
},
{
"name": "C",
"bytes": "2568464"
},
{
"name": "C#",
"bytes": "74462"
},
{
"name": "C++",
"bytes": "48454693"
},
{
"name": "CSS",
"bytes": "4128"
},
{
"name": "Groff",
"bytes": "6728"
},
{
"name": "HTML",
"bytes": "288504"
},
{
"name": "Makefile",
"bytes": "2486"
},
{
"name": "Matlab",
"bytes": "2076"
},
{
"name": "Objective-C",
"bytes": "154572"
},
{
"name": "Pascal",
"bytes": "32082"
},
{
"name": "Perl",
"bytes": "6080"
},
{
"name": "Shell",
"bytes": "4383"
},
{
"name": "XSLT",
"bytes": "12347"
},
{
"name": "xBase",
"bytes": "146245"
}
],
"symlink_target": ""
} |
<?php //print_r($purchase);die(); ?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header"><h1>Purchase</h1></section>
<!-- Main content -->
<section class="content">
<!-- Default box -->
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Purchase</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Collapse">
<i class="fa fa-minus"></i></button>
</div>
</div>
<!-- /.box-body -->
<?php $id = (empty($purchase['id'])) ? '' : $purchase['id'] ;?>
<form role="form" method="post" action="<?php echo base_url().'purchase/submit/'.$id ?>">
<div class="box-body">
<div class="row">
<div class="box-body">
<div class="row">
<div class="col-xs-3"></div>
<div class="col-xs-6">
<div class="form-group">
<label for="biro" class="col-xs-4 control-label">Nama Purchase<label style="color:#f00;">*</label></label>
<div class="col-xs-8">
<input required="required" name="purchasing" value="<?php echo (empty($purchase['purchasing'])) ? '' : $purchase['purchasing']; ?>" type="text" class="form-control">
</div>
</div>
</div>
<div class="col-xs-3"> </div>
</div><br>
<div class="row">
<div class="col-xs-3">
<div class="form-group">
<label for="biro" class="col-xs-4 control-label">Bagian/ Biro</label>
<div class="col-xs-8">
<input type="hidden" name="id" value="<?php echo $id ; ?>">
<?php echo $_SESSION['masuk']['biro']; ?>
<input value="harga" type="hidden" id="param">
</div>
</div>
</div>
<div class="col-xs-3">
<div class="form-group">
<label for="tanggal" class="col-xs-4 control-label">Tanggal<label style="color:#f00;">*</label></label>
<div class="col-xs-8">
<input required="required" type="text" class="form-control datepicker" name="tanggal" id="tanggal" placeholder="<?php echo date('d-m-Y'); ?>" value="<?php echo (empty($purchase['tanggal'])) ? date('d-m-Y') : date("d-m-Y",strtotime($purchase['tanggal'])); ?>">
</div>
</div>
</div>
<div class="col-xs-3">
<div class="form-group">
<label for="ref" class="col-xs-4 control-label">No. Ref</label>
<div class="col-xs-8">
<input type="text" class="form-control" name="ref" id="ref" placeholder="<?php echo uniqid().date('dmY') ?>" value="<?php echo (empty($purchase['ref'])) ? '' : $purchase['ref'] ; ?>">
</div>
</div>
</div>
<div class="col-xs-3">
<div class="form-group">
<label for="biro" class="col-xs-4 control-label">Jenis<label style="color:#f00;">*</label> Purchase</label>
<div class="col-xs-8">
<?php $purchase['type'] = (empty($purchase['type'])) ? '' : $purchase['type'] ; ?>
<input type="radio" value="0" name="type" <?php echo ($purchase['type'] == 0) ? 'checked="checked"' : ''; ?>> Beli
<input type="radio" value="1" name="type" <?php echo ($purchase['type'] == 1) ? 'checked="checked"' : ''; ?>> Stok
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="box-header">
<h3 class="box-title">Barang</h3>
</div>
<div class="box-body table-responsive no-padding">
<table class="table table-hover table-striped">
<thead>
<tr>
<th class="text-center" width="22%">Barang<label style="color:#f00;">*</label></th>
<th class="text-center" width="8%">Jumlah<label style="color:#f00;">*</label></th>
<th class="text-center" width="20%">Merk</th>
<th class="text-center" width="30%">Spesifikasi</th>
<th class="text-center" width="10%">Anggaran Perbarang<label style="color:#f00;">*</label></th>
<th class="text-center" width="10%">Opsi</th>
</tr>
</thead>
<tbody id="purchase">
<?php if(empty($purchase['id'])){ ?>
<tr id="baris1">
<td>
<input required="required" type="text" id="1" value="" placeholder="Mac Book Air" class="form-control autocomplete">
<input type="hidden" id="id1" name="id_barang[]" value="" placeholder="Mac Book Air" class="form-control">
</td>
<td><input required="required" type="number" value="" pattern="[0-9]" name="jumlah[]" placeholder="10" class="form-control"></td>
<td><p id="merk1"></p></td>
<td><p id="spec1"></p></td>
<td><input required="required" type="number" value="" pattern="[0-9]" name="harga[]" placeholder="1000" class="form-control"></td>
<td><p id="op1"><button type="button" onclick="minus(1)" class="btn btn-danger btn-xs btn-circle hapus" title="Hapus"><i class="fa fa-trash"></i></button></p></td>
</tr>
<?php } else {
foreach ($purchase['item'] as $key => $value) { ?>
<tr id="baris<?php echo $key ?>">
<td>
<input required="required" type="text" id="<?php echo $key ?>" placeholder="Mac Book Air" class="form-control autocomplete" value="<?php echo $value['nama'] ?>">
<input type="hidden" id="id<?php echo $key ?>" name="id_barang[]" placeholder="Mac Book Air" class="form-control" value="<?php echo $value['id_barang'] ?>">
<input type="hidden" name="id_[]" value="<?php echo $value['id'] ?>">
</td>
<td><input required="required" type="number" pattern="[0-9]" name="jumlah[]" placeholder="10" class="form-control" value="<?php echo $value['jumlah'] ?>"></td>
<td><p id="merk<?php echo $key ?>"><?php echo $value['merk'] ?></p></td>
<td><p id="spec<?php echo $key ?>"><?php echo $value['spesifikasi'] ?></p></td>
<td><input required="required" type="number" pattern="[0-9]" name="harga[]" placeholder="10" class="form-control" value="<?php echo $value['harga'] ?>"></td>
<td><p id="op<?php echo $key ?>"><button type="button" onclick="minus(<?php echo $key ?>)" class="btn btn-danger btn-xs btn-circle hapus" title="Hapus"><i class="fa fa-trash"></i></button></p></td>
</tr>
<?php }
} ?>
</tbody>
</table>
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<div class="box-footer text-right">
<input type="hidden" id="baris" value="<?php echo (empty($purchase['id'])) ? 1 : count($purchase['item']) ; ?>">
<button type="button" onclick="plus();" class="btn btn-success btn-circle" title="Tambah Baris"><i class="fa fa-plus"></i></button>
<button type="submit" class="btn btn-primary btn-circle" title="Simpan"><i class="fa fa-check"></i></button>
<button type="reset" onclick="window.location='http://<?php echo $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; ?>'" class="btn btn-warning btn-circle" title="ReSet"><i class="fa fa-undo"></i></button>
<button type="button" onclick="window.location='<?php echo base_url(); ?>purchase'" class="btn btn-danger btn-circle batal" title="Batal"><i class="fa fa-close"></i></button>
</div>
</div>
</form>
<!-- /.box-footer-->
</div>
<!-- /.box -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper --> | {
"content_hash": "76433c694997037fbc1e865b48d1ad11",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 279,
"avg_line_length": 55.766666666666666,
"alnum_prop": 0.49348475791990437,
"repo_name": "archaeophoenix/purchase",
"id": "618f53e99eb1c2021eb0614415416721f06d43e9",
"size": "8365",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/views/form/purchase.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "364"
},
{
"name": "CSS",
"bytes": "620866"
},
{
"name": "HTML",
"bytes": "9925396"
},
{
"name": "JavaScript",
"bytes": "2957096"
},
{
"name": "PHP",
"bytes": "2012604"
}
],
"symlink_target": ""
} |
import sun.rmi.runtime.Log;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
import java.util.Stack;
import java.util.logging.Logger;
/**
* Created by jsybrand on 6/25/15.
*/
public class Worker extends Thread {
private int numAvalibleProcs;
ObjectInputStream in;
ObjectOutputStream out;
Socket socket;
Worker(String serverAddress)
{
try {
socket = new Socket(serverAddress, Constants.PORT);
}
catch(Exception e)
{
System.err.println("Worker failed to connect to server. " + e);
}
numAvalibleProcs = Math.max(1,Runtime.getRuntime().availableProcessors()-1);//we want to make sure theres room for this worker
}
@Override
public void finalize() throws Throwable{
try {
in.close();
out.close();
socket.close();
super.finalize();
}
catch(Exception e)
{
System.err.println("Worker failed to close.");
}
}
@Override
public void run()
{
long startTime = -1;
try {
while(true) {
if(socket.isClosed())
break;
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
Job received = (Job)in.readObject();
System.out.println("Client Received:" + received);
if (received==null) {
out.writeObject(null);
break;
}
out.writeObject("STARTED");
startTime = System.nanoTime();
try {
switch(received.getType()) {
case CREATE_DIR:
preformCreateDir(received);
break;
case RM_DIR:
preformRemoveDirectory(received);
break;
case CREATE_FILES:
preformCopy(received);
break;
case RM_FILES:
preformRemoveFiles(received);
break;
case MODIFY_FILES:
preformSyncFiles(received);
break;
case MODIFY_DIRS:
preformSyncDirs(received);
case BUILD_LINKS:
preformBuildLinks(received);
break;
case OTHER:break;
}
Long diffTime = System.nanoTime()-startTime;
CustomLog.log(diffTime.toString(),received.logFile);
out.writeObject("FINISHED");
}
catch(IOException e)
{
if(startTime > 0) {
Long diffTime = System.nanoTime()-startTime;
CustomLog.log(e.getMessage() + "\n" +diffTime.toString(), received.logFile);
}
else
CustomLog.log(e.getMessage(),received.logFile);
Exception newE = new Exception(e.getMessage() + "\nLog file should be:" + received.logFile+"\nWas given " + received.path);
//out.writeObject(newE);
out.writeObject("FINISHED");
System.err.println(newE);
}
}
}
catch(Exception e){
System.err.println("Client Failed to listen: " + e);
e.printStackTrace();
}
finally{
CustomLog.close();
}
}
private boolean checkAndRepairStaleNSF(SystemRunner [] runners) throws IOException, InterruptedException
{
boolean ret = false;
//pre check for stale nfs (if the whole file system drops out, this is a fixable issue
for(int i = 0 ; i < runners.length;i++)
{
//if any runner has a stale nsf handle
if(runners[i]!=null && runners[i].staleNFS.get())
{
ret = true;
CustomLog.log("Attempting to reset NFS Handle: Up:" + Job.upToDateDevice + " Out:" + Job.outOfDateDevice, runners[i].getLogfile());
//attempt to toggle the mounts of
Runtime.getRuntime().exec("umount " + Job.upToDateDevice).waitFor();
Runtime.getRuntime().exec("mount " + Job.upToDateDevice).waitFor();
Runtime.getRuntime().exec("umount " + Job.outOfDateDevice).waitFor();
Runtime.getRuntime().exec("mount " + Job.outOfDateDevice).waitFor();
sleep(10000);
//loop through all runners and restart any that have failed.
for(int j = 0 ; j < runners.length;j++)
{
if(runners[j]!=null && runners[j].staleNFS.get())
{
runners[j].staleNFS.set(false);
runners[j].isComplete.set(false);
runners[j].start();
}
}
break;
}
}
return ret;
}
private void preformCopy(Job job) throws IOException, InterruptedException{
System.out.println("COPY STARTED");
Scanner scan = new Scanner(new File(job.path));
String cmd[] = {"cp","-Pp","",""};
SystemRunner runners[] = new SystemRunner[numAvalibleProcs];
while(scan.hasNextLine())
{
checkAndRepairStaleNSF(runners);
for(int i = 0 ; i < runners.length;i++)
{
if(runners[i]==null || runners[i].isComplete.get())
{
String path = scan.nextLine();
cmd[2]=job.upToDateMountPoint+path;
cmd[3]=job.outOfDateMountPoint+path;
runners[i]= new SystemRunner(cmd.clone(),job.logFile);
runners[i].start();
break;
}
}
}
for(SystemRunner s : runners)
{
if(s != null)
s.join();
}
}
//this relies on the job file listing dirs in order
private void preformCreateDir(Job job)throws IOException, InterruptedException{
Scanner scan = new Scanner(new File(job.path));
String cmd1[] = {"chown","",""};
String cmd2[] = {"chmod","",""};
SystemRunner runners[][] = new SystemRunner[Math.max(1,numAvalibleProcs/2)][2];
while(scan.hasNextLine())
{
for(int i = 0 ; i < runners.length;i++)
{
if((runners[i][0]==null && runners[i][1]==null)
|| (runners[i][0].isComplete.get()&&runners[i][1].isComplete.get()))
{
String path = scan.nextLine();
new File(job.outOfDateMountPoint+path).mkdir();
//System.out.println("Making : " + job.outOfDateMountPoint+path);
cmd1[1] = cmd2[1]="--reference="+job.upToDateMountPoint+path;
cmd1[2] = cmd2[2]=job.outOfDateMountPoint+path;
runners[i][0]= new SystemRunner(cmd1.clone(),job.logFile);
runners[i][1]= new SystemRunner(cmd2.clone(),job.logFile);
runners[i][0].start();
runners[i][1].start();
break;
}
}
}
for(SystemRunner s[] : runners)
{
for(SystemRunner r : s)
if(r != null)
r.join();
}
}
private void preformRemoveFiles(Job job) throws IOException, InterruptedException{
Scanner scan = new Scanner(new File(job.path));
String cmd[] = {"rm","-f",""};
SystemRunner runners[] = new SystemRunner[numAvalibleProcs];
while(scan.hasNextLine())
{
checkAndRepairStaleNSF(runners);
for(int i = 0 ; i < runners.length;i++)
{
if(runners[i]==null || runners[i].isComplete.get())
{
String path = scan.nextLine();
cmd[2]=job.outOfDateMountPoint+path;
runners[i]= new SystemRunner(cmd.clone(),job.logFile);
runners[i].start();
break;
}
}
}
for(SystemRunner s : runners)
{
if(s != null)
s.join();
}
}
private void preformRemoveDirectory(Job job) throws IOException{
boolean containedErrors = false;
Runtime r = Runtime.getRuntime();
Scanner scan = new Scanner(new File(job.path));
Stack<String> stack = new Stack<>();
while(scan.hasNext()){
String path = job.outOfDateMountPoint+scan.nextLine();
stack.push(path);
}
String cmd[] = {"rm","-rf",""};
while(!stack.empty()){
cmd[2]=stack.pop();
try {
Process p = r.exec(cmd);
p.waitFor();
if(p.exitValue()!=0) {
containedErrors = true;
CustomLog.log("Failed to rm " + cmd[2],job.logFile);
}
} catch(InterruptedException e){System.err.println("RM Interupted. " + e);}
}
if(containedErrors)
throw new IOException("RM -r Proc Error somewhere within " + job.fileName);
}
private void preformSyncFiles(Job job) throws IOException, InterruptedException{
Scanner scan = new Scanner(new File(job.path));
String cmd[] = {"rsync","-aSHAXd","",""};
SystemRunner runners[] = new SystemRunner[numAvalibleProcs];
while(scan.hasNextLine())
{
checkAndRepairStaleNSF(runners);
for(int i = 0 ; i < runners.length;i++)
{
if(runners[i]==null || runners[i].isComplete.get())
{
String path = scan.nextLine();
cmd[2]=job.upToDateMountPoint+path;
cmd[3]=job.outOfDateMountPoint+path;
runners[i]= new SystemRunner(cmd.clone(),job.logFile);
runners[i].start();
break;
}
}
}
for(SystemRunner s : runners)
{
if(s != null)
s.join();
}
}
private void preformSyncDirs(Job job) throws IOException, InterruptedException{
Scanner scan = new Scanner(new File(job.path));
String cmd1[] = {"chown","",""};
String cmd2[] = {"chmod","",""};
SystemRunner runners[][] = new SystemRunner[numAvalibleProcs/2][2];
while(scan.hasNextLine())
{
for(int i = 0 ; i < runners.length;i++)
{
if((runners[i][0]==null && runners[i][1]==null)
|| (runners[i][0].isComplete.get()&&runners[i][1].isComplete.get()))
{
String path = scan.nextLine();
cmd1[1] = cmd2[1]="--reference="+job.upToDateMountPoint+path;
cmd1[2] = cmd2[2]=job.outOfDateMountPoint+path;
runners[i][0]= new SystemRunner(cmd1.clone(),job.logFile);
runners[i][1]= new SystemRunner(cmd2.clone(),job.logFile);
runners[i][0].start();
runners[i][1].start();
break;
}
}
}
for(SystemRunner s[] : runners)
{
for(SystemRunner r : s)
if(r != null)
r.join();
}
}
private void preformBuildLinks(Job job) throws IOException{
String cmd[] = {"rsync","-aSHAXd","--files-from="+job.path,Job.upToDateMountPoint,Job.outOfDateMountPoint};
Process p = Runtime.getRuntime().exec(cmd);
try {
p.waitFor();
int val = p.exitValue();
if(val!=0)//err
throw new IOException("RSYNC failed to process links");
}
catch(InterruptedException e) {
System.err.println("RSYNC Interupted. " + e);
}
}
}
| {
"content_hash": "9810409b90fbbb2bae6ef26d8ad2fe97",
"timestamp": "",
"source": "github",
"line_count": 364,
"max_line_length": 147,
"avg_line_length": 34.434065934065934,
"alnum_prop": 0.4757459709589915,
"repo_name": "JSybrandt/Distributed_Copy",
"id": "7e7f79ba475d3ecfb806f4fb8649319be1d59fd3",
"size": "12534",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Worker.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "11540"
},
{
"name": "Java",
"bytes": "54085"
}
],
"symlink_target": ""
} |
/* global define, module, require, exports */
/* requires modal, combo, qtip, and nfeditor plugins to be loaded first*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery',
'Slick',
'nf.Common',
'nf.UniversalCapture',
'nf.Dialog',
'nf.Storage',
'nf.Client',
'nf.ErrorHandler',
'nf.ProcessGroup',
'nf.ProcessGroupConfiguration',
'nf.Settings',
'nf.ParameterContexts',
'lodash'],
function ($,
Slick,
nfCommon,
nfUniversalCapture,
nfDialog,
nfStorage,
nfClient,
nfErrorHandler,
nfProcessGroup,
nfProcessGroupConfiguration,
nfSettings,
nfParameterContexts,
_) {
factory($,
Slick,
nfCommon,
nfUniversalCapture,
nfDialog,
nfStorage,
nfClient,
nfErrorHandler,
nfProcessGroup,
nfProcessGroupConfiguration,
nfSettings,
nfParameterContexts,
_);
});
} else if (typeof exports === 'object' && typeof module === 'object') {
factory(require('jquery'),
require('Slick'),
require('nf.Common'),
require('nf.UniversalCapture'),
require('nf.Dialog'),
require('nf.Storage'),
require('nf.Client'),
require('nf.ErrorHandler'),
require('nf.ProcessGroup'),
require('nf.ProcessGroupConfiguration'),
require('nf.Settings'),
recuire('nf.ParameterContexts'),
require('lodash'));
} else {
factory(root.$,
root.Slick,
root.nf.Common,
root.nf.UniversalCapture,
root.nf.Dialog,
root.nf.Storage,
root.nf.Client,
root.nf.ErrorHandler,
root.nf.ProcessGroup,
root.nf.ProcessGroupConfiguration,
root.nf.Settings,
root.nf.ParameterContexts,
root._);
}
}(this, function ($,
Slick,
nfCommon,
nfUniversalCapture,
nfDialog,
nfStorage,
nfClient,
nfErrorHandler,
nfProcessGroup,
nfProcessGroupConfiguration,
nfSettings,
nfParameterContexts,
_) {
var groupId = null;
var supportsSensitiveDynamicProperties = false;
var propertyVerificationCallback = null;
var COMBO_MIN_WIDTH = 212;
var EDITOR_MIN_WIDTH = 212;
var EDITOR_MIN_HEIGHT = 100;
var EL_SUPPORTED_TITLE = '<div>Expression Language (EL) supported</div>';
var EL_SUPPORTED_DESCRIPTION = '<div>After beginning with the start delimiter <span class="hint-pattern">${</span> use the keystroke '
+ '<span class="hint-keystroke">control+space</span> to see a list of available functions.</div>';
var EL_UNSUPPORTED_TITLE = '<div>Expression Language (EL) not supported</div>';
var PARAM_SUPPORTED_TITLE = '<div>Parameters (PARAM) supported</div>';
var PARAM_SUPPORTED_DESCRIPTION = '<div>After beginning with the start delimiter <span class="hint-pattern">#{</span> use the keystroke '
+ '<span class="hint-keystroke">control+space</span> to see a list of available parameters.</div>';
var PARAM_UNSUPPORTED_TITLE = '<div>Parameters (PARAM) not supported</div>';
/**
* Determines if the specified value represents a reference to a parameter.
*
* @param value The value to check
* @returns {boolean} Whether the value represents a reference to a parameter
*/
var referencesParameter = function (value) {
if (nfCommon.isDefinedAndNotNull(value)) {
return value.startsWith('#{') && value.endsWith('}');
}
return false;
};
var containsParameterReference = function (value) {
var paramRefsRegex = /#{[a-zA-Z0-9-_. ]+}/;
return paramRefsRegex.test(value);
};
var getSupportTip = function (isEl, isSupported) {
var supportContainer = $('<div></div>');
var supportTitleContainer = $('<div></div>')
.addClass('mode-hint-tip-title-container')
.appendTo(supportContainer);
if (isSupported) {
$('<div></div>')
.addClass('fa fa-check')
.appendTo(supportTitleContainer);
$(isEl ? EL_SUPPORTED_TITLE : PARAM_SUPPORTED_TITLE)
.addClass('mode-supported')
.appendTo(supportTitleContainer);
var supportDescriptionContainer = $('<div></div>')
.addClass('mode-hint-tip-description-container')
.appendTo(supportContainer);
$(isEl ? EL_SUPPORTED_DESCRIPTION : PARAM_SUPPORTED_DESCRIPTION)
.appendTo(supportDescriptionContainer);
} else {
$('<div></div>')
.addClass('fa fa-ban')
.appendTo(supportTitleContainer);
$(isEl ? EL_UNSUPPORTED_TITLE : PARAM_UNSUPPORTED_TITLE)
.addClass('mode-unsupported')
.appendTo(supportTitleContainer);
}
return supportContainer;
};
var getNfEditor = function (getMode) {
return function (args) {
var scope = this;
var initialValue = '';
var previousValue;
var propertyDescriptor;
var isEmpty;
var wrapper;
var editor;
var tip;
this.init = function () {
var container = $('body');
// get the property descriptor
var gridContainer = $(args.grid.getContainerNode());
var descriptors = gridContainer.data('descriptors');
propertyDescriptor = descriptors[args.item.property];
var mode = getMode(propertyDescriptor);
// determine if this is a sensitive property
var sensitive = nfCommon.isSensitiveProperty(propertyDescriptor);
// record the previous value
previousValue = args.item[args.column.field];
// create the wrapper
wrapper = $('<div></div>')
.addClass('slickgrid-nf-editor')
.css({
'z-index': 14000,
'position': 'absolute',
'padding': '10px 20px',
'overflow': 'hidden',
'border-radius': '2px',
'box-shadow': 'rgba(0, 0, 0, 0.247059) 0px 2px 5px',
'background-color': 'rgb(255, 255, 255)',
'cursor': 'move',
'transform': 'translate3d(0px, 0px, 0px)'
}).draggable({
cancel: '.button, .mode-hint-element, .nf-editor, .string-check-container > *',
containment: 'parent'
}).appendTo(container);
// create the tip
tip = $('<div></div>')
.addClass('mode-hint-tip')
.appendTo(container);
var supportsEl = mode.supportsEl();
var supportsParameterReference = mode.supportsParameterReference();
tip.append(getSupportTip(true, supportsEl));
tip.append(getSupportTip(false, supportsParameterReference));
// create the mode hint
var modeHintContainer = $('<div></div>')
.addClass('mode-hint-container')
.appendTo(wrapper);
var modeHintElement = $('<div></div>')
.addClass('mode-hint-element')
.on('mouseenter', function () {
var wrapperPosition = wrapper.position();
var tipTop = wrapperPosition.top - tip.outerHeight() + 2;
var tipLeft = wrapperPosition.left + wrapper.outerWidth() - tip.outerWidth() + 5;
tip.css({
top: tipTop + 'px',
left: tipLeft + 'px'
});
tip.show();
})
.on('mouseleave', function () {
tip.hide();
})
.appendTo(modeHintContainer);
// el hint
var elModeHintContainer = $('<div></div>')
.addClass('mode-hint')
.appendTo(modeHintElement);
$('<div>EL</div>')
.appendTo(elModeHintContainer);
$('<div></div>')
.addClass('mode-hint-value fa')
.addClass(supportsEl ? 'fa-check' : 'fa-ban')
.appendTo(elModeHintContainer);
// parameter hint
var paramModeHitContainer = $('<div></div>')
.addClass('mode-hint')
.appendTo(modeHintElement);
$('<div>PARAM</div>')
.appendTo(paramModeHitContainer);
$('<div></div>')
.addClass('mode-hint-value fa')
.addClass(supportsParameterReference ? 'fa-check' : 'fa-ban')
.appendTo(paramModeHitContainer);
var editorWidth = Math.max(args.position.width, EDITOR_MIN_WIDTH);
// create the editor
editor = $('<div></div>')
.addClass('nf-editor')
.appendTo(wrapper)
.nfeditor({
languageMode: mode,
width: editorWidth,
minWidth: EDITOR_MIN_WIDTH,
minHeight: EDITOR_MIN_HEIGHT,
resizable: true,
sensitive: sensitive,
escape: function () {
scope.cancel();
},
enter: function () {
scope.save();
}
});
// create the button panel
var stringCheckPanel = $('<div class="string-check-container" />');
stringCheckPanel.appendTo(wrapper);
// build the custom checkbox
isEmpty = $('<div class="nf-checkbox string-check" />')
.on('change', function (event, args) {
// if we are setting as an empty string, disable the editor
if (args.isChecked) {
editor.nfeditor('setValue', '');
editor.nfeditor('setReadOnly', 'nocursor');
} else {
editor.nfeditor('setValue', initialValue);
editor.nfeditor('setReadOnly', false);
}
})
.appendTo(stringCheckPanel);
$('<span class="string-check-label nf-checkbox-label"> Set empty string</span>')
.appendTo(stringCheckPanel);
var ok = $('<div class="button">Ok</div>').css({
'color': '#fff',
'background': '#728E9B'
}).hover(
function () {
$(this).css('background', '#004849');
}, function () {
$(this).css('background', '#728E9B');
}).on('click', scope.save);
var cancel = $('<div class="secondary-button">Cancel</div>').css({
'color': '#004849',
'background': '#E3E8EB'
}).hover(
function () {
$(this).css('background', '#C7D2D7');
}, function () {
$(this).css('background', '#E3E8EB');
}).on('click', scope.cancel);
$('<div></div>').css({
'position': 'relative',
'top': '10px',
'left': '20px',
'width': '212px',
'clear': 'both',
'float': 'right'
}).append(ok).append(cancel).append('<div class="clear"></div>').appendTo(wrapper);
// position and focus
scope.position(args.position);
editor.nfeditor('focus').nfeditor('selectAll');
};
this.save = function () {
args.commitChanges();
};
this.cancel = function () {
editor.nfeditor('setValue', initialValue);
args.cancelChanges();
};
this.hide = function () {
wrapper.hide();
};
this.show = function () {
wrapper.show();
editor.nfeditor('refresh');
};
this.position = function (position) {
wrapper.css({
'top': position.top - 16,
'left': position.left - 42
});
};
this.destroy = function () {
editor.nfeditor('destroy');
wrapper.remove();
tip.remove();
};
this.focus = function () {
editor.nfeditor('focus');
};
this.loadValue = function (item) {
// determine if this is a sensitive property
var isEmptyChecked = false;
var sensitive = nfCommon.isSensitiveProperty(propertyDescriptor);
// determine the value to use when populating the text field
if (nfCommon.isDefinedAndNotNull(item[args.column.field])) {
if (sensitive) {
initialValue = nfCommon.config.sensitiveText;
} else {
initialValue = item[args.column.field];
isEmptyChecked = initialValue === '';
}
}
var checkboxStyle;
if (isEmptyChecked) {
checkboxStyle = 'checkbox-checked';
editor.nfeditor('setReadOnly', 'nocursor');
} else {
checkboxStyle = 'checkbox-unchecked';
}
isEmpty.addClass(checkboxStyle);
editor.nfeditor('setValue', initialValue).nfeditor('selectAll');
};
this.serializeValue = function () {
var value = editor.nfeditor('getValue');
// if the field has been cleared, set the value accordingly
if (value === '') {
// if the user has checked the empty string checkbox, use emtpy string
if (isEmpty.hasClass('checkbox-checked')) {
return '';
}
// otherwise if the property is required
if (nfCommon.isRequiredProperty(propertyDescriptor)) {
if (nfCommon.isBlank(propertyDescriptor.defaultValue)) {
return previousValue;
}
return propertyDescriptor.defaultValue;
}
// if the property is not required, clear the value
return null;
}
// if the field wasn't modified return the previous value
if (editor.nfeditor('isModified') === false) {
return previousValue;
}
// if there is text specified, use that value
return value;
};
this.applyValue = function (item, state) {
item[args.column.field] = state;
};
this.isValueChanged = function () {
return scope.serializeValue() !== previousValue;
};
this.validate = function () {
return {
valid: true,
msg: null
};
};
// initialize the custom long nfel editor
this.init();
};
};
// combo editor
var getComboEditor = function (parametersSupported, loadParameters) {
return function (args) {
var PARAMETER_REFERENCE_OPTION = {
text: 'Reference parameter...',
value: undefined,
optionClass: 'unset'
};
var LOADING_PARAMETERS_OPTION = {
text: 'Loading parameters...',
value: null,
optionClass: 'unset',
disabled: true
};
var CREATE_CONTROLLER_SERVICE_OPTION = {
text: 'Create new service...',
value: 'createControllerService',
optionClass: 'unset'
};
var scope = this;
var allowableValueOptions = [];
var parameterOptions = [];
var initialValue = null;
var wrapper;
var allowableValuesCombo;
var parameterCombo;
var propertyDescriptor;
var parametersLoading = true;
var parametersLoaded;
this.init = function () {
var container = $('body');
// get the property descriptor
var gridContainer = $(args.grid.getContainerNode());
var descriptors = gridContainer.data('descriptors');
propertyDescriptor = descriptors[args.item.property];
// get the options
var propertyContainer = gridContainer.closest('.property-container');
var configurationOptions = propertyContainer.data('options');
// create the wrapper
wrapper = $('<div class="combo-editor"></div>').css({
'z-index': 1999,
'position': 'absolute',
'padding': '10px 20px',
'overflow': 'hidden',
'border-radius': '2px',
'box-shadow': 'rgba(0, 0, 0, 0.247059) 0px 2px 5px',
'background-color': 'rgb(255, 255, 255)',
'cursor': 'move',
'transform': 'translate3d(0px, 0px, 0px)'
}).draggable({
cancel: '.button, .combo',
containment: 'parent'
}).appendTo(container);
// check for allowable values which will drive which editor to use
var allowableValues = nfCommon.getAllowableValues(propertyDescriptor);
// show the allowable values
if ($.isArray(allowableValues)) {
$.each(allowableValues, function (i, allowableValueEntity) {
var allowableValue = allowableValueEntity.allowableValue;
allowableValueOptions.push({
text: allowableValue.displayName,
value: allowableValue.value,
disabled: allowableValueEntity.canRead === false && allowableValue.value !== args.item['previousValue'],
description: nfCommon.escapeHtml(allowableValue.description)
});
});
}
if (propertyDescriptor.required === false) {
allowableValueOptions.push({
text: 'No value',
value: null,
optionClass: 'unset'
});
}
// if this does not represent an identify a controller service
if (parametersSupported) {
allowableValueOptions.push(PARAMETER_REFERENCE_OPTION);
}
// ensure the options there is at least one option
if (allowableValueOptions.length === 0) {
allowableValueOptions.push({
text: 'No value',
value: null,
optionClass: 'unset',
disabled: true
});
}
// if this descriptor identifies a controller service, provide a way to create one
if (nfCommon.isDefinedAndNotNull(propertyDescriptor.identifiesControllerService)) {
allowableValueOptions.push(CREATE_CONTROLLER_SERVICE_OPTION);
}
// determine the max height
var position = args.position;
var windowHeight = $(window).height();
var maxHeight = windowHeight - position.bottom - 16;
// determine the width
var comboWidth = Math.max(position.width - 16, COMBO_MIN_WIDTH);
// build the combo field
allowableValuesCombo = $('<div class="value-combo combo"></div>').combo({
options: allowableValueOptions,
maxHeight: maxHeight,
select: function (option) {
var promptForControllerService = function () {
// cancel the current edit
scope.cancel();
// prompt for the new service type
promptForNewControllerService(gridContainer, args.grid, args.item, propertyDescriptor.identifiesControllerService, propertyDescriptor.identifiesControllerServiceBundle, configurationOptions);
};
if (parametersSupported) {
if (nfCommon.isDefinedAndNotNull(parameterCombo)) {
if (option === PARAMETER_REFERENCE_OPTION) {
parameterCombo.show();
} else {
parameterCombo.hide();
if (option === CREATE_CONTROLLER_SERVICE_OPTION) {
promptForControllerService();
}
}
}
} else if (option === CREATE_CONTROLLER_SERVICE_OPTION) {
promptForControllerService()
}
}
}).css({
'margin-top': '10px',
'margin-bottom': '10px',
'width': comboWidth + 'px'
}).appendTo(wrapper);
if (parametersSupported) {
// create the parameter combo
parameterCombo = $('<div class="value-combo combo"></div>')
.combo({
options: [LOADING_PARAMETERS_OPTION],
maxHeight: maxHeight
})
.css({
'margin-bottom': '10px',
'width': comboWidth + 'px'
})
.appendTo(wrapper);
// load the parameters
parametersLoaded = new $.Deferred(function (deferred) {
loadParameters(propertyDescriptor, function (parameterListing) {
var sortedParams = _.sortBy(parameterListing, 'name');
sortedParams.forEach(function (parameter) {
parameterOptions.push({
text: parameter.name,
value: '#{' + parameter.name + '}',
description: nfCommon.escapeHtml(parameter.description)
});
});
// create the parameter combo
parameterCombo.combo('destroy').combo({
options: parameterOptions,
maxHeight: maxHeight
});
deferred.resolve();
parametersLoading = false;
});
}).promise();
}
// add buttons for handling user input
var cancel = $('<div class="secondary-button">Cancel</div>').css({
'color': '#004849',
'background': '#E3E8EB'
}).hover(
function () {
$(this).css('background', '#C7D2D7');
}, function () {
$(this).css('background', '#E3E8EB');
}).on('click', scope.cancel);
var ok = $('<div class="button">Ok</div>').css({
'color': '#fff',
'background': '#728E9B'
}).hover(
function () {
$(this).css('background', '#004849');
}, function () {
$(this).css('background', '#728E9B');
}).on('click', scope.save);
$('<div></div>').css({
'position': 'relative',
'top': '10px',
'left': '20px',
'width': '212px',
'float': 'right'
}).append(ok).append(cancel).appendTo(wrapper);
// position and focus
scope.position(position);
};
this.save = function () {
args.commitChanges();
};
this.cancel = function () {
args.cancelChanges();
};
this.hide = function () {
wrapper.hide();
};
this.show = function () {
wrapper.show();
};
this.position = function (position) {
wrapper.css({
'top': position.top - 24,
'left': position.left - 20
});
};
this.destroy = function () {
if (parametersSupported) {
parameterCombo.combo('destroy');
}
allowableValuesCombo.combo('destroy');
wrapper.remove();
allowableValueOptions.length = 0;
parameterOptions.length = 0;
};
this.focus = function () {
};
this.loadValue = function (item) {
var configuredValue;
if (!nfCommon.isUndefined(item.value)) {
configuredValue = item.value;
} else if (nfCommon.isDefinedAndNotNull(propertyDescriptor.defaultValue)) {
configuredValue = propertyDescriptor.defaultValue;
}
// if there is a value determine how to populate the editor
if (!nfCommon.isUndefined(configuredValue)) {
initialValue = configuredValue;
// determine if the initial value is an allowable value
var selectedOption = allowableValueOptions.find(function (option) {
return initialValue === option.value;
});
// if the initial value is an allowable value select it, otherwise see if it is a parameter reference
if (!nfCommon.isUndefined(selectedOption)) {
allowableValuesCombo.combo('setSelectedOption', selectedOption);
} else if (parametersSupported && referencesParameter(initialValue)) {
// select the option for reference a parameter
allowableValuesCombo.combo('setSelectedOption', PARAMETER_REFERENCE_OPTION);
// construct the initial option
var initialOption = {
value: initialValue
};
// populate the parameter combo with the parameter reference
if (parametersLoading) {
parametersLoaded.then(function () {
parameterCombo.combo('setSelectedOption', initialOption);
});
} else {
parameterCombo.combo('setSelectedOption', initialOption);
}
} else {
// select the first option
allowableValuesCombo.combo('setSelectedOption', allowableValueOptions[0]);
}
} else {
// select the first option
allowableValuesCombo.combo('setSelectedOption', allowableValueOptions[0]);
}
};
this.serializeValue = function () {
var selectedOption = allowableValuesCombo.combo('getSelectedOption');
var selectedValue = selectedOption.value;
// if the value is undefined, it indicates that the value in the editor references a parameter
if (parametersSupported && _.isUndefined(selectedValue)) {
selectedOption = parameterCombo.combo('getSelectedOption');
// if the parameters are still loading, revert to the initial value, otherwise use the selected parameter
if (selectedOption === LOADING_PARAMETERS_OPTION) {
selectedValue = initialValue;
} else {
selectedValue = selectedOption.value;
}
}
return selectedValue;
};
this.applyValue = function (item, state) {
item[args.column.field] = state;
};
this.isValueChanged = function () {
var configuredValue = scope.serializeValue();
return configuredValue !== initialValue;
};
this.validate = function () {
return {
valid: true,
msg: null
};
};
// initialize the custom long text editor
this.init();
};
};
/**
* Shows the property value for the specified row and cell.
*
* @param {type} propertyGrid
* @param {type} descriptors
* @param {type} row
* @param {type} cell
*/
var showPropertyValue = function (propertyGrid, descriptors, row, cell) {
// remove any currently open detail dialogs
nfUniversalCapture.removeAllPropertyDetailDialogs();
// get the property in question
var propertyData = propertyGrid.getData();
var property = propertyData.getItem(row);
// ensure there is a value
if (nfCommon.isDefinedAndNotNull(property.value)) {
// get the descriptor to insert the description tooltip
var propertyDescriptor = descriptors[property.property];
// ensure we're not dealing with a sensitive property
if (!nfCommon.isSensitiveProperty(propertyDescriptor)) {
// get details about the location of the cell
var cellNode = $(propertyGrid.getCellNode(row, cell));
var offset = cellNode.offset();
// create the wrapper
var wrapper = $('<div class="property-detail"></div>').css({
'z-index': 1999,
'position': 'absolute',
'padding': '10px 20px',
'overflow': 'hidden',
'border-radius': '2px',
'box-shadow': 'rgba(0, 0, 0, 0.247059) 0px 2px 5px',
'background-color': 'rgb(255, 255, 255)',
'cursor': 'move',
'transform': 'translate3d(0px, 0px, 0px)',
'top': offset.top - 24,
'left': offset.left - 20
}).appendTo('body');
var allowableValues = nfCommon.getAllowableValues(propertyDescriptor);
if ($.isArray(allowableValues)) {
// prevent dragging over the combo
wrapper.draggable({
cancel: '.button, .combo',
containment: 'parent'
});
// create the read only options
var options = [];
$.each(allowableValues, function (i, allowableValueEntity) {
var allowableValue = allowableValueEntity.allowableValue;
options.push({
text: allowableValue.displayName,
value: allowableValue.value,
description: nfCommon.escapeHtml(allowableValue.description),
disabled: true
});
});
// ensure the options there is at least one option
if (options.length === 0) {
options.push({
text: 'No value',
value: null,
optionClass: 'unset',
disabled: true
});
}
// determine the max height
var windowHeight = $(window).height();
var maxHeight = windowHeight - (offset.top + cellNode.height()) - 16;
var width = cellNode.width() - 16;
// build the combo field
$('<div class="value-combo combo"></div>').css({
'width': width,
'margin-top': '10px',
'margin-bottom': '10px'
}).combo({
options: options,
maxHeight: maxHeight,
selectedOption: {
value: property.value
}
}).appendTo(wrapper);
$('<div class="button">Ok</div>').css({
'position': 'relative',
'top': '10px',
'left': '20px'
}).hover(
function () {
$(this).css('background', '#004849');
}, function () {
$(this).css('background', '#728E9B');
}).on('click', function () {
wrapper.hide().remove();
}).appendTo(wrapper);
} else {
var editor = null;
// so the nfel editor is appropriate
if (nfCommon.supportsEl(propertyDescriptor)) {
// prevent dragging over the nf editor
wrapper.css({
'z-index': 1999,
'position': 'absolute',
'padding': '10px 20px',
'overflow': 'hidden',
'border-radius': '2px',
'box-shadow': 'rgba(0, 0, 0, 0.247059) 0px 2px 5px',
'background-color': 'rgb(255, 255, 255)',
'cursor': 'move',
'transform': 'translate3d(0px, 0px, 0px)',
'top': offset.top - 22,
'left': offset.left - 43
}).draggable({
cancel: 'input, textarea, pre, .button, .nf-editor',
containment: 'parent'
});
// create the editor
editor = $('<div></div>').addClass('nf-editor').appendTo(wrapper).nfeditor({
languageMode: nf.nfel,
width: cellNode.width(),
content: property.value,
minWidth: 175,
minHeight: 100,
readOnly: true,
resizable: true,
escape: function () {
cleanUp();
}
});
} else {
wrapper.css({
'z-index': 1999,
'position': 'absolute',
'padding': '10px 20px',
'overflow': 'hidden',
'border-radius': '2px',
'box-shadow': 'rgba(0, 0, 0, 0.247059) 0px 2px 5px',
'background-color': 'rgb(255, 255, 255)',
'cursor': 'move',
'transform': 'translate3d(0px, 0px, 0px)',
'top': offset.top - 26,
'left': offset.left - 20
});
// create the input field
$('<textarea hidefocus rows="5" readonly="readonly" />').css({
'height': '80px',
'resize': 'both',
'width': cellNode.width() + 'px',
'margin': '10px 0px',
'white-space': 'pre'
}).text(property.value).on('keydown', function (evt) {
if (evt.which === $.ui.keyCode.ESCAPE) {
cleanUp();
evt.stopImmediatePropagation();
evt.preventDefault();
}
}).appendTo(wrapper);
// prevent dragging over standard components
wrapper.draggable({
containment: 'parent'
});
}
var cleanUp = function () {
// clean up the editor
if (editor !== null) {
editor.nfeditor('destroy');
}
// clean up the rest
wrapper.hide().remove();
};
// add an ok button that will remove the entire pop up
var ok = $('<div class="button">Ok</div>').css({
'position': 'relative',
'top': '10px',
'left': '20px'
}).hover(
function () {
$(this).css('background', '#004849');
}, function () {
$(this).css('background', '#728E9B');
}).on('click', function () {
cleanUp();
});
$('<div></div>').append(ok).append('<div class="clear"></div>').appendTo(wrapper);
}
}
}
};
/**
* Gets the available controller services that implement the specified type and
* prompts the user to create one.
*
* @param {jQuery} gridContainer The grid container
* @param {slickgrid} grid The grid
* @param {object} item The item
* @param {string} serviceType The type of service to create
* @param {object} bundle The bundle the service impl should implement
* @param {object} configurationOptions The configuration options
*/
var promptForNewControllerService = function (gridContainer, grid, item, serviceType, bundle, configurationOptions) {
$.ajax({
type: 'GET',
url: '../nifi-api/flow/controller-service-types',
data: {
'serviceType': serviceType,
'serviceBundleGroup': bundle.group,
'serviceBundleArtifact': bundle.artifact,
'serviceBundleVersion': bundle.version
},
dataType: 'json'
}).done(function (response) {
// get the property descriptor
var descriptors = gridContainer.data('descriptors');
var propertyDescriptor = descriptors[item.property];
var controllerServiceLookup = d3.map();
var options = [];
$.each(response.controllerServiceTypes, function (i, controllerServiceType) {
controllerServiceLookup.set(i, controllerServiceType);
options.push({
text: nfCommon.formatType(controllerServiceType),
value: i,
description: nfCommon.escapeHtml(controllerServiceType.description)
});
});
// ensure there are some applicable controller services
if (options.length === 0) {
nfDialog.showOkDialog({
headerText: 'Controller Service',
dialogContent: 'No controller service types found that are applicable for this property.'
});
} else {
var newControllerServiceDialogMarkup =
'<div id="new-inline-controller-service-dialog" class="hidden dialog medium-dialog cancellable">' +
'<div class="dialog-content">' +
'<div>' +
'<div class="setting-name">Requires Controller Service</div>' +
'<div class="setting-field">' +
'<div class="new-inline-controller-service-requirement"></div>' +
'</div>' +
'</div>' +
'<div>' +
'<div class="setting-name">Compatible Controller Services</div>' +
'<div class="setting-field">' +
'<div class="new-inline-controller-service-combo"></div>' +
'</div>' +
'</div>' +
'<div>' +
'<div class="setting-name">Controller Service Name</div>' +
'<div class="setting-field">' +
'<input type="text" class="new-inline-controller-service-name"/>' +
'</div>' +
'</div>' +
'<div>' +
'<div class="setting-name">Bundle</div>' +
'<div class="setting-field">' +
'<div class="new-inline-controller-service-bundle"></div>' +
'</div>' +
'</div>' +
'<div>' +
'<div class="setting-name">Tags</div>' +
'<div class="setting-field">' +
'<div class="new-inline-controller-service-tags"></div>' +
'</div>' +
'</div>' +
'<div>' +
'<div class="setting-name">Description</div>' +
'<div class="setting-field">' +
'<div class="new-inline-controller-service-description"></div>' +
'</div>' +
'</div>' +
'</div>' +
'</div>';
var newControllerServiceDialog = $(newControllerServiceDialogMarkup).appendTo(configurationOptions.dialogContainer);
var newControllerServiceRequirement = newControllerServiceDialog.find('div.new-inline-controller-service-requirement');
var newControllerServiceCombo = newControllerServiceDialog.find('div.new-inline-controller-service-combo');
var newControllerServiceNameInput = newControllerServiceDialog.find('input.new-inline-controller-service-name');
var newControllerServiceBundle = newControllerServiceDialog.find('div.new-inline-controller-service-bundle');
var newControllerServiceTags = newControllerServiceDialog.find('div.new-inline-controller-service-tags');
var newControllerServiceDescription = newControllerServiceDialog.find('div.new-inline-controller-service-description');
// include the required service
var formattedType = nfCommon.formatType({
'type': propertyDescriptor.identifiesControllerService,
'bundle': propertyDescriptor.identifiesControllerServiceBundle
});
var formattedBundle = nfCommon.formatBundle(propertyDescriptor.identifiesControllerServiceBundle);
newControllerServiceRequirement.text(formattedType + ' from ' + formattedBundle);
// sort the text version visible to the user
options.sort(function (a, b) {
var aCS = controllerServiceLookup.get(a.value);
var bCS = controllerServiceLookup.get(b.value);
var aName = nfCommon.substringAfterLast(aCS.type, '.');
var bName = nfCommon.substringAfterLast(bCS.type, '.');
return aName === bName ? -nfCommon.sortVersion(aCS.bundle.version, bCS.bundle.version) : aName > bName ? 1 : -1;
});
// default to the first service
var newControllerServiceNameDefault = nfCommon.formatClassName(controllerServiceLookup.get(0));
newControllerServiceNameInput.val(newControllerServiceNameDefault);
// build the combo field
newControllerServiceCombo.combo({
options: options,
select: function (option) {
// set the service details
var service = controllerServiceLookup.get(option.value);
newControllerServiceBundle.text(nfCommon.formatBundle(service.bundle));
newControllerServiceTags.text(service.tags.join(', '));
newControllerServiceDescription.text(service.description);
// update default when no edits were made
if (newControllerServiceNameDefault === newControllerServiceNameInput.val().trim()) {
newControllerServiceNameDefault = nfCommon.formatClassName(service);
newControllerServiceNameInput.val(newControllerServiceNameDefault);
}
}
});
newControllerServiceDialog.modal({
headerText: 'Add Controller Service',
scrollableContentStyle: 'scrollable',
buttons: [{
buttonText: 'Create',
color: {
base: '#728E9B',
hover: '#004849',
text: '#ffffff'
},
handler: {
click: function () {
create();
}
}
},
{
buttonText: 'Cancel',
color: {
base: '#E3E8EB',
hover: '#C7D2D7',
text: '#004849'
},
handler: {
click: function () {
cancel();
}
}
}]
});
var create = function () {
var newControllerServiceKey = newControllerServiceCombo.combo('getSelectedOption').value;
var newControllerServiceType = controllerServiceLookup.get(newControllerServiceKey);
var newControllerServiceName = newControllerServiceNameInput.val();
// build the controller service entity
var controllerServiceEntity = {
'revision': nfClient.getRevision({
'revision': {
'version': 0,
}
}),
'disconnectedNodeAcknowledged': nfStorage.isDisconnectionAcknowledged(),
'component': {
'type': newControllerServiceType.type,
'bundle': newControllerServiceType.bundle
}
};
// set custom name when specified
if (newControllerServiceName.trim() !== '') {
controllerServiceEntity.component.name = newControllerServiceName.trim();
}
// determine the appropriate uri for creating the controller service
var uri = '../nifi-api/controller/controller-services';
if (nfCommon.isDefinedAndNotNull(groupId)) {
uri = '../nifi-api/process-groups/' + encodeURIComponent(groupId) + '/controller-services';
}
// add the new controller service
$.ajax({
type: 'POST',
url: uri,
data: JSON.stringify(controllerServiceEntity),
dataType: 'json',
contentType: 'application/json'
}).done(function (response) {
// load the descriptor and update the property
// Controller Service dynamic property descriptors will not be marked as sensitive
configurationOptions.descriptorDeferred(item.property, false).done(function (descriptorResponse) {
var descriptor = descriptorResponse.propertyDescriptor;
// store the descriptor for use later
var descriptors = gridContainer.data('descriptors');
if (!nfCommon.isUndefined(descriptors)) {
descriptors[descriptor.name] = descriptor;
}
// add a row for the new property
var data = grid.getData();
data.updateItem(item.id, $.extend(item, {
value: response.component.id
}));
// close the dialog
newControllerServiceDialog.modal('hide');
});
// invoke callback if necessary
if (typeof configurationOptions.controllerServiceCreatedDeferred === 'function') {
configurationOptions.controllerServiceCreatedDeferred(response);
}
}).fail(nfErrorHandler.handleAjaxError);
};
var cancel = function () {
newControllerServiceDialog.modal('hide');
};
newControllerServiceDialog.modal('show');
}
}).fail(nfErrorHandler.handleAjaxError);
};
var initPropertiesTable = function (table, options) {
// function for closing the dialog
var closeDialog = function () {
// close the dialog
var dialog = table.closest('.dialog');
if (dialog.hasClass('modal')) {
dialog.modal('hide');
} else {
dialog.hide();
}
}
// function for formatting the property name
var nameFormatter = function (row, cell, value, columnDef, dataContext) {
var nameWidthOffset = 30;
var cellContent = $('<div></div>');
// format the contents
var formattedValue = $('<span/>').addClass('table-cell').text(value).appendTo(cellContent);
if (dataContext.type === 'required') {
formattedValue.addClass('required');
}
// get the property descriptor
var descriptors = table.data('descriptors');
var propertyDescriptor = descriptors[dataContext.property];
// show the property description if applicable
if (nfCommon.isDefinedAndNotNull(propertyDescriptor)) {
if (!nfCommon.isBlank(propertyDescriptor.description) || !nfCommon.isBlank(propertyDescriptor.defaultValue) || !nfCommon.isBlank(propertyDescriptor.supportsEl)) {
$('<div class="fa fa-question-circle" alt="Info" style="float: right;"></div>').appendTo(cellContent);
$('<span class="hidden property-descriptor-name"></span>').text(dataContext.property).appendTo(cellContent);
nameWidthOffset = 46; // 10 + icon width (10) + icon margin (6) + padding (20)
}
}
// adjust the width accordingly
formattedValue.width(columnDef.width - nameWidthOffset).ellipsis();
// return the cell content
return cellContent.html();
};
// function for formatting the property value
var valueFormatter = function (row, cell, value, columnDef, dataContext) {
var valueMarkup;
var valueWidthOffset = 0;
if (nfCommon.isDefinedAndNotNull(value)) {
// get the property descriptor
var descriptors = table.data('descriptors');
var propertyDescriptor = descriptors[dataContext.property];
// determine if the property is sensitive
if (nfCommon.isSensitiveProperty(propertyDescriptor)) {
valueMarkup = '<span class="table-cell sensitive">Sensitive value set</span>';
} else {
var resolvedAllowableValue = false;
// if there are allowable values, attempt to swap out for the display name
var allowableValues = nfCommon.getAllowableValues(propertyDescriptor);
if ($.isArray(allowableValues)) {
$.each(allowableValues, function (_, allowableValueEntity) {
var allowableValue = allowableValueEntity.allowableValue;
if (value === allowableValue.value) {
value = allowableValue.displayName;
resolvedAllowableValue = true;
return false;
}
});
}
if (value === '') {
valueMarkup = '<span class="table-cell blank">Empty string set</span>';
} else {
valueWidthOffset = 10;
// check for multi-line
if (nfCommon.isMultiLine(value)) {
valueMarkup = '<div class="table-cell value"><div class="ellipsis-white-space-pre multi-line-clamp-ellipsis">' + nfCommon.escapeHtml(value) + '</div></div>';
} else {
valueMarkup = '<div class="table-cell value"><div class="ellipsis-white-space-pre">' + nfCommon.escapeHtml(value) + '</div></div>';
}
// check for leading or trailing whitespace
if (nfCommon.hasLeadTrailWhitespace(value)) {
valueMarkup += '<div class="fa fa-info" alt="Info" style="float: right;"></div>';
valueWidthOffset = 20;
}
}
}
} else {
valueMarkup = '<span class="unset">No value set</span>';
}
// format the contents
var content = $(valueMarkup);
if (dataContext.type === 'required') {
content.addClass('required');
}
var contentValue = content.find('.ellipsis-white-space-pre');
contentValue.attr('title', contentValue.text()).width(columnDef.width - 10 - valueWidthOffset);
// return the appropriate markup
return $('<div />').append(content).html();
};
var propertyColumns = [
{
id: 'property',
field: 'displayName',
name: 'Property',
sortable: false,
resizable: true,
rerenderOnResize: true,
formatter: nameFormatter
},
{
id: 'value',
field: 'value',
name: 'Value',
sortable: false,
resizable: true,
cssClass: 'pointer',
rerenderOnResize: true,
formatter: valueFormatter
}
];
// custom formatter for the actions column
var actionFormatter = function (row, cell, value, columnDef, dataContext) {
var markup = '';
// get the property descriptor
var descriptors = table.data('descriptors');
var propertyDescriptor = descriptors[dataContext.property];
var identifiesControllerService = nfCommon.isDefinedAndNotNull(propertyDescriptor.identifiesControllerService);
var isConfigured = nfCommon.isDefinedAndNotNull(dataContext.value);
// check to see if we should provide a button for going to a controller service
if (identifiesControllerService && isConfigured && (options.supportsGoTo === true)) {
// ensure the configured value is referencing a valid service
$.each(propertyDescriptor.allowableValues, function (_, allowableValueEntity) {
var allowableValue = allowableValueEntity.allowableValue;
if (allowableValue.value === dataContext.value) {
markup += '<div class="pointer go-to-service fa fa-long-arrow-right" title="Go To"></div>';
return false;
}
});
}
var referencesParam = containsParameterReference(dataContext.value);
var canConvertPropertyToParam = false;
var canReadParamContext = false;
if (_.isFunction(options.getParameterContext)) {
var paramContext = options.getParameterContext(groupId);
var canWriteParamContext = _.get(paramContext, 'permissions.canWrite', false);
canReadParamContext = _.get(paramContext, 'permissions.canRead', false);
canConvertPropertyToParam = canWriteParamContext && canReadParamContext;
}
if (referencesParam && canReadParamContext) {
markup += '<div title="Go to parameter" class="go-to-parameter pointer fa fa-long-arrow-right"></div>';
}
if (options.readOnly !== true) {
if (canConvertPropertyToParam && !referencesParam) {
markup += '<div title="Convert to parameter" class="convert-to-parameter pointer fa fa-level-up"></div>';
}
// allow user defined properties to be removed
if (dataContext.type === 'userDefined') {
markup += '<div title="Delete" class="delete-property pointer fa fa-trash"></div>';
}
}
return markup;
};
propertyColumns.push(
{
id: "actions",
name: " ",
minWidth: 20,
width: 20,
formatter: actionFormatter
});
var propertyConfigurationOptions = {
autosizeColsMode: Slick.GridAutosizeColsMode.LegacyForceFit,
enableTextSelectionOnCells: true,
enableCellNavigation: true,
enableColumnReorder: false,
editable: options.readOnly !== true,
enableAddRow: false,
autoEdit: false,
rowHeight: 24
};
// initialize the dataview
var propertyData = new Slick.Data.DataView({
inlineFilters: false
});
propertyData.setItems([]);
propertyData.setFilterArgs({
searchString: '',
property: 'hidden'
});
propertyData.setFilter(filter);
propertyData.getItemMetadata = function (index) {
var item = propertyData.getItem(index);
// get the property descriptor
var descriptors = table.data('descriptors');
var propertyDescriptor = descriptors[item.property];
// sets the available parameters for the specified property descriptor
var loadParameters = function (propertyDescriptor, parameterDeferred, setParameters) {
parameterDeferred(propertyDescriptor, groupId).done(function (parameters) {
setParameters(parameters);
});
};
var parametersSupported = typeof options.parameterDeferred === 'function';
// support el if specified or unsure yet (likely a dynamic property)
if (nfCommon.isUndefinedOrNull(propertyDescriptor) || nfCommon.supportsEl(propertyDescriptor)) {
return {
columns: {
value: {
editor: getNfEditor(function (propertyDescriptor) {
if (parametersSupported) {
// set the available parameters
nf.nfel.enableParameters();
loadParameters(propertyDescriptor, options.parameterDeferred, nf.nfel.setParameters);
} else {
nf.nfel.disableParameters();
}
return nf.nfel;
})
}
}
};
} else {
// check for allowable values which will drive which editor to use
var allowableValues = nfCommon.getAllowableValues(propertyDescriptor);
if ($.isArray(allowableValues)) {
return {
columns: {
value: {
editor: getComboEditor(parametersSupported, function (propertyDescriptor, setParameters) {
if (parametersSupported) {
// set the available parameters
loadParameters(propertyDescriptor, options.parameterDeferred, setParameters);
}
})
}
}
};
} else {
return {
columns: {
value: {
editor: getNfEditor(function (propertyDescriptor) {
if (parametersSupported) {
// set the available parameters
nf.nfpr.enableParameters()
loadParameters(propertyDescriptor, options.parameterDeferred, nf.nfpr.setParameters);
} else {
nf.nfpr.disableParameters();
}
return nf.nfpr;
})
}
}
};
}
}
};
var goToControllerService = function (property) {
$.ajax({
type: 'GET',
url: '../nifi-api/controller-services/' + encodeURIComponent(property.value),
dataType: 'json',
data: {
uiOnly: true
}
}).done(function (controllerServiceEntity) {
// close the dialog
closeDialog();
var controllerService = controllerServiceEntity.component;
$.Deferred(function (deferred) {
if (nfCommon.isDefinedAndNotNull(controllerService.parentGroupId)) {
nfProcessGroup.enterGroup(controllerService.parentGroupId).done(function () {
if ($('#process-group-configuration').is(':visible')) {
nfProcessGroupConfiguration.loadConfiguration(controllerService.parentGroupId).done(function () {
deferred.resolve();
});
} else {
nfProcessGroupConfiguration.showConfiguration(controllerService.parentGroupId).done(function () {
deferred.resolve();
});
}
});
} else {
if ($('#settings').is(':visible')) {
// reload the settings
nfSettings.loadSettings().done(function () {
deferred.resolve();
});
} else {
// reload the settings and show
nfSettings.showSettings().done(function () {
deferred.resolve();
});
}
}
}).done(function () {
if (nfCommon.isDefinedAndNotNull(controllerService.parentGroupId)) {
nfProcessGroupConfiguration.selectControllerService(property.value);
} else {
nfSettings.selectControllerService(property.value);
}
});
}).fail(nfErrorHandler.handleAjaxError);
};
// initialize the grid
var propertyGrid = new Slick.Grid(table, propertyData, propertyColumns, propertyConfigurationOptions);
propertyGrid.setSelectionModel(new Slick.RowSelectionModel());
propertyGrid.onClick.subscribe(function (e, args) {
if (propertyGrid.getColumns()[args.cell].id === 'value') {
if (options.readOnly === true) {
var descriptors = table.data('descriptors');
showPropertyValue(propertyGrid, descriptors, args.row, args.cell);
} else {
// edits the clicked cell
propertyGrid.gotoCell(args.row, args.cell, true);
}
// prevents standard edit logic
e.stopImmediatePropagation();
} else if (propertyGrid.getColumns()[args.cell].id === 'actions') {
var property = propertyData.getItem(args.row);
var target = $(e.target);
if (target.hasClass('delete-property')) {
// mark the property in question for removal and refresh the table
propertyData.updateItem(property.id, $.extend(property, {
hidden: true
}));
// Delete property descriptor
var descriptors = table.data('descriptors');
delete descriptors[property.property];
// prevents standard edit logic
e.stopImmediatePropagation();
} else if (target.hasClass('go-to-service')) {
if (options.readOnly === true) {
goToControllerService(property);
} else {
// load the property descriptor if possible
if (typeof options.goToServiceDeferred === 'function') {
options.goToServiceDeferred().done(function () {
goToControllerService(property);
});
}
}
} else if (target.hasClass('convert-to-parameter')) {
var parameterContext;
var canConvertPropertyToParam = false;
if (_.isFunction(options.getParameterContext)) {
parameterContext = options.getParameterContext(groupId);
var canWriteParamContext = _.get(parameterContext, 'permissions.canWrite', false);
var canReadParamContext = _.get(parameterContext, 'permissions.canRead', false);
canConvertPropertyToParam = canWriteParamContext && canReadParamContext;
}
if (options.readOnly !== true && canConvertPropertyToParam) {
var descriptors = table.data('descriptors');
var propertyDescriptor = descriptors[property.property];
nfParameterContexts.convertPropertyToParameter(property, propertyDescriptor, parameterContext.id)
.done(function (parameter) {
var updatedItem = _.extend({}, property, {
previousValue: property.value,
value: '#{' + parameter.name + '}'
});
// set the property value to the reference the parameter that was created
propertyData.updateItem(property.id, updatedItem);
});
}
} else if (target.hasClass('go-to-parameter')) {
var parameterContext;
if (_.isFunction(options.getParameterContext)) {
parameterContext = options.getParameterContext(groupId);
var canReadParamContext = _.get(parameterContext, 'permissions.canRead', false);
if (canReadParamContext && !_.isNil(property.value)) {
// get the reference parameter
var paramRefsRegex = /#{([a-zA-Z0-9-_. ]+)}/;
var result = property.value.match(paramRefsRegex);
if (!_.isEmpty(result) && result.length === 2) {
// close the dialog since we are sending the user to the parameter context
closeDialog();
var parameterName = result[1];
nfParameterContexts.showParameterContext(parameterContext.id, null, parameterName);
}
}
}
}
}
});
propertyGrid.onKeyDown.subscribe(function (e, args) {
if (e.which === $.ui.keyCode.ESCAPE) {
var editorLock = propertyGrid.getEditorLock();
if (editorLock.isActive()) {
editorLock.cancelCurrentEdit();
// prevents standard cancel logic - standard logic does
// not stop propagation when escape is pressed
e.stopImmediatePropagation();
e.preventDefault();
}
}
});
if (options.readOnly !== true) {
propertyGrid.onBeforeEditCell.subscribe(function (e, args) {
nfCommon.cleanUpTooltips(table, 'div.fa-question-circle, div.fa-info');
});
propertyGrid.onBeforeCellEditorDestroy.subscribe(function (e, args) {
setTimeout(function() {
var propertyData = propertyGrid.getData();
// Get the default properties object
var descriptors = table.data('descriptors');
// Get the rows from the table
var items = propertyData.getItems();
// Loop over each row
$.each(items, function (id, item) {
// Get the property descriptor object
var descriptor = descriptors[item.property];
var dependent = false;
// Check if descriptor is a dynamic property
if (!descriptor.dynamic) {
var hidden = false;
// Check for dependencies
if (descriptor.dependencies.length > 0) {
// Loop over each dependency
$.each(descriptor.dependencies, function (i, dependency) {
// It is sufficient to have found a single instance of not meeting the
// requirement for a dependent value in order to hide a property
if (hidden) {
return false;
}
// Check the row's dependent values against all other row's current values to determine hidden state
$.each(items, function (k, property) {
if (property.property === dependency.propertyName) {
dependent = true;
if (property.hidden === false) {
// Get the current property value to compare with the dependent value
var propertyValue = property.value;
// Test the dependentValues array against the current value of the property
// If not, then mark the current property hidden attribute is true
if (propertyValue != null) {
if (dependency.hasOwnProperty("dependentValues")) {
hidden = !dependency.dependentValues.includes(propertyValue);
}
} else {
hidden = true;
}
} else {
hidden = true;
}
if (hidden) {
// It is sufficient to have found a single instance of not meeting the
// requirement for a dependent value in order to hide a property
return false;
}
}
})
});
}
} else {
hidden = item.hidden;
}
propertyData.beginUpdate();
propertyData.updateItem(id, $.extend(item, {
hidden: hidden,
dependent: dependent
}));
propertyData.endUpdate();
// Reset hidden property
hidden = false;
});
propertyGrid.resizeCanvas();
}, 50);
});
}
// wire up the dataview to the grid
propertyData.onRowCountChanged.subscribe(function (e, args) {
propertyGrid.updateRowCount();
propertyGrid.render();
});
propertyData.onRowsChanged.subscribe(function (e, args) {
propertyGrid.invalidateRows(args.rows);
propertyGrid.render();
});
// hold onto an instance of the grid and listen for mouse events to add tooltips where appropriate
table.data('gridInstance', propertyGrid).on('mouseenter', 'div.slick-cell', function (e) {
var infoIcon = $(this).find('div.fa-question-circle');
if (infoIcon.length && !infoIcon.data('qtip')) {
var property = $(this).find('span.property-descriptor-name').text();
// get the property descriptor
var descriptors = table.data('descriptors');
var propertyDescriptor = descriptors[property];
// get the history
var history = table.data('history');
var propertyHistory;
if (history) {
propertyHistory = history[property];
}
// format the tooltip
var propertyTooltip = nfCommon.formatPropertyTooltip(propertyDescriptor, propertyHistory);
if (nfCommon.isDefinedAndNotNull(propertyTooltip)) {
infoIcon.qtip($.extend({},
nfCommon.config.tooltipConfig,
{
content: propertyTooltip
}));
}
}
var whitespaceIcon = $(this).find('div.fa-info');
if (whitespaceIcon.length && !whitespaceIcon.data('qtip')) {
var whitespaceTooltip = nfCommon.formatWhitespaceTooltip();
whitespaceIcon.qtip($.extend({},
nfCommon.config.tooltipConfig,
{
content: whitespaceTooltip
}));
}
});
};
var saveRow = function (table) {
// get the property grid to commit the current edit
var propertyGrid = table.data('gridInstance');
if (nfCommon.isDefinedAndNotNull(propertyGrid)) {
var editController = propertyGrid.getEditController();
editController.commitCurrentEdit();
}
};
var marshalProperties = function (table) {
var properties = {};
var propertyGrid = table.data('gridInstance');
var propertyData = propertyGrid.getData();
$.each(propertyData.getItems(), function () {
if (this.hidden === true && !(this.dependent === true)) {
// hidden properties were removed by the user, clear the value
properties[this.property] = null;
} else if (this.value !== this.previousValue) {
// the value has changed
properties[this.property] = this.value;
}
});
return properties;
};
var getSensitiveDynamicPropertyNames = function (table) {
var sensitiveDynamicPropertyNames = [];
var descriptors = table.data('descriptors');
$.each(descriptors, function () {
if (nfCommon.isSensitiveProperty(this) === true && nfCommon.isDynamicProperty(this) === true) {
sensitiveDynamicPropertyNames.push(this.name);
}
});
return sensitiveDynamicPropertyNames;
};
/**
* Performs the filtering.
*
* @param {object} item The item subject to filtering
* @param {object} args Filter arguments
* @returns {Boolean} Whether or not to include the item
*/
var filter = function (item, args) {
return item.hidden === false;
};
/**
* Loads the specified properties.
*
* @param {type} table
* @param {type} properties
* @param {type} descriptors
* @param {type} history
*/
var loadProperties = function (table, properties, descriptors, history) {
// save the original descriptors and history
table.data({
'descriptors': descriptors,
'history': history
});
// get the grid
var propertyGrid = table.data('gridInstance');
var propertyData = propertyGrid.getData();
// generate the properties
if (nfCommon.isDefinedAndNotNull(properties)) {
propertyData.beginUpdate();
var i = 0;
$.each(properties, function (name, value) {
// get the property descriptor
var descriptor = descriptors[name];
// determine the property type
var type = 'userDefined';
var displayName = name;
if (nfCommon.isDefinedAndNotNull(descriptor)) {
if (nfCommon.isRequiredProperty(descriptor)) {
type = 'required';
} else if (nfCommon.isDynamicProperty(descriptor)) {
type = 'userDefined';
} else {
type = 'optional';
}
// use the display name if possible
displayName = descriptor.displayName;
// determine the value
if (nfCommon.isNull(value) && nfCommon.isDefinedAndNotNull(descriptor.defaultValue)) {
value = descriptor.defaultValue;
}
}
var hidden = false;
var dependent = false;
// Check for dependencies
if (descriptor.dependencies.length > 0) {
$.each(descriptor.dependencies, function (i, dependency) {
// It is sufficient to have found a single instance of not meeting the
// requirement for a dependent value in order to hide a property
if (hidden) {
return false;
}
// Get the rows from the table
var items = propertyData.getItems();
// Get the item's hidden attribute to compare. If item.hidden=true, hidden = true.
$.each(items, function (k, property) {
if (property.property === dependency.propertyName) {
dependent = true;
if (property.hidden === false) {
// Get the property value by propertyName
var propertyValue = properties[dependency.propertyName];
// Test the dependentValues against the current value of the property
// If not, then mark the current property hidden attribute is true
if (propertyValue != null) {
if (dependency.hasOwnProperty("dependentValues")) {
hidden = !dependency.dependentValues.includes(propertyValue);
}
} else {
hidden = true;
}
} else {
hidden = true;
}
if (hidden) {
return false;
}
}
})
});
}
// add the row
propertyData.addItem({
id: i++,
hidden: hidden,
dependent: dependent,
property: name,
displayName: displayName,
previousValue: value,
value: value,
type: type
});
// Reset hidden property
hidden = false;
});
propertyData.endUpdate();
}
};
/**
* Clears the property table container.
*
* @param {jQuery} propertyTableContainer
*/
var clear = function (propertyTableContainer) {
var options = propertyTableContainer.data('options');
if (options.readOnly === true) {
nfUniversalCapture.removeAllPropertyDetailDialogs();
} else {
// clear any existing new property dialogs
if (nfCommon.isDefinedAndNotNull(options.dialogContainer)) {
$('#new-property-dialog').modal("hide");
}
}
// clean up data
var table = propertyTableContainer.find('div.property-table');
table.removeData('descriptors history');
// clean up any tooltips that may have been generated
nfCommon.cleanUpTooltips(table, 'div.fa-question-circle, div.fa-info');
// clear the data in the grid
var propertyGrid = table.data('gridInstance');
var propertyData = propertyGrid.getData();
propertyData.setItems([]);
};
var methods = {
/**
* Create a property table. The options are specified in the following
* format:
*
* {
* readOnly: true,
* dialogContainer: 'body',
* descriptorDeferred: function () {
* return $.Deferred(function (deferred) {
* deferred.resolve();
* }).promise;
* },
* supportsGoTo: true,
* goToServiceDeferred: function () {
* return $.Deferred(function (deferred) {
* deferred.resolve();
* }).promise;
* },
* propertyVerificationCallback: function () {}
* }
*
* @argument {object} options The options for the tag cloud
*/
init: function (options) {
return this.each(function () {
// ensure the options have been properly specified
if (nfCommon.isDefinedAndNotNull(options)) {
// get the tag cloud
var propertyTableContainer = $(this);
// clear any current contents, remote events, and store options
propertyTableContainer.empty().unbind().addClass('property-container').data('options', options);
// build the component
var header = $('<div class="properties-header"></div>').appendTo(propertyTableContainer);
$('<div class="required-property-note">Required field</div>').appendTo(header);
// build the table
var table = $('<div class="property-table"></div>').appendTo(propertyTableContainer);
// optionally add a add new property button
if (options.readOnly !== true && nfCommon.isDefinedAndNotNull(options.dialogContainer)) {
// build the new property dialog
var newPropertyDialogMarkup =
'<div id="new-property-dialog" class="dialog cancellable small-dialog hidden">' +
'<div class="dialog-content">' +
'<div class="setting">' +
'<div class="setting-name">Property name</div>' +
'<div class="setting-field new-property-name-container">' +
'<input class="new-property-name" type="text"/>' +
'</div>' +
'</div>' +
'<div class="setting">' +
'<div class="setting-name">Sensitive Value ' +
'<span class="fa fa-question-circle" alt="Info"' +
' title="Components must declare support for Sensitive Dynamic Properties to enable selection of Sensitive Value status.' +
' Components that flag dynamic properties as sensitive do not allow Sensitive Value status to be changed."' +
'>' +
'</span>' +
'</div>' +
'<div class="setting-field">' +
'<input id="value-sensitive-radio-button" type="radio" name="sensitive" value="sensitive" /> Yes' +
'<input id="value-not-sensitive-radio-button" type="radio" name="sensitive" value="plain" style="margin-left: 20px;"/> No' +
'</div>' +
'</div>' +
'</div>' +
'</div>';
var newPropertyDialog = $(newPropertyDialogMarkup).appendTo(options.dialogContainer);
var newPropertyNameField = newPropertyDialog.find('input.new-property-name');
var valueSensitiveField = newPropertyDialog.find('#value-sensitive-radio-button');
var valueNotSensitiveField = newPropertyDialog.find('#value-not-sensitive-radio-button');
newPropertyDialog.modal({
headerText: 'Add Property',
buttons: [{
buttonText: 'Ok',
color: {
base: '#728E9B',
hover: '#004849',
text: '#ffffff'
},
handler: {
click: function () {
add();
}
}
},
{
buttonText: 'Cancel',
color: {
base: '#E3E8EB',
hover: '#C7D2D7',
text: '#004849'
},
handler: {
click: function () {
cancel();
}
}
}]
});
var add = function () {
var propertyName = $.trim(newPropertyNameField.val());
// ensure the property name is specified
if (propertyName !== '') {
var propertyGrid = table.data('gridInstance');
var propertyData = propertyGrid.getData();
// ensure the property name is unique
var existingItem = null;
$.each(propertyData.getItems(), function (_, item) {
if (propertyName === item.property) {
existingItem = item;
return false;
}
});
if (existingItem === null || existingItem.hidden === true) {
// load the descriptor with requested sensitive status
var sensitive = valueSensitiveField.prop('checked');
options.descriptorDeferred(propertyName, sensitive).done(function (response) {
var descriptor = response.propertyDescriptor;
// store the descriptor for use later
var descriptors = table.data('descriptors');
if (!nfCommon.isUndefined(descriptors)) {
descriptors[descriptor.name] = descriptor;
}
// add the property when existing item not found
if (existingItem === null) {
// add a row for the new property
var id = propertyData.getItems().length;
propertyData.addItem({
id: id,
hidden: false,
property: propertyName,
displayName: propertyName,
previousValue: null,
value: null,
type: 'userDefined'
});
// select the new properties row
var row = propertyData.getRowById(id);
propertyGrid.setActiveCell(row, propertyGrid.getColumnIndex('value'));
propertyGrid.editActiveCell();
} else {
// if this row is currently hidden, clear the value and show it
propertyData.updateItem(existingItem.id, $.extend(existingItem, {
hidden: false,
previousValue: null,
value: null
}));
// select the new properties row
var row = propertyData.getRowById(existingItem.id);
propertyGrid.invalidateRow(row);
propertyGrid.render();
propertyGrid.setActiveCell(row, propertyGrid.getColumnIndex('value'));
propertyGrid.editActiveCell();
}
});
} else {
nfDialog.showOkDialog({
headerText: 'Property Exists',
dialogContent: 'A property with this name already exists.'
});
// select the existing properties row
var row = propertyData.getRowById(existingItem.id);
propertyGrid.setSelectedRows([row]);
propertyGrid.scrollRowIntoView(row);
}
} else {
nfDialog.showOkDialog({
headerText: 'Property Name',
dialogContent: 'Property name must be specified.'
});
}
// close the dialog
newPropertyDialog.modal('hide');
};
var cancel = function () {
newPropertyDialog.modal('hide');
};
// enable enter to add
newPropertyNameField.on('keydown', function (e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code === $.ui.keyCode.ENTER) {
add();
// prevents the enter from propagating into the field for editing the new property value
e.stopImmediatePropagation();
e.preventDefault();
}
});
newPropertyDialog.on('click', 'div.new-property-ok', add).on('click', 'div.new-property-cancel', cancel);
// build the control to open the new property dialog
var addProperty = $('<div class="add-property" title="Add Property"></div>').appendTo(header);
$('<button class="button fa fa-plus"></button>').on('click', function () {
// close all fields currently being edited
saveRow(table);
// clear the dialog
newPropertyNameField.val('');
// open the new property dialog
newPropertyDialog.modal('show');
// set the initial focus
newPropertyNameField.focus();
// Set initial Sensitive Value radio button status
valueSensitiveField.prop('checked', false);
valueNotSensitiveField.prop('checked', true);
// Set disabled status based on component support indicated
var sensitiveFieldDisabled = supportsSensitiveDynamicProperties !== true;
valueSensitiveField.prop('disabled', sensitiveFieldDisabled);
valueNotSensitiveField.prop('disabled', sensitiveFieldDisabled);
}).appendTo(addProperty);
// build the control to trigger verification
var verifyProperties = $('<div class="verify-properties hidden" title="Verify Properties"></div>').appendTo(header);
$('<button class="button fa fa-check-circle-o"></button>').on('click', function () {
// close all fields currently being edited
saveRow(table);
// invoke the verification callback with the current properties
propertyVerificationCallback(marshalProperties(table));
}).appendTo(verifyProperties);
// if there is a verification callback registered show the verify button
propertyVerificationCallback = options.propertyVerificationCallback;
var supportsVerification = typeof propertyVerificationCallback === 'function';
verifyProperties.toggleClass('hidden', !supportsVerification);
}
$('<div class="clear"></div>').appendTo(header);
// initializes the properties table
initPropertiesTable(table, options);
}
});
},
/**
* Loads the specified properties.
*
* @argument {object} properties The properties
* @argument {map} descriptors The property descriptors (property name -> property descriptor)
* @argument {map} history
*/
loadProperties: function (properties, descriptors, history) {
return this.each(function () {
var table = $(this).find('div.property-table');
loadProperties(table, properties, descriptors, history);
});
},
/**
* Saves the last edited row in the specified grid.
*/
saveRow: function () {
return this.each(function () {
var table = $(this).find('div.property-table');
saveRow(table);
});
},
/**
* Update the size of the grid based on its container's current size.
*/
resetTableSize: function () {
return this.each(function () {
var table = $(this).find('div.property-table');
var propertyGrid = table.data('gridInstance');
if (nfCommon.isDefinedAndNotNull(propertyGrid)) {
propertyGrid.resizeCanvas();
}
});
},
/**
* Cancels the edit in the specified row.
*/
cancelEdit: function () {
return this.each(function () {
var table = $(this).find('div.property-table');
var propertyGrid = table.data('gridInstance');
if (nfCommon.isDefinedAndNotNull(propertyGrid)) {
var editController = propertyGrid.getEditController();
editController.cancelCurrentEdit();
}
});
},
/**
* Destroys the property table.
*/
destroy: function () {
return this.each(function () {
var propertyTableContainer = $(this);
var options = propertyTableContainer.data('options');
if (nfCommon.isDefinedAndNotNull(options)) {
// clear the property table container
clear(propertyTableContainer);
// clear any existing new property dialogs
if (nfCommon.isDefinedAndNotNull(options.dialogContainer)) {
$('#new-property-dialog').modal("hide");
$(options.dialogContainer).children('div.new-inline-controller-service-dialog').remove();
}
}
});
},
/**
* Clears the property table.
*/
clear: function () {
return this.each(function () {
clear($(this));
});
},
/**
* Determines if a save is required for the first matching element.
*/
isSaveRequired: function () {
var isSaveRequired = false;
this.each(function () {
// get the property grid
var table = $(this).find('div.property-table');
var propertyGrid = table.data('gridInstance');
var propertyData = propertyGrid.getData();
// determine if any of the properties have changed
$.each(propertyData.getItems(), function () {
if (this.value !== this.previousValue) {
isSaveRequired = true;
return false;
}
});
return false;
});
return isSaveRequired;
},
/**
* Marshalls the properties for the first matching element.
*/
marshalProperties: function () {
// properties
var properties = {};
this.each(function () {
// get the property grid data
var table = $(this).find('div.property-table');
properties = marshalProperties(table);
return false;
});
return properties;
},
/**
* Get Sensitive Dynamic Property Names based on Property Descriptor status
*/
getSensitiveDynamicPropertyNames: function () {
var sensitiveDynamicPropertyNames = [];
this.each(function () {
// get the property grid data
var table = $(this).find('div.property-table');
sensitiveDynamicPropertyNames = getSensitiveDynamicPropertyNames(table);
return false;
});
return sensitiveDynamicPropertyNames;
},
/**
* Sets the current group id. This is used to indicate where inline Controller Services are created
* and to obtain the parameter context.
*/
setGroupId: function (currentGroupId) {
return this.each(function () {
groupId = currentGroupId;
});
},
/**
* Set Support status for Sensitive Dynamic Properties
*/
setSupportsSensitiveDynamicProperties: function (currentSupportsSensitiveDynamicProperties) {
return this.each(function () {
supportsSensitiveDynamicProperties = currentSupportsSensitiveDynamicProperties;
});
},
/**
* Sets the property verification callback.
*/
setPropertyVerificationCallback: function (currentPropertyVerificationCallback) {
return this.each(function () {
propertyVerificationCallback = currentPropertyVerificationCallback;
var supportsVerification = typeof currentPropertyVerificationCallback === 'function';
$(this).find('div.verify-properties').toggleClass('hidden', !supportsVerification);
});
}
};
$.fn.propertytable = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else {
return methods.init.apply(this, arguments);
}
};
}));
| {
"content_hash": "ced1edb0508c276727e01b71362806c5",
"timestamp": "",
"source": "github",
"line_count": 2422,
"max_line_length": 219,
"avg_line_length": 44.679190751445084,
"alnum_prop": 0.4498812527145537,
"repo_name": "pvillard31/nifi",
"id": "17db5f12ea0672956401298ad3b2880a805da9d6",
"size": "109014",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/jquery/propertytable/jquery.propertytable.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "48535"
},
{
"name": "C++",
"bytes": "652"
},
{
"name": "CSS",
"bytes": "297537"
},
{
"name": "Clojure",
"bytes": "3993"
},
{
"name": "Dockerfile",
"bytes": "24868"
},
{
"name": "GAP",
"bytes": "31198"
},
{
"name": "Groovy",
"bytes": "1948079"
},
{
"name": "HTML",
"bytes": "1212191"
},
{
"name": "Handlebars",
"bytes": "39081"
},
{
"name": "Java",
"bytes": "57094735"
},
{
"name": "JavaScript",
"bytes": "4277719"
},
{
"name": "Lua",
"bytes": "983"
},
{
"name": "Mustache",
"bytes": "2438"
},
{
"name": "Python",
"bytes": "27513"
},
{
"name": "Ruby",
"bytes": "23018"
},
{
"name": "SCSS",
"bytes": "22032"
},
{
"name": "Shell",
"bytes": "164326"
},
{
"name": "TypeScript",
"bytes": "1337"
},
{
"name": "XSLT",
"bytes": "7835"
}
],
"symlink_target": ""
} |
require 'rspec/expectations'
RSpec::Matchers.define :be_a_url do |expected|
match do |actual|
URI.parse(actual) rescue false
end
end
| {
"content_hash": "ddc0e4a1aaa343ec38c000b734ea4457",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 46,
"avg_line_length": 20.285714285714285,
"alnum_prop": 0.7253521126760564,
"repo_name": "duncanjbrown/wp-api-client",
"id": "b36455dc4087fe942df760605f8333fe8d8e9c6c",
"size": "142",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/support/matchers.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "34653"
},
{
"name": "Shell",
"bytes": "131"
}
],
"symlink_target": ""
} |
<ng2v-tabset>
<ng2v-tab title="One">
<ng-template ng2vTabContent>
<p>These tabs are displayed as pills...</p>
</ng-template>
</ng2v-tab>
<ng2v-tab title="Two">
<ng-template ng2vTabContent>
<p>Because default values have been customized.</p>
</ng-template>
</ng2v-tab>
</ng2v-tabset>
| {
"content_hash": "af0a85b02e5241c9c4696e95aecf1a74",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 57,
"avg_line_length": 26.583333333333332,
"alnum_prop": 0.6332288401253918,
"repo_name": "rajkeshwar/ng2v",
"id": "2ec39a8fc3ab77c1ae67907d0ce23894be3cb57d",
"size": "319",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bk-demo/src/app/components/tabset/demos/config/tabset-config.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "352244"
},
{
"name": "HTML",
"bytes": "1223680"
},
{
"name": "JavaScript",
"bytes": "66516"
},
{
"name": "Shell",
"bytes": "2096"
},
{
"name": "TypeScript",
"bytes": "2380049"
}
],
"symlink_target": ""
} |
<?php
/**
* Includes Smarty engine class.
*/
require_once getShopBasePath() . "core/smarty/Smarty.class.php";
/**
* General utils class
*
*/
class oxUtils extends oxSuperCfg
{
/**
* Cached currency precision
*
* @var int
*/
protected $_iCurPrecision = null;
/**
* Some files, like object structure should not be deleted, because they are changed rarely
* and each regeneration eats additional page load time. This array keeps patterns of file
* names which should not be deleted on regular cache cleanup
*
* @var string
*/
protected $_sPermanentCachePattern = "/c_fieldnames_|c_tbdsc_|_allfields_/";
/**
* Pattern used to filter needed to remove language cache files.
*
* @var string
*/
protected $_sLanguageCachePattern = "/c_langcache_/i";
/**
* Pattern used to filter needed to remove admin menu cache files.
*
* @var string
*/
protected $_sMenuCachePattern = "/c_menu_/i";
/**
* File cache contents.
*
* @var array
*/
protected $_aLockedFileHandles = array();
/**
* Local cache
*
* @var array
*/
protected $_aFileCacheContents = array();
/**
* Search engine indicator
*
* @var bool
*/
protected $_blIsSe = null;
/**
* Statically cached data
*
* @var array
*/
protected $_aStaticCache;
/**
* Seo mode marker - SEO is active or not
*
* @var bool
*/
protected $_blSeoIsActive = null;
/**
* OXID specific string manipulation method
*
* @param string $sVal string
* @param string $sKey key
*
* @deprecated since v5.2 (2014-08-11); use oxEncryptor::encrypt() instead.
*
* @return string
*/
public function strMan($sVal, $sKey = null)
{
$oEncryptor = oxNew('oxEncryptor');
$sKey = $sKey ? $sKey : $this->getConfig()->getConfigParam('sConfigKey');
return $oEncryptor->encrypt($sVal, $sKey);
}
/**
* OXID specific string manipulation method
*
* @param string $sVal string
* @param string $sKey key
*
* @deprecated since v5.2 (2014-08-11); use oxDecryptor::decrypt() instead.
*
* @return string
*/
public function strRem($sVal, $sKey = null)
{
$oDecryptor = oxNew('oxDecryptor');
$sKey = $sKey ? $sKey : $this->getConfig()->getConfigParam('sConfigKey');
return $oDecryptor->decrypt($sVal, $sKey);
}
/**
* Returns string witch "." symbols were replaced with "__".
*
* @param string $sName String to search replaceable char
*
* @return string
*/
public function getArrFldName($sName)
{
return str_replace(".", "__", $sName);
}
/**
* Takes a string and assign all values, returns array with values.
*
* @param string $sIn Initial string
* @param float $dVat Article VAT (optional)
*
* @return array
*/
public function assignValuesFromText($sIn, $dVat = null)
{
$aRet = array();
$aPieces = explode('@@', $sIn);
while (list($sKey, $sVal) = each($aPieces)) {
if ($sVal) {
$aName = explode('__', $sVal);
if (isset($aName[0]) && isset($aName[1])) {
$aRet[] = $this->_fillExplodeArray($aName, $dVat);
}
}
}
return $aRet;
}
/**
* Takes an array and builds again a string. Returns string with values.
*
* @param array $aIn Initial array of strings
*
* @return string
*/
public function assignValuesToText($aIn)
{
$sRet = "";
reset($aIn);
while (list($sKey, $sVal) = each($aIn)) {
$sRet .= $sKey;
$sRet .= "__";
$sRet .= $sVal;
$sRet .= "@@";
}
return $sRet;
}
/**
* Returns formatted currency string, according to formatting standards.
*
* @param string $sValue Formatted price
*
* @return float
*/
public function currency2Float($sValue)
{
$fRet = $sValue;
$iPos = strrpos($sValue, ".");
if ($iPos && ((strlen($sValue) - 1 - $iPos) < 2 + 1)) {
// replace decimal with ","
$fRet = substr_replace($fRet, ",", $iPos, 1);
}
// remove thousands
$fRet = str_replace(array(" ", "."), "", $fRet);
$fRet = str_replace(",", ".", $fRet);
return (float) $fRet;
}
/**
* Returns formatted float, according to formatting standards.
*
* @param string $sValue Formatted price
*
* @return float
*/
public function string2Float($sValue)
{
$fRet = str_replace(" ", "", $sValue);
$iCommaPos = strpos($fRet, ",");
$iDotPos = strpos($fRet, ".");
if (!$iDotPos xor !$iCommaPos) {
if (substr_count($fRet, ",") > 1 || substr_count($fRet, ".") > 1) {
$fRet = str_replace(array(",", "."), "", $fRet);
} else {
$fRet = str_replace(",", ".", $fRet);
}
} else {
if ($iDotPos < $iCommaPos) {
$fRet = str_replace(".", "", $fRet);
$fRet = str_replace(",", ".", $fRet);
}
}
// remove thousands
$fRet = str_replace(array(" ", ","), "", $fRet);
return (float) $fRet;
}
/**
* Checks if current web client is Search Engine. Returns true on success.
*
* @param string $sClient user browser agent
*
* @return bool
*/
public function isSearchEngine($sClient = null)
{
if (is_null($this->_blIsSe)) {
$this->setSearchEngine(null, $sClient);
}
return $this->_blIsSe;
}
/**
* Sets if current web client is Search Engine.
*
* @param bool $blIsSe sets if Search Engine is on
* @param string $sClient user browser agent
*
* @return null
*/
public function setSearchEngine($blIsSe = null, $sClient = null)
{
if (isset($blIsSe)) {
$this->_blIsSe = $blIsSe;
return;
}
startProfile("isSearchEngine");
$myConfig = $this->getConfig();
$blIsSe = false;
if (!($myConfig->getConfigParam('iDebug') && $this->isAdmin())) {
$aRobots = $myConfig->getConfigParam('aRobots');
$aRobots = is_array($aRobots) ? $aRobots : array();
$aRobotsExcept = $myConfig->getConfigParam('aRobotsExcept');
$aRobotsExcept = is_array($aRobotsExcept) ? $aRobotsExcept : array();
$sClient = $sClient ? $sClient : strtolower(getenv('HTTP_USER_AGENT'));
$blIsSe = false;
$aRobots = array_merge($aRobots, $aRobotsExcept);
foreach ($aRobots as $sRobot) {
if (strpos($sClient, $sRobot) !== false) {
$blIsSe = true;
break;
}
}
}
$this->_blIsSe = $blIsSe;
stopProfile("isSearchEngine");
}
/**
* User email validation function. Returns true if email is OK otherwise - false;
* Syntax validation is performed only.
*
* @param string $sEmail user email
*
* @deprecated since v4.9.0/v5.2.0 (2014-06-17); Use MailValidator::isValidEmail().
*
* @return bool
*/
public function isValidEmail($sEmail)
{
$oMailValidator = oxNew('oxMailValidator');
return $oMailValidator->isValidEmail($sEmail);
}
/**
* Parses profile configuration, loads stored info in cookie
*
* @param array $aInterfaceProfiles ($myConfig->getConfigParam( 'aInterfaceProfiles' ))
*
* @return null
*/
public function loadAdminProfile($aInterfaceProfiles)
{
// improved #533
// checking for available profiles list
if (is_array($aInterfaceProfiles)) {
//checking for previous profiles
$sPrevProfile = oxRegistry::get("oxUtilsServer")->getOxCookie('oxidadminprofile');
if (isset($sPrevProfile)) {
$aPrevProfile = @explode("@", trim($sPrevProfile));
}
//array to store profiles
$aProfiles = array();
foreach ($aInterfaceProfiles as $iPos => $sProfile) {
$aProfileSettings = array($iPos, $sProfile);
$aProfiles[] = $aProfileSettings;
}
// setting previous used profile as active
if (isset($aPrevProfile[0]) && isset($aProfiles[$aPrevProfile[0]])) {
$aProfiles[$aPrevProfile[0]][2] = 1;
}
oxRegistry::getSession()->setVariable("aAdminProfiles", $aProfiles);
return $aProfiles;
}
return null;
}
/**
* Rounds the value to currency cents. This method does NOT format the number.
*
* @param string $sVal the value that should be rounded
* @param object $oCur Currency Object
*
* @return float
*/
public function fRound($sVal, $oCur = null)
{
startProfile('fround');
//cached currency precision, this saves about 1% of execution time
$iCurPrecision = null;
if (!defined('OXID_PHP_UNIT')) {
$iCurPrecision = $this->_iCurPrecision;
}
if (is_null($iCurPrecision)) {
if (!$oCur) {
$oCur = $this->getConfig()->getActShopCurrencyObject();
}
$iCurPrecision = $oCur->decimal;
$this->_iCurPrecision = $iCurPrecision;
}
// if < 5.3.x this is a workaround for #36008 bug in php - incorrect round() & number_format() result (R)
static $dprez = null;
if (!$dprez) {
$prez = @ini_get("precision");
if (!$prez || $prez > 12) {
$prez = 12;
}
$dprez = pow(10, -$prez);
}
stopProfile('fround');
return round($sVal + $dprez * ($sVal >= 0 ? 1 : -1), $iCurPrecision);
}
/**
* Stores something into static cache to avoid double loading
*
* @param string $sName name of the content
* @param mixed $sContent the content
* @param string $sKey optional key, where to store the content
*/
public function toStaticCache($sName, $sContent, $sKey = null)
{
// if it's an array then we add
if ($sKey) {
$this->_aStaticCache[$sName][$sKey] = $sContent;
} else {
$this->_aStaticCache[$sName] = $sContent;
}
}
/**
* Retrieves something from static cache
*
* @param string $sName name under which the content is stored in the static cache
*
* @return mixed
*/
public function fromStaticCache($sName)
{
if (isset($this->_aStaticCache[$sName])) {
return $this->_aStaticCache[$sName];
}
return null;
}
/**
* Cleans all or specific data from static cache
*
* @param string $sCacheName Cache name
*/
public function cleanStaticCache($sCacheName = null)
{
if ($sCacheName) {
unset($this->_aStaticCache[$sCacheName]);
} else {
$this->_aStaticCache = null;
}
}
/**
* Generates php file, which could later be loaded as include instead of parsed data.
* Currently this method supports simple arrays only.
*
* @param string $sKey Cache key
* @param mixed $mContents Cache contents. At this moment only simple array type is supported.
*/
public function toPhpFileCache($sKey, $mContents)
{
//only simple arrays are supported
if (is_array($mContents) && ($sCachePath = $this->getCacheFilePath($sKey, false, 'php'))) {
// setting meta
$this->setCacheMeta($sKey, array("serialize" => false, "cachepath" => $sCachePath));
// caching..
$this->toFileCache($sKey, $mContents);
}
}
/**
* Includes cached php file and loads stored contents.
*
* @param string $sKey Cache key.
*
* @return null;
*/
public function fromPhpFileCache($sKey)
{
// setting meta
$this->setCacheMeta($sKey, array("include" => true, "cachepath" => $this->getCacheFilePath($sKey, false, 'php')));
return $this->fromFileCache($sKey);
}
/**
* If available returns cache meta data array
*
* @param string $sKey meta data/cache key
*
* @return mixed
*/
public function getCacheMeta($sKey)
{
return isset($this->_aFileCacheMeta[$sKey]) ? $this->_aFileCacheMeta[$sKey] : false;
}
/**
* Saves cache meta data (information)
*
* @param string $sKey meta data/cache key
* @param array $aMeta meta data array
*/
public function setCacheMeta($sKey, $aMeta)
{
// cache meta data
$this->_aFileCacheMeta[$sKey] = $aMeta;
}
/**
* Adds contents to cache contents by given key. Returns true on success.
* All file caches are supposed to be written once by commitFileCache() method.
*
* @param string $sKey Cache key
* @param mixed $mContents Contents to cache
* @param int $iTtl Time to live in seconds (0 for forever).
*
* @return bool
*/
public function toFileCache($sKey, $mContents, $iTtl = 0)
{
$aCacheData['content'] = $mContents;
$aMeta = $this->getCacheMeta($sKey);
if ($iTtl) {
$aCacheData['ttl'] = $iTtl;
$aCacheData['timestamp'] = oxRegistry::get("oxUtilsDate")->getTime();
}
$this->_aFileCacheContents[$sKey] = $aCacheData;
// looking for cache meta
$sCachePath = isset($aMeta["cachepath"]) ? $aMeta["cachepath"] : $this->getCacheFilePath($sKey);
return ( bool ) $this->_lockFile($sCachePath, $sKey);
}
/**
* Fetches contents from file cache.
*
* @param string $sKey Cache key
*
* @return mixed
*/
public function fromFileCache($sKey)
{
if (!array_key_exists($sKey, $this->_aFileCacheContents)) {
$sRes = null;
$aMeta = $this->getCacheMeta($sKey);
$blInclude = isset($aMeta["include"]) ? $aMeta["include"] : false;
$sCachePath = isset($aMeta["cachepath"]) ? $aMeta["cachepath"] : $this->getCacheFilePath($sKey);
// trying to lock
$this->_lockFile($sCachePath, $sKey, LOCK_SH);
clearstatcache();
if (is_readable($sCachePath)) {
$sRes = $blInclude ? $this->_includeFile($sCachePath) : $this->_readFile($sCachePath);
}
if (isset($sRes['ttl']) && $sRes['ttl'] != 0) {
$iTimestamp = $sRes['timestamp'];
$iTtl = $sRes['ttl'];
$iTime = oxRegistry::get("oxUtilsDate")->getTime();
if ($iTime > $iTimestamp + $iTtl) {
return null;
}
}
// release lock
$this->_releaseFile($sKey, LOCK_SH);
// caching
$this->_aFileCacheContents[$sKey] = $sRes;
}
return $this->_aFileCacheContents[$sKey]['content'];
}
/**
* Reads and returns cache file contents
*
* @param string $sFilePath cache fiel path
*
* @return string
*/
protected function _readFile($sFilePath)
{
$sRes = file_get_contents($sFilePath);
return $sRes ? unserialize($sRes) : null;
}
/**
* Includes cache file
*
* @param string $sFilePath cache file path
*
* @return mixed
*/
protected function _includeFile($sFilePath)
{
$_aCacheContents = null;
include $sFilePath;
return $_aCacheContents;
}
/**
* Serializes or writes php array for class file cache
*
* @param string $sKey cache key
* @param mixed $mContents cache data
*
* @return mixed
*/
protected function _processCache($sKey, $mContents)
{
// looking for cache meta
$aCacheMeta = $this->getCacheMeta($sKey);
$blSerialize = isset($aCacheMeta["serialize"]) ? $aCacheMeta["serialize"] : true;
if ($blSerialize) {
$mContents = serialize($mContents);
} else {
$mContents = "<?php\n//automatically generated file\n//" . date("Y-m-d H:i:s") . "\n\n\$_aCacheContents = " . var_export($mContents, true) . "\n?>";
}
return $mContents;
}
/**
* Writes all cache contents to file at once. This method was introduced due to possible
* race conditions. Cache is cleaned up after commit
*/
public function commitFileCache()
{
if (!empty($this->_aLockedFileHandles[LOCK_EX])) {
startProfile("!__SAVING CACHE__! (warning)");
foreach ($this->_aLockedFileHandles[LOCK_EX] as $sKey => $rHandle) {
if ($rHandle !== false && isset($this->_aFileCacheContents[$sKey])) {
// #0002931A truncate file once more before writing
ftruncate($rHandle, 0);
// writing cache
fwrite($rHandle, $this->_processCache($sKey, $this->_aFileCacheContents[$sKey]));
// releasing locks
$this->_releaseFile($sKey);
}
}
stopProfile("!__SAVING CACHE__! (warning)");
//empty buffer
$this->_aFileCacheContents = array();
}
}
/**
* Locks cache file and returns its handle on success or false on failure
*
* @param string $sFilePath name of file to lock
* @param string $sIdent lock identifier
* @param int $iLockMode lock mode - LOCK_EX/LOCK_SH
*
* @return mixed lock file resource or false on error
*/
protected function _lockFile($sFilePath, $sIdent, $iLockMode = LOCK_EX)
{
$rHandle = isset($this->_aLockedFileHandles[$iLockMode][$sIdent]) ? $this->_aLockedFileHandles[$iLockMode][$sIdent] : null;
if ($rHandle === null) {
$blLocked = false;
$rHandle = @fopen($sFilePath, "a+");
if ($rHandle !== false) {
if (flock($rHandle, $iLockMode | LOCK_NB)) {
if ($iLockMode === LOCK_EX) {
// truncate file
$blLocked = ftruncate($rHandle, 0);
} else {
// move to a start position
$blLocked = fseek($rHandle, 0) === 0;
}
}
// on failure - closing and setting false..
if (!$blLocked) {
fclose($rHandle);
$rHandle = false;
}
}
// in case system does not support file locking
if (!$blLocked && $iLockMode === LOCK_EX) {
// clearing on first call
if (count($this->_aLockedFileHandles) == 0) {
clearstatcache();
}
// start a blank file to inform other processes we are dealing with it.
if (!(file_exists($sFilePath) && !filesize($sFilePath) && abs(time() - filectime($sFilePath) < 40))) {
$rHandle = @fopen($sFilePath, "w");
}
}
$this->_aLockedFileHandles[$iLockMode][$sIdent] = $rHandle;
}
return $rHandle;
}
/**
* Releases file lock and returns release state
*
* @param string $sIdent lock ident
* @param int $iLockMode lock mode
*
* @return bool
*/
protected function _releaseFile($sIdent, $iLockMode = LOCK_EX)
{
$blSuccess = true;
if (isset($this->_aLockedFileHandles[$iLockMode][$sIdent]) &&
$this->_aLockedFileHandles[$iLockMode][$sIdent] !== false
) {
// release the lock and close file
$blSuccess = flock($this->_aLockedFileHandles[$iLockMode][$sIdent], LOCK_UN) &&
fclose($this->_aLockedFileHandles[$iLockMode][$sIdent]);
unset($this->_aLockedFileHandles[$iLockMode][$sIdent]);
}
return $blSuccess;
}
/**
* Removes most files stored in cache (default 'tmp') folder. Some files
* e.g. table files names description, are left. Excluded cache file name
* patterns are defined in oxUtils::_sPermanentCachePattern parameter
*/
public function oxResetFileCache()
{
$aFiles = glob($this->getCacheFilePath(null, true) . '*');
if (is_array($aFiles)) {
// delete all the files, except cached tables field names
$aFiles = preg_grep($this->_sPermanentCachePattern, $aFiles, PREG_GREP_INVERT);
foreach ($aFiles as $sFile) {
@unlink($sFile);
}
}
}
/**
* Removes smarty template cache for given templates
*
* @param array $aTemplates Template name array
*/
public function resetTemplateCache($aTemplates)
{
$sSmartyDir = oxRegistry::get("oxUtilsView")->getSmartyDir();
//$aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
$aFiles = glob($sSmartyDir . '*');
if (is_array($aFiles) && is_array($aTemplates) && count($aTemplates)) {
// delete all template cache files
foreach ($aTemplates as &$sTemplate) {
$sTemplate = preg_quote(basename(strtolower($sTemplate), '.tpl'));
}
$sPattern = sprintf("/%%(%s)\.tpl\.php$/i", implode('|', $aTemplates));
$aFiles = preg_grep($sPattern, $aFiles);
if (is_array($aFiles)) {
foreach ($aFiles as $sFile) {
@unlink($sFile);
}
}
}
}
/**
* Removes language constant cache
*/
public function resetLanguageCache()
{
$aFiles = glob($this->getCacheFilePath(null, true) . '*');
if (is_array($aFiles)) {
// delete all language cache files
$sPattern = $this->_sLanguageCachePattern;
$aFiles = preg_grep($sPattern, $aFiles);
foreach ($aFiles as $sFile) {
@unlink($sFile);
}
}
}
/**
* Removes admin menu cache
*/
public function resetMenuCache()
{
$aFiles = glob($this->getCacheFilePath(null, true) . '*');
if (is_array($aFiles)) {
// delete all menu cache files
$sPattern = $this->_sMenuCachePattern;
$aFiles = preg_grep($sPattern, $aFiles);
foreach ($aFiles as $sFile) {
@unlink($sFile);
}
}
}
/**
* If $sLocal file is older than 24h or does not exist, tries to
* download it from $sRemote and save it as $sLocal
*
* @param string $sRemote the file
* @param string $sLocal the address of the remote source
*
* @return mixed
*/
public function getRemoteCachePath($sRemote, $sLocal)
{
clearstatcache();
if (file_exists($sLocal) && filemtime($sLocal) && filemtime($sLocal) > time() - 86400) {
return $sLocal;
}
$hRemote = @fopen($sRemote, "rb");
$blSuccess = false;
if (isset($hRemote) && $hRemote) {
$hLocal = fopen($sLocal, "wb");
stream_copy_to_stream($hRemote, $hLocal);
fclose($hRemote);
fclose($hLocal);
$blSuccess = true;
} else {
// try via fsockopen
$aUrl = @parse_url($sRemote);
if (!empty($aUrl["host"])) {
$sPath = $aUrl["path"];
if (empty($sPath)) {
$sPath = "/";
}
$sHost = $aUrl["host"];
$hSocket = @fsockopen($sHost, 80, $iErrorNumber, $iErrStr, 5);
if ($hSocket) {
fputs($hSocket, "GET " . $sPath . " HTTP/1.0\r\nHost: $sHost\r\n\r\n");
$headers = stream_get_line($hSocket, 4096, "\r\n\r\n");
if (($hLocal = @fopen($sLocal, "wb")) !== false) {
rewind($hLocal);
// does not copy all the data
// stream_copy_to_stream($hSocket, $hLocal);
fwrite($hLocal, stream_get_contents($hSocket));
fclose($hLocal);
fclose($hSocket);
$blSuccess = true;
}
}
}
}
if ($blSuccess || file_exists($sLocal)) {
return $sLocal;
}
return false;
}
/**
* Checks if preview mode is ON
*
* @return bool
*/
public function canPreview()
{
$blCan = null;
if (($sPrevId = oxRegistry::getConfig()->getRequestParameter('preview')) &&
($sAdminSid = oxRegistry::get("oxUtilsServer")->getOxCookie('admin_sid'))
) {
$sTable = getViewName('oxuser');
$oDb = oxDb::getDb();
$sQ = "select 1 from $sTable where MD5( CONCAT( " . $oDb->quote($sAdminSid) . ", {$sTable}.oxid, {$sTable}.oxpassword, {$sTable}.oxrights ) ) = " . oxDb::getDb()->quote($sPrevId);
$blCan = (bool) $oDb->getOne($sQ);
}
return $blCan;
}
/**
* Returns id which is used for product preview in shop during administration
*
* @return string
*/
public function getPreviewId()
{
$sAdminSid = oxRegistry::get("oxUtilsServer")->getOxCookie('admin_sid');
if (($oUser = $this->getUser())) {
return md5($sAdminSid . $oUser->getId() . $oUser->oxuser__oxpassword->value . $oUser->oxuser__oxrights->value);
}
}
/**
* This function checks if logged in user has access to admin or not
*
* @return bool
*/
public function checkAccessRights()
{
$myConfig = $this->getConfig();
$blIsAuth = false;
$sUserID = oxRegistry::getSession()->getVariable("auth");
// deleting admin marker
oxRegistry::getSession()->setVariable("malladmin", 0);
oxRegistry::getSession()->setVariable("blIsAdmin", 0);
oxRegistry::getSession()->deleteVariable("blIsAdmin");
$myConfig->setConfigParam('blMallAdmin', false);
//#1552T
$myConfig->setConfigParam('blAllowInheritedEdit', false);
if ($sUserID) {
// escaping
$oDb = oxDb::getDb();
$sRights = $oDb->getOne("select oxrights from oxuser where oxid = " . $oDb->quote($sUserID));
if ($sRights != "user") {
// malladmin ?
if ($sRights == "malladmin") {
oxRegistry::getSession()->setVariable("malladmin", 1);
$myConfig->setConfigParam('blMallAdmin', true);
//#1552T
//So far this blAllowSharedEdit is Equal to blMallAdmin but in future to be solved over rights and roles
$myConfig->setConfigParam('blAllowSharedEdit', true);
$sShop = oxRegistry::getSession()->getVariable("actshop");
if (!isset($sShop)) {
oxRegistry::getSession()->setVariable("actshop", $myConfig->getBaseShopId());
}
$blIsAuth = true;
} else {
// Shopadmin... check if this shop is valid and exists
$sShopID = $oDb->getOne("select oxid from oxshops where oxid = " . $oDb->quote($sRights));
if (isset($sShopID) && $sShopID) {
// success, this shop exists
oxRegistry::getSession()->setVariable("actshop", $sRights);
oxRegistry::getSession()->setVariable("currentadminshop", $sRights);
oxRegistry::getSession()->setVariable("shp", $sRights);
// check if this subshop admin is evil.
if ('chshp' == oxRegistry::getConfig()->getRequestParameter('fnc')) {
// dont allow this call
$blIsAuth = false;
} else {
$blIsAuth = true;
$aShopIdVars = array('actshop', 'shp', 'currentadminshop');
foreach ($aShopIdVars as $sShopIdVar) {
if ($sGotShop = oxRegistry::getConfig()->getRequestParameter($sShopIdVar)) {
if ($sGotShop != $sRights) {
$blIsAuth = false;
break;
}
}
}
}
}
}
// marking user as admin
oxRegistry::getSession()->setVariable("blIsAdmin", 1);
}
}
return $blIsAuth;
}
/**
* Checks if Seo mode should be used
*
* @param bool $blReset used to reset cached SEO mode
* @param string $sShopId shop id (optional; if not passed active session shop id will be used)
* @param int $iActLang language id (optional; if not passed active session language will be used)
*
* @return bool
*/
public function seoIsActive($blReset = false, $sShopId = null, $iActLang = null)
{
if (!is_null($this->_blSeoIsActive) && !$blReset) {
return $this->_blSeoIsActive;
}
$myConfig = $this->getConfig();
if (($this->_blSeoIsActive = $myConfig->getConfigParam('blSeoMode')) === null) {
$this->_blSeoIsActive = true;
$aSeoModes = $myConfig->getconfigParam('aSeoModes');
$sActShopId = $sShopId ? $sShopId : $myConfig->getActiveShop()->getId();
$iActLang = $iActLang ? $iActLang : (int) oxRegistry::getLang()->getBaseLanguage();
// checking special config param for active shop and language
if (is_array($aSeoModes) && isset($aSeoModes[$sActShopId]) && isset($aSeoModes[$sActShopId][$iActLang])) {
$this->_blSeoIsActive = (bool) $aSeoModes[$sActShopId][$iActLang];
}
}
return $this->_blSeoIsActive;
}
/**
* Checks if string is only alpha numeric symbols
*
* @param string $sField field name to test
*
* @return bool
*/
public function isValidAlpha($sField)
{
return (boolean) getStr()->preg_match('/^[a-zA-Z0-9_]*$/', $sField);
}
/**
* redirects browser to given url, nothing else done just header send
* may be used for redirection in case of an exception or similar things
*
* @param string $sUrl the URL to redirect to
* @param string $sHeaderCode code to add to the header(e.g. "HTTP/1.1 301 Moved Permanently", or "HTTP/1.1 500 Internal Server Error"
*/
protected function _simpleRedirect($sUrl, $sHeaderCode)
{
$oHeader = oxNew("oxHeader");
$oHeader->setHeader($sHeaderCode);
$oHeader->setHeader("Location: $sUrl");
$oHeader->setHeader("Connection: close");
$oHeader->sendHeader();
}
/**
* Redirects to shop offline page
*
* @param int $iHeaderCode header code, default 302
*/
public function redirectOffline($iHeaderCode = 302)
{
$sUrl = $this->getConfig()->getShopUrl() . 'offline.html';
$this->redirect($sUrl, false, $iHeaderCode);
}
/**
* redirect user to the specified URL
*
* @param string $sUrl URL to be redirected
* @param bool $blAddRedirectParam add "redirect" param
* @param int $iHeaderCode header code, default 302
*
* @return null or exit
*/
public function redirect($sUrl, $blAddRedirectParam = true, $iHeaderCode = 302)
{
//preventing possible cyclic redirection
//#M341 and check only if redirect parameter must be added
if ($blAddRedirectParam && oxRegistry::getConfig()->getRequestParameter('redirected')) {
return;
}
if ($blAddRedirectParam) {
$sUrl = $this->_addUrlParameters($sUrl, array('redirected' => 1));
}
$sUrl = str_ireplace("&", "&", $sUrl);
switch ($iHeaderCode) {
case 301:
$sHeaderCode = "HTTP/1.1 301 Moved Permanently";
break;
case 500:
$sHeaderCode = "HTTP/1.1 500 Internal Server Error";
break;
case 302:
default:
$sHeaderCode = "HTTP/1.1 302 Found";
}
$this->_simpleRedirect($sUrl, $sHeaderCode);
try { //may occur in case db is lost
$this->getSession()->freeze();
} catch (oxException $oEx) {
$oEx->debugOut();
//do nothing else to make sure the redirect takes place
}
if (defined('OXID_PHP_UNIT')) {
return;
}
$this->showMessageAndExit('');
}
/**
* shows given message and quits
* message might be whole content like 404 page.
*
* @param string $sMsg message to show
*
* @return null dies
*/
public function showMessageAndExit($sMsg)
{
$this->getSession()->freeze();
$this->commitFileCache();
if (defined('OXID_PHP_UNIT')) {
return;
}
exit($sMsg);
}
/**
* set header sent to browser
*
* @param string $sHeader header to sent
*/
public function setHeader($sHeader)
{
header($sHeader);
}
/**
* adds the given parameters at the end of the given url
*
* @param string $sUrl a url
* @param array $aParams the params which will be added
*
* @return string
*/
protected function _addUrlParameters($sUrl, $aParams)
{
$sDelimiter = ((getStr()->strpos($sUrl, '?') !== false)) ? '&' : '?';
foreach ($aParams as $sName => $sVal) {
$sUrl = $sUrl . $sDelimiter . $sName . '=' . $sVal;
$sDelimiter = '&';
}
return $sUrl;
}
/**
* Fill array.
*
* @param array $aName Initial array of strings
* @param float $dVat Article VAT
*
* @return string
*
* @todo rename function more closely to actual purpose
* @todo finish refactoring
*/
protected function _fillExplodeArray($aName, $dVat = null)
{
$myConfig = $this->getConfig();
$oObject = new stdClass();
$aPrice = explode('!P!', $aName[0]);
if (($myConfig->getConfigParam('bl_perfLoadSelectLists') && $myConfig->getConfigParam('bl_perfUseSelectlistPrice') && isset($aPrice[0]) && isset($aPrice[1])) || $this->isAdmin()) {
// yes, price is there
$oObject->price = isset($aPrice[1]) ? $aPrice[1] : 0;
$aName[0] = isset($aPrice[0]) ? $aPrice[0] : '';
$iPercPos = getStr()->strpos($oObject->price, '%');
if ($iPercPos !== false) {
$oObject->priceUnit = '%';
$oObject->fprice = $oObject->price;
$oObject->price = substr($oObject->price, 0, $iPercPos);
} else {
$oCur = $myConfig->getActShopCurrencyObject();
$oObject->price = str_replace(',', '.', $oObject->price);
$oObject->fprice = oxRegistry::getLang()->formatCurrency($oObject->price * $oCur->rate, $oCur);
$oObject->priceUnit = 'abs';
}
// add price info into list
if (!$this->isAdmin() && $oObject->price != 0) {
$aName[0] .= " ";
$dPrice = $this->_preparePrice($oObject->price, $dVat);
if ($oObject->price > 0) {
$aName[0] .= "+";
}
//V FS#2616
if ($dVat != null && $oObject->priceUnit == 'abs') {
$oPrice = oxNew('oxPrice');
$oPrice->setPrice($oObject->price, $dVat);
$aName[0] .= oxRegistry::getLang()->formatCurrency($dPrice * $oCur->rate, $oCur);
} else {
$aName[0] .= $oObject->fprice;
}
if ($oObject->priceUnit == 'abs') {
$aName[0] .= " " . $oCur->sign;
}
}
} elseif (isset($aPrice[0]) && isset($aPrice[1])) {
// A. removing unused part of information
$aName[0] = getStr()->preg_replace("/!P!.*/", "", $aName[0]);
}
$oObject->name = $aName[0];
$oObject->value = $aName[1];
return $oObject;
}
/**
* Prepares price depending what options are used(show as net, brutto, etc.) for displaying
*
* @param double $dPrice Price
* @param double $dVat VAT
*
* @return float
*/
protected function _preparePrice($dPrice, $dVat)
{
$blCalculationModeNetto = $this->_isPriceViewModeNetto();
$oCurrency = $this->getConfig()->getActShopCurrencyObject();
$blEnterNetPrice = $this->getConfig()->getConfigParam('blEnterNetPrice');
if ($blCalculationModeNetto && !$blEnterNetPrice) {
$dPrice = round(oxPrice::brutto2Netto($dPrice, $dVat), $oCurrency->decimal);
} elseif (!$blCalculationModeNetto && $blEnterNetPrice) {
$dPrice = round(oxPrice::netto2Brutto($dPrice, $dVat), $oCurrency->decimal);
}
return $dPrice;
}
/**
* Checks and return true if price view mode is netto.
*
* @return bool
*/
protected function _isPriceViewModeNetto()
{
$blResult = (bool) $this->getConfig()->getConfigParam('blShowNetPrice');
$oUser = $this->_getArticleUser();
if ($oUser) {
$blResult = $oUser->isPriceViewModeNetto();
}
return $blResult;
}
/**
* Return article user.
*
* @return oxUser
*/
protected function _getArticleUser()
{
if ($this->_oUser) {
return $this->_oUser;
}
return $this->getUser();
}
/**
* returns manually set mime types
*
* @param string $sFileName the file
*
* @return string
*/
public function oxMimeContentType($sFileName)
{
$sFileName = strtolower($sFileName);
$iLastDot = strrpos($sFileName, '.');
if ($iLastDot !== false) {
$sType = substr($sFileName, $iLastDot + 1);
switch ($sType) {
case 'gif':
$sType = 'image/gif';
break;
case 'jpeg':
case 'jpg':
$sType = 'image/jpeg';
break;
case 'png':
$sType = 'image/png';
break;
default:
$sType = false;
break;
}
}
return $sType;
}
/**
* Processes logging.
*
* @param string $sText Log message text
* @param bool $blNewline If true, writes message to new line (default false)
*/
public function logger($sText, $blNewline = false)
{
$myConfig = $this->getConfig();
if ($myConfig->getConfigParam('iDebug') == -2) {
if (gettype($sText) != 'string') {
$sText = var_export($sText, true);
}
$sLogMsg = "----------------------------------------------\n{$sText}" . (($blNewline) ? "\n" : "") . "\n";
$this->writeToLog($sLogMsg, "log.txt");
}
}
/**
* Applies ROT13 encoding to $sStr
*
* @param string $sStr to encoding string
*
* @return string
*/
public function strRot13($sStr)
{
$sFrom = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$sTo = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';
return strtr($sStr, $sFrom, $sTo);
}
/**
* Returns full path (including file name) to cache file
*
* @param string $sCacheName cache file name
* @param bool $blPathOnly if TRUE, name parameter will be ignored and only cache folder will be returned (default FALSE)
* @param string $sExtension cache file extension
*
* @return string
*/
public function getCacheFilePath($sCacheName, $blPathOnly = false, $sExtension = 'txt')
{
$sVersionPrefix = 'pe';
$sPath = realpath($this->getConfig()->getConfigParam('sCompileDir'));
if (!$sPath) {
return false;
}
return $blPathOnly ? "{$sPath}/" : "{$sPath}/ox{$sVersionPrefix}c_{$sCacheName}." . $sExtension;
}
/**
* Tries to load lang cache array from cache file
*
* @param string $sCacheName cache file name
*
* @return array
*/
public function getLangCache($sCacheName)
{
$aLangCache = null;
$sFilePath = $this->getCacheFilePath($sCacheName);
if (file_exists($sFilePath) && is_readable($sFilePath)) {
include $sFilePath;
}
return $aLangCache;
}
/**
* Writes language array to file cache
*
* @param string $sCacheName name of cache file
* @param array $aLangCache language array
*
* @return null
*/
public function setLangCache($sCacheName, $aLangCache)
{
$sCache = "<?php\n\$aLangCache = " . var_export($aLangCache, true) . ";\n?>";
$blRes = file_put_contents($this->getCacheFilePath($sCacheName), $sCache, LOCK_EX);
return $blRes;
}
/**
* Checks if url has ending slash / - if not, adds it
*
* @param string $sUrl url string
*
* @return string
*/
public function checkUrlEndingSlash($sUrl)
{
if (!getStr()->preg_match("/\/$/", $sUrl)) {
$sUrl .= '/';
}
return $sUrl;
}
/**
* Writes given log message. Returns write state
*
* @param string $sLogMessage log message
* @param string $sLogFileName log file name
*
* @return bool
*/
public function writeToLog($sLogMessage, $sLogFileName)
{
$sLogDist = $this->getConfig()->getLogsDir() . $sLogFileName;
$blOk = false;
if (($oHandle = fopen($sLogDist, 'a')) !== false) {
fwrite($oHandle, $sLogMessage);
$blOk = fclose($oHandle);
}
return $blOk;
}
/**
* handler for 404 (page not found) error
*
* @param string $sUrl url which was given, can be not specified in some cases
*/
public function handlePageNotFoundError($sUrl = '')
{
$this->setHeader("HTTP/1.0 404 Not Found");
if (oxRegistry::getConfig()->isUtf()) {
$this->setHeader("Content-Type: text/html; charset=UTF-8");
}
$sReturn = "Page not found.";
try {
$oView = oxNew('oxUBase');
$oView->init();
$oView->render();
$oView->setClassName('oxUBase');
$oView->addTplParam('sUrl', $sUrl);
if ($sRet = oxRegistry::get("oxUtilsView")->getTemplateOutput('message/err_404.tpl', $oView)) {
$sReturn = $sRet;
}
} catch (Exception $e) {
}
$this->showMessageAndExit($sReturn);
}
/**
* Extracts domain name from given host
*
* @param string $sHost host name
*
* @return string
*/
public function extractDomain($sHost)
{
$oStr = getStr();
if (!$oStr->preg_match('/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/', $sHost) &&
($iLastDot = strrpos($sHost, '.')) !== false
) {
$iLen = $oStr->strlen($sHost);
if (($iNextDot = strrpos($sHost, '.', ($iLen - $iLastDot + 1) * -1)) !== false) {
$sHost = trim($oStr->substr($sHost, $iNextDot), '.');
}
}
return $sHost;
}
}
| {
"content_hash": "9b8108f9786d5555efc957084aee23f9",
"timestamp": "",
"source": "github",
"line_count": 1468,
"max_line_length": 191,
"avg_line_length": 30.486376021798364,
"alnum_prop": 0.5151047951021138,
"repo_name": "EllisV/oxid-standard",
"id": "6d0c6af056d2aad676422c286305ce931342f873",
"size": "45627",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "web/core/oxutils.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "2444"
},
{
"name": "CSS",
"bytes": "158741"
},
{
"name": "HTML",
"bytes": "9228"
},
{
"name": "JavaScript",
"bytes": "245692"
},
{
"name": "PHP",
"bytes": "10033058"
},
{
"name": "Smarty",
"bytes": "1867164"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// Demonstratie: import multiple methods.
namespace InterfaceDemoLibrary
{
interface IGroteInterface
{
void method1()
{
}
void method2()
{
}
void method3()
{
}
void method4()
{
}
void method5()
{
}
}
}
| {
"content_hash": "ee7606238d1b33d3ca8f439a5182ce62",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 41,
"avg_line_length": 13.114285714285714,
"alnum_prop": 0.514161220043573,
"repo_name": "T4wb/UCMeldenChatbericht",
"id": "f936aacbddc46c533347c7954a2dc4b7b5792064",
"size": "461",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "InterfaceDemoLibrary/InterfaceDemoLibrary/IGroteInterface.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "38809"
},
{
"name": "C#",
"bytes": "73105"
},
{
"name": "CSS",
"bytes": "872"
},
{
"name": "HTML",
"bytes": "5127"
},
{
"name": "JavaScript",
"bytes": "170489"
}
],
"symlink_target": ""
} |
from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union, cast
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.polling.base_polling import LROBasePolling
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from .. import models as _models
from .._serialization import Serializer
from .._vendor import _convert_request, _format_url_section
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_get_datasets_by_workspace_request(**kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/datasets")
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_or_update_dataset_request(
dataset_name: str, *, if_match: Optional[str] = None, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/datasets/{datasetName}")
path_format_arguments = {
"datasetName": _SERIALIZER.url(
"dataset_name",
dataset_name,
"str",
max_length=260,
min_length=1,
pattern=r"^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$",
),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if if_match is not None:
_headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str")
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_dataset_request(dataset_name: str, *, if_none_match: Optional[str] = None, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/datasets/{datasetName}")
path_format_arguments = {
"datasetName": _SERIALIZER.url(
"dataset_name",
dataset_name,
"str",
max_length=260,
min_length=1,
pattern=r"^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$",
),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if if_none_match is not None:
_headers["If-None-Match"] = _SERIALIZER.header("if_none_match", if_none_match, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_dataset_request(dataset_name: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) # type: str
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/datasets/{datasetName}")
path_format_arguments = {
"datasetName": _SERIALIZER.url(
"dataset_name",
dataset_name,
"str",
max_length=260,
min_length=1,
pattern=r"^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$",
),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
def build_rename_dataset_request(dataset_name: str, **kwargs: Any) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str]
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop("template_url", "/datasets/{datasetName}/rename")
path_format_arguments = {
"datasetName": _SERIALIZER.url(
"dataset_name",
dataset_name,
"str",
max_length=260,
min_length=1,
pattern=r"^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$",
),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
class DatasetOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.synapse.artifacts.ArtifactsClient`'s
:attr:`dataset` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def get_datasets_by_workspace(self, **kwargs: Any) -> Iterable["_models.DatasetResource"]:
"""Lists datasets.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either DatasetResource or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.synapse.artifacts.models.DatasetResource]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.DatasetListResponse]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_get_datasets_by_workspace_request(
api_version=api_version,
template_url=self.get_datasets_by_workspace.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
path_format_arguments = {
"endpoint": self._serialize.url(
"self._config.endpoint", self._config.endpoint, "str", skip_quote=True
),
}
request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore
else:
request = HttpRequest("GET", next_link)
request = _convert_request(request)
path_format_arguments = {
"endpoint": self._serialize.url(
"self._config.endpoint", self._config.endpoint, "str", skip_quote=True
),
}
request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("DatasetListResponse", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
return pipeline_response
return ItemPaged(get_next, extract_data)
get_datasets_by_workspace.metadata = {"url": "/datasets"} # type: ignore
def _create_or_update_dataset_initial(
self, dataset_name: str, properties: _models.Dataset, if_match: Optional[str] = None, **kwargs: Any
) -> Optional[_models.DatasetResource]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DatasetResource]]
_dataset = _models.DatasetResource(properties=properties)
_json = self._serialize.body(_dataset, "DatasetResource")
request = build_create_or_update_dataset_request(
dataset_name=dataset_name,
if_match=if_match,
api_version=api_version,
content_type=content_type,
json=_json,
template_url=self._create_or_update_dataset_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
path_format_arguments = {
"endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
}
request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize("DatasetResource", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_dataset_initial.metadata = {"url": "/datasets/{datasetName}"} # type: ignore
@distributed_trace
def begin_create_or_update_dataset(
self, dataset_name: str, properties: _models.Dataset, if_match: Optional[str] = None, **kwargs: Any
) -> LROPoller[_models.DatasetResource]:
"""Creates or updates a dataset.
:param dataset_name: The dataset name. Required.
:type dataset_name: str
:param properties: Dataset properties. Required.
:type properties: ~azure.synapse.artifacts.models.Dataset
:param if_match: ETag of the dataset entity. Should only be specified for update, for which it
should match existing entity or can be * for unconditional update. Default value is None.
:type if_match: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be LROBasePolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either DatasetResource or the result of
cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.synapse.artifacts.models.DatasetResource]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.DatasetResource]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_or_update_dataset_initial( # type: ignore
dataset_name=dataset_name,
properties=properties,
if_match=if_match,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("DatasetResource", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
"endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
}
if polling is True:
polling_method = cast(
PollingMethod, LROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update_dataset.metadata = {"url": "/datasets/{datasetName}"} # type: ignore
@distributed_trace
def get_dataset(
self, dataset_name: str, if_none_match: Optional[str] = None, **kwargs: Any
) -> Optional[_models.DatasetResource]:
"""Gets a dataset.
:param dataset_name: The dataset name. Required.
:type dataset_name: str
:param if_none_match: ETag of the dataset entity. Should only be specified for get. If the ETag
matches the existing entity tag, or if * was provided, then no content will be returned.
Default value is None.
:type if_none_match: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: DatasetResource or None or the result of cls(response)
:rtype: ~azure.synapse.artifacts.models.DatasetResource or None
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DatasetResource]]
request = build_get_dataset_request(
dataset_name=dataset_name,
if_none_match=if_none_match,
api_version=api_version,
template_url=self.get_dataset.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
path_format_arguments = {
"endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
}
request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 304]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize("DatasetResource", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_dataset.metadata = {"url": "/datasets/{datasetName}"} # type: ignore
def _delete_dataset_initial( # pylint: disable=inconsistent-return-statements
self, dataset_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_delete_dataset_request(
dataset_name=dataset_name,
api_version=api_version,
template_url=self._delete_dataset_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
path_format_arguments = {
"endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
}
request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
if cls:
return cls(pipeline_response, None, {})
_delete_dataset_initial.metadata = {"url": "/datasets/{datasetName}"} # type: ignore
@distributed_trace
def begin_delete_dataset(self, dataset_name: str, **kwargs: Any) -> LROPoller[None]:
"""Deletes a dataset.
:param dataset_name: The dataset name. Required.
:type dataset_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be LROBasePolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_dataset_initial( # type: ignore
dataset_name=dataset_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
"endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
}
if polling is True:
polling_method = cast(
PollingMethod, LROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete_dataset.metadata = {"url": "/datasets/{datasetName}"} # type: ignore
def _rename_dataset_initial( # pylint: disable=inconsistent-return-statements
self, dataset_name: str, new_name: Optional[str] = None, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
_request = _models.ArtifactRenameRequest(new_name=new_name)
_json = self._serialize.body(_request, "ArtifactRenameRequest")
request = build_rename_dataset_request(
dataset_name=dataset_name,
api_version=api_version,
content_type=content_type,
json=_json,
template_url=self._rename_dataset_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
path_format_arguments = {
"endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
}
request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
if cls:
return cls(pipeline_response, None, {})
_rename_dataset_initial.metadata = {"url": "/datasets/{datasetName}/rename"} # type: ignore
@distributed_trace
def begin_rename_dataset(self, dataset_name: str, new_name: Optional[str] = None, **kwargs: Any) -> LROPoller[None]:
"""Renames a dataset.
:param dataset_name: The dataset name. Required.
:type dataset_name: str
:param new_name: New name of the artifact. Default value is None.
:type new_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be LROBasePolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) # type: str
content_type = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = self._rename_dataset_initial( # type: ignore
dataset_name=dataset_name,
new_name=new_name,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
"endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
}
if polling is True:
polling_method = cast(
PollingMethod, LROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
) # type: PollingMethod
elif polling is False:
polling_method = cast(PollingMethod, NoPolling())
else:
polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_rename_dataset.metadata = {"url": "/datasets/{datasetName}/rename"} # type: ignore
| {
"content_hash": "f3f3e8b4ea7bf5ec05f184691e232936",
"timestamp": "",
"source": "github",
"line_count": 711,
"max_line_length": 120,
"avg_line_length": 43.748241912798875,
"alnum_prop": 0.6167818678669025,
"repo_name": "Azure/azure-sdk-for-python",
"id": "8da08e7e90a7451757c3b493191434d1ce1d5ec5",
"size": "31605",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/synapse/azure-synapse-artifacts/azure/synapse/artifacts/operations/_dataset_operations.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1224"
},
{
"name": "Bicep",
"bytes": "24196"
},
{
"name": "CSS",
"bytes": "6089"
},
{
"name": "Dockerfile",
"bytes": "4892"
},
{
"name": "HTML",
"bytes": "12058"
},
{
"name": "JavaScript",
"bytes": "8137"
},
{
"name": "Jinja",
"bytes": "10377"
},
{
"name": "Jupyter Notebook",
"bytes": "272022"
},
{
"name": "PowerShell",
"bytes": "518535"
},
{
"name": "Python",
"bytes": "715484989"
},
{
"name": "Shell",
"bytes": "3631"
}
],
"symlink_target": ""
} |
require "google/cloud/asset/v1"
##
# Example demonstrating basic usage of
# Google::Cloud::Asset::V1::AssetService::Client#delete_saved_query
#
def delete_saved_query
# Create a client object. The client can be reused for multiple calls.
client = Google::Cloud::Asset::V1::AssetService::Client.new
# Create a request. To set request fields, pass in keyword arguments.
request = Google::Cloud::Asset::V1::DeleteSavedQueryRequest.new
# Call the delete_saved_query method.
result = client.delete_saved_query request
# The returned object is of type Google::Protobuf::Empty.
p result
end
# [END cloudasset_v1_generated_AssetService_DeleteSavedQuery_sync]
| {
"content_hash": "da0870ff0333988afb8380aa4e05347d",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 72,
"avg_line_length": 33.55,
"alnum_prop": 0.7555886736214605,
"repo_name": "googleapis/google-cloud-ruby",
"id": "8826018a4983a70f617edaa005aa4537d88d2998",
"size": "1403",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "google-cloud-asset-v1/snippets/asset_service/delete_saved_query.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "23930"
},
{
"name": "CSS",
"bytes": "1422"
},
{
"name": "DIGITAL Command Language",
"bytes": "2216"
},
{
"name": "Go",
"bytes": "1321"
},
{
"name": "HTML",
"bytes": "66414"
},
{
"name": "JavaScript",
"bytes": "1862"
},
{
"name": "Ruby",
"bytes": "103945852"
},
{
"name": "Shell",
"bytes": "19653"
}
],
"symlink_target": ""
} |
var lift = require('lift-result/cps')
var ghtag = lift(require('github-latest'))
var Result = require('result')
var log = require('./logger')
var fs = require('fs')
exports.parseKeyValue = function(dep){
// github shorthand
var m = /^([-.\w]+)\/([-.\w]+)(?:@([-.\w]+|\d+\.\d+\.\d+))?$/.exec(dep)
if (m) {
var key = m[1] + '/' + m[2]
if (m[3]) return Result.wrap([key, m[3]])
return exports.latest(m[1], m[2]).then(function(tag){
return [key, tag || '*']
})
}
throw new Error('search not implemented')
}
exports.latest = function(user, repo){
log.info('fetching', 'latest tag for %s/%s', user, repo)
return ghtag(user, repo)
}
exports.getDeps = function(file){
if (!fs.existsSync(file)) throw new Error('no component.json')
return JSON.parse(fs.readFileSync(file, 'utf8'))
}
/**
* add an entry to the component.json file
*
* @param {String} key
* @param {String} url
*/
exports.add = function(key, tag, opts){
var json = exports.getDeps(opts.file)
// --development
if (opts.development) {
var deps = json.development || (json.development = {})
} else {
var deps = json.dependencies || (json.dependencies = {})
}
deps[key] = tag
fs.writeFileSync(opts.file, JSON.stringify(json, null, 2))
} | {
"content_hash": "4efacb44672163a96f6ac93e395e2d1f",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 72,
"avg_line_length": 24.15686274509804,
"alnum_prop": 0.6258116883116883,
"repo_name": "jkroso/component-set",
"id": "5be899dbec99be950a822862cb1f0f68613a1fd3",
"size": "1232",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bin/utils.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "5460"
}
],
"symlink_target": ""
} |
<?php
namespace Venus\lib\Cache;
/**
* This class manage the Cache by Apc
*
* @category lib
* @package lib\Cache
* @author Judicaël Paquet <[email protected]>
* @copyright Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
* @license https://github.com/las93/venus/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
* @version Release: 1.0.0
* @filesource https://github.com/las93/venus
* @link https://github.com/las93
* @since 1.0
*/
class Apc implements CacheInterface {
/**
* set a value
*
* @access public
* @param string $sName name of the session
* @param mixed $mValue value of this sesion var
* @param int $iFlag unused
* @param int $iExpire expiration of cache
* @return \Venus\lib\Cache\Apc
*/
public function set($sName, $mValue, $iFlag = 0, $iExpire = 0) {
apc_add($sName, $mValue, $iExpire);
return $this;
}
/**
* get a value
*
* @access public
* @param string $sName name of the session
* @param int $iFlags flags
* @param int $iTimeout expiration of cache
* @return mixed
*/
public function get($sName, &$iFlags = null, $iTimeout = 0) {
return apc_fetch($sName);
}
/**
* delete a value
*
* @access public
* @param string $sName name of the session
* @return mixed
*/
public function delete($sName) {
return apc_delete($sName);
}
/**
* flush the cache
*
* @access public
* @return mixed
*/
public function flush() {
return flush();
}
}
| {
"content_hash": "4fe280eaef1d43010ad5463c6a55415c",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 105,
"avg_line_length": 19.39240506329114,
"alnum_prop": 0.6344647519582245,
"repo_name": "las93/venus_website",
"id": "3147d6d46e411fa79858858cddfc303e4fb36cd1",
"size": "2009",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "private/lib/Cache/Apc.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "385805"
}
],
"symlink_target": ""
} |
package com.bazaarvoice.emodb.common.cassandra.test;
import com.bazaarvoice.emodb.common.cassandra.CassandraKeyspace;
import com.bazaarvoice.emodb.common.cassandra.health.CassandraHealthCheck;
import com.codahale.metrics.health.HealthCheck;
import com.datastax.driver.core.ExecutionInfo;
import com.datastax.driver.core.Host;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;
import com.google.common.base.Stopwatch;
import com.netflix.astyanax.Keyspace;
import com.netflix.astyanax.connectionpool.OperationResult;
import com.netflix.astyanax.connectionpool.exceptions.OperationException;
import com.netflix.astyanax.cql.CqlStatement;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.time.Clock;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
public class TestCassandraHealthCheck {
private String _queryString = "SELECT peer FROM system.peers LIMIT 1";
private CqlStatement _astyanaxStatement;
private Session _cqlSession;
private Clock _clock;
private CassandraHealthCheck _healthCheck;
@BeforeMethod
public void setUp() throws Exception {
CassandraKeyspace keyspace = mock(CassandraKeyspace.class);
_astyanaxStatement = mock(CqlStatement.class);
when(_astyanaxStatement.withCql(_queryString)).thenReturn(_astyanaxStatement);
when(_astyanaxStatement.withConsistencyLevel(any())).thenReturn(_astyanaxStatement);
Keyspace astyanaxKeyspace = mock(Keyspace.class);
when(astyanaxKeyspace.prepareCqlStatement()).thenReturn(_astyanaxStatement);
when(keyspace.getAstyanaxKeyspace()).thenReturn(astyanaxKeyspace);
_cqlSession = mock(Session.class);
when(keyspace.getCqlSession()).thenReturn(_cqlSession);
_clock = mock(Clock.class);
_healthCheck = new CassandraHealthCheck(keyspace, _queryString, _clock);
}
@SuppressWarnings("unchecked")
@Test
public void testHealthCheckCaching() throws Exception {
// Perform one positive health check to get it cached.
OperationResult operationResult = createPositiveOperationResult("host1");
ResultSet resultSet = createPositiveResultSet("host1");
when(_astyanaxStatement.execute()).thenReturn(operationResult);
when(_cqlSession.execute(_queryString)).thenReturn(resultSet);
long now = 1478789200000L;
when(_clock.millis()).thenReturn(now);
HealthCheck.Result result = _healthCheck.execute();
assertTrue(result.isHealthy());
assertTrue(result.getMessage().contains("host1"));
// Change the health checks to return a different host
operationResult = createPositiveOperationResult("host2");
resultSet = createPositiveResultSet("host2");
when(_astyanaxStatement.execute()).thenReturn(operationResult);
when(_cqlSession.execute(_queryString)).thenReturn(resultSet);
// Move time forward 4.9 seconds to ensure the cached result is still returned
when(_clock.millis()).thenReturn(now = now + 4900L);
result = _healthCheck.execute();
assertTrue(result.isHealthy());
// Since the cached value should have been returned the old hosts should still be included in the message
assertTrue(result.getMessage().contains("host1"));
assertFalse(result.getMessage().contains("host2"));
// Move time forward another 0.1 seconds for a total of 5.
when(_clock.millis()).thenReturn(now + 100L);
// Now the health check should perform the ping queries again
result = _healthCheck.execute();
assertTrue(result.isHealthy());
assertTrue(result.getMessage().contains("host2"));
assertFalse(result.getMessage().contains("host1"));
}
@SuppressWarnings({"ThrowableResultOfMethodCallIgnored", "unchecked"})
@Test(timeOut = 15000L)
public void testConcurrentHealthChecks() throws Exception {
// Perform one positive health check to get it cached.
OperationResult operationResult = createPositiveOperationResult("host1");
ResultSet resultSet = createPositiveResultSet("host1");
when(_astyanaxStatement.execute()).thenReturn(operationResult);
when(_cqlSession.execute(_queryString)).thenReturn(resultSet);
long now = 1478789200000L;
when(_clock.millis()).thenReturn(now);
HealthCheck.Result result = _healthCheck.execute();
assertTrue(result.isHealthy());
assertTrue(result.getMessage().contains("host1"));
// Change the CQL health check to block for a controlled amount of time
final CountDownLatch cqlBlocked = new CountDownLatch(1);
final CountDownLatch raiseConnectionException = new CountDownLatch(1);
when(_cqlSession.execute(_queryString)).thenAnswer(new Answer<ResultSet>() {
@Override
public ResultSet answer(InvocationOnMock invocationOnMock) throws Throwable {
// Let the main thread know we are blocked
cqlBlocked.countDown();
// Wait for the main thread to give the signal to raise the connection exception
raiseConnectionException.await();
// Raise the exception
throw new OperationException("simulated cassandra exception");
}
});
// Move time forward 5 seconds to ensure the cached value isn't being returned.
when(_clock.millis()).thenReturn(now = now + TimeUnit.SECONDS.toMillis(5));
ExecutorService service = Executors.newFixedThreadPool(1);
try {
// In a new thread perform a health check
Future<HealthCheck.Result> blockedThreadResult = service.submit(() -> _healthCheck.execute());
// Wait for the thread's CQL call to be blocked
assertTrue(cqlBlocked.await(5, TimeUnit.SECONDS), "Thread taking too long to make CQL call");
// Make a call to the health check. It should return immediately with the old healthy value
result = _healthCheck.execute();
assertTrue(result.isHealthy());
assertTrue(result.getMessage().contains("host1"));
// Move time forward 29 seconds and check again
when(_clock.millis()).thenReturn(now = now + TimeUnit.SECONDS.toMillis(29));
result = _healthCheck.execute();
assertTrue(result.isHealthy());
assertTrue(result.getMessage().contains("host1"));
// Now move time forward one more second for a total of 30. At this point this health check should return
// unhealthy because the other health check is taking too long.
when(_clock.millis()).thenReturn(now + TimeUnit.SECONDS.toMillis(1));
Stopwatch stopWatch = Stopwatch.createStarted();
result = _healthCheck.execute();
stopWatch.stop();
// Health check shouldn't have taken long
assertTrue(stopWatch.elapsed(TimeUnit.SECONDS) < 1, "Heath check should not have been blocked");
assertFalse(result.isHealthy());
assertEquals(result.getMessage(), "Asynchronous health check update is taking too long");
// Unblock the thread's health check and let it finish
raiseConnectionException.countDown();
result = blockedThreadResult.get(2, TimeUnit.SECONDS);
assertFalse(result.isHealthy());
assertTrue(result.getError() instanceof OperationException);
} catch (Exception e) {
// Always ensure the thread completes
raiseConnectionException.countDown();
service.shutdownNow();
}
}
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
@Test
public void testNegativeHealthCheck() throws Exception {
when(_astyanaxStatement.execute()).thenThrow(new OperationException("simulated cassandra exception"));
when(_clock.millis()).thenReturn(1478789200000L);
HealthCheck.Result result = _healthCheck.execute();
assertFalse(result.isHealthy());
assertTrue(result.getError() instanceof OperationException);
}
private OperationResult createPositiveOperationResult(String hostName) {
OperationResult operationResult = mock(OperationResult.class);
com.netflix.astyanax.connectionpool.Host host = mock(com.netflix.astyanax.connectionpool.Host.class);
when(host.toString()).thenReturn(hostName);
when(operationResult.getHost()).thenReturn(host);
when(operationResult.getAttemptsCount()).thenReturn(1);
return operationResult;
}
private ResultSet createPositiveResultSet(String hostName) {
ExecutionInfo executionInfo = mock(ExecutionInfo.class);
Host host = mock(Host.class);
when(host.toString()).thenReturn(hostName);
when(executionInfo.getQueriedHost()).thenReturn(host);
ResultSet resultSet = mock(ResultSet.class);
when(resultSet.getExecutionInfo()).thenReturn(executionInfo);
return resultSet;
}
}
| {
"content_hash": "4597bd0d16c7f7f55a0d37632152f172",
"timestamp": "",
"source": "github",
"line_count": 210,
"max_line_length": 119,
"avg_line_length": 45.82380952380952,
"alnum_prop": 0.6984308427725242,
"repo_name": "bazaarvoice/emodb",
"id": "f7c672754918f44b05d2bb627766d237d41609f3",
"size": "9623",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "common/astyanax/src/test/java/com/bazaarvoice/emodb/common/cassandra/test/TestCassandraHealthCheck.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1012"
},
{
"name": "Java",
"bytes": "6388105"
},
{
"name": "Shell",
"bytes": "12562"
}
],
"symlink_target": ""
} |
package com.intellij.codeInspection.ui.actions.suppress;
import com.intellij.codeInspection.*;
import com.intellij.codeInspection.ex.GlobalInspectionContextImpl;
import com.intellij.codeInspection.ex.InspectionManagerEx;
import com.intellij.codeInspection.ex.InspectionToolWrapper;
import com.intellij.codeInspection.reference.RefElement;
import com.intellij.codeInspection.reference.RefEntity;
import com.intellij.codeInspection.ui.ProblemDescriptionNode;
import com.intellij.codeInspection.ui.SuppressableInspectionTreeNode;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.PsiElement;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.SequentialTask;
import com.intellij.util.ThrowableRunnable;
import com.intellij.util.containers.Queue;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* @author Dmitry Batkovich
*/
public class SuppressActionSequentialTask implements SequentialTask {
private static final Logger LOG = Logger.getInstance(SuppressActionSequentialTask.class);
private SuppressableInspectionTreeNode[] myNodesToSuppress;
@NotNull private final SuppressIntentionAction mySuppressAction;
@NotNull private final InspectionToolWrapper myWrapper;
@NotNull private final GlobalInspectionContextImpl myContext;
private int myCount = 0;
public SuppressActionSequentialTask(@NotNull SuppressableInspectionTreeNode[] nodesToSuppress,
@NotNull SuppressIntentionAction suppressAction,
@NotNull InspectionToolWrapper wrapper,
@NotNull GlobalInspectionContextImpl context) {
myNodesToSuppress = nodesToSuppress;
mySuppressAction = suppressAction;
myWrapper = wrapper;
myContext = context;
}
@Override
public boolean iteration() {
final SuppressableInspectionTreeNode node = myNodesToSuppress[myCount++];
final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null) {
indicator.setFraction((double)myCount / myNodesToSuppress.length);
}
final Pair<PsiElement, CommonProblemDescriptor> content = node.getSuppressContent();
if (content.first != null) {
final PsiElement element = content.first;
RefEntity refEntity = node.getElement();
LOG.assertTrue(refEntity != null);
suppress(element, content.second, mySuppressAction, refEntity, myWrapper, node);
}
return false;
}
@Override
public boolean isDone() {
return myCount > myNodesToSuppress.length - 1;
}
@Override
public void stop() {
}
@Override
public void prepare() {
final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null) {
indicator.setText(InspectionsBundle.message("inspection.action.suppress", myWrapper.getDisplayName()));
}
}
private void suppress(@NotNull final PsiElement element,
@Nullable final CommonProblemDescriptor descriptor,
@NotNull final SuppressIntentionAction action,
@NotNull final RefEntity refEntity, InspectionToolWrapper wrapper,
@NotNull final SuppressableInspectionTreeNode node) {
if (action instanceof SuppressIntentionActionFromFix && !(descriptor instanceof ProblemDescriptor)) {
LOG.info("local suppression fix for specific problem descriptor: " + wrapper.getTool().getClass().getName());
}
final Project project = element.getProject();
try {
PsiElement container = null;
if (action instanceof SuppressIntentionActionFromFix) {
container = ((SuppressIntentionActionFromFix)action).getContainer(element);
}
if (container == null) {
container = element;
}
if (action.isAvailable(project, null, element)) {
ThrowableRunnable<RuntimeException> runnable = () -> action.invoke(project, null, element);
if (action.startInWriteAction()) {
WriteAction.run(runnable);
}
else {
runnable.run();
}
}
final Set<GlobalInspectionContextImpl> globalInspectionContexts =
((InspectionManagerEx)InspectionManager.getInstance(element.getProject())).getRunningContexts();
for (GlobalInspectionContextImpl context : globalInspectionContexts) {
context.ignoreElement(wrapper.getTool(), container);
if (descriptor != null) {
context.getPresentation(wrapper).ignoreCurrentElementProblem(refEntity, descriptor);
}
}
final RefElement containerRef = refEntity.getRefManager().getReference(container);
final Set<Object> suppressedNodes = myContext.getView().getSuppressedNodes(wrapper.getShortName());
if (containerRef != null) {
Queue<RefEntity> toIgnoreInView = new Queue<>(1);
toIgnoreInView.addLast(containerRef);
while (!toIgnoreInView.isEmpty()) {
final RefEntity entity = toIgnoreInView.pullFirst();
if (node instanceof ProblemDescriptionNode) {
final CommonProblemDescriptor[] descriptors = myContext.getPresentation(wrapper).getIgnoredElements().get(entity);
if (descriptors != null) {
Collections.addAll(suppressedNodes, descriptors);
}
} else {
suppressedNodes.add(entity);
}
final List<RefEntity> children = entity.getChildren();
for (RefEntity child : children) {
toIgnoreInView.addLast(child);
}
}
}
if (node instanceof ProblemDescriptionNode) {
suppressedNodes.add(descriptor);
}
}
catch (IncorrectOperationException e1) {
LOG.error(e1);
}
node.removeSuppressActionFromAvailable(mySuppressAction);
}
}
| {
"content_hash": "314587ad8ffdf6f69e38b79013fc779b",
"timestamp": "",
"source": "github",
"line_count": 158,
"max_line_length": 126,
"avg_line_length": 39.60126582278481,
"alnum_prop": 0.7075275691225827,
"repo_name": "asedunov/intellij-community",
"id": "09d48b33596d0b29d4251d19adb08e9e904401df",
"size": "6857",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "platform/lang-impl/src/com/intellij/codeInspection/ui/actions/suppress/SuppressActionSequentialTask.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "20665"
},
{
"name": "AspectJ",
"bytes": "182"
},
{
"name": "Batchfile",
"bytes": "60827"
},
{
"name": "C",
"bytes": "211454"
},
{
"name": "C#",
"bytes": "1264"
},
{
"name": "C++",
"bytes": "199030"
},
{
"name": "CMake",
"bytes": "1675"
},
{
"name": "CSS",
"bytes": "201445"
},
{
"name": "CoffeeScript",
"bytes": "1759"
},
{
"name": "Erlang",
"bytes": "10"
},
{
"name": "Groovy",
"bytes": "3250629"
},
{
"name": "HLSL",
"bytes": "57"
},
{
"name": "HTML",
"bytes": "1899872"
},
{
"name": "J",
"bytes": "5050"
},
{
"name": "Java",
"bytes": "165745831"
},
{
"name": "JavaScript",
"bytes": "570364"
},
{
"name": "Jupyter Notebook",
"bytes": "93222"
},
{
"name": "Kotlin",
"bytes": "4687386"
},
{
"name": "Lex",
"bytes": "147047"
},
{
"name": "Makefile",
"bytes": "2352"
},
{
"name": "NSIS",
"bytes": "51039"
},
{
"name": "Objective-C",
"bytes": "27861"
},
{
"name": "Perl",
"bytes": "903"
},
{
"name": "Perl6",
"bytes": "26"
},
{
"name": "Protocol Buffer",
"bytes": "6680"
},
{
"name": "Python",
"bytes": "25459263"
},
{
"name": "Roff",
"bytes": "37534"
},
{
"name": "Ruby",
"bytes": "1217"
},
{
"name": "Shell",
"bytes": "66338"
},
{
"name": "Smalltalk",
"bytes": "338"
},
{
"name": "TeX",
"bytes": "25473"
},
{
"name": "Thrift",
"bytes": "1846"
},
{
"name": "TypeScript",
"bytes": "9469"
},
{
"name": "Visual Basic",
"bytes": "77"
},
{
"name": "XSLT",
"bytes": "113040"
}
],
"symlink_target": ""
} |
package com.kzmen.sczxjf.bean.kzbean;
import java.io.Serializable;
import java.util.List;
/**
* Created by pjj18 on 2017/9/9.
*/
public class KnowageIndexItem implements Serializable{
/**
* id : 1
* title : 信用知识,快速问专家
* image : http://api.kzmen.cn/Uploads/Picture/2017-09-09/59b39b8df376b.png
* des : 信用提升,维护,利用
* options : ["100%解答","认证专家学者","快速响应"]
* share_title : 信用知识,快速问专家分享标题
* share_des : 信用提升,维护,利用分享摘要
* share_image : http://api.kzmen.cn/Uploads/Picture/2017-09-09/59b39b8df376b.png
* share_linkurl : https://www.baidu.com/
*/
private String id;
private String title;
private String image;
private String des;
private String share_title;
private String share_des;
private String share_image;
private String share_linkurl;
private List<String> options;
public KnowageIndexItem(String id, String title, String image, String des) {
this.id = id;
this.title = title;
this.image = image;
this.des = des;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getDes() {
return des;
}
public void setDes(String des) {
this.des = des;
}
public String getShare_title() {
return share_title;
}
public void setShare_title(String share_title) {
this.share_title = share_title;
}
public String getShare_des() {
return share_des;
}
public void setShare_des(String share_des) {
this.share_des = share_des;
}
public String getShare_image() {
return share_image;
}
public void setShare_image(String share_image) {
this.share_image = share_image;
}
public String getShare_linkurl() {
return share_linkurl;
}
public void setShare_linkurl(String share_linkurl) {
this.share_linkurl = share_linkurl;
}
public List<String> getOptions() {
return options;
}
public void setOptions(List<String> options) {
this.options = options;
}
}
| {
"content_hash": "7c5340dcbc358acc5c67c69062876fbb",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 85,
"avg_line_length": 21.535714285714285,
"alnum_prop": 0.6011608623548922,
"repo_name": "18380460383/eshare",
"id": "a3558f9df02bc173bb305e13763b6451e11db32d",
"size": "2532",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/kzmen/sczxjf/bean/kzbean/KnowageIndexItem.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "118"
},
{
"name": "Java",
"bytes": "4337188"
}
],
"symlink_target": ""
} |
/***************************************************************************/
/* */
/* ftccback.h */
/* */
/* Callback functions of the caching sub-system (specification only). */
/* */
/* Copyright 2004-2006, 2011, 2013 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#ifndef __FTCCBACK_H__
#define __FTCCBACK_H__
#include "ft2build.h"
#include FT_CACHE_H
#include "ftcmru.h"
#include "ftcimage.h"
#include "ftcmanag.h"
#include "ftcglyph.h"
#include "ftcsbits.h"
FT_LOCAL( void )
ftc_inode_free( FTC_Node inode,
FTC_Cache cache );
FT_LOCAL( FT_Error )
ftc_inode_new( FTC_Node *pinode,
FT_Pointer gquery,
FTC_Cache cache );
FT_LOCAL( FT_Offset )
ftc_inode_weight( FTC_Node inode,
FTC_Cache cache );
FT_LOCAL( void )
ftc_snode_free( FTC_Node snode,
FTC_Cache cache );
FT_LOCAL( FT_Error )
ftc_snode_new( FTC_Node *psnode,
FT_Pointer gquery,
FTC_Cache cache );
FT_LOCAL( FT_Offset )
ftc_snode_weight( FTC_Node snode,
FTC_Cache cache );
FT_LOCAL( FT_Bool )
ftc_snode_compare( FTC_Node snode,
FT_Pointer gquery,
FTC_Cache cache,
FT_Bool* list_changed );
FT_LOCAL( FT_Bool )
ftc_gnode_compare( FTC_Node gnode,
FT_Pointer gquery,
FTC_Cache cache,
FT_Bool* list_changed );
FT_LOCAL( FT_Error )
ftc_gcache_init( FTC_Cache cache );
FT_LOCAL( void )
ftc_gcache_done( FTC_Cache cache );
FT_LOCAL( FT_Error )
ftc_cache_init( FTC_Cache cache );
FT_LOCAL( void )
ftc_cache_done( FTC_Cache cache );
FT_LOCAL( void )
ftc_node_destroy( FTC_Node node,
FTC_Manager manager );
#endif /* __FTCCBACK_H__ */
/* END */
| {
"content_hash": "43c4d4e8b55106ba6d5ee2d5b5145786",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 77,
"avg_line_length": 31.747252747252748,
"alnum_prop": 0.4250605745932849,
"repo_name": "paintdream/PaintsNow",
"id": "e33f8248aabdd2a79c465fc0c70dffd5341ed95d",
"size": "2889",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source/General/Driver/Font/Freetype/Core/src/cache/ftccback.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "91826"
},
{
"name": "Awk",
"bytes": "4021"
},
{
"name": "Batchfile",
"bytes": "4046"
},
{
"name": "C",
"bytes": "49335279"
},
{
"name": "C#",
"bytes": "3242"
},
{
"name": "C++",
"bytes": "17424751"
},
{
"name": "CMake",
"bytes": "353888"
},
{
"name": "CSS",
"bytes": "35454"
},
{
"name": "Clarion",
"bytes": "7135"
},
{
"name": "DIGITAL Command Language",
"bytes": "35904"
},
{
"name": "HTML",
"bytes": "1473281"
},
{
"name": "JavaScript",
"bytes": "46807"
},
{
"name": "Less",
"bytes": "9584"
},
{
"name": "Lua",
"bytes": "250991"
},
{
"name": "M4",
"bytes": "262328"
},
{
"name": "Makefile",
"bytes": "667253"
},
{
"name": "Objective-C",
"bytes": "143734"
},
{
"name": "PHP",
"bytes": "2913"
},
{
"name": "Perl",
"bytes": "16817"
},
{
"name": "Python",
"bytes": "228688"
},
{
"name": "Roff",
"bytes": "328102"
},
{
"name": "Shell",
"bytes": "1150162"
},
{
"name": "VBScript",
"bytes": "4926"
},
{
"name": "Yacc",
"bytes": "154301"
},
{
"name": "sed",
"bytes": "1026"
}
],
"symlink_target": ""
} |
(function () {
'use strict';
/**
* The component representing latest build for given Build Configuration or Build Group Configuration
*/
angular.module('pnc.common.components').component('pncLatestBuild', {
bindings: {
/**
* Object: The configuration representing Build Configuration
*/
buildConfig: '<?',
/**
* Object: The configuration representing Build Group Configuration
*/
buildGroup: '<?'
},
templateUrl: 'common/components/pnc-latest-build/pnc-latest-build.html',
controller: ['BuildRecord', 'BuildConfigurationSetDAO', Controller]
});
/*
* This component requires extensive refactoring when BC refactor takes place
*/
function Controller(BuildRecord, BuildConfigurationSetDAO) {
var $ctrl = this;
$ctrl.isLoaded = false;
function setLatestBuild(data) {
$ctrl.latestBuild = data;
$ctrl.isLoaded = true;
}
function loadLatestBuild() {
var resultPromise;
if ($ctrl.buildGroup) {
resultPromise = BuildConfigurationSetDAO.getLatestBuildConfigSetRecordsForConfigSet({ configurationSetId: $ctrl.buildGroup.id }).then(function (data) {
setLatestBuild(_.isArray(data) ? data[0] : null);
});
} else {
// it will be refactored when working on BuildConfigResource (NCL-4198)
resultPromise = BuildRecord.getLastByConfiguration({ id: $ctrl.buildConfig.id }).$promise.then(function (data) {
setLatestBuild(_.isArray(data.content) ? data.content[0] : null);
});
}
resultPromise.finally(function() {
$ctrl.isLoaded = true;
});
}
$ctrl.$onInit = function() {
loadLatestBuild();
};
}
})();
| {
"content_hash": "cb40b785387cc1bfef4c6458bd77d24c",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 159,
"avg_line_length": 28.983333333333334,
"alnum_prop": 0.6377228292121909,
"repo_name": "matedo1/pnc",
"id": "57f978774032f459476d3622fa1689432344d3e3",
"size": "2446",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ui/app/common/components/pnc-latest-build/pncLatestBuild.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "113378"
},
{
"name": "HTML",
"bytes": "374178"
},
{
"name": "Java",
"bytes": "4641347"
},
{
"name": "JavaScript",
"bytes": "3087740"
},
{
"name": "TSQL",
"bytes": "49789"
}
],
"symlink_target": ""
} |
import { Commander } from "./Commander/Commander";
var program = require('commander');
class Packages extends Commander{
public VERSION = "0.0.1";
private program;
constructor(program){
this.program = program;
}
public setProcess(process)
{
this.setOptions(process);
}
private setOptions(process)
{
this.program.version(this.VERSION).option('-l, --listpackages', 'Lista os pacotes NodeJSInstalados').parse(process);
}
public getCommander() {
return this.program;
}
public execute(type) {
this.execCommand(this.program);
}
}
var Package = new Packages(program);
export = Package; | {
"content_hash": "8141389a70b6e56758e71c7aaad58771",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 124,
"avg_line_length": 20.08823529411765,
"alnum_prop": 0.636896046852123,
"repo_name": "michaeldouglas/listpackages-nodejs",
"id": "fc2ee2a9d058f49e4af3c0867d713d996b4fc6f1",
"size": "683",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Packages.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1589"
},
{
"name": "TypeScript",
"bytes": "987"
}
],
"symlink_target": ""
} |
<a name="toaster"></a>
<div class="container-fluid">
<div class="row">
<div class="col-sm-12">
<div class="page-header">
<h1>Soc Alerts <small>Information blocks or disaster announcements
<span class="label label-success">Continue grid</span>
<span class="label label-default">Wrap</span>
<span class="label label-warning">JS</span>
</small></h1>
</div>
</div>
<div class="col-sm-12">
<div class="alert alert-success" role="alert">
<strong>Success!</strong> Everything is alright
</div>
<div class="alert alert-info" role="alert">
<strong>Informational</strong> It might have worked, but maybe check some things
</div>
<div class="alert alert-warning" role="alert">
<strong>Warning!</strong> Looks innocent, but probably went wrong underneath
</div>
<div class="alert alert-danger" role="alert">
<strong>Error!</strong> Run
</div>
<hr/>
<p>Dismissable alert</p>
<div class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Warning!</strong> Better check it
</div>
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Error!</strong> Action failed
</div>
<hr/>
<p>Links in alerts</p>
<div class="alert alert-info" role="alert">
<strong>Informational</strong> It might have worked, but maybe check some <a href="#" class="alert-link">things</a>
</div>
<div class="well">
<span>emmets:
<pre><code>.alert.alert-success>strong{success}+{ Everything is alright}</code></pre>
<pre><code>.alert.alert-info>strong{info}+{ Everything is alright}</code></pre>
<pre><code>.alert.alert-warning>strong{warning}+{ Everything is alright}</code></pre>
<pre><code>.alert.alert-danger>strong{danger}+{ Everything is alright}</code></pre>
</span>
<span>Dismissible emmet:
<pre><code>.alert.alert-danger.alert-dismissible>button.close[type="button" data-dismiss="alert" aria-label="Close"]>span[aria-hidden="true"]{×}^strong{danger}+{ Everything is alright}</code></pre>
</span>
</div>
</div>
</div>
</div> | {
"content_hash": "1805f6afe59df889f59ee1ae1da1f8d2",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 235,
"avg_line_length": 52.964285714285715,
"alnum_prop": 0.5249494268374916,
"repo_name": "svennoreillie/soc-core",
"id": "3aeddfdf2e8540b87dc0a1501916c10d89a6937f",
"size": "2966",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/html/elements/components_alerts.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "602"
},
{
"name": "CSS",
"bytes": "38691"
},
{
"name": "HTML",
"bytes": "102215"
},
{
"name": "JavaScript",
"bytes": "6133"
}
],
"symlink_target": ""
} |
LSFEventScraper is a multithreaded Python scraper, that extracts all events of the current semster from HTW-Berlin.de
# How it works
Currently, HTW-Berlin.de has an semester-overview page, from where the crawler can reach a page for every day of the current semster.
These day-overview pages are the source, from where every event of the semester can be extracted. What the module does is:<br>
• fetching the semester-overview<br>
• extracting all day-overview URLs<br>
• fetching all day-overviews<br>
• extracting every event<br>
• save the events to a database<br>
# Database Configuration
LSFEventScraper can store the events to either MYSQL or PostgreSQL. If you want to use it with the corresponding HTWRoomFinder, you need to use PostgreSQL.
The first thing you need to do is to create the appropriate tables.
This is how you do it for PostgreSQL:
```python
psql -h <your host> <db-name> <user> < RoomDBInit_PSQL.db
```
And here for mysql:
```python
mysql -p -h <your host> -u <user> -p <db-name> < RoomDBInit_MYSQL.db
```
The LSFEventScraper needs to connect to your database, so you also need to provide your credentials.
Just add your credentials to db_credentials_PSQL.json, if you want to use PostgreSQL,
or to db_credentials_MYSQL.json, if you want to use MYSQL.
# Requirements
The module requires psycopg2, beautifulsoup4, mysql-python. You need pip to install them. for example like this:
pip install requirements.txt
# Usage
To reduce dependencies, the whole project is built up with the facade pattern. Thus the only class, you need to use is LSFEventScraper,
which is an interface for the whole functionality.
There are 2 scenarios for how you can use the LSFEventScraper in a reasonable manner:
1. Scenario:
============
Scraping all events and store them to a database
```python
# - Fetches all events from HTW-Berlin.de and stores them to memory.
scraper.scrape_events()
# - Sends a TRUNCATE command to the database, to delete all current rows.
scraper.db_access.reset()
# - Sends saves all events to the database.
scraper.save_events_to_db()
```
2. Scenario
===========
Fetching all day-overviews and store them as html-files to disk. Scrape the locally stored events and store them to a database later.
```python
# - Fetches all day-overviews and stores them as html files to ./data_events/
scraper.crawl_day_pages_and_save_to_disk()
# - ...Later... After you've fetched the pages, you can scrape and store the events later.
# - Scrapes all local sites and stores them to memory
scraper.scrape_local_sites()
# - Sends a TRUNCATE command to the database, to delete all current rows.
scraper.db_access.reset()
# - Sends saves all events to the database.
scraper.save_events_to_db()
```
test
===
If all requirements are installed, you can test the scraper with
```python
python main.py
```
| {
"content_hash": "139ad4c30679a52945fbe5d06c948ce8",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 155,
"avg_line_length": 36.243589743589745,
"alnum_prop": 0.7576936681995048,
"repo_name": "pascalweiss/LSFEventScraper",
"id": "60db2950e65be5efcd35ff4248867454c85ad358",
"size": "2855",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "23309"
}
],
"symlink_target": ""
} |
NOTICE
======
moodle-tools is no longer under active development. Deployment strategies are easier than ever with Git; I may, however, go back sometime and look at backup/restore functionality via the command line.
moodle-tools
============

What is moodle-tools
--------------------
moodle-tools is a collect of programs used to facilitate administering Moodle
installations. Configuration files store information about one or more
servers, and all moodle-tools programs use this configuration data.
Getting Help
------------
Every program included in moodle-tools shows helpful output with the `-h` or
`--help` option. Similar to Git, you can also get help on a command by running
`mdl help COMMAND`.
It Can Do
---------
* `mdl server` - Shows server configuration data as defined in an XML-based
configuration file. This XML file allows you to define an installation
directory and a data directory for one or more installations of Moodle on
one or more servers.
Other programs that need to access information about your Moodle
installations will use the output from `mdl server` to do so.
`mdl server` tries to locate a valid XML file in the following order:
1. Look for the file passed by the command line (`mdl server -f FILE` or
`mdl server --file=FILE`)
2. Look for the file defined by the environment variable named
`MDL_SERVER_CONFIG`
3. Look for a file named `mdl-server.xml` in the current working directory
Note that if the environment variable exists and points to a valid file,
you MUST pass `-f` or `--file` if you want to specify a different file
(having `mdl-server.xml` in your working directory is not enough, as the
environment variable takes precedence).
See the file `src/mdl-server-schema.xml` for the details of how to
construct this XML file, and `src/mdl-server.sample.xml` for a sample file.
It Might Will Can Do
--------------------
* `mdl archive` - Archive a working git branch or a source distribution
to a file
* `mdl deploy` - Deploy a working git branch, source distribution, or
archive file to a working Moodle installation. Can use data from
`mdl server` to determine installation locations
* `mdl maintenance` - Turn maintenance mode on or off for a Moodle
installation.
* `mdl backup` - Back up certain parts of a Moodle installation, including
source code, data directory, and database schema and data.
* `mdl roll-course` - Back up a current course and restore it into a new
course. (Might be easier to use RPC mechanisms?)
Dependencies
------------
moodle-tools is written in Python, so you will obviously need a working
installation. Currently, any version after 2.4 will work. I personally currently
use version 2.6.1.
moodle-tools itself currently depends on no non-standard modules.
Unit tests using nose and coverage (the default in rununittests.sh) requires the
[coverage module](http://pypi.python.org/pypi/coverage/)
and the [nose package](http://somethingaboutorange.com/mrl/projects/nose/).
Installation
------------
Install from the root of the repository by running `sudo python setup.py
install`. Create a source distribution by running `python setup.py sdist`.
Cleaning and/or Uninstalling
----------------------------
`clean.sh` is a bash script located at the root of the repository that helps
clean up your repository (and system, after an install).
Running `clean.sh` with no parameters removes all `.pyc` files, the `.coverage`
file created during unit testing, and the `MANIFEST` file generated by
`setup.py`.
Running `clean.sh uninstall` attempts to uninstall moodle-tools from your
system. It does this in the following way:
1. Find out where Python keeps installed packages by looking at
`distutils.sysconfig.get_python_lib()`.
2. Removing `MoodleTools` from the Python library path.
3. Removing `moodle_tools-*.egg-info` from the Python library path.
4. Removing `mdl` and `mdl-*` from `/usr/local/bin`. (Currently it only
removes a hard-coded list of files--just `mdl` and `mdl-server` for now.)
In either case, `clean.sh` runs checks to see if it can find any remnants of a
moodle-tools installation on your system. It does the following:
1. `ls /usr/local/bin/mdl*` to try to find scripts that weren't removed.
2. Checking for the existance of the MoodleTools folder in the Python
library path.
Contributing
------------
moodle-tools is still in very early planning and development. I decided to
put it on GitHub to get things organized and give anyone who might be crazy
enough to be interested a chance to take a look at it.
Most of these tools stem from specific needs that I have managing the
multiple Moodle installations I have to administer, so some of the tools may
feel very specific, and the package may feel pretty narrow. I'd like to
expand this into a generic toolset that works for a good number of other people.
If you'd like to contribute code, feel free to fork the project, make changes,
and initiate a pull request. It'd be nice if changes came with documentation
and unit tests, but it's not required (yet). I'm not 100% sure how I want
the documentation to work yet (HTML? man pages?), so I haven't checked anything
in quite yet. However, every program should present helpful information
via `mdl-program --help` or `mdl-program -h`.
Clone the project with `git clone git://github.com/BinaryMuse/moodle-tools.git`
Notes
-----
Notes (thoughts, discussion, etc.) for moodle-tools is held at the
[GitHub wiki for moodle-tools](http://wiki.github.com/BinaryMuse/moodle-tools/).
Running Unit Tests
------------------
If you are working off of the source distribution of moodle-tools (checked
out from git or downloaded as a source archive), your directory structure
should resemble the following:
.gitignore
LICENSE
MANIFEST.in
README.md
clean.sh
rununittests.sh
setup.py
src/
source files
test/
unit tests
To run the unit tests, be sure to have the `nose` module installed, change
directories into the root of the source distribution, and run
`./rununittests`. This runs `nosetests` with the appropriate coverage options.
If you don't have coverage installed, a simple `nosetests` will run just the
tests.
Licensing
---------
Copyright (c) 2010, Fresno Pacific University
Licensed under the New BSD license; see the LICENSE file for details.
| {
"content_hash": "8ec9e0d5e3c8c30d6a7e8b356f5f26f1",
"timestamp": "",
"source": "github",
"line_count": 170,
"max_line_length": 200,
"avg_line_length": 38.34117647058824,
"alnum_prop": 0.7356551089291193,
"repo_name": "BinaryMuse/moodle-tools",
"id": "980077014a1d4692298f4065ca28b57d36dfdcb1",
"size": "6518",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "13460"
},
{
"name": "Shell",
"bytes": "1974"
}
],
"symlink_target": ""
} |
Originally published: 2012-02-19 00:16:08
Last updated: 2012-02-19 00:17:07
Author: FB36
I found this equation in Wikipedia page for "List of fractals by Hausdorff dimension".
The problem is how to calculate the scaling coefficients for any given IFS fractal.
You can see the heuristic I used in the code.
It gave correct values for all the fractals listed except for Centipede it gave 2.27.
I do not know its correct fractal dimension to compare though.
| {
"content_hash": "71289cda15330ccc23cb609d7e60301d",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 87,
"avg_line_length": 52.44444444444444,
"alnum_prop": 0.7669491525423728,
"repo_name": "ActiveState/code",
"id": "68744c9d220e3c88289df57be39dbe655848df68",
"size": "511",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "recipes/Python/578048_IFS_fractal/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "35894"
},
{
"name": "C",
"bytes": "56048"
},
{
"name": "C++",
"bytes": "90880"
},
{
"name": "HTML",
"bytes": "11656"
},
{
"name": "Java",
"bytes": "57468"
},
{
"name": "JavaScript",
"bytes": "181218"
},
{
"name": "PHP",
"bytes": "250144"
},
{
"name": "Perl",
"bytes": "37296"
},
{
"name": "Perl 6",
"bytes": "9914"
},
{
"name": "Python",
"bytes": "17387779"
},
{
"name": "Ruby",
"bytes": "40233"
},
{
"name": "Shell",
"bytes": "190732"
},
{
"name": "Tcl",
"bytes": "674650"
}
],
"symlink_target": ""
} |
#pragma once
#include "maxheap.h"
#include "iFnPub.h"
#include "units.h"
#include "BuildWarnings.h"
#include "assetmanagement\assetUser.h"
#include "object.h"
#include "quat.h"
#include "control.h"
#include "ipoint3.h"
//----------------------------------------------------------------
// The following are parameter block IDs for procedural objects
/*! \defgroup paramBlockIDs Parameter Block IDs
\sa BaseObject::GetParamBlockIndex
*/
//@{
/*! \defgroup paramBlockIDs_arc Arc Parameter Block IDs
*/
//@{
#define ARC_RADIUS 0
#define ARC_FROM 1
#define ARC_TO 2
#define ARC_PIE 3
#define ARC_REVERSE 4
//@}
/*! \defgroup paramBlockIDs_boxObject Box Object Parameter Block IDs */
//@{
#define BOXOBJ_LENGTH 0
#define BOXOBJ_WIDTH 1
#define BOXOBJ_HEIGHT 2
#define BOXOBJ_WSEGS 3
#define BOXOBJ_LSEGS 4
#define BOXOBJ_HSEGS 5
#define BOXOBJ_GENUVS 6
//@}
/*! \defgroup paramBlockIDs_circle Circle Parameter Block IDs */
//@{
#define CIRCLE_RADIUS 0
//@}
/*! \defgroup paramBlockIDs_cone Cone Parameter Block IDs */
//@{
#define CONE_RADIUS1 0
#define CONE_RADIUS2 1
#define CONE_HEIGHT 2
#define CONE_SEGMENTS 3
#define CONE_CAPSEGMENTS 4
#define CONE_SIDES 5
#define CONE_SMOOTH 6
#define CONE_SLICEON 7
#define CONE_PIESLICE1 8
#define CONE_PIESLICE2 9
#define CONE_GENUVS 10
//@}
/*! \defgroup paramBlockIDs_cylinder Cylinder Parameter Block IDs */
//@{
#define CYLINDER_RADIUS 0
#define CYLINDER_HEIGHT 1
#define CYLINDER_SEGMENTS 2
#define CYLINDER_CAPSEGMENTS 3
#define CYLINDER_SIDES 4
#define CYLINDER_SMOOTH 5
#define CYLINDER_SLICEON 6
#define CYLINDER_PIESLICE1 7
#define CYLINDER_PIESLICE2 8
#define CYLINDER_GENUVS 9
//@}
/*! \defgroup paramBlockIDs_donut Donut Parameter Block IDs */
//@{
#define DONUT_RADIUS1 0
#define DONUT_RADIUS2 1
//@}
/*! \defgroup paramBlockIDs_ellipse Ellipse Parameter Block IDs */
//@{
#define ELLIPSE_LENGTH 0
#define ELLIPSE_WIDTH 1
//@}
/*! \defgroup paramBlockIDs_hedra Hedra Parameter Block IDs */
//@{
#define HEDRA_RADIUS 0
#define HEDRA_FAMILY 1
#define HEDRA_P 2
#define HEDRA_Q 3
#define HEDRA_SCALEP 4
#define HEDRA_SCALEQ 5
#define HEDRA_SCALER 6
#define HEDRA_VERTS 7
#define HEDRA_GENUVS 8
//@}
/*! \defgroup paramBlockIDs_helix Helix Parameter Block IDs*/
//@{
#define HELIX_RADIUS1 0
#define HELIX_RADIUS2 1
#define HELIX_HEIGHT 2
#define HELIX_TURNS 3
#define HELIX_BIAS 4
#define HELIX_DIRECTION 5
//@}
/*! \defgroup paramBlockIDs_ngon NGon Parameter Block IDs */
//@{
#define NGON_RADIUS 0
#define NGON_SIDES 1
#define NGON_CIRCULAR 2
//@}
/*! \defgroup paramBlockIDs_patchGrid PatchGrid Parameter Block IDs */
//@{
#define PATCHGRID_LENGTH 0
#define PATCHGRID_WIDTH 1
#define PATCHGRID_WSEGS 2
#define PATCHGRID_LSEGS 3
#define PATCHGRID_TEXTURE 4
//@}
/*! \defgroup paramBlockIDs_rainSnow Rain/Snow Parameter Block IDs */
//@{
#define RSPART_VPTPARTICLES 0
#define RSPART_RNDPARTICLES 1
#define RSPART_DROPSIZE 2
#define RSPART_SPEED 3
#define RSPART_VARIATION 4
#define RSPART_DISPTYPE 5
#define RSPART_STARTTIME 6
#define RSPART_LIFETIME 7
#define RSPART_EMITTERWIDTH 8
#define RSPART_EMITTERHEIGHT 9
#define RSPART_HIDEEMITTER 10
#define RSPART_BIRTHRATE 11
#define RSPART_CONSTANT 12
#define RSPART_RENDER 13
#define RSPART_TUMBLE 14
#define RSPART_SCALE 15
//@}
/*! \defgroup paramBlockIDs_rectangle Rectangle Parameter Block IDs */
//@{
#define RECTANGLE_LENGTH 0
#define RECTANGLE_WIDTH 1
#define RECTANGLE_FILLET 2
//@}
/*! \defgroup paramBlockIDs_sphere Sphere Parameter Block IDs */
//@{
#define SPHERE_RADIUS 0
#define SPHERE_SEGS 1
#define SPHERE_SMOOTH 2
#define SPHERE_HEMI 3
#define SPHERE_SQUASH 4
#define SPHERE_RECENTER 5
#define SPHERE_GENUVS 6
//@}
/*! \defgroup paramBlockIDs_star Star Parameter Block IDs */
//@{
#define START_RADIUS1 0
#define START_RADIUS2 1
#define START_POINTS 2
#define START_DISTORT 3
#define START_FILLET1 4
#define START_FILLET2 5
//@}
/*! \defgroup paramBlockIDs_teaPot Tea Pot Parameter Block IDs */
//@{
#define TEAPOT_RADIUS 0
#define TEAPOT_SEGS 1
#define TEAPOT_SMOOTH 2
#define TEAPOT_TEAPART 3
#define TEAPOT_BODY 4
#define TEAPOT_HANDLE 5
#define TEAPOT_SPOUT 6
#define TEAPOT_LID 7
#define TEAPOT_GENUVS 8
//@}
/*! \defgroup paramBlockIDs_text Text Parameter Block IDs */
//@{
#define TEXT_SIZE 0
#define TEXT_KERNING 1
#define TEXT_LEADING 2
//@}
/*! \defgroup paramBlockIDs_torus Torus Parameter Block IDs */
//@{
#define TORUS_RADIUS 0
#define TORUS_RADIUS2 1
#define TORUS_ROTATION 2
#define TORUS_TWIST 3
#define TORUS_SEGMENTS 4
#define TORUS_SIDES 5
#define TORUS_SMOOTH 6
#define TORUS_SLICEON 7
#define TORUS_PIESLICE1 8
#define TORUS_PIESLICE2 9
#define TORUS_GENUVS 10
//@}
/*! \defgroup paramBlockIDs_tube Tube Parameter Block IDs */
//@{
#define TUBE_RADIUS 0
#define TUBE_RADIUS2 1
#define TUBE_HEIGHT 2
#define TUBE_SEGMENTS 3
#define TUBE_CAPSEGMENTS 4
#define TUBE_SIDES 5
#define TUBE_SMOOTH 6
#define TUBE_SLICEON 7
#define TUBE_PIESLICE1 8
#define TUBE_PIESLICE2 9
#define TUBE_GENUVS 10
//@}
/*! \defgroup paramBlockIDs_grid Grid Parameter Block IDs */
//@{
#define GRIDHELP_LENGTH 0
#define GRIDHELP_WIDTH 1
#define GRIDHELP_GRID 2
//@}
//----------------------------------------------------------------
// The following are parameter block IDs for modifiers
/*! \defgroup paramBlockIDs_bend Bend Parameter Block IDs*/
//@{
#define BEND_ANGLE 0
#define BEND_DIR 1
#define BEND_AXIS 2
#define BEND_DOREGION 3
#define BEND_FROM 4
#define BEND_TO 5
//@}
/*! \defgroup paramBlockIDs_bomb Bomb Parameter Block IDs */
//@{
#define BOMB_STRENGTH 0
#define BOMB_GRAVITY 1
#define BOMB_CHAOS 2
#define BOMB_DETONATION 3
//@}
/*! \defgroup paramBlockIDs_deflector Deflector Parameter Block IDs */
//@{
#define DEFLECTOR_BOUNCE 0
#define DEFLECTOR_WIDTH 1
#define DEFLECTOR_HEIGHT 2
//@}
/*! \defgroup paramBlockIDs_displace Displace Parameter Block IDs
For modifier and space warp object */
//@{
#define DISPLACE_MAPTYPE 0
#define DISPLACE_UTILE 1
#define DISPLACE_VTILE 2
#define DISPLACE_WTILE 3
#define DISPLACE_BLUR 4
#define DISPLACE_USEMAP 5
#define DISPLACE_APPLYMAP 6
#define DISPLACE_STRENGTH 7
#define DISPLACE_DECAY 8
#define DISPLACE_CENTERLUM 9
#define DISPLACE_UFLIP 10
#define DISPLACE_VFLIP 11
#define DISPLACE_WFLIP 12
#define DISPLACE_CENTERL 13
#define DISPLACE_CAP 14
#define DISPLACE_LENGTH 15
#define DISPLACE_WIDTH 16
#define DISPLACE_HEIGHT 17
#define DISPLACE_AXIS 18
//@}
/*! \defgroup paramBlockIDs_extrude Extrude Parameter Block IDs */
//@{
#define EXTRUDE_AMOUNT 0
#define EXTRUDE_SEGS 1
#define EXTRUDE_CAPSTART 2
#define EXTRUDE_CAPEND 3
#define EXTRUDE_CAPTYPE 4
#define EXTRUDE_OUTPUT 5
#define EXTRUDE_MAPPING 6
#define EXTRUDE_GEN_MATIDS 7
#define EXTRUDE_USE_SHAPEIDS 8
#define EXTRUDE_SMOOTH 9
//@}
/*! \defgroup paramBlockIDs_gravity Gravity Parameter Block IDs */
//@{
#define GRAVITY_STRENGTH 0
#define GRAVITY_DECAY 1
#define GRAVITY_TYPE 2
#define GRAVITY_DISPLENGTH 3
//@}
/*! \defgroup paramBlockIDs_wind Wind Parameter Block IDs */
//@{
#define WIND_STRENGTH 0
#define WIND_DECAY 1
#define WIND_TYPE 2
#define WIND_DISPLENGTH 3
#define WIND_TURBULENCE 4
#define WIND_FREQUENCY 5
#define WIND_SCALE 6
//@}
/*! \defgroup paramBlockIDs_uvwMap UVW Map Parameter Block IDs */
//@{
#define UVWMAP_MAPTYPE 0
#define UVWMAP_UTILE 1
#define UVWMAP_VTILE 2
#define UVWMAP_WTILE 3
#define UVWMAP_UFLIP 4
#define UVWMAP_VFLIP 5
#define UVWMAP_WFLIP 6
#define UVWMAP_CAP 7
#define UVWMAP_CHANNEL 8
#define UVWMAP_LENGTH 9
#define UVWMAP_WIDTH 10
#define UVWMAP_HEIGHT 11
#define UVWMAP_AXIS 12
//@}
/*! \defgroup paramBlockIDs_noiseMod Noise Mod Parameter Block IDs */
//@{
#define NOISEMOD_SEED 0
#define NOISEMOD_SCALE 1
#define NOISEMOD_FRACTAL 2
#define NOISEMOD_ROUGH 3
#define NOISEMOD_ITERATIONS 4
#define NOISEMOD_ANIMATE 5
#define NOISEMOD_FREQ 6
#define NOISEMOD_PHASE 7
#define NOISEMOD_STRENGTH 8
//@}
/*! \defgroup paramBlockIDs_optimize Optimize Parameter Block IDs */
//@{
#define OPTMOD_RENDER 0
#define OPTMOD_VIEWS 1
#define OPTMOD_FACETHRESH1 2
#define OPTMOD_EDGETHRESH1 3
#define OPTMOD_BIAS1 4
#define OPTMOD_PRESERVEMAT1 5
#define OPTMOD_PRESERVESMOOTH1 6
#define OPTMOD_MAXEDGE1 7
#define OPTMOD_FACETHRESH2 8
#define OPTMOD_EDGETHRESH2 9
#define OPTMOD_BIAS2 10
#define OPTMOD_PRESERVEMAT2 11
#define OPTMOD_PRESERVESMOOTH2 12
#define OPTMOD_MAXEDGE2 13
#define OPTMOD_AUTOEDGE 14
#define OPTMOD_MANUPDATE 15
//@}
/*! \defgroup paramBlockIDs_volumeSelectionModifier Volume Selection Modifier Parameter Block IDs */
//@{
#define VOLSEL_LEVEL 0
#define VOLSEL_METHOD 1
#define VOLSEL_TYPE 2
#define VOLSEL_VOLUME 3
#define VOLSEL_INVERT 4
//@}
/*! \defgroup paramBlockIDs_rippleWaveModifier Ripple/Wave Modifier Parameter Block IDs
For Space Warp Object and Object Space */
//@{
#define RWAVE_AMPLITUDE 0
#define RWAVE_AMPLITUDE2 1
#define RWAVE_WAVELEN 2
#define RWAVE_PHASE 3
#define RWAVE_DECAY 4
#define RWAVE_CIRCLES 5 //!< Valid for space warp objects only
#define RWAVE_SEGMENTS 6 //!< Valid for space warp objects only
#define RWAVE_DIVISIONS 7 //!< Valid for space warp objects only
//@}
/*! \defgroup paramBlockIDs_rippleWaveBinding Ripple/Wave Binding (modifier) Parameter Block IDs */
//@{
#define RWAVE_FLEX 0
//@}
/*! \defgroup paramBlockIDs_skew Skew Parameter Block IDs */
//@{
#define SKEW_AMOUNT 0
#define SKEW_DIR 1
#define SKEW_AXIS 2
#define SKEW_DOREGION 3
#define SKEW_FROM 4
#define SKEW_TO 5
//@}
/*! \defgroup paramBlockIDs_materialModifier Material Modifier Parameter Block IDs */
//@{
#define MATMOD_MATID 0
//@}
/*! \defgroup paramBlockIDs_smoothingGroupModifier Smoothing Group Modifier Parameter Block IDs */
//@{
#define SMOOTHMOD_AUTOSMOOTH 0
#define SMOOTHMOD_THRESHOLD 1
#define SMOOTHMOD_SMOOTHBITS 2
//@}
/*! \defgroup paramBlockIDs_normalModifier Normal Modifier Parameter Block IDs */
//@{
#define NORMMOD_UNIFY 0
#define NORMMOD_FLIP 1
//@}
/*! \defgroup paramBlockIDs_surfRevModifier SurfRev (Lathe) Modifier Parameter Block IDs */
//@{
#define SURFREV_DEGREES 0
#define SURFREV_SEGS 1
#define SURFREV_CAPSTART 2
#define SURFREV_CAPEND 3
#define SURFREV_CAPTYPE 4
#define SURFREV_WELDCORE 5
#define SURFREV_OUTPUT 6
#define SURFREV_MAPPING 7
//@}
/*! \defgroup paramBlockIDs_taper Taper Parameter Block IDs */
//@{
#define TAPER_AMT 0
#define TAPER_CRV 1
#define TAPER_AXIS 2
#define TAPER_EFFECTAXIS 3
#define TAPER_SYMMETRY 4
#define TAPER_DOREGION 5
#define TAPER_FROM 6
#define TAPER_TO 7
//@}
/*! \defgroup paramBlockIDs_twist Twist Parameter Block IDs */
//@{
#define TWIST_ANGLE 0
#define TWIST_BIAS 1
#define TWIST_AXIS 2
#define TWIST_DOREGION 3
#define TWIST_FROM 4
#define TWIST_TO 5
//@}
/*! \defgroup paramBlockIDs_materialMod Material Mod Parameter Block IDs */
//@{
#define MATMOD_MATID 0
//@}
/*! \defgroup paramBlockIDs_smoothMod Smooth Mod Parameter Block IDs */
//@{
#define SMOOTH_AUTOSMOOTH 0
#define SMOOTH_THRESHOLD 1
#define SMOOTH_SMOOTHBITS 2
//@}
/*! \defgroup paramBlockIDs_normalMod Normal Mod Parameter Block IDs */
//@{
#define NORMALMOD_UNIFY 0
#define NORMALMOD_FLIP 1
//@}
/*! \defgroup paramBlockIDs_tessellationMod Tessellation Mod Parameter Block IDs */
//@{
#define TESSMOD_TYPE 0
#define TESSMOD_TENSION 1
#define TESSMOD_ITERATIONS 2
#define TESSMOD_FACE_TYPE 3
//@}
/*! \defgroup paramBlockIDs_uvmXform UVW Xform Parameter Block IDs */
//@{
#define UVWXFORM_UTILE 0
#define UVWXFORM_VTILE 1
#define UVWXFORM_WTILE 2
#define UVWXFORM_UOFFSET 3
#define UVWXFORM_VOFFSET 4
#define UVWXFORM_WOFFSET 5
#define UVWXFORM_UFLIP 6
#define UVWXFORM_VFLIP 7
#define UVWXFORM_WFLIP 8
#define UVWXFORM_CHANNEL 9
//@}
//@} END OF PARAMETER BLOCK IDS
//-- Text shape object interface -------------------------
// Use GetTextObjectInterface() to get a pointer to an
// ITextObject given a pointer to an Object.
// Flags passed to ChangeFont()
#define TEXTOBJ_ITALIC (1<<1)
#define TEXTOBJ_UNDERLINE (1<<2)
// Alignment types
#define TEXTOBJ_LEFT 0
#define TEXTOBJ_CENTER 1
#define TEXTOBJ_RIGHT 2
#define TEXTOBJ_JUSTIFIED 3
/*! \sa Class Animatable.\n\n
\par Description:
This is the text shape object interface. This class gives access to the
standard 3ds Max text object. It allows the text objects font, string, and
style bits to be retrieved and set. All methods of this class are implemented
by the system.\n\n
To get a pointer to an <b>ITextObject</b> interface given a pointer to a
object, use the following macro (defined in AnimatableInterfaceIDs.h ). Using this
macro, given any Animatable, it is easy to ask for the text object
interface.\n\n
<b>#define GetTextObjectInterface(anim)</b>\n\n
<b>((ITextObject*)anim-\>GetInterface(I_TEXTOBJECT))</b>\n\n
A plug-in developer may use this macro as follows:\n\n
<b>ITextObject *ito = GetTextObjectInterface(anim);</b>\n\n
This return value will either be NULL or a pointer to a valid text object
interface. You may then use this pointer to call methods of this class to
retrieve and modify the object data. For example:\n\n
<b>ito-\>SetUnderline(TRUE);</b>\n\n
Note: Some aspects of the text are controlled by its parameter block.
Developers can access the parameter block by calling
<b>ito-\>GetParamBlock()</b>. The following are the indices into the parameter
block used to access the size, kerning and leading parameters:\n\n
<b>TEXT_SIZE</b>\n\n
<b>TEXT_KERNING</b>\n\n
<b>TEXT_LEADING</b> */
class ITextObject: public MaxHeapOperators {
public:
// Returns TRUE if string is changed. Can't change string if current font is not installed
/*! \remarks This method may be called to change the text string. Note
that you can't change the string if the current font is not installed.
\par Parameters:
<b>MSTR string</b>\n\n
The new text string.
\return TRUE if the string is changed; otherwise FALSE. */
virtual BOOL ChangeText(MSTR string)=0;
// Returns TRUE if font is successfully changed.
/*! \remarks This method may be called to change the text font.
\par Parameters:
<b>MSTR name</b>\n\n
The name of the font.\n\n
<b>DWORD flags</b>\n\n
One or more of the following values:\n\n
<b>TEXTOBJ_ITALIC</b>\n\n
<b>TEXTOBJ_UNDERLINE</b>
\return TRUE if the font was successfully changed; otherwise FALSE. */
virtual BOOL ChangeFont(MSTR name, DWORD flags)=0;
// Get fount and string
/*! \remarks Returns the name of the text font. */
virtual MSTR GetFont()=0;
/*! \remarks Returns the text string. */
virtual MSTR GetString()=0;
// Get/Set styles
/*! \remarks Returns TRUE if the text is italicized; otherwise FALSE.
*/
virtual BOOL GetItalic()=0;
/*! \remarks Returns TRUE if the text is underlined; otherwise FALSE.
*/
virtual BOOL GetUnderline()=0;
/*! \remarks Sets if the text is italicized or not.
\par Parameters:
<b>BOOL sw</b>\n\n
TRUE if the text should be italicized; FALSE if not. */
virtual void SetItalic(BOOL sw)=0;
/*! \remarks Sets if the text is underlined or not.
\par Parameters:
<b>BOOL sw</b>\n\n
TRUE if the text should be underlined; FALSE if not. */
virtual void SetUnderline(BOOL sw)=0;
// Get/Set alignment
virtual BOOL SetAlignment(int type)=0;
virtual int GetAlignment()=0;
};
//-- Controller interfaces -------------------------------
// Base key class
/*! \sa Class IKeyControl, Class Animatable.\n\n
\par Description:
This is the base class for keys that are part of the controller interface. This
class stores the time of the key, and some flags that describe the properties
of the key.
\par Data Members:
<b>TimeValue time;</b>\n\n
The time of the key.\n\n
<b>DWORD flags;</b>\n\n
The flag bits for keys. One or more of the following values:\n\n
General flags\n\n
<b>IKEY_SELECTED</b>\n\n
The key is selected.\n\n
<b>IKEY_XSEL</b>\n\n
In the function curve editor X is selected.\n\n
<b>IKEY_YSEL</b>\n\n
In the function curve editor Y is selected.\n\n
<b>IKEY_ZSEL</b>\n\n
In the function curve editor Z is selected.\n\n
<b>IKEY_FLAGGED</b>\n\n
The key is flagged. See <b>Animatable:: FlagKey()</b>.\n\n
<b>IKEY_TIME_LOCK</b>\n\n
The key is locked in time so it won't move.\n\n
TCB specific key flags:\n\n
<b>TCBKEY_QUATVALID</b>\n\n
The quaternion TCB key has inside it both a quaternion and an angle axis. When
this bit is set the angle/axis is derived from the quaternion instead of
vice/versa.\n\n
Bezier specific key flags:\n\n
<b>BEZKEY_CONSTVELOCITY</b>\n\n
This key is interpolated using arclength as the interpolation parameter.\n\n
<b>BEZKEY_XBROKEN</b>\n\n
<b>BEZKEY_YBROKEN</b>\n\n
<b>BEZKEY_ZBROKEN</b>\n\n
Indicates if the tangent handles are locked together. Broken means not
locked.\n\n
The following macros may be used to test and set the tangent locks:\n\n
<b>TangentsLocked(f,j);</b>\n\n
<b>SetTangentLick(f,j,l);</b>\n\n
The following macros may be used to access the hybrid tangent types:\n\n
<b>GetInTanType(f);</b>\n\n
<b>GetOutTanType(f);</b>\n\n
<b>SetINTanType(f,t);</b>\n\n
<b>SetOutTanType(f,t);</b> */
class IKey: public MaxHeapOperators {
public:
TimeValue time;
DWORD flags;
/*! \remarks Constructor. The time and flags are set to zero. */
IKey() {time=0;flags=0;}
};
//--- TCB keys -------------
/*! \sa Class IKey.\n\n
\par Description:
This is the base class for Tension Continuity and Bias keys.
\par Data Members:
<b>float tens;</b>\n\n
The tension setting. Values are in the range -1.0 to 1.0, where 0.0 is the
default.\n\n
<b>float cont;</b>\n\n
The continuity setting. Values are in the range -1.0 to 1.0, where 0.0 is the
default.\n\n
<b>float bias;</b>\n\n
The bias setting. Values are in the range -1.0 to 1.0, where 0.0 is the
default.\n\n
<b>float easeIn;</b>\n\n
The ease in value. Values are in the range 0.0 to 50.0, where25.0 is the
default.\n\n
<b>float easeOut;</b>\n\n
The ease out value. Values are in the range 0.0 to 50.0, where 25.0 is the
default. */
class ITCBKey : public IKey {
public:
float tens, cont, bias, easeIn, easeOut;
};
/*! \sa Class ITCBKey.\n\n
\par Description:
This class stores a Tension Continuity and Bias (TCB) floating point key.
\par Data Members:
<b>float val;</b>\n\n
The value of the key. */
class ITCBFloatKey : public ITCBKey {
public:
float val;
};
class ITCBPoint4Key : public ITCBKey {
public:
Point4 val;
};
/*! \sa Class ITCBKey, Class Point3.\n\n
\par Description:
This class stores a Tension Continuity and Bias (TCB) Point3 key.
\par Data Members:
<b>Point3 val;</b>\n\n
The value of the key. */
class ITCBPoint3Key : public ITCBKey {
public:
Point3 val;
};
/*! \sa Class ITCBKey, Class AngAxis.\n\n
\par Description:
This class stores a Tension Continuity and Bias (TCB) rotation key.
\par Data Members:
<b>AngAxis val;</b>\n\n
The value of the key. */
class ITCBRotKey : public ITCBKey {
public:
AngAxis val;
};
/*! \sa Class ITCBKey, Class ScaleValue.\n\n
\par Description:
This class stores a Tension Continuity and Bias (TCB) Scale key.
\par Data Members:
<b>ScaleValue val;</b>\n\n
The value of the key. */
class ITCBScaleKey : public ITCBKey {
public:
ScaleValue val;
};
//--- Bezier keys -------------
/*! \sa Class IKey.\n\n
\par Description:
This class stores a Bezier floating point key.
\par Data Members:
<b>float intan;</b>\n\n
The in tangent value.\n\n
<b>float outtan;</b>\n\n
The out tangent value.\n\n
<b>float val;</b>\n\n
The value of the key.\n\n
<b>float inLength;</b>\n\n
The in length of the horizontal handle.\n\n
<b>float outLength;</b>\n\n
The out length of the horizontal handle. */
class IBezFloatKey : public IKey {
public:
float intan, outtan;
float val;
//watje horizontal handles
//these are the length of the handles
float inLength, outLength;
};
/*! \sa Class IKey, Class Point3.\n\n
\par Description:
This class stores a Bezier Point3 key.\n\n
The value of the intan and outtan values of IBezPoint3Key returned from GetKey
is actually the tangent of the angle that is spanned between the horizontal
axis and the tangent. In order to get the actual handle of the tangent it is
important to know that the horizontal (time) distance from the handle to the
key value is dependent on the previous (for intan) or next (for outtan) point.
The horizontal distance is basically a third of the total distance between the
current key and the previous (or next) key :\n\n
<b>Control *c = node-\>GetTMController()-\>GetPositionController();</b>\n\n
<b>dt = (c-\>GetKeyTime(PreviousIdx)-c-\>GetKeyTime(CurrentIdx)) /
3.0f;</b>\n\n
since the value in IBezPoint3Key pos_key.intan.x is the tan(alpha), you can
easily get the vertical location of the handle by calculating :\n\n
<b>tan(alpha) = pos_key.intan.x = dy/dt -\> dy = pos_key.intan.x * dt</b>\n\n
dt is the horizontal coordinate of the tangent handle relative to the key
value.\n\n
dy is the vertical coordinate of the tangent handle relative to the key value.
\par Data Members:
<b>Point3 intan;</b>\n\n
The incoming tangent vector. This can be thought of as the tangent handle of a
3D spline. The value is relative to <b>val</b>.\n\n
<b>Point3 outtan;</b>\n\n
The outgoing tangent vector. This can be thought of as the tangent handle of a
3D spline. The value is relative to <b>val</b>.\n\n
<b>Point3 val;</b>\n\n
The value of the key.\n\n
<b>Point3 inLength;</b>\n\n
The in length of the horizontal handle.\n\n
<b>Point3 outLength;</b>\n\n
The out length of the horizontal handle. */
class IBezPoint3Key : public IKey {
public:
Point3 intan, outtan;
Point3 val;
//watje horizontal handles
//these are the length of the handles
Point3 inLength, outLength;
};
/*! \sa Class IKey, Class Quat.\n\n
\par Description:
This class stores a Bezier quaternion key.
\par Data Members:
<b>Quat val;</b>\n\n
The value of the key. */
class IBezQuatKey : public IKey {
public:
Quat val;
};
/*! \sa Class IKey, Class Point3, Class ScaleValue.\n\n
\par Description:
This class stores a Bezier scale key.
\par Data Members:
<b>Point3 intan;</b>\n\n
The int tangent vector.\n\n
<b>Point3 outtan;</b>\n\n
The out tangent vector.\n\n
<b>ScaleValue val;</b>\n\n
The value of the key.\n\n
<b>Point3 inLength;</b>\n\n
The in length of the horizontal handle.\n\n
<b>Point3 outLength;</b>\n\n
The out length of the horizontal handle. */
class IBezScaleKey : public IKey {
public:
Point3 intan, outtan;
ScaleValue val;
//watje horizontal handles
//these are the length of the handles
Point3 inLength, outLength;
};
/*! \sa Class IKey, Class Point4.\n\n
\par Description:
This class stores a Bezier Point4 key.
\par Data Members:
<b>Point4 intan;</b>\n\n
The int tangent vector.\n\n
<b>Point4 outtan;</b>\n\n
The out tangent vector.\n\n
<b>Point4 val;</b>\n\n
The value of the key.\n\n
<b>Point4 inLength;</b>\n\n
The in length of the horizontal handle.\n\n
<b>Point4 outLength;</b>\n\n
The out length of the horizontal handle. */
class IBezPoint4Key : public IKey {
public:
Point4 intan, outtan;
Point4 val;
//watje horizontal handles
//these are the length of the handles
Point4 inLength, outLength;
};
/*! \sa Class IKey, Class Point2.\n\n
\par Description:
This class stores a Bezier Point2 key.
\par Data Members:
<b>Point2 intan;</b>\n\n
The int tangent vector.\n\n
<b>Point2 outtan;</b>\n\n
The out tangent vector.\n\n
<b>Point2 val;</b>\n\n
The value of the key.\n\n
<b>Point2 inLength;</b>\n\n
The in length of the horizontal handle.\n\n
<b>Point2 outLength;</b>\n\n
The out length of the horizontal handle. */
class IBezPoint2Key : public IKey {
public:
Point2 intan, outtan;
Point2 val;
//watje horizontal handles
//these are the length of the handles
Point2 inLength, outLength;
};
//--- Linear Keys --------------
/*! \sa Class IKey.\n\n
\par Description:
This class stores a Linear floating point key.
\par Data Members:
<b>float val;</b>\n\n
The value of the key. */
class ILinFloatKey : public IKey {
public:
float val;
};
/*! \sa Class IKey, Class Point3.\n\n
\par Description:
This class stores a Linear Point3 key.
\par Data Members:
<b>Point3 val;</b>\n\n
The value of the key. */
class ILinPoint3Key : public IKey {
public:
Point3 val;
};
/*! \sa Class IKey, Class Quat.\n\n
\par Description:
This class stores a Linear rotation key.
\par Data Members:
<b>Quat val;</b>\n\n
The value of the key. */
class ILinRotKey : public IKey {
public:
Quat val;
};
/*! \sa Class IKey,
Class ScaleValue.\n\n
\par Description:
This class stores a Linear scale key.
\par Data Members:
<b>ScaleValue val;</b>\n\n
The value of the key. */
class ILinScaleKey : public IKey {
public:
ScaleValue val;
};
//--- Boolean Controller Keys -------------- AG: 11/08/01
/*! \sa : Class Animatable, Class IKey\n\n
class IBoolFloatKey : public IKey\n\n
\par Description:
<b>This class is only available in release 5 or later.</b>\n\n
\remarks Derived from standard IKey with an additional data called
val.\n\n
\par Parameters:
<b>float val;</b>\n\n
Value of the last key which can only be either 0 or 1 */
class IBoolFloatKey : public IKey {
public:
float val;
};
/*! \defgroup keyFlagBits Flag Bits for Keys */
//@{
/*! \defgroup keyFlagBits_generalFlags General Key Flags
*/
//@{
#define IKEY_SELECTED (1<<0)
#define IKEY_XSEL (1<<1)
#define IKEY_YSEL (1<<2)
#define IKEY_ZSEL (1<<3)
#define IKEY_WSEL (1<<30)
#define IKEY_FLAGGED (1<<31) //13
#define IKEY_TIME_LOCK (1<<14)
#define IKEY_ALLSEL (IKEY_SELECTED|IKEY_XSEL|IKEY_YSEL|IKEY_ZSEL|IKEY_WSEL)
#define IKEY_VALLOCK_SHIFT 16
#define IKEY_VALX_LOCK (1<<IKEY_VALLOCK_SHIFT)
#define IKEY_VALY_LOCK (1<<(IKEY_VALLOCK_SHIFT+1))
#define IKEY_VALZ_LOCK (1<<(IKEY_VALLOCK_SHIFT+2))
#define IKEY_VALA_LOCK (1<<(IKEY_VALLOCK_SHIFT+3))
//@}
/*! \defgroup keyFlagBits_tcbSpecific TCB-specific Key Flags */
//@{
#define TCBKEY_QUATVALID (1<<4) //!< Angle/axis is derived from the quat instead of vice/versa
//@}
/*! \defgroup keyFlagBits_bezierSpecific Bezier-specific Key Flags */
//@{
#define BEZKEY_XBROKEN (1<<4) //!< Broken means not locked
#define BEZKEY_YBROKEN (1<<5)
#define BEZKEY_ZBROKEN (1<<6)
#define BEZKEY_WBROKEN (1<<21)
//@}
/*! \defgroup keyFlagBits_inOutTypes In and Out types
Stored in bits 7-13 */
//@{
#define BEZKEY_NUMTYPEBITS 3
#define BEZKEY_INTYPESHIFT 7
#define BEZKEY_OUTTYPESHIFT (BEZKEY_INTYPESHIFT+BEZKEY_NUMTYPEBITS)
#define BEZKEY_TYPEMASK 7
//@}
/*! \defgroup keyFlagBits_bezierTangentTypes Bezier Tangeant Types */
//@{
#define BEZKEY_SMOOTH 0
#define BEZKEY_LINEAR 1
#define BEZKEY_STEP 2
#define BEZKEY_FAST 3
#define BEZKEY_SLOW 4
#define BEZKEY_USER 5
#define BEZKEY_FLAT 6
#define NUM_TANGENTTYPES 7
//@}
/*! \defgroup keyFlagBits_macros Key Flagbit Macros */
//@{
#define BEZKEY_CONSTVELOCITY (1<<15) //!< Interpolated using arclength as the interpolation parameter
#define BEZKEY_UNCONSTRAINHANDLE (1<<20) //!< Determines whether a user handle is limited
#define TangentsLocked(f,j) (!(f&(j <= 2 ? (BEZKEY_XBROKEN<<j) : BEZKEY_WBROKEN)))
#define SetTangentLock(f,j,l) {if (l) (f)=(f)&(~(j <= 2 ? (BEZKEY_XBROKEN<<j) : BEZKEY_WBROKEN)); else (f)|=(j <= 2 ? (BEZKEY_XBROKEN<<j) : BEZKEY_WBROKEN);}
//@}
/*! \defgroup keyFlagBits_hybridTangeantAccessMacros Macros to Access Hybrid Tangent Types */
//@{
#define GetInTanType(f) int(((f)>>BEZKEY_INTYPESHIFT)&BEZKEY_TYPEMASK)
#define GetOutTanType(f) int(((f)>>BEZKEY_OUTTYPESHIFT)&BEZKEY_TYPEMASK)
#define SetInTanType(f,t) {(f) = ((f)&(~(BEZKEY_TYPEMASK<<BEZKEY_INTYPESHIFT)))|(t<<BEZKEY_INTYPESHIFT);}
#define SetOutTanType(f,t) {(f) = ((f)&(~(BEZKEY_TYPEMASK<<BEZKEY_OUTTYPESHIFT)))|(t<<BEZKEY_OUTTYPESHIFT);}
//@}
//@} END OF KEYFLAGBITS GROUP
// HitTrackRecord flags
// KEY_XSEL, KEY_YSEL, KEY_ZSEL, and KEY_WSEL are also used to identify the component
#define HITKEY_INTAN (1<<10)
#define HITKEY_OUTTAN (1<<11)
// Track flags
#define TFLAG_CURVESEL (1<<0)
#define TFLAG_RANGE_UNLOCKED (1<<1)
#define TFLAG_LOOPEDIN (1<<3)
#define TFLAG_LOOPEDOUT (1<<4)
#define TFLAG_COLOR (1<<5) // Set for Bezier Point3/Point4 controlers that are color controllers
#define TFLAG_HSV (1<<6) // Set for color controls that interpolate in HSV
#define TRACK_XLOCKED (1<<7) // Used by controller to lock Y and Z to X.
#define KT_FLAG_DELAY_KEYSCHANGED (1<<8)
#define TFLAG_NOTKEYABLE (1<<9)
#define TFLAG_TCBQUAT_NOWINDUP (1<<10)
//! \brief Interface to the Key Property
//! This interface allows defining properties for keys.
//! Properties are additional attributes that are not interpolated
//! between keys.
class IKeyProperty: public MaxHeapOperators {
public:
//! Virtual destructor
virtual ~IKeyProperty() {}
//! Property ID enumeration.
enum PropID {
//! Property ID of IIKKeyProp
kIKProp
};
//! Get the Property ID.
//! \return the property ID enum.
virtual PropID GetPropID() const = 0;
};
//! \brief Interface to the IK Key Property.
//! This class defines the interface to the IK key property.
//! This property has a property ID of IKeyProperty::kIKProp.
//! A pointer to IKeyProperty whose propertyID is kIKProp
//! can be safely cast to a pointer to an IIKKeyProp:
//! \code
//! if (ptr->GetPropID() == IKeyProperty::kIKProp)
//! IIKKeyProp* ikProp = (IIKKeyProp*)ptr;
//! \endcode
class IIKKeyProp : public IKeyProperty {
public:
//! The enum type for the space with regard to which the IK goal is interpreted.
enum EnumIKSpace {
//! The body space is the parent space of the start bone shifted by the position of the start bone.
kBodySpace,
//! The object space if the parent space of the IK goal object.
kObjectSpace,
};
//! The Property ID of this interface.
//! \see IKeyProperty::GetPropID
PropID GetPropID() const { return IKeyProperty::kIKProp; }
//! Get the IK Blend attribute of the property.
//! It should be in the range of [0,1].
virtual float GetIKBlend() const =0;
//! Get the IK Space attribute of the property.
virtual EnumIKSpace GetIKSpace() const =0;
//! Get the Pivot On attribute of the property.
virtual bool GetPivotOn() const =0;
//! Get the World Pivot attribute of the property.
virtual Point3 GetWorldPivot() const =0;
//! Get the Pivot Node attribute of the property.
virtual INode* GetPivotNode() const =0;
//! When passed in IKeyControl2::SetKeyProp(), it tells whether to set value to the
//! IK Blend attribute. If it is true, GetIKBlend() will be used as the
//! target of the set value.
virtual bool SetIKBlend() const { return false; }
//! When passed in IKeyControl2::SetKeyProp(), it tells whether to set value to the
//! IK Space attribute. If it is true, GetIKSpace() will be used as the
//! target of the set value.
virtual bool SetIKSpace() const { return false; }
//! When passed in IKeyControl2::SetKeyProp(), it tells whether to
//! set value to the Pivot On attribute. If it is true, GetPivotOn()
//! will be used as the target of the set value.
virtual bool SetPivotOn() const { return false; }
//! When passed in IKeyControl2::SetKeyProp(), it tells whether to
//! set value to the World Pivot attribute. If it is true, GetWorldPivot()
//! will be used as the target of the set value.
virtual bool SetWorldPivot() const { return false; }
//! When passed in IKeyControl2::SetKeyProp(), it tells whether to
//! set value to the Pivot Node attribute. If it is true, GetPivotNode()
//! will be used as the target of the set value.
virtual bool SetPivotNode() const { return false; }
};
//! This is a helper class. If we want to set just one attribute of the
//! IK Key Property, we can derive a new class from it as follows:
//! \code
//! class SetIKBlendProp : public ISetIKKeyProp {
//! public:
//! SetIKBlendProp(float blend) : mBlend(blend) {}
//! float GetIKBlend() const { return mBlend; }
//! bool SetIKBlend() const { return true; }
//! float mBlend;
//! };
//! IKeyControl2* keyControl = (IKeyControl2*)control->GetInterface(I_KEYCONTROL2);
//! SetIKBlendProp prop(new_blend_value);
//! keyControl->SetKeyProp(IKeyProperty::kIKProp, key_index, prop);
//! \endcode
class ISetIKKeyProp : public IIKKeyProp {
public:
//! Override IIKKeyProp::GetIKBlend().
float GetIKBlend() const { return 0.0f; }
//! Override IIKKeyProp::GetIKSpace().
EnumIKSpace GetIKSpace() const { return kObjectSpace; }
//! Override IIKKeyProp::GetPivotOn().
bool GetPivotOn() const { return false; }
//! Override IIKKeyProp::GetWorldPivot().
Point3 GetWorldPivot() const { return Point3::Origin; }
//! Override IIKKeyProp::GetPivotNode().
INode* GetPivotNode() const { return NULL; }
};
//-------------------------------------------------------
// This is an interface into key frame controllers.
// To get a pointer to the IKeyControl interface given a pointer to a controller,
// use the macro defined in AnimatableInterfaceIDs.h: GetKeyControlInterface()
// Use class AnyKey as wrapper for IKey for automatic handling of memory. See example below
/*! \sa Class Animatable, Class IKey, Class Control, <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_super_class_ids.html">List of SuperClass IDs</a>,
<a href="ms-its:3dsmaxsdk.chm::/anim_keyframe_and_procedural_controller_data_access.html">Keyframe and Procedural Controller Data Access</a>.\n\n
\par Description:
This is an interface into the TCB, Linear, and Bezier keyframe controllers. It
allows a developer to add, delete, retrieve and store the keys of the
controller. This is for controllers that have made their keys accessible using
this interface. 3ds Max has done this for its keyframe controllers. It is up to
other third party developers to decide if they wish to make their keys
available through this interface as well. See below for more details.\n\n
It is up to the developer to make sure that the <b>IKey*</b> points to a key of
the appropriate derived class based on the <b>ClassID()</b> of the controller.
For the details of using these APIs see the Advanced Topics section
<a href="ms-its:3dsmaxsdk.chm::/anim_keyframe_and_procedural_controller_data_access.html">Keyframe
and Procedural Cotroller Data Access</a>.\n\n
All methods of this class are implemented by the system.\n\n
To get a pointer to this interface given a pointer to a controller, use the
following macro (defined in AnimatableInterfaceIDs.h). Using this macro, given any
Animatable, it is easy to ask for the control interface.\n\n
<b>#define GetKeyControlInterface(anim)</b>\n\n
<b>((IKeyControl*)anim-\>GetInterface(I_KEYCONTROL))</b>\n\n
A plug-in developer may use this macro as follows:\n\n
<b>IKeyControl *ikc = GetKeyControlInterface(anim);</b>\n\n
This return value will either be NULL or a pointer to a valid controller
interface. Here is an example of getting the controller interface from a node
in the scene. First get the position controller from the node (see
Class INode) and then get the controller interface.\n\n
<b> Control *c;</b>\n\n
<b> c = node-\>GetTMController()-\>GetPositionController();</b>\n\n
<b> IKeyControl *ikeys = GetKeyControlInterface(c);</b>\n\n
With this controller interface you can use its methods to get information about
the keys.\n\n
<b> int num = ikeys-\>GetNumKeys();</b>\n\n
Developers should note that the values that are retrieved from this class may
differ from the values that appear in Key Info in the 3ds Max user interface.
For instance, the Intan and Outtan values are multiplied by the global function
<b>GetFrameRate()</b> when displayed. Additionally, the sign of angles (+ or -)
may be reversed from the what is found in the UI. For example, the following
shows the values shown in Key Info versus the values retrieved from
<b>GetKey()</b>:\n\n
Motion branch Key Info:\n\n
<b>Key#1</b>\n\n
<b>X: -1.0</b>\n\n
<b>Y: 0.0</b>\n\n
<b>Z: 0.0</b>\n\n
<b>Ang: 0.0</b>\n\n
<b>Key#2</b>\n\n
<b>X: 0.0</b>\n\n
<b>Y: 1.0</b>\n\n
<b>Z: 0.0</b>\n\n
<b>Ang: 90.0</b>\n\n
<b>Key#3</b>\n\n
<b>X: 0.0</b>\n\n
<b>Y: 0.0</b>\n\n
<b>Z: 1.0</b>\n\n
<b>Ang: 90.0</b>\n\n
<b>ITCBRotKey key;</b>\n\n
<b>ikc-\>GetKey(i, \&key);</b>\n\n
<b>Key#1</b>\n\n
<b>X: 1.0</b>\n\n
<b>Y: 0.0</b>\n\n
<b>Z: 0.0</b>\n\n
<b>Ang: 0.0</b>\n\n
<b>Key#2</b>\n\n
<b>X: 0.0</b>\n\n
<b>Y: -1.0</b>\n\n
<b>Z: 0.0</b>\n\n
<b>Ang: 1.57</b>\n\n
<b>Key#3</b>\n\n
<b>X: 0.0</b>\n\n
<b>Y: 0.0</b>\n\n
<b>Z: -1.0</b>\n\n
<b>Ang: 1.57</b>\n\n
Sample code in the SDK that makes use of this interface is the 3D Studio Export
plug-in. See <b>/MAXSDK/SAMPLES/IMPEXP/3DSEXP.CPP</b>.
\par Tension/Continuity/Bias:
Class ITCBKey\n\n
Class ITCBFloatKey\n\n
Class ITCBPoint3Key,\n\n
Class ITCBRotKey\n\n
Class ITCBScaleKey
\par Bezier:
Class IBezFloatKey\n\n
Class IBezPoint3Key\n\n
Class IBezQuatKey\n\n
Class IBezScaleKey
\par Linear:
Class ILinFloatKey\n\n
Class ILinPoint3Key\n\n
Class ILinRotKey\n\n
Class ILinScaleKey\n\n
Note: Developers creating controller plug-ins may wish to make their keys
accessible to others through this interface. The way 3ds Max does this is by
deriving the controllers from this class (<b>IKeyControl</b>) in addition to
class <b>Control</b>. So, multiple inheritance is used, and 3ds Max then
implements the methods of this class to provide the interface.\n\n
Below is the code from 3ds Max implementation of
<b>Animatable::GetInterface()</b> (as part of a template). Note the cast of the
<b>this</b> pointer to <b>IKeyControl</b>.\n\n
\code
INTERP_CONT_TEMPLATE
void* InterpControl<INTERP_CONT_PARAMS>::GetInterface(ULONG id)
{
if (id==I_KEYCONTROL) {
return (IKeyControl*)this;
}
else {
return Control::GetInterface(id);
}
}
\endcode */
class IKeyControl: public MaxHeapOperators {
public:
// Total number of keys.
/*! \remarks Returns the total number of keys. */
virtual int GetNumKeys()=0;
// Sets the number of keys allocated.
// May add blank keys or delete existing keys
/*! \remarks Sets the number of keys allocated. This may add blank
keys or delete existing keys. It is more efficient to set a large
number of keys using this method and then calling <b>SetKey()</b> to
store the values rather than calling <b>AppendKey()</b> over and over
for each key.
\par Parameters:
<b>int n</b>\n\n
The new number of keys. */
virtual void SetNumKeys(int n)=0;
// Fill in 'key' with the ith key
/*! \remarks Retrieves the 'i-th' key and stores the result in key.
\par Parameters:
<b>int i</b>\n\n
The index of the key to retrieve.\n\n
<b>IKey *key</b>\n\n
Storage for the key data. */
virtual void GetKey(int i,IKey *key)=0;
// Set the ith key
/*! \remarks Sets the 'i-th' key. The 'i-th' key must exist.
\par Parameters:
<b>int i</b>\n\n
The index of the key to set.\n\n
<b>IKey *key</b>\n\n
Pointer to the key data. */
virtual void SetKey(int i,IKey *key)=0;
// Append a new key onto the end. Note that the
// key list will ultimately be sorted by time. Returns
// the key's index.
/*! \remarks This method will append a new key onto the end of the key
list. Note that the key list will ultimately be sorted by time.
\par Parameters:
<b>IKey *key</b>\n\n
Pointer to the key data to append.
\return The key's index. */
virtual int AppendKey(IKey *key)=0;
// If any changes are made that would require the keys to be sorted
// this method should be called.
/*! \remarks This method should be called if any changes are made that
would require the keys to be sorted. The keys are stored in order by
TimeValue. */
virtual void SortKeys()=0;
// Access track flags
/*! \remarks Retrieves the track flags.
\return One or more of the following values:\n\n
<b>TFLAG_CURVESEL</b>\n\n
Determines if the curve is selected in the track view in the function
curve editor.\n\n
<b>TFLAG_RANGE_UNLOCKED</b>\n\n
Determines if the range is locked to the first key and the last key. If
a user goes into Position Ranges mode and moves the range bar, the
range becomes unlocked.\n\n
<b>TFLAG_LOOPEDIN</b>\n\n
This is set if the in out of range type is set to loop.\n\n
<b>TFLAG_LOOPEDOUT</b>\n\n
This is set if the out of range type is set to loop.\n\n
<b>TFLAG_COLOR</b>\n\n
Set for Bezier Point3 controllers that are color controllers.\n\n
<b>TFLAG_HSV</b>\n\n
Set for color controls that interpolate in HSV rather than RGB. */
virtual DWORD &GetTrackFlags()=0;
// Specify the max size of a key in bytes. Just need to implement if
// size of IKey is greater than this default value.
/*! \remarks Retrieves the maximim size of a key in bytes. Implement
only if size of IKey is greater than the default value.<br>
\return 128 (default), or the value you specify in your
implementation. \n\n
*/
virtual int GetKeySize() {return 128;}
};
//! Extend IKeyControl to include interfaces to IKeyProperty.
//! Keys of a key controller may have extra properties that does not affect
//! the interpolated value. These properties are accessed through interface
//! IKeyProperty. IKeyControl2 provides interface to the Key Property of
//! individual keys.\n
//! The interface ID is I_KEYCONTROL2 defined in AnimatableInterfaceIDs.h.
#pragma warning(push)
#pragma warning(disable:4100)
class IKeyControl2 : public IKeyControl {
public:
//! Whether the key of this key controller has property of ID id.
//! \param[in] id - the property ID being queried.
//! \return true if it has the property of ID id.
virtual bool DoesKeyPropExist(IKeyProperty::PropID id) { return false;}
//! Get the property of the i-th key.
//! Use this method to get the property of the i-th key.
//! \param[in] id - the property ID.
//! \param[in] i - the index of the key
//! \return a pointer to the key property object. It may return null\n
//! if the property of the respected ID does not exist at the key\n
//! of this key frame controller. To get the actual attributes of the\n
//! properties, cast the returned pointer to the appropriate property
//! interface.\n
//! The returned pointer must be deleted after use.
virtual const IKeyProperty* GetKeyProp(IKeyProperty::PropID id, int i) { return NULL; }
//! Set the property to the i-th key.
//! \param[in] id - the property ID.
//! \param[in] i the index for the key at which to set.
//! \param[in] prop - the property object whose values are used for set-value.\n
//! The implementation will cast it to appropriate property interface\n
//! and call the get methods to extract values. The values will be\n
//! checked against the expected range. An attribute of the key property\n
//! won't be affected if the value of that particular attribute is out of range.
//! \return true if set the key property has actually affected. It can\n
//! be false if (a) this key controller does not have the property, or\n
//! (b) the values in prop are out of expected ranges.
virtual bool SetKeyProp(IKeyProperty::PropID id, int i, const IKeyProperty& prop) { return false; }
};
class AnyKey: public MaxHeapOperators
{
public:
Tab<char> data;
AnyKey(int size = 128) { data.SetCount(size); } // 128 is default from IKeyControl::GetKeySize()
void SetSize(int size) { data.SetCount(size); }
operator IKey*() { return (IKey*)data.Addr(0); }
};
// ------- example:
// IKeyControl* ki = GetKeyControlInterface(controller);
// if (ki != NULL)
// {
// if (key_index >= ki->GetNumKeys())
// throw RuntimeError (GetString(IDS_KEY_NO_LONGER_EXISTS_IN_CONTROLLER), controller);
// AnyKey ak(ki->GetKeySize()); IKey* k = ak;
// ki->GetKey(key_index, k);
//--------------------------------------------------------------
// The following interface is an FP interface to flag TFLAG_TCBQUAT_NOWINDUP
// of IKeyControl::GetTrackFlags(). Specifically,
// IRotWindup::GetRotWindup() ==
// !(IKeyControl::GetTrackFlags()&TFLAG_TCBQUAT_NOWINDUP)
// However, IRotWindup::SetRotWindup() will notify dependents and handle
// undo/redo, etc.
// This interface is only available to TCB rotation controller (of class id,
// TCBINTERP_ROTATION_CLASS_ID).
// R4.5 and later only.
//
#define ROTWINDUP_INTERFACE Interface_ID(0x13a3032c, 0x381345ca)
class IRotWindup : public FPMixinInterface {
public:
static IRotWindup* GetIRotWindup(Animatable& a) {
return static_cast<IRotWindup*>(a.GetInterface(ROTWINDUP_INTERFACE));}
FPInterfaceDesc* GetDesc() { return GetDescByID(ROTWINDUP_INTERFACE); }
virtual bool GetRotWindup() const =0;
virtual void SetRotWindup(bool) =0;
enum FuncID {
kRotWindupGet, kRotWindupSet
};
BEGIN_FUNCTION_MAP
PROP_FNS(kRotWindupGet, GetRotWindup, kRotWindupSet, SetRotWindup, TYPE_bool)
END_FUNCTION_MAP
};
// Access to default key parameters
CoreExport void SetBezierDefaultTangentType(int in, int out);
CoreExport void GetBezierDefaultTangentType(int &in, int &out);
CoreExport void SetTCBDefaultParams(float t, float c, float b, float easeIn, float easeOut);
CoreExport void GetTCBDefaultParams(float &t, float &c, float &b, float &easeIn, float &easeOut);
// An interface for supporting mutiple tangent adjustment.
// If the user adjusts a tangent from a different track this tells the controller what angle to apply to its selected keys
// The first track hit is called to adjust its own handles and return the difference in angle and the
// percentage difference in length. All other tracks use this info to adjust their own handles.
// R4.5 and later only
class IAdjustMultipleTangents: public MaxHeapOperators {
public:
virtual void AdjustInitialTangents(TrackHitRecord hit,ParamDimensionBase *dim,Rect& rcGraph,
float tzoom,int tscroll,float vzoom,int vscroll,int dx,int dy,DWORD flags,
float &angle, float &length)=0; // the angle and percentage of length offsets are retrieved here
virtual void AdjustSecondaryTangents(DWORD hitFlags,ParamDimensionBase *dim,Rect& rcGraph,
float tzoom,int tscroll,float vzoom,int vscroll,float angle, float length, DWORD flags)=0;
};
// An interface for computing and gathering weighted key info
// If a keyframe controller wants to support soft selections, they should return an instance of this class when
// GetInterface(I_SOFTSELECT) is called. In order to limit the amount of data held by keyframe controllers
// the controller should build a weight table when ComputeWeights is called, and delete the weight table when ReleaseWeights()
// is called. The weight table is only valid while in Soft Selection mode. The controller should keep track of how many times
// GetInterface is called and only ReleaseWeights when the last client calls it.
// R4.5 and later only
class ISoftSelect: public MaxHeapOperators {
public:
virtual void ComputeWeights(TimeValue range, float falloff)=0;
virtual float GetWeight(int i)=0;
virtual void ReleaseWeights()=0;
};
//-----------------------------------------------------------
// A plug-in can register itself to read a particular APP_DATA
// chunk when a 3DS file is loaded. If a chunk is encountered
// that matches a registered plug-in, that plug-in will be
// asked to create an instance of itself based on the contents
// of the APP_DATA chunk.
class TriObject;
/*! \sa Class TriObject.\n\n
\par Description:
3D Studio DOS allowed developers to store APP_DATA with objects and nodes in
the scene. When the 3DS DOS file is imported into 3ds Max, and no plug-in has
registered to convert it, then it is just hung off the object (or INode in the
case of KXP app data).\n\n
A 3ds Max plug-in can register itself to read a particular APP_DATA chunk when
a 3DS DOS file is loaded. If a chunk is encountered that matches a registered
plug-in, that plug-in will be asked to create an instance of itself based on
the contents of the APP_DATA chunk. The plug-in callback is given an
opportunity to read the chunk and create an object other than a
<b>TriObject</b> based on the contents of the chunk and the original
object.\n\n
A plug-in that wants to process app data registers a new class derived from
this class by calling <b>void
RegisterObjectAppDataReader(ObjectDataReaderCallback *cb);</b>\n\n
The system then maintains a list of these <b>ObjectDataReaderCallbacks</b>.
*/
class ObjectDataReaderCallback: public MaxHeapOperators {
public:
// Chunk name
/*! \remarks Returns the name that identifies the app data chunk. When the 3DS
Import plug-in is loading objects, it will look for app data. For each
app data chunk that the object has, it will go through the list of
registered callbacks and call this method looking for a name match.
When it does find a match it will call <b>ReadData()</b> on the
callback that matched. */
virtual char *DataName()=0;
// Create an instance of an object based on the data and the original mesh object
/*! \remarks This method is called to read the app data and create an instance of an
object based on the data and the original mesh object. For example, the
3D Surfer plug-in from 3DS DOS creates a patch object based on the app
data parameters and returns a pointer to it.
\par Parameters:
<b>TriObject *obj</b>\n\n
The original mesh object the app data was assigned to. If no callback
was registered, this would be the object that would get created.\n\n
<b>void *data</b>\n\n
Points to the particular app data chunk handled by the registered
callback.\n\n
<b>DWORD len</b>\n\n
The length of the app data chunk.
\return The Object created by the plug-in to hold the appdata. This
would be the object created to take the place of the TriObject. For
example, consider a 3DS object that had appdata embedded in it which
represented the patch object from which the mesh was created (like 3D
Surfer for example). This method would take that data and created a
patch object so that the user could work with the object as a patch
object in 3ds Max instead of a tri object. */
virtual Object *ReadData(TriObject *obj, void *data, DWORD len)=0;
/*! \remarks This method is called to delete this callback object. When the user
exits 3ds Max, this method is called on each of the registered
callbacks. So if the callback was allocated dynamically, it could free
itself in this implementation. */
virtual void DeleteThis()=0;
};
/*! \remarks Implemented by the System.\n\n
This method allows a plug-in to register a callback that will be called when
reading a 3DS file that has a particular appdata chunk. The plug-in callback is
given an opportunity to read the chunk and create an object other than a
TriObject based on the contents of the chunk and the original object.
\par Parameters:
<b>ObjectDataReaderCallback *cb</b>\n\n
The callback to read the chunk and create an object. */
CoreExport void RegisterObjectAppDataReader(ObjectDataReaderCallback *cb);
/*! \remarks This function is used internally by the 3DS Import plug-in.\n\n
Note the following about 3DS App Data. If app data is encountered and no
plug-in has registered to convert it, then it is just hung off the object (or
INode in the case of KXP app data). For object app data, TriObject's super
class and class ID are used to identify the chunk and the sub ID is set to 0.
For node app data, INode's super class and class ID are used to identify the
chunk and the sub ID is set to 0.\n\n
This single 3ds Max app data chunk will contain the entire 3DS app data chunk,
which may have sub chunks (see the IPAS SDK). The following routines will aid
in parsing 3DS app data. */
CoreExport Object *ObjectFromAppData(TriObject *obj, char *name, void *data, DWORD len);
// Note about 3DS App Data:
// If app data is encountered and no plug-in has registered to
// convert it, then it is just hung off the object (or INode in
// the case of KXP app data).
// For object app data, TriObject's super class and class ID are used
// to identify the chunk and the sub ID is set to 0.
// For node app data, INode's super class and class ID are used
// to identify the chunk and the sub ID is set to 0.
//
// This single MAX app data chunk will contain the entire
// 3DS app data chunk, which may have sub chunks (see IPAS SDK).
// The following routines will aid in parsing 3DS app data.
// Get the ID string out of an XDATA_ENTRY chunk and null terminates it
/*! \remarks This function gets the ID string out of an <b>XDATA_ENTRY</b>
chunk and null terminates it.
\par Parameters:
<b>char *chunk</b>\n\n
A pointer to the chunk.\n\n
<b>char *idstring</b>\n\n
The ID string. */
CoreExport void GetIDStr(char *chunk, char *idstring);
// Returns the offset into 'appd' of the specified chunk
// or -1 if it is not found
/*! \remarks Returns the offset into <b>appd</b> of the specified chunk or -1
if it is not found.
\par Parameters:
<b>void *appd</b>\n\n
The is the entire app data chunk containing all the sub-chunks.\n\n
<b>DWORD len</b>\n\n
This is the length of the entire app data chunk.\n\n
<b>char *idstring</b>\n\n
The ID of the chunk to find.
\return The offset into <b>appd</b> of the specified chunk or -1 if it is not
found. */
CoreExport int FindAppDataChunk(void *appd, DWORD len, char *idstring);
// Similar to Find, but actually returns a pointer to the chunk
// or NULL if it is not found
/*! \remarks This function is similar to <b>FindAppDataChunk()</b> above, but
returns a pointer to the chunk or NULL if it is not found.
\par Parameters:
<b>void *appd</b>\n\n
The is the entire app data chunk containing all the sub-chunks.\n\n
<b>DWORD len</b>\n\n
This is the length of the entire app data chunk.\n\n
<b>char *idstring</b>\n\n
The ID of the chunk to find.
\return A pointer to the chunk or NULL if it is not found. */
CoreExport void *GetAppDataChunk(void *appd, DWORD len, char *idstring);
// Adds the chunk to the appdata chunk, preserving existing chunks.
// 'chunk' should point to the new chunk header followed by its data.
/*! \remarks This function adds the chunk to the appdata chunk, preserving
existing chunks. <b>chunk</b> should point to the new chunk header followed by
its data.
\par Parameters:
<b>void **pappd</b>\n\n
The is the entire app data chunk containing all the sub-chunks.\n\n
<b>DWORD \&len</b>\n\n
This is the length of the entire app data chunk.\n\n
<b>void *chunk</b>\n\n
A pointer to the new chunk header.
\return Nonzero if the chunk was added; otherwise zero. */
CoreExport int SetAppDataChunk(void **pappd, DWORD &len, void *chunk);
// Deletes a chunk from the appdata while preserving other chunks.
/*! \remarks Deletes a chunk from the appdata while preserving other chunks.
\par Parameters:
<b>void **pappd</b>\n\n
The is the entire app data chunk containing all the sub-chunks.\n\n
<b>DWORD \&len</b>\n\n
This is the length of the entire app data chunk.\n\n
<b>char *idstring</b>\n\n
The ID of the chunk to delete.
\return Nonzero if the chunk was deleted; otherwise zero. */
CoreExport int DeleteAppDataChunk(void **pappd, DWORD &len, char *idstring);
// Known sub chunks inside an appdata chunk
#define XDATA_ENTRY 0x8001
#define XDATA_APPNAME 0x8002
//---------------------------------------------------------
// Interface into MAX's default WAV sound object
// use the Interface method GetSoundObject() to get a pointer
// to the current sound object and then use the
// GetWaveSoundInterface() on the result to see if it supports
// this interface.
/*! SeeAlso: Class Interface.\n\n
\par Description:
This class provides an interface into 3ds Max's default WAV sound object. Use
the <b>Interface</b> method <b>GetSoundObject()</b> to get a pointer to the
current sound object and then use the macro <b>GetWaveSoundInterface()</b> on
the result to see if it supports this interface. See the sample code below:\n\n
<b>// Retrieve the current sound object</b>\n\n
<b>SoundObj *sound = ip-\>GetSoundObject();</b>\n\n
<b>// Attempt to get a wave interface</b>\n\n
<b>IWaveSound *iWave = GetWaveSoundInterface(sound);</b>\n\n
<b>if (iWave) {</b>\n\n
<b>iWave-\>SetSoundFileName(_M("LedZep.wav"))</b>\n\n
<b>}</b>\n\n
All methods of this class are implemented by the system. */
class IWaveSound: public MaxHeapOperators {
public:
//! \deprecated see virtual MaxSDK::AssetManagement::AssetUser GetSoundFile()=0;
MAX_DEPRECATED MSTR GetSoundFileName();
// Retreives the name of the current sound file asset
/*! \remarks Returns the name of the current sound file asset. */
virtual const MaxSDK::AssetManagement::AssetUser& GetSoundFile()=0;
//! \deprecated see virtual BOOL SetSoundFile(const MaxSDK::AssetManagement::AssetUser& name)=0;
MAX_DEPRECATED BOOL SetSoundFileName(MSTR name);
// Sets the sound file asset. This will cause the WAV to
// be loaded into the tack view. Returns FALSE if
// the file can't be opened or no wave track exist.
/*! \remarks Sets the sound file asset. This will cause the .WAV to be
loaded into the track view.
\par Parameters:
<b>MSTR name</b>\n\n
The name of the sound file asset to set.
\return FALSE if the file can't be opened or no wave track exists;
otherwise TRUE. */
virtual BOOL SetSoundFile(const MaxSDK::AssetManagement::AssetUser& name)=0;
// Set the time offset for the wave
/*! \remarks Sets the time offset for the wave file.
\par Parameters:
<b>TimeValue t</b>\n\n
The start time. */
virtual void SetStartTime(TimeValue t)=0;
// Get the time offset for the wave
/*! \remarks Returns the start time offset for the wave. */
virtual TimeValue GetStartTime()=0;
/*! \remarks Returns the end time for the wave. */
virtual TimeValue GetEndTime()=0;
};
//-----------------------------------------------------------
//
// Access to the boolean object's parameters. Given a pointer to
// an object whose class ID is Class_ID(BOOLOBJ_CLASS_ID,0) or
// NEWBOOL_CLASS_ID, you can cast that pointer to the following
// class. Note that some options do not work in the old Boolean
// (BOOLOBJ_CLASS_ID), and there is no Optimize parameter in
// the new Boolean.
//
#define BOOLOP_UNION 0
#define BOOLOP_INTERSECTION 1
#define BOOLOP_SUB_AB 2
#define BOOLOP_SUB_BA 3
#define BOOLOP_CUT 4
#define BOOLOP_CUT_REFINE 0
#define BOOLOP_CUT_SEPARATE 1
#define BOOLOP_CUT_REMOVE_IN 2
#define BOOLOP_CUT_REMOVE_OUT 3
#define BOOLUPDATE_ALWAYS 0
#define BOOLUPDATE_SELECTED 1
#define BOOLUPDATE_RENDER 2
#define BOOLUPDATE_MANUAL 3
#define BOOL_ADDOP_REFERENCE 0
#define BOOL_ADDOP_INSTANCE 1
#define BOOL_ADDOP_COPY 2
#define BOOL_ADDOP_MOVE 3
#define BOOL_MAT_NO_MODIFY 0
#define BOOL_MAT_IDTOMAT 1
#define BOOL_MAT_MATTOID 2
#define BOOL_MAT_DISCARD_ORIG 3
#define BOOL_MAT_DISCARD_NEW 4
/*! \sa Class GeomObject.\n\n
\par Description:
This class is available in release 2.0 and later only.\n\n
This class provides access to the boolean object's parameters. Given a pointer
to an object whose ClassID is <b>BOOLOBJ_CLASS_ID</b>, you can cast that
pointer to this class and use the methods to access the parameters. Note: In
3ds Max 3.0 and later the new boolean object is used and it has its own
ClassID. Therefore where you previously used
<b>Class_ID(BOOLOBJ_CLASS_ID,0)</b> you should now use <b>NEWBOOL_CLASS_ID</b>
(<b>#define NEWBOOL_CLASS_ID Class_ID(0x51db4f2f,0x1c596b1a)</b>).\n\n
The boolean object has four references. 2 references to the operand objects and
2 references to transform controllers providing a transformation matrix for the
2 operands. The following values may be used to access the boolean object's
references:\n\n
<b>BOOLREF_OBJECT1</b>\n\n
<b>BOOLREF_OBJECT2</b>\n\n
<b>BOOLREF_CONT1</b>\n\n
<b>BOOLREF_CONT2</b>\n\n
All methods of this class are implemented by the system. */
class IBoolObject : public GeomObject {
public:
/*! \remarks Returns TRUE if the specified operand is selected; otherwise
FALSE.
\par Parameters:
<b>int which</b>\n\n
Specifies which operand to check.\n\n
<b>0</b> for operand A, <b>1</b> for operand B. */
virtual BOOL GetOperandSel(int which)=0;
/*! \remarks Sets the selected state of the specified operand.
\par Parameters:
<b>int which</b>\n\n
Specifies which operand to select.\n\n
<b>0</b> for operand A, <b>1</b> for operand B.\n\n
<b>BOOL sel</b>\n\n
TRUE to select it; FALSE to deselect it. */
virtual void SetOperandSel(int which,BOOL sel)=0;
/*! \remarks Returns the boolean operation setting.
\return One of the following values:\n\n
<b>BOOLOP_UNION</b>\n\n
<b>BOOLOP_INTERSECTION</b>\n\n
<b>BOOLOP_SUB_AB</b>\n\n
<b>BOOLOP_SUB_BA</b>\n\n
<b>BOOLOP_CUT</b> -- This option is available in release 3.0 and later
only. */
virtual int GetBoolOp()=0;
/*! \remarks Sets the boolean operation.
\par Parameters:
<b>int op</b>\n\n
One of the following values:\n\n
<b>BOOLOP_UNION</b>\n\n
<b>BOOLOP_INTERSECTION</b>\n\n
<b>BOOLOP_SUB_AB</b>\n\n
<b>BOOLOP_SUB_BA</b>\n\n
<b>BOOLOP_CUT</b> -- This option is available in release 3.0 and later
only. */
virtual void SetBoolOp(int op)=0;
/*! \remarks Returns the type if the 'Cut' operation is choosen. One of the following
values:\n\n
<b>BOOLOP_CUT_REFINE</b>\n\n
<b>BOOLOP_CUT_SEPARATE</b>\n\n
<b>BOOLOP_CUT_REMOVE_IN</b>\n\n
<b>BOOLOP_CUT_REMOVE_OUT</b> */
virtual int GetBoolCutType()=0;
/*! \remarks Sets the type for the 'Cut' operation. One of the following values:
\par Parameters:
<b>int ct</b>\n\n
One of the following values:\n\n
<b>BOOLOP_CUT_REFINE</b>\n\n
<b>BOOLOP_CUT_SEPARATE</b>\n\n
<b>BOOLOP_CUT_REMOVE_IN</b>\n\n
<b>BOOLOP_CUT_REMOVE_OUT</b> */
virtual void SetBoolCutType(int ct)=0;
/*! \remarks Returns the display result setting. If TRUE the result is
display; otherwise the operands are displayed. */
virtual BOOL GetDisplayResult()=0;
/*! \remarks Sets the display result state.
\par Parameters:
<b>BOOL onOff</b>\n\n
TRUE to show the result; FALSE to show the operands. */
virtual void SetDisplayResult(BOOL onOff)=0;
/*! \remarks Returns the show hidden operands state. TRUE if on; FALSE if
off. */
virtual BOOL GetShowHiddenOps()=0;
/*! \remarks Sets the state of the show hidden operands setting.
\par Parameters:
<b>BOOL onOff</b>\n\n
TRUE for on; FALSE for off. */
virtual void SetShowHiddenOps(BOOL onOff)=0;
/*! \remarks Returns the state of the update mode.
\return One of the following values:\n\n
<b>BOOLUPDATE_ALWAYS</b>\n\n
<b>BOOLUPDATE_SELECTED</b>\n\n
<b>BOOLUPDATE_RENDER</b>\n\n
<b>BOOLUPDATE_MANUAL</b> */
virtual int GetUpdateMode()=0;
/*! \remarks Sets the state of the update mode.
\par Parameters:
<b>int mode</b>\n\n
One of the following values:\n\n
<b>BOOLUPDATE_ALWAYS</b>\n\n
<b>BOOLUPDATE_SELECTED</b>\n\n
<b>BOOLUPDATE_RENDER</b>\n\n
<b>BOOLUPDATE_MANUAL</b> */
virtual void SetUpdateMode(int mode)=0;
/*! \remarks Returns the state of the optimize result setting. TRUE if on;
FALSE if off. Note: This method does not work on 'new' boolean objects as
there is no optimize setting for these. */
virtual BOOL GetOptimize()=0;
/*! \remarks Sets the state of the optimize result setting. Note: This
method does not work on 'new' boolean objects as there is no optimize
setting for these.
\par Parameters:
<b>BOOL onOff</b>\n\n
TRUE for on; FALSE for off. */
virtual void SetOptimize(BOOL onOff)=0;
/*! \remarks Sets the node used for operand A. This method adds a restore object if
<b>theHold.Holding()</b>, but the <b>Begin()</b> and <b>Accept()</b> should
be done in the calling routine.\n\n
Note the following:\n\n
- In a Boolean Object, A should be specified before B. (This allows
material merges, etc, to work.)\n\n
- This method adds a restore object if <b>theHold.Holding()</b>, but the
<b>Begin()</b> and <b>Accept()</b> should be done in the calling routine.
\par Parameters:
<b>TimeValue t</b>\n\n
The time at which to set the operand.\n\n
<b>INode *node</b>\n\n
Points to the operand A node. */
virtual void SetOperandA (TimeValue t, INode *node)=0;
/*! \remarks Sets the node used for operand B. This method adds a restore object if
<b>theHold.Holding()</b>, but the <b>Begin()</b> and <b>Accept()</b> should be
done in the calling routine.
\par Parameters:
<b>TimeValue t</b>\n\n
The time at which to set the operand.\n\n
<b>INode *node</b>\n\n+
Points to the operand B node.\n\n
<b>INode *boolNode</b>\n\n
Points to the node of the boolean object.\n\n
<b>int addOpMethod=0</b>\n\n
One of the following values:\n\n
<b>BOOL_ADDOP_REFERENCE</b>\n\n
Operand is a reference to original node.\n\n
<b>BOOL_ADDOP_INSTANCE</b>\n\n
Operand is an instance of the original node.\n\n
<b>BOOL_ADDOP_COPY</b>\n\n
Operand is a copy of the original node.\n\n
<b>BOOL_ADDOP_MOVE</b>\n\n
Original node should be deleted.\n\n
<b>int matMergeMethod=0</b>\n\n
One of the following values:\n\n
<b>BOOL_MAT_NO_MODIFY</b>\n\n
Combines materials without changing them or the ID's.\n\n
<b>BOOL_MAT_IDTOMAT</b>\n\n
Matches ID's to materials, then combines materials.\n\n
<b>BOOL_MAT_MATTOID</b>\n\n
Matches materials to ID's, then combines them.\n\n
<b>BOOL_MAT_DISCARD_ORIG</b>\n\n
Discards original material, uses new node's instead.\n\n
<b>BOOL_MAT_DISCARD_NEW</b>\n\n
Discards new node's material, uses original. */
virtual void SetOperandB (TimeValue t, INode *node, INode *boolNode,
int addOpMethod=0, int matMergeMethod=0, bool *canUndo=NULL)=0;
};
// The boolean object has five references. 2 references to the
// operand objects, 2 references to transform controllers
// providing a transformation matrix for the 2 operands,
// and one to the parameter block.
#define BOOLREF_OBJECT1 0
#define BOOLREF_OBJECT2 1
#define BOOLREF_CONT1 2
#define BOOLREF_CONT2 3
#define BOOLREF_PBLOCK 4
//-------------------------------------------------------------
// Access to path controller's parameters.
//
//Function Publishing interface Added by Ambarish Goswami (8-26-2000)
//***********************************************************
class IPathPosition;
#define PATH_CONSTRAINT_INTERFACE Interface_ID(0x79d15f78, 0x1f901f8e)
#define GetIPathConstInterface(cd) \
(IPathPosition*)(cd)->GetInterface(PATH_CONSTRAINT_INTERFACE)
/*! \sa Class Control, Class INode.\n\n
\par Description:
This class is available in release 2.0 and later only.\n\n
This class represents the interface to the Path Position Controller. You can
obtain a pointer to the path position controller interface using;
<b>GetIPathConstInterface(cd)</b>. This macro will return\n\n
<b>(IPathPosition*)(CD)-\>GetFPInterface(PATH_CONSTRAINT_INTERFACE).</b>\n\n
<b>PATHPOS_PATH_REF</b> may be used to access the position constraint
controller's references and <b>PATHPOS_PBLOCK_REF</b> to reference the
parameter block.\n\n
All methods of this class are Implemented by the System. */
class IPathPosition : public Control, public FPMixinInterface
{
public:
enum { get_num_targets, get_node, get_target_weight,
set_target_weight, append_target, delete_target,};
// Function Map for Function Publish System
//***********************************
BEGIN_FUNCTION_MAP
FN_0(get_num_targets, TYPE_INT, GetNumTargets);
FN_1(get_node, TYPE_INODE, GetNode, TYPE_INDEX);
FN_1(get_target_weight, TYPE_FLOAT, GetTargetWeight, TYPE_INDEX);
FN_2(set_target_weight, TYPE_BOOL, SetTargetWeight, TYPE_INDEX, TYPE_FLOAT);
FN_2(append_target, TYPE_BOOL, AppendTarget, TYPE_INODE, TYPE_FLOAT);
FN_1(delete_target, TYPE_BOOL, DeleteTarget, TYPE_INDEX);
END_FUNCTION_MAP
FPInterfaceDesc* GetDesc(); // <-- must implement
//End of Function Publishing system code
//***********************************
/*! \remarks This method is available in release 4.0 and later
only.\n\n
Returns the number of nodes in the path list. */
virtual int GetNumTargets()=0;
/*! \remarks This method is available in release 4.0 and later
only.\n\n
Gets one of the path nodes that the path controller follows, specified
by <b>targetNumber</b>.
\par Parameters:
<b>int targetNumber</b>\n\n
The node number in the path list to be obtained. */
virtual INode* GetNode(int targetNumber)=0;
/*! \remarks This method is available in release 4.0 and later
only.\n\n
Gets the weight of one of the path nodes that the path controller
follows, specified by <b>targetNumber</b>, and time t. If the
<b>targetNumber</b> is not relevant then 0.0f is returned.
\par Parameters:
<b>int targetNumber</b>\n\n
The node number in the path list whose weight is to be obtained. */
virtual float GetTargetWeight(int targetNumber)=0;
/*! \remarks This method is available in release 4.0 and later
only.\n\n
Sets the weight of one of the path nodes that the path controller
follows, specified by <b>targetNumber</b>.
\par Parameters:
<b>int targetNumber</b>\n\n
The node number in the path list whose weight is to be set.\n\n
<b>float weight</b>\n\n
The weight to assign.
\return TRUE if there is more than one path in the list and you are
trying to set weight, FALSE otherwise. */
virtual BOOL SetTargetWeight(int targetNumber, float weight)=0;
/*! \remarks This method is available in release 4.0 and later
only.\n\n
Appends the current path list by one and appends the current weight
list by one.
\par Parameters:
<b>INode *target</b>\n\n
The node that is to be appended to the current path list.\n\n
<b>float weight=50.0</b>\n\n
The weight to be assigned to the newly appended path. */
virtual BOOL AppendTarget(INode *target, float weight=50.0)=0;
/*! \remarks This method is available in release 4.0 and later
only.\n\n
This method allows you to delete a specified target.
\par Parameters:
<b>int selection</b>\n\n
The node number in the orientation target list to delete.
\return TRUE if successful, otherwise FALSE. */
virtual BOOL DeleteTarget(int selection)=0;
/*! \remarks This method allows you to set the follow flag.
\par Parameters:
<b>BOOL f</b>\n\n
TRUE for on, FALSE for off.\n\n
*/
virtual void SetFollow(BOOL f)=0;
/*! \remarks This method returns the state of the follow flag. TRUE if
on; FALSE if off. */
virtual BOOL GetFollow()=0;
/*! \remarks Sets the bank amount parameter.\n\n
Bank and tracking are scaled in the UI.\n\n
The bank values are scaled in the user interface. The following macros
may be used to convert to and from the UI values.\n\n
<b>#define BANKSCALE 100.0f</b>\n\n
<b>#define FromBankUI(a) ((a)*BANKSCALE)</b>\n\n
<b>#define ToBankUI(a) ((a)/BANKSCALE)</b>
\par Parameters:
<b>float a</b>\n\n
The bank amount. */
virtual void SetBankAmount(float a)=0;
/*! \remarks Returns the bank amount setting. See the remarks in
<b>SetBankAmount()</b> above. */
virtual float GetBankAmount()=0;
/*! \remarks Sets the bank parameter to on or off.
\par Parameters:
<b>BOOL b</b>\n\n
TRUE for on; FALSE for off. */
virtual void SetBank(BOOL b)=0;
/*! \remarks Returns the on/off state of the bank parameter. TRUE if
on; FALSE if off. */
virtual BOOL GetBank()=0;
/*! \remarks Sets the smoothness parameter.\n\n
The smoothing (tracking) values are scaled in the user interface. The
following macros may be used to convert to and from the UI values.\n\n
<b>#define TRACKSCALE 0.04f</b>\n\n
<b>#define FromTrackUI(a) ((a)*TRACKSCALE)</b>\n\n
<b>#define ToTrackUI(a) ((a)/TRACKSCALE)</b>
\par Parameters:
<b>float t</b>\n\n
The smoothness setting. */
virtual void SetTracking(float t)=0; // smoothness
/*! \remarks Returns the smoothness setting. See remarks in
<b>SetTracking()</b> above. */
virtual float GetTracking()=0;
/*! \remarks Sets the state of the 'Allow Upside Down' parameter.
\par Parameters:
<b>BOOL f</b>\n\n
TRUE for on; FALSE for off. */
virtual void SetAllowFlip(BOOL f)=0;
/*! \remarks Returns the state of the 'Allow Upside Down' parameter.
\return TRUE for on; FALSE for off. */
virtual BOOL GetAllowFlip()=0;
/*! \remarks Sets the state of the 'Constant Velocity' parameter.
\par Parameters:
<b>BOOL cv</b>\n\n
TRUE for on; FALSE for off. */
virtual void SetConstVel(BOOL cv)=0;
/*! \remarks Returns the state of the 'Constant Velocity' parameter.
\return TRUE for on; FALSE for off. */
virtual BOOL GetConstVel()=0;
/*! \remarks Sets the state of the 'Flip' parameter.
\par Parameters:
<b>BOOL onOff</b>\n\n
TRUE for on; FALSE for off. */
virtual void SetFlip(BOOL onOff)=0;
/*! \remarks Returns the state of the 'Flip' parameter.
\return TRUE for on; FALSE for off. */
virtual BOOL GetFlip()=0;
/*! \remarks Set the state of the axis parameter.
\par Parameters:
<b>int axis</b>\n\n
The axis setting. One of the following values:\n\n
<b>0</b>: X axis.\n\n
<b>1</b>: Y axis.\n\n
<b>2</b>: Z axis. */
virtual void SetAxis(int axis)=0;
/*! \remarks Returns the axis setting.
\return One of the following values:\n\n
<b>0</b>: X axis.\n\n
<b>1</b>: Y axis.\n\n
<b>2</b>: Z axis. */
virtual int GetAxis()=0;
/*! \remarks This method allows you to set the state of the loop flag.
\par Parameters:
<b>BOOL l</b>\n\n
TRUE for on; FALSE for off. */
virtual void SetLoop(BOOL l)=0; // AG added
/*! \remarks Returns the state of the loop flag.
\return TRUE for on; FALSE for off. */
virtual BOOL GetLoop()=0; // AG added
/*! \remarks This method allows you to set the state of the
relative/absolute flag.
\par Parameters:
<b>BOOL rel</b>\n\n
TRUE to set to relative; FALSE to set to absolute. */
virtual void SetRelative(BOOL rel)=0; // AG added
/*! \remarks Returns the state of the relative/absolute flag.
\return TRUE if relative is on; FALSE is off (i.e. absolute). */
virtual BOOL GetRelative()=0;
};
// block IDs
enum { path_params, path_joint_params };
// path_params param IDs
enum { path_percent, path_path, path_follow,
path_bank, path_bank_amount, path_smoothness,
path_allow_upsidedown, path_constant_vel, path_axis,
path_axis_flip, path_path_weight, path_path_list,
path_loop, path_relative,};
// Bank and tracking are scaled in the UI.
#define BANKSCALE 100.0f
#define FromBankUI(a) ((a)*BANKSCALE)
#define ToBankUI(a) ((a)/BANKSCALE)
#define TRACKSCALE 0.04f
#define FromTrackUI(a) ((a)*TRACKSCALE)
#define ToTrackUI(a) ((a)/TRACKSCALE)
// percent controller, path node and paramblock2 refs
// #define PATHPOS_PERCENT_REF 0 // obsolete in Ed. 2, percent is an animatable in the ParamBlock
#define PATHPOS_PATH_REF 1
#define PATHPOS_PBLOCK_REF 2
//-------------------------------------------------------------
// // Access to Position Constraint controller's parameters.
// Ambarish Goswami implemented April, 2000
//Function Publishing interface Added by Adam Felt (5-16-00)
//***********************************************************
class IPosConstPosition;
#define POS_CONSTRAINT_INTERFACE Interface_ID(0x32040779, 0x794a1278)
#define GetIPosConstInterface(cd) \
(IPosConstPosition*)(cd)->GetInterface(POS_CONSTRAINT_INTERFACE)
//***********************************************************
/*! \sa Class Control, Class FPMixinInterface.\n\n
\par Description:
This class is available in release 4.0 and later only.\n\n
This class represents the interface to the Position Constraint. You can obtain
a pointer to the position constraint interface using;
<b>GetIPosConstInterface(cd)</b>. This macro will return\n\n
<b>(IPosConstPosition*)(CD)-\>GetFPInterface(POS_CONSTRAINT_INTERFACE).</b>\n\n
<b>POSPOS_PBLOCK_REF</b> may be used to access the position constraint
controller's references:\n\n
All methods of this class are Implemented by the System. */
class IPosConstPosition : public Control, public FPMixinInterface {
public:
enum { get_num_targets, get_node, get_target_weight,
set_target_weight, append_target, delete_target,};
// Function Map for Function Publish System
//***********************************
BEGIN_FUNCTION_MAP
FN_0(get_num_targets, TYPE_INT, GetNumTargets);
FN_1(get_node, TYPE_INODE, GetNode, TYPE_INDEX);
FN_1(get_target_weight, TYPE_FLOAT, GetTargetWeight, TYPE_INDEX);
FN_2(set_target_weight, TYPE_BOOL, SetTargetWeight, TYPE_INDEX, TYPE_FLOAT);
FN_2(append_target, TYPE_BOOL, AppendTarget, TYPE_INODE, TYPE_FLOAT);
FN_1(delete_target, TYPE_BOOL, DeleteTarget, TYPE_INDEX);
END_FUNCTION_MAP
FPInterfaceDesc* GetDesc(); // <-- must implement
//End of Function Publishing system code
//***********************************
/*! \remarks Returns the number of target nodes in the position target
list. */
virtual int GetNumTargets()=0;
/*! \remarks Gets one of the position nodes that the position
constraint controller targets, specified by <b>targetNumber</b>.
\par Parameters:
<b>int targetNumber</b>\n\n
The node number in the position target list to be obtained. */
virtual INode* GetNode(int targetNumber)=0;
/*! \remarks Gets the weight of one of the position nodes that the
position constraint controller targets, specified by
<b>targetNumber</b>.
\par Parameters:
<b>int targetNumber</b>\n\n
The node number in the position target list to set.
\return Returns the position target weight if the <b>targetNumber</b>
is relevant, 0.0f otherwise. */
virtual float GetTargetWeight(int targetNumber)=0;
/*! \remarks Sets the weight of one of the position nodes that the
position constraint controller follows, specified by
<b>targetNumber</b>.
\par Parameters:
<b>int targetNumber</b>\n\n
The node number in the position target list whose weight is to be
set.\n\n
<b>float weight</b>\n\n
The weight to set.
\return TRUE if there is more than one position target in the list and
you are trying to set weight, FALSE otherwise. */
virtual BOOL SetTargetWeight(int targetNumber, float weight)=0;
/*! \remarks Appends the current position target list by one and
appends.
\par Parameters:
<b>INode *target</b>\n\n
The node that is to be appended to the current position target
list.\n\n
<b>float weight=50.0</b>\n\n
This is the weight that is to be assigned to the newly appended
position target. The default weight is 50.0.
\return TRUE if the target was appended, otherwise FALSE.\n\n
*/
virtual BOOL AppendTarget(INode *target, float weight=50.0)=0;
/*! \remarks This method allows you to delete a specified target.
\par Parameters:
<b>int selection</b>\n\n
The node number in the position target list to delete.
\return TRUE if successful, otherwise FALSE. */
virtual BOOL DeleteTarget(int selection)=0;
};
#define POSPOS_PBLOCK_REF 0
//-------------------------------------------------------------
// // Access to Orientation Constraint controller's parameters.
// Ambarish Goswami implemented May, 2000
//Function Publishing interface Added by Ambarish Goswami 6/18/2000 adapted from Adam Felt (5-16-00)
//**************************************************************************************************
class IOrientConstRotation;
#define ORIENT_CONSTRAINT_INTERFACE Interface_ID(0x71e2231b, 0x72522ab2)
#define GetIOrientConstInterface(cd) \
(IOrientConstRotation*)(cd)->GetInterface(ORIENT_CONSTRAINT_INTERFACE)
//***********************************************************
/*! \sa Class Control, Class FPMixinInterface.\n\n
\par Description:
This class is available in release 4.0 and later only.\n\n
The Orientation Constraint matches the orientation of an object to its target
without affecting its position. Multiple weighted targets are supported. This
class is an interface to the parameters of this controllers. You can obtain a
pointer to the list control interface using;
<b>GetIOrientConstInterface(cd)</b>. This macro will return
<b>(IOrientConstRotation*)(CD)-\>GetFPInterface(ORIENT_CONSTRAINT_INTERFACE).</b>\n\n
<b>ORIENT_ROT_PBLOCK_REF</b> may be used to access the orientation constraint
controller's references:\n\n
All methods of this class are Implemented by the System. */
class IOrientConstRotation : public Control, public FPMixinInterface {
public:
enum { get_num_targets, get_node, get_target_weight,
set_target_weight, append_target, delete_target,};
// Function Map for Function Publish System
//***********************************
BEGIN_FUNCTION_MAP
FN_0(get_num_targets, TYPE_INT, GetNumTargets);
FN_1(get_node, TYPE_INODE, GetNode, TYPE_INDEX);
FN_1(get_target_weight, TYPE_FLOAT, GetTargetWeight, TYPE_INDEX);
FN_2(set_target_weight, TYPE_BOOL, SetTargetWeight, TYPE_INDEX, TYPE_FLOAT);
FN_2(append_target, TYPE_BOOL, AppendTarget, TYPE_INODE, TYPE_FLOAT);
FN_1(delete_target, TYPE_BOOL, DeleteTarget, TYPE_INDEX);
END_FUNCTION_MAP
FPInterfaceDesc* GetDesc(); // <-- must implement
//End of Function Publishing system code
//***********************************
/*! \remarks Returns the number of target nodes in the orientation
target list. */
virtual int GetNumTargets()=0;
/*! \remarks Gets one of the orientation nodes that the orientation
constraint controller targets, specified by <b>targetNumber</b>.
\par Parameters:
<b>int targetNumber</b>\n\n
The node number in the orientation target list to be obtained. */
virtual INode* GetNode(int targetNumber)=0;
/*! \remarks Gets the weight of one of the orientation nodes that the
orientation constraint controller targets, specified by
<b>targetNumber</b>.
\par Parameters:
<b>int targetNumber</b>\n\n
The node number in the orientation target list to set.
\return Returns the orientation target weight if the
<b>targetNumber</b> is relevant, 0.0f otherwise. */
virtual float GetTargetWeight(int targetNumber)=0;
/*! \remarks Sets the weight of one of the orientation nodes that the
orientation constraint controller follows, specified by
<b>targetNumber</b>.
\par Parameters:
<b>int targetNumber</b>\n\n
The node number in the orientation target list whose weight is to be
set.\n\n
<b>float weight</b>\n\n
The weight to set.
\return TRUE if there is more than one orientation target in the list
and you are trying to set weight, FALSE otherwise. */
virtual BOOL SetTargetWeight(int targetNumber, float weight)=0;
/*! \remarks Appends the current orientation target list by one and
appends the current orient_targ_wtlist (orientation target weightlist)
by one.
\par Parameters:
<b>INode *target</b>\n\n
The node that is to be appended to the current orientation target
list.\n\n
<b>float weight=50.0</b>\n\n
This is the weight that is to be assigned to the newly appended
orientation target. The default weight is 50.0.
\return TRUE if the target was appended, otherwise FALSE. */
virtual BOOL AppendTarget(INode *target, float weight=50.0)=0;
/*! \remarks This method allows you to delete a specified target.
\par Parameters:
<b>int selection</b>\n\n
The node number in the orientation target list to delete.
\return TRUE if successful, otherwise FALSE. */
virtual BOOL DeleteTarget(int selection)=0;
};
#define ORIENT_ROT_PBLOCK_REF 0
//-------------------------------------------------------------
// // Access to LookAt Constraint controller's parameters.
// Ambarish Goswami implemented May, 2000
//Function Publishing interface Added by Ambarish Goswami 5/24/2000 adapted from Adam Felt (5-16-00)
//**************************************************************************************************
class ILookAtConstRotation;
#define LOOKAT_CONSTRAINT_INTERFACE Interface_ID(0x5dbe7ad8, 0x1d1b488b)
#define GetILookAtConstInterface(cd) \
(ILookAtConstRotation*)(cd)->GetInterface(LOOKAT_CONSTRAINT_INTERFACE)
//***********************************************************
/*! \sa Class Control, Class FPMixinInterface.\n\n
\par Description:
This class is available in release 4.0 and later only.\n\n
This class is an interface to the LookAt Constraint rotation controller. You
can obtain a pointer to the list control interface using;
<b>GetILookAtConstInterface(cd)</b>. This macro will return
<b>(ILookAtConstRotation*)(CD)-\>GetFPInterface(LOOKAT_CONSTRAINT_INTERFACE).</b>\n\n
<b>LOOKAT_ROT_PBLOCK_REF</b> may be used to access the look-at controller's
references:\n\n
All methods of this class are Implemented by the System. */
class ILookAtConstRotation : public Control , public FPMixinInterface {
public:
enum { get_num_targets, get_node, get_target_weight,
set_target_weight, append_target, delete_target,};
// FUNCTION_PUBLISHING
// Function Map for Function Publish System
//***********************************
BEGIN_FUNCTION_MAP
FN_0(get_num_targets, TYPE_INT, GetNumTargets);
FN_1(get_node, TYPE_INODE, GetNode, TYPE_INDEX);
FN_1(get_target_weight, TYPE_FLOAT, GetTargetWeight, TYPE_INDEX);
FN_2(set_target_weight, TYPE_BOOL, SetTargetWeight, TYPE_INDEX, TYPE_FLOAT);
FN_2(append_target, TYPE_BOOL, AppendTarget, TYPE_INODE, TYPE_FLOAT);
FN_1(delete_target, TYPE_BOOL, DeleteTarget, TYPE_INDEX);
END_FUNCTION_MAP
FPInterfaceDesc* GetDesc(); // <-- must implement
//End of Function Publishing system code
//***********************************
/*! \remarks Returns the number of nodes in the list of nodes to look
at. */
virtual int GetNumTargets()=0;
virtual INode* GetNode(int targetNumber)=0;
/*! \remarks Gets the weight of one of the Look-At nodes that the
Look-At constraint controller targets, specified by
<b>targetNumber</b>.
\par Parameters:
<b>int targetNumber</b>\n\n
The node number in the Look-At target list whose weight is to be
obtained. */
virtual float GetTargetWeight(int targetNumber)=0;
/*! \remarks Sets the weight of one of the Look-At nodes that the Look-At
constraint controller follows, specified by <b>targetNumber</b>.
\par Parameters:
<b>targetNumber</b>\n\n
The node number in the Look-At target list whose weight is to be set.
<b>float weight</b>\n\n
The weight to set.\n\n
\return TRUE if there is more than one Look-At targets in the list and you are
trying to set weight, FALSE otherwise. */
virtual BOOL SetTargetWeight(int targetNumber, float weight)=0;
/*! \remarks Appends the current Look-At target list by one and
appends the current Look-At target weightlist by one.
\par Parameters:
<b>INode *target</b>\n\n
The node that is to be appended to the current Look-At target list.\n\n
<b>float weight=50.0</b>\n\n
This is the weight that is to be assigned to the newly appended Look-At
target. The default weight is 50.0.
\return TRUE if the target was appended, otherwise FALSE. */
virtual BOOL AppendTarget(INode *target, float weight=50.0)=0;
/*! \remarks This method allows you to delete a specified target.
\par Parameters:
<b>int selection</b>\n\n
The zero based node number in the list of nodes the controller looks at. */
virtual BOOL DeleteTarget(int selection)=0;
/*! \remarks Gets the relative/absolute mode corresponding to the
"Keep Initial Offset" checkbox in the UI. */
virtual BOOL GetRelative()=0;
/*! \remarks Gets the ViewLine relative/absolute mode corresponding to
the "Keep ViewLine Length Absolute" checkbox in the UI. When Viewline
Length is absolute, the "ViewLine Length" spinner sets the length of
the ViewLine. A negative length implies that starting from the source
object the line travels opposite to the direction of the target object.
The source/target distance has no effect on the ViewLine length in this
mode. If the "Keep ViewLine Length Absolute" checkbox is unchecked, the
ViewLine length is determined from the spinner value, which is
interpreted as a percentage of the source/target distance.
\return TRUE if the ViewLine length is absolute, FALSE otherwise. */
virtual BOOL GetVLisAbs()=0;
/*! \remarks Returns TRUE if the "World" checkbox is on; FALSE if off.
*/
virtual BOOL GetUpnodeWorld()=0;
/*! \remarks Returns TRUE if the "selected" axis flip checkbox is on;
FALSE if off. */
virtual BOOL GetStoUPAxisFlip()=0;
/*! \remarks Returns TRUE if the "source" axis flip checkbox is on;
FALSE if off. */
virtual BOOL GetTargetAxisFlip()=0;
/*! \remarks Returns TRUE if the orientation flag is set, FALSE if
off. */
virtual BOOL Get_SetOrientation()=0;
/*! \remarks Gets the selection corresponding to the "Select LookAt
Axis" button in the UI. Obtains which of the source axes is required to
coincide with the target axis.
\return (0) if the target axis coincides with the x axis of the source
object. (1) if the target axis coincides with the y axis of the source
object. (2) if the target axis coincides with the z axis of the source
object. */
virtual int GetTargetAxis()=0;
/*! \remarks Gets the selection corresponding to the "Source/Upnode
Alignment: Aligned to UpNode Axis:" radiobutton in the UI. Obtains
which of the upnode axes is required to align with a specified source
axis.
\return (0) if the upnode x axis coincides with a specified source
object. (1) if the upnode y axis coincides with a specified source
object. (2) if the upnode z axis coincides with a specified source
object. */
virtual int GetUpNodeAxis()=0;
/*! \remarks Gets the selection corresponding to the "Source/Upnode
Alignment: Aligned to UpNode Axis:" radiobutton in the UI. Obtains
which of the source axes is required to align with a specified upnode
axis.
\return (0) if the source x axis coincides with a specified upnode
axis. (1) if the source y axis coincides with a specified upnode axis.
(2) if the source z axis coincides with a specified upnode axis. */
virtual int Get_StoUPAxis()=0;
virtual int Get_upnode_control()=0;
/*! \remarks This method allows you to set the "relative" flag.
\par Parameters:
<b>BOOL rel</b>\n\n
TRUE to set the relative flag, otherwise FALSE. */
virtual void SetRelative(BOOL rel)=0;
/*! \remarks Sets the relative/absolute mode corresponding to the
"Keep ViewLine Length Absolute" checkbox in the UI.
\par Parameters:
<b>BOOL rel</b>\n\n
TRUE if "Keep ViewLine Length Absolute" is active (checked), FALSE
otherwise. */
virtual void SetVLisAbs(BOOL rel)=0;
/*! \remarks This method allows you to set the "World" flag.
\par Parameters:
<b>BOOL uw</b>\n\n
TRUE to set the world flag, otherwise false. */
virtual void SetUpnodeWorld(BOOL uw)=0;
/*! \remarks This method allows you to set the "source" flip axis
flag.
\par Parameters:
<b>BOOL rel</b>\n\n
TRUE to set the source flip axis flag, otherwise FALSE. */
virtual void SetTargetAxisFlip(BOOL rel)=0;
/*! \remarks This method allows you to set the "selected" axis flip
flag.
\par Parameters:
<b>BOOL rel</b>\n\n
TRUE to set the selected axis flip flag, otherwise FALSE. */
virtual void SetStoUPAxisFlip(BOOL rel)=0;
/*! \remarks This method allows you to set the orientation flag.
\par Parameters:
<b>BOOL rel</b>\n\n
TRUE to set the orientation flag, otherwise FALSE. */
virtual void Set_SetOrientation(BOOL rel)=0;
/*! \remarks Resets to zero the amount of orientation offset, effected
through the "Set Orientation" feature. */
virtual void Set_Reset_Orientation()=0;
/*! \remarks Sets the selection corresponding to the "Set Orientation"
button in the UI. Specifies which of the source axes is required to
coincide with the target axis.
\par Parameters:
<b>int axis</b>\n\n
(0) if TargetAxis coincides with the X axis of the source object. (1)
if TargetAxis coincides with the Y axis of the source object. (2) if
TargetAxis coincides with the Z axis of the source object */
virtual void SetTargetAxis(int axis)=0;
/*! \remarks Sets the selection corresponding to the "Source/Upnode
Alignment: Aligned to UpNode Axis:" radiobutton in the UI. Specifies
which of the upnode axes is required to align with a specified source
axis.
\par Parameters:
<b>int axis</b>\n\n
(0) if the upnode X axis coincides with a specified source axis. (1) if
the upnode Y axis coincides with a specified source axis. (2) if the
upnode Z axis coincides with a specified source axis. */
virtual void SetUpNodeAxis(int axis)=0;
/*! \remarks Sets the selection corresponding to the "Source/Upnode
Alignment: Aligned to UpNode Axis:" radiobutton in the UI. Specifies
which of the source axes is required to align with a specified upnode
axis.
\par Parameters:
<b>int axis</b>\n\n
(0) if the source X axis coincides with a specified upnode axis. (1) if
the source Y axis coincides with a specified upnode axis. (2) if the
source Z axis coincides with a specified upnode axis. */
virtual void Set_StoUPAxis(int axis)=0;
};
#define LOOKAT_ROT_PBLOCK_REF 0
//-------------------------------------------------------------
// Access to noise controller's parameters.
// All noise controllers are derived from this class
//
/*! \sa Class Control.\n\n
\par Description:
This class is available in release 2.0 and later only.\n\n
This class provides access to noise controller's parameters. All noise
controllers are derived from this class.\n\n
All methods of this class are implemented by the system. */
class INoiseControl : public StdControl {
public:
/*! \remarks Sets the seed value for the noise controller.
\par Parameters:
<b>int seed</b>\n\n
The seed value, greater than or equal to zero. */
virtual void SetSeed(int seed)=0;
/*! \remarks Returns the seed value. */
virtual int GetSeed()=0;
/*! \remarks Sets the frequency parameter.
\par Parameters:
<b>float f</b>\n\n
The value to set, greater than zero. */
virtual void SetFrequency(float f)=0;
/*! \remarks Returns the frequency value. */
virtual float GetFrequency()=0;
/*! \remarks Sets the fractal setting on or off.
\par Parameters:
<b>BOOL f</b>\n\n
TRUE for on; FALSE for off. */
virtual void SetFractal(BOOL f)=0;
/*! \remarks Returns the state of the fractal setting. TRUE if on;
FALSE if off. */
virtual BOOL GetFractal()=0;
/*! \remarks Sets the roughness setting.
\par Parameters:
<b>float f</b>\n\n
The value to set, between 0.0 and 1.0. */
virtual void SetRoughness(float f)=0;
/*! \remarks Returns the roughness setting. */
virtual float GetRoughness()=0;
/*! \remarks Sets the ramp in setting.
\par Parameters:
<b>TimeValue in</b>\n\n
The value to set, greater than or equal to zero. */
virtual void SetRampIn(TimeValue in)=0;
/*! \remarks Returns the ramp in setting. */
virtual TimeValue GetRampIn()=0;
/*! \remarks Sets the ramp out setting.
\par Parameters:
<b>TimeValue out</b>\n\n
The value to set, greater than or equal to zero. */
virtual void SetRampOut(TimeValue out)=0;
/*! \remarks Returns the ramp out setting. */
virtual TimeValue GetRampOut()=0;
/*! \remarks Sets the positive only setting (\>0) for the specified
axis to the specified value.
\par Parameters:
<b>int which</b>\n\n
Specifes the axis. One of the following values:\n\n
<b>0</b>: X, <b>1</b>: y, <b>2</b>: Z.\n\n
<b>BOOL onOff</b>\n\n
TRUE for on; FALSE for off. */
virtual void SetPositiveOnly(int which,BOOL onOff)=0;
/*! \remarks Returns the positive only setting (\>0) for the specified
axis to the specified value.
\par Parameters:
<b>int which</b>\n\n
Specifes the axis. One of the following values:\n\n
<b>0</b>: X, <b>1</b>: y, <b>2</b>: Z. */
virtual BOOL GetPositiveOnly(int which)=0;
/*! \remarks Returns a pointer to the controller for the strength
parameter. */
virtual Control *GetStrengthController()=0;
/*! \remarks Sets the controller used for the strength parameter.
\par Parameters:
<b>Control *c</b>\n\n
Points to the controller to set. */
virtual void SetStrengthController(Control *c)=0;
};
//-------------------------------------------------------------
// Access to SurfPosition controller
//
/*! \sa Class Control, Class INode.\n\n
\par Description:
This class is available in release 2.0 and later only.\n\n
This class provides access to the surface position controller's parameters.\n\n
The following values may be used to access the surface controller's
references.\n\n
<b>SURFCONT_U_REF</b>\n\n
<b>SURFCONT_V_REF</b>\n\n
<b>SURFCONT_SURFOBJ_REF</b>\n\n
All methods of this class are implemented by the system. */
class ISurfPosition : public Control {
public:
/*! \remarks Sets the node that this controller uses as the surface
object.
\par Parameters:
<b>INode *node</b>\n\n
Points to the node to set. */
virtual void SetSurface(INode *node)=0;
/*! \remarks Returns the alignment setting.
\return One of the following values:\n\n
<b>0</b>: No Alignment.\n\n
<b>1</b>: Align to U.\n\n
<b>2</b>: Align to V. */
virtual int GetAlign()=0;
/*! \remarks Sets the alignment setting.
\par Parameters:
<b>int a</b>\n\n
One of the following values:\n\n
<b>0</b>: No Alignment.\n\n
<b>1</b>: Align to U.\n\n
<b>2</b>: Align to V. */
virtual void SetAlign(int a)=0;
/*! \remarks Returns the flip setting. TRUE if on; FALSE if off. */
virtual BOOL GetFlip()=0;
/*! \remarks Sets the flip setting.
\par Parameters:
<b>BOOL f</b>\n\n
TRUE for on; FALSE for off. */
virtual void SetFlip(BOOL f)=0;
};
// Surface controller references
#define SURFCONT_U_REF 0
#define SURFCONT_V_REF 1
#define SURFCONT_SURFOBJ_REF 2
//-------------------------------------------------------------
// Access to the LinkCtrl
//
class ILinkCtrl;
#define LINK_CONSTRAINT_INTERFACE Interface_ID(0x32f03b37, 0x6700693a)
#define GetLinkConstInterface(cd) \
(LinkConstTransform*)(cd)->GetInterface(LINK_CONSTRAINT_INTERFACE)
#define ADD_WORLD_LINK PROPID_USER + 10
#define LINK_TIME_CONTROL_CLASS_ID Class_ID(0x5d084b4b, 0x1b1d318a)
/*! \sa Class Control.\n\n
\par Description:
This class is available in release 2.0 and later only.\n\n
This class represents the interface to the Link Controller. You can obtain a
pointer to the link controller interface using;
<b>GetLinkConstInterface(cd)</b>. This macro will return\n\n
<b>(LinkConstTransform*)(CD)-\>GetFPInterface(LINK_CONSTRAINT_INTERFACE).</b>\n\n
Developers may use the following values to access the references of the Link
controller.\n\n
<b>LINKCTRL_CONTROL_REF</b>\n\n
The TM controller\n\n
<b>LINKCTRL_FIRSTPARENT_REF</b>\n\n
The index of the first parent node.\n\n
<b>LINKCTRL_PBLOCK_REF</b>\n\n
The parameter block.\n\n
All methods of this class are Implemented by the System. */
class ILinkCtrl : public Control, public FPMixinInterface
{
public:
enum { get_num_targets, get_node, set_node,
get_frame_no, set_frame_no, add_target,
delete_target, add_world, };
// FUNCTION_PUBLISHING
// Function Map for Function Publish System
//***********************************
BEGIN_FUNCTION_MAP
FN_0(get_num_targets, TYPE_INT, GetNumTargets);
FN_1(get_node, TYPE_INODE, GetNode, TYPE_INDEX);
// FN_2(set_node, TYPE_BOOL, SetNode, TYPE_INODE, TYPE_INT);
FN_1(get_frame_no, TYPE_INT, GetFrameNumber, TYPE_INDEX);
FN_2(set_frame_no, TYPE_BOOL, SetFrameNumber, TYPE_INDEX, TYPE_INT);
FN_2(add_target, TYPE_BOOL, AddTarget, TYPE_INODE, TYPE_INT);
FN_1(delete_target, TYPE_BOOL, DeleteTarget, TYPE_INDEX);
FN_1(add_world, TYPE_INT, AddWorld, TYPE_INT);
END_FUNCTION_MAP
FPInterfaceDesc* GetDesc(); // <-- must implement
//End of Function Publishing system code
//***********************************{
// public:
/*! \remarks This method is available in release 4.0 and later
only.\n\n
This method returns the number of parents (links). */
virtual int GetNumTargets()=0;
/*! \remarks Returns the start time associated with the 'i-th' link.
\par Parameters:
<b>int i</b>\n\n
Specifies which parent (link). */
virtual TimeValue GetLinkTime(int i)=0;
/*! \remarks Sets the start time associated with the 'i-th' link. See
<b>LinkTimeChanged()</b> below. Note: This method also sorts the
indices according to increasing time values.
\par Parameters:
<b>int i</b>\n\n
Specifies which parent (link).\n\n
<b>TimeValue t</b>\n\n
The time to set. */
virtual void SetLinkTime(int i,TimeValue t)=0;
/*! \remarks This method should be called after changing link times.
Note: This method also sorts the indices according to increasing time
values. */
virtual void LinkTimeChanged()=0; // call after changing Link times
/*! \remarks Adds a new link at the specified time.
\par Parameters:
<b>INode *node</b>\n\n
Points to the node of the link to add.\n\n
<b>TimeValue t</b>\n\n
The time to change to this link. */
virtual void AddNewLink(INode *node,TimeValue t)=0;
/*! \remarks This method will delete the specified link.
\par Parameters:
<b>int frameNo</b>\n\n
Specifies which link to delete. */
virtual BOOL DeleteTarget(int frameNo)=0;
/*! \remarks This method returns the start frame of the specified
target.
\par Parameters:
<b>int targetNumber</b>\n\n
The target number for which to get the start frame. */
virtual int GetFrameNumber(int targetNumber)=0;
/*! \remarks This method is available in release 4.0 and later
only.\n\n
This method allows you to set the start frame of the specified target.
\par Parameters:
<b>int targetNumber</b>\n\n
The target number for which to set the start frame.\n\n
<b>int frameNumber</b>\n\n
The time value.
\return TRUE if the start frame is set, otherwise FALSE. */
virtual BOOL SetFrameNumber(int targetNumber, int frameNumber)=0;
// virtual BOOL SetNode(INode *target, int targetNumber)=0;
/*! \remarks This method is available in release 4.0 and later
only.\n\n
This method allows you to append a target.
\par Parameters:
<b>INode *target</b>\n\n
The target node to append.\n\n
<b>int frameNo</b>\n\n
The frame time.
\return TRUE if the target was appended, otherwise FALSE. */
virtual BOOL AddTarget(INode *target, int frameNo)=0;
// BOOL AddWorld(int frameNo)=0;
/*! \remarks This method is available in release 4.0 and later
only.\n\n
This method returns one of the link nodes that the link constraint
controller targets, specified by <b>targetNumber</b>.
\par Parameters:
<b>int targetNumber</b>\n\n
The node number in the link target list to be obtained. */
virtual INode* GetNode(int targetNumber)=0;
private:
virtual int AddWorld(int frameNo)
{
if (frameNo==-99999) frameNo = GetCOREInterface()->GetTime()/GetTicksPerFrame();
return SetProperty(ADD_WORLD_LINK, &frameNo);
}
};
// LinkCtrl references
#define LINKCTRL_CONTROL_REF 0 // the TM controller
#define LINKCTRL_FIRSTPARENT_REF 1 // parent nodes... refs 1-n
#define LINKCTRL_PBLOCK_REF 2 // added for Paramblock implementation
#define LINKCTRL_LTCTL_REF 3
#define LINKCTRL_CORE_REFs 4 //Total "core" refs for LINKCTRL, nodes references start at this index
//-------------------------------------------------------------
// Access to the OLD LookatControl
//
/*! \sa Class Control.\n\n
\par Description:
This class is available in release 2.0 and later only.\n\n
This class provides access to the LookAt Controller parameters.\n\n
Developers may use the following values to access the references of the Look At
controller.\n\n
<b>LOOKAT_TARGET_REF</b>\n\n
<b>LOOKAT_POS_REF</b>\n\n
<b>LOOKAT_ROLL_REF</b>\n\n
<b>LOOKAT_SCL_REF</b>\n\n
All methods of this class are implemented by the system. */
class ILookatControl : public Control {
public:
/*! \remarks Sets the flip setting.
\par Parameters:
<b>BOOL f</b>\n\n
TRUE for on; FALSE for off. */
virtual void SetFlip(BOOL f)=0;
/*! \remarks Returns the state of the flip setting. TRUE if on; FALSE
if off. */
virtual BOOL GetFlip()=0;
/*! \remarks Sets the axis setting.
\par Parameters:
<b>int a</b>\n\n
One of the following values:\n\n
<b>0</b>: X axis.\n\n
<b>1</b>: Y axis.\n\n
<b>2</b>: Z axis. */
virtual void SetAxis(int a)=0;
/*! \remarks Returns the axis setting.
\return One of the following values:\n\n
<b>0</b>: X axis.\n\n
<b>1</b>: Y axis.\n\n
<b>2</b>: Z axis. */
virtual int GetAxis()=0;
};
// References for the lookat controller
#define LOOKAT_TARGET_REF 0
#define LOOKAT_POS_REF 1
#define LOOKAT_ROLL_REF 2
#define LOOKAT_SCL_REF 3
//-------------------------------------------------------------
//Access to the New Boolean Controller AG 11/08/01
//
class IBoolCntrl;
#define BOOL_CONTROL_INTERFACE Interface_ID(0x5d511b6, 0x52a302db)
#define GetIBoolCntrlInterface(cd) \
(IBoolCntrl*)(cd)->GetInterface(BOOL_CONTROL_INTERFACE)
/*! \sa Class Animatable, Class StdControl, Class IKeyControl\n\n
\par Description:
<b>This class is only available in release 5 or later.</b>\n\n
Certain problems plague the current ON/OFF controller that produces
counter-intuitive results and makes it difficult to use it in an animation
system. The objective of this feature is to overcome these problems, either by
fixing the existing controller or by creating a new controller. In the
beginning we'll focus on the first option.\n\n
We have decided to keep the current ON/OFF controller as it is because of its
utility to certain users and develop a new Boolean controller.\n\n
This is a controller similar to On/Off. However, its animation behavior is
quite different in that, unlike On/Off, it is NOT a flip flop control. Each key
in On/Off merely creates a state change. Its output is -1 or 1.\n\n
The Boolean controller is a True/False control. Its output is the value of the
last key which can only be either 0 or 1, thus any number of similar keys may
be in sequence; the controller is merely evaluated at the current time and its
value is output. This is not possible with the On/Off controller where each key
must necessarily be a change of state from either -1 to 1 <b>OR</b> 1 to
-1.\n\n
The Boolean Controller will be useful for any situation where something must be
turned on and off and the user wishes to work in a non-linear fashion i.e.
jumping backwards and forwards at will in the time line. For example, such
binary functions as object smoothing, object visibility scale multipliers,
light on/off state, etc.\n\n
The most pressing need for the Boolean is in the IK enabled state. Currently,
the enable state is controlled by the On/Off controller. The On/Off behavior is
in direct conflict with the idea of non-linear IK/FK blend animation. For
multiple reasons that are too difficult and involved to go into here the flip
flop behavior of On/Off becomes cumbersome at best. Furthermore, in R4 the
behavior of On/Off was modified to mitigate this problem: if the Animate button
is active and the IK Enable button is pressed, the enable track is examined, if
any enable keys exist in the track later in time they are "rippled" back to the
current time in order to preserve the overall animated state of IK Enable. With
the Animate button off On/Off behaves as it did in R3: the new key is
introduced and all existing animation in the Enable track is inverted. It is
only when an even number of keys is added to the track that existing animation
is preserved.\n\n
The code for this controller is in: <b>maxsdk/samples/controllers/boolcntrl</b>
*/
class IBoolCntrl: public StdControl, public IKeyControl {
};
// References for the boolean controller controller
#define BOOL_PBLOCK_REF 0
//-------------------------------------------------------------
// [dl | 22mar2002]
// Interface for exposing the new parameter "Use Target as Up Node" of the
// LookAtControl
#define ILOOKATCONTROL_EXTENSION Interface_ID(0x40ce4981, 0x3ea31c3b)
class ILookatControl_Extension : public FPMixinInterface {
public:
virtual void SetTargetIsUpNode(bool val) = 0;
virtual bool GetTargetIsUpNode() const = 0;
// -- From BaseInterface
virtual Interface_ID GetID() { return ILOOKATCONTROL_EXTENSION; }
};
//-------------------------------------------------------------
//Access to the List Controller
//
#define FLOATLIST_CONTROL_CLASS_ID 0x4b4b1000
#define POINT3LIST_CONTROL_CLASS_ID 0x4b4b1001
#define POSLIST_CONTROL_CLASS_ID 0x4b4b1002
#define ROTLIST_CONTROL_CLASS_ID 0x4b4b1003
#define SCALELIST_CONTROL_CLASS_ID 0x4b4b1004
#define DUMMY_CONTROL_CLASS_ID 0xeeefffff
#define MASTERLIST_CONTROL_CLASS_ID 0x4b4b1015
#define POINT4LIST_CONTROL_CLASS_ID 0x4b4b1005
class IListControl;
#define LIST_CONTROLLER_INTERFACE Interface_ID(0x444e7687, 0x722e6e36)
#define GetIListControlInterface(cd) \
(IListControl*)(cd)->GetInterface(LIST_CONTROLLER_INTERFACE)
//! \brief IListControl provides API access to list control functionality.
/*! The interface is returned by calling GetIListControlInterface.
*/
/*! \sa Class Control, Class FPMixinInterface\n\n
\par Description:
This class is available in release 4.0 and later only.\n\n
This class represents the interface to the list controller. You can obtain a
pointer to the list control interface using;
<b>GetIListControlInterface(cd)</b>. This macro will return
<b>(IListControl*)(CD)-\>GetFPInterface(LIST_CONTROLLER_INTERFACE).</b>\n\n
The Class ID's of individual controllers are; <b>FLOATLIST_CONTROL_CLASS_ID,
POINT3LIST_CONTROL_CLASS_ID, POSLIST_CONTROL_CLASS_ID,
ROTLIST_CONTROL_CLASS_ID, SCALELIST_CONTROL_CLASS_ID, DUMMY_CONTROL_CLASS_ID,
MASTERLIST_CONTROL_CLASS_ID.</b>\n\n
All methods of this class are Implemented by the System. */
class IListControl : public Control, public FPMixinInterface {
public:
enum{ list_getNumItems, list_setActive, list_getActive, list_cutItem, list_pasteItem,
list_deleteItem, list_count, list_setActive_prop, list_getActive_prop,
list_getName, list_setName,
list_getSubCtrl, list_getSubCtrlWeight};
// FUNCTION_PUBLISHING
// Function Map for Function Publish System
//***********************************
#pragma warning(push)
#pragma warning(disable:4238)
BEGIN_FUNCTION_MAP
FN_0 (list_getNumItems, TYPE_INT, GetListCount );
VFN_1 (list_setActive, SetActive, TYPE_INDEX );
FN_0 (list_getActive, TYPE_INDEX, GetActive );
VFN_1 (list_deleteItem, DeleteItem, TYPE_INDEX );
VFN_1 (list_cutItem, CutItem, TYPE_INDEX );
VFN_1 (list_pasteItem, PasteItem, TYPE_INDEX );
FN_1 (list_getName, TYPE_TSTR_BV, GetName, TYPE_INDEX );
VFN_2 (list_setName, SetName, TYPE_INDEX, TYPE_STRING );
RO_PROP_FN (list_count, GetListCount, TYPE_INT );
PROP_FNS (list_getActive_prop, GetActive, list_setActive_prop, SetActive, TYPE_INDEX );
FN_1 (list_getSubCtrl, TYPE_CONTROL, GetSubCtrl, TYPE_INDEX );
FNT_1 (list_getSubCtrlWeight, TYPE_FLOAT, GetSubCtrlWeight, TYPE_INDEX );
END_FUNCTION_MAP
#pragma warning(pop)
FPInterfaceDesc* GetDesc(); // <-- must implement
//End of Function Publishing system code
//***********************************
/*! \remarks This method returns the number of items that appear in
the List controllers list box. */
virtual int GetListCount()=0;
/*! \remarks This method allows you to sets the indexed item in the
list active so its parameters appear in the motion panel, and any input
is directed to the indexed sub controller.
\par Parameters:
<b>int index</b>\n\n
The index of the item to set as the active item. */
virtual void SetActive(int index)=0;
/*! \remarks This method returns the index of the currently active
item. */
virtual int GetActive()=0;
/*! \remarks This method allows you to delete the indexed sub
controller from the list.
\par Parameters:
<b>int index</b>\n\n
The index of the item to delete from the list. */
virtual void DeleteItem(int index)=0;
/*! \remarks This method allows you to cutsthe index sub controller
from the list and stores it in the buffer to paste later.
\par Parameters:
<b>int index</b>\n\n
The index of the item you wish to cut. */
virtual void CutItem(int index)=0;
/*! \remarks This method allows you to paste the sub-controller from
the buffer into the indexed slot in the\n\n
list.
\par Parameters:
<b>int index</b>\n\n
The index of the slot to paste into. */
virtual void PasteItem(int index)=0;
/*! \remarks This method allows you to set the name of an indexed
item.
\par Parameters:
<b>int index</b>\n\n
The index of the item.\n\n
<b>MSTR name</b>\n\n
The name to set it to. */
virtual void SetName(int index, MSTR name)=0;
/*! \remarks This method returns the class name of the indexed
sub-controller if a user defined name doesn't exist.
\par Parameters:
<b>int index</b>\n\n
The index of the item for which to get the name. */
virtual MSTR GetName(int index)=0;
//! Get a subcontroller from its index.
//! \return - a pointer to a Control, or NULL if the index is invalid.
//! \param[in] in_index - index of the list controller subcontroller
virtual Control* GetSubCtrl(int in_index) const =0;
//! Get the weight of a subcontroller at a given time.
//! \return - the weight of the subcontroller (non-percent, typically 0.0f to 1.0f), or -1.0f if the index is invalid.
//! \param[in] in_time - time of the weight evaluation (in case of an animated weight)
//! \param[in] in_index - index of the list controller subcontroller
virtual float GetSubCtrlWeight(int in_index, TimeValue in_time) const=0;
};
//-------------------------------------------------------------
// Access to Spline IK Control modifier
//
class ISplineIKControl;
#define SPLINEIK_CONTROL_INTERFACE Interface_ID(0x7c93607a, 0x47d54f80)
#define GetISplineIKControlInterface(cd) \
(ISplineIKControl*)(cd)->GetInterface(SPLINEIK_CONTROL_INTERFACE)
/*! <b>This class is only available in release 5 or later.</b>\n\n
This class refers to the new modifier which, when assigned to a spline (or a
NURBS) curve, generates a certain number of helper objects attached to the
knots of the curve.\n\n
Spline IK Control Modifier (works for NURBS Point curve and NURBS CV Curve
too): This is a modifier and can be used independently of the SplineIK. When
applied to a spline, this modifier creates one point helper for each knot of
the spline. The user can then animate the spline by simply animating (position
and rotation) the point helpers. Thus to animate the spline, the user wouldn't
need to get into the sub-object level.\n\n
There are three options Link Types, presented as a set of 3 radio buttons:\n\n
<b>Link All in Hierarchy (default):</b>\n\n
Makes a helper a child to its immediately previous helper. So, Helper#2 is
child to Helper#1, Helper#3 is child to Helper#2, and so on. Helper#1 is still
child to the world. Translation and rotation of a helper then "solidly"
moves/rotates part of the spline _subsequent_ to the selected helper. The part
of the spline previous to the helper is unaffected.\n\n
<b>Link All to Root</b>\n\n
Makes all helpers children to Helper#1, i.e., knot#1. Helper#1 can be position
constrained or linked to another object, like it is possible above.
Additionally individual helpers can be moved and rotated without any other
helper being affect.\n\n
<b>No Linking</b>\n\n
All helpers are independent -- not linked to any other helper -- so that they
can be moved and rotated without any other helper being affect. \n\n
<b>"Create Helpers" button:</b>\n\n
Helpers are not automatically added to the spline on the assignment of the
modifier. To do that the user need to press the "Create Helpers" button.\n\n
Helper Display:\n\n
These are the all the options: <ul> <li> center marker (default OFF) </li> <li>
axis tripod (default OFF) </li> <li> cross (default OFF) </li> <li> box
(default ON) </li> <li> size (default 20.0) </li> <li> constant screen size
(default OFF) </li> <li> draw on top (default ON) for a standard point object.
</li> </ul> If the user adds ("insert") a knot to the spline, a new helper
object is automatically created at that knotpoint.\n\n
Furthermore, please refer to the implementation project which is in
<b>/maxsdk/samples/modifiers/splineikcontrol</b>.\n\n
The following helper methods have been added to <b>istdplug.h</b> for general
access: */
class ISplineIKControl: public Modifier, public FPMixinInterface {
public:
enum { SplineIKControl_params };
enum {
sm_point_node_list, sm_helpersize, sm_helper_centermarker, sm_helper_axistripod,
sm_helper_cross, sm_helper_box, sm_helper_screensize, sm_helper_drawontop,
sm_link_types,
};
enum{ getHelperCount, getKnotCount, link_allToRoot, link_allinHierarchy, link_none, create_hlpr};
// FUNCTION_PUBLISHING
// Function Map for Function Publish System
//***********************************
BEGIN_FUNCTION_MAP
FN_0 (getHelperCount, TYPE_INT, GetHelperCount );
FN_0 (getKnotCount, TYPE_INT, GetKnotCount );
FN_0 (link_allToRoot, TYPE_BOOL, LinkToRoot );
FN_0 (link_allinHierarchy, TYPE_BOOL, LinkInHierarchy );
FN_0 (link_none, TYPE_BOOL, UnLink );
FN_1 (create_hlpr, TYPE_BOOL, CreateHelpers, TYPE_INT);
END_FUNCTION_MAP
FPInterfaceDesc* GetDesc(); // <-- must implement
//End of Function Publishing system code
//***********************************
/*! \remarks Obtain the number of helpers created\n\n
*/
virtual int GetHelperCount()=0;
/*! \remarks Gets the total number of knots for spline.\n\n
*/
virtual int GetKnotCount()=0;
/*! \remarks Makes all helpers children to Helper#1, i.e., knot#1.
Helper#1 can be position constrained or linked to another object, like
it is possible above. Additionally individual helpers can be moved and
rotated without any other helper being affected.\n\n
*/
virtual BOOL LinkToRoot() = 0;
/*! \remarks Makes a helper a child to its immediately previous
helper. So, Helper#2 is child to Helper#1, Helper#3 is child to
Helper#2, and so on. Helper#1 is still child to the world. Translation
and rotation of a helper then "solidly" moves/rotates part of the
spline _subsequent_ to the selected helper. The part of the spline
previous to the helper is unaffected.\n\n
*/
virtual BOOL LinkInHierarchy() = 0;
/*! \remarks All helpers are independent - not linked to any other
helper so that they can be moved and rotated without any other helper
being affected.\n\n
*/
virtual BOOL UnLink() = 0;
/*! \remarks Helpers are not automatically added to the spline on the
assignment of the modifier. To do that the user need to press the
"<b>Create Helpers</b>" button. */
virtual BOOL CreateHelpers(int knotCt) = 0;
};
// References for the splineIK controller
#define SPLINEIKCONTROL_PBLOCK_REF 0
// The following two enums are transfered from helpers\pthelp.cpp by AG: 01/20/2002
// in order to access the parameters for use in Spline IK Control modifier
// and the Spline IK Solver
// block IDs
enum { pointobj_params, };
// pointobj_params IDs
enum {
pointobj_size, pointobj_centermarker, pointobj_axistripod,
pointobj_cross, pointobj_box, pointobj_screensize, pointobj_drawontop };
// The following two enums are transfered from modifiers\nspline.cpp by AG: 01/20/2002
// in order to access the parameters for use in Spline IK Solver
// block IDs
enum { nspline_params};
// nspline_params ID
enum { nspline_length};
//! Access to the new ISplineIKControl2 interface. This interface exposes the helper nodes
//! that drive the spline ik modifier.
class ISplineIKControl2;
#define SPLINEIK_CONTROL_INTERFACE2 Interface_ID(0x72428cc, 0x2a4a1b5f)
#define GetISplineIKControlInterface2(cd) \
(ISplineIKControl2*)(cd)->GetInterface(SPLINEIK_CONTROL_INTERFACE2)
class ISplineIKControl2 : public BaseInterface
{
public:
//!Get's the helper nodes that define the spline.
//! param [out] helperNodes. The node of the spline helpers.
virtual void GetHelperNodes(INodeTab & helperNodes)=0;
};
//-------------------------------------------------------------
// Access to FFD modifiers
//
// Can either be casted to IFFDMod<Modifier> or IFFDMod<WSMObject> based on the ClassID
/*! \sa Class Control, Class Point3, Class IPoint3, Class Modifier.\n\n\
\par Description:
This class is available in release 3.0 and later only.\n\n
This class is an interface into both FFD OS modifiers and also into helper
objects for FFD spacewarps.\n\n
Given a pointer to ReferenceTarget <b>ref</b>, you can use it as follows:
\code
Class_ID id = ref->ClassID();
if (id==FFDNMOSSQUARE_CLASS_ID || id==FFDNMOSCYL_CLASS_ID ||
id==FFD44_CLASS_ID || id==FFD33_CLASS_ID || id==FFD22_CLASS_ID)
IFFDMod<Modifier>* ffd = (IFFDMod<Modifier>*)ref;
// call various methods
}
else if(id==FFDNMWSSQUARE_CLASS_ID || id = FFDNMWSCYL_CLASS_ID)
IFFDMod<WSMObject>* ffd = (IFFDMod<WSMObject>*)ref;
// call various methods
}
\endcode */
template <class T> class IFFDMod : public T {
public:
/*! \remarks Returns the number of lattice control points. */
virtual int NumPts()=0; // number of lattice control points
/*! \remarks Returns the number of Control Ponits having controllers.
*/
virtual int NumPtConts()=0; // number of CP's having controllers
/*! \remarks Returns a pointer to the 'i-th' Control Point controller.
\par Parameters:
<b>int i</b>\n\n
The zero based index of the Control Point. */
virtual Control* GetPtCont(int i)=0; // get i'th CP controller
/*! \remarks Sets the controller used by the specified Control Point.
\par Parameters:
<b>int i</b>\n\n
The zero based index of the Control Point.\n\n
<b>Control *c</b>\n\n
Points to the controller to set. */
virtual void SetPtCont(int i,Control *c)=0; // set i'th CP controller
/*! \remarks Returns the 'i-th' Control Point.
\par Parameters:
<b>int i</b>\n\n
The zero based index of the Control Point. */
virtual Point3 GetPt(int i)=0; // get i'th CP
/*! \remarks Sets the 'i-th' control point.
\par Parameters:
<b>int i</b>\n\n
The zero based index of the Control Point.\n\n
<b>Point3 p</b>\n\n
The point to set. */
virtual void SetPt(int i, Point3 p)=0; // set i'th CP
/*! \remarks Sets the lattice dimension.
\par Parameters:
<b>IPoint3 d</b>\n\n
The dimensions to set.
\par Default Implementation:
<b>{ }</b> */
virtual void SetGridDim(IPoint3 d) { } // set the lattice dimensions
/*! \remarks Returns the lattice dimensions.
\par Default Implementation:
<b>{ return IPoint3(0,0,0); }</b> */
virtual IPoint3 GetGridDim() { return IPoint3(0,0,0); } // get the lattice dimensions
/*! \remarks This method assigns controllers to all the Control
Points.
\par Default Implementation:
<b>{ }</b> */
virtual void AnimateAll() { } // assign controllers to all CP's
/*! \remarks Calling this method is the equivalent of pressing the
Conform button in the FFD UI. Note: This method is not valid for
WSMObject's.
\par Default Implementation:
<b>{ }</b> */
virtual void Conform() { } // not valid for WSMObject's
/*! \remarks Selects or de-selects the specified Control Point.
\par Parameters:
<b>int i</b>\n\n
The zero based index of the Control Point.\n\n
<b>BOOL sel</b>\n\n
TRUE to select; FALSE to de-selelct.\n\n
<b>BOOL clearAll=FALSE</b>\n\n
TRUE to clear all the currently selected Control Points before setting
the specified one; FALSE to leave the selected points alone.
\par Default Implementation:
<b>{ }</b> */
virtual void SelectPt(int i, BOOL sel, BOOL clearAll=FALSE) { }
virtual void PlugControllers(TimeValue t,BOOL all)=0;
};
//-------------------------------------------------------------
// Access to mesh selections in editable mesh and edit mesh mod
//
#include "namesel.h"
// Selection levels:
#define IMESHSEL_OBJECT 0
#define IMESHSEL_VERTEX 1
#define IMESHSEL_FACE 2
#define IMESHSEL_EDGE 3
/*! \sa Class Mesh, Class LocalModData, Class IMeshSelectData.\n\n
\par Description:
This class is available in release 2.0 and later only.\n\n
This class provides access to selection data for the Mesh Select Modifier,
Editable Mesh and Edit Mesh modifier.\n\n
To get a pointer to this interface given a pointer to a modifier or editable
mesh object, use the following macro (defined in AnimatableInterfaceIDs.h ). Using this
macro, given any Animatable, it is easy to ask for the interface.\n\n
<b>#define GetMeshSelectInterface(anim)
((IMeshSelect*)anim-\>GetInterface(I_MESHSELECT))</b>\n\n
A plug-in developer may use this macro as follows:\n\n
<b>IMeshSelect *ims = GetMeshSelectInterface(anim);</b>\n\n
This return value will either be NULL or a pointer to a valid Mesh Select
interface. */
class IMeshSelect: public MaxHeapOperators {
public:
/*! \remarks Returns the current level of selection for the modifier.
\return One of the following values:\n\n
<b>IMESHSEL_OBJECT</b>: Object level.\n\n
<b>IMESHSEL_VERTEX</b>: Vertex level.\n\n
<b>IMESHSEL_FACE</b>: Face level.\n\n
<b>IMESHSEL_EDGE</b>: Edge level. */
virtual DWORD GetSelLevel()=0;
/*! \remarks Sets the selection level of the modifier.
\par Parameters:
<b>DWORD level</b>\n\n
One of the following values:\n\n
<b>IMESHSEL_OBJECT</b>: Object level.\n\n
<b>IMESHSEL_VERTEX</b>: Vertex level.\n\n
<b>IMESHSEL_FACE</b>: Face level.\n\n
<b>IMESHSEL_EDGE</b>: Edge level. */
virtual void SetSelLevel(DWORD level)=0;
/*! \remarks This method must be called when the <b>LocalModData</b> of
the modifier is changed. Developers can use the methods of
<b>IMeshSelectData</b> to get and set the actual selection for vertex, face
and edge. When a developers does set any of these selection sets this
method must be called when done. */
virtual void LocalDataChanged()=0;
/*! \remarks Returns TRUE if this modifier or object has weighted vertex selection data
(Soft Selection data), FALSE if not.
\par Default Implementation:
<b>{ return FALSE; }</b> */
virtual BOOL HasWeightedVertSel () { return FALSE; }
/*! \remarks Returns TRUE if this modifier or object can assign weighted vertex
selection data; FALSE if it cannot.
\par Default Implementation:
<b>{ return FALSE; }</b> */
virtual BOOL CanAssignWeightedVertSel () { return FALSE; }
};
/*! \sa Class ModContext, Class BitArray, Class IMeshSelect, Class Interface, Class GenericNamedSelSetList.\n\n
\par Description:
This class is available in release 2.0 and later only.\n\n
When a developer gets the <b>LocalModData</b> from the <b>ModContext</b> of the
Mesh Select Modifier or Edit Mesh Modifier, they may cast it to this class and
use these methods. They may be used to get/set the vert/face/edge selection
state of the modifier. This class also provides access to the named sub-object
selection sets.\n\n
To get a pointer to this interface given a pointer to a modifier use the
following macro (defined in AnimatableInterfaceIDs.h ). Using this macro, given any
Animatable, it is easy to ask for the interface.\n\n
<b>#define GetMeshSelectDataInterface(anim)
((IMeshSelectData*)anim-\>GetInterface(I_MESHSELECTDATA))</b>\n\n
A plug-in developer may use this macro as follows:\n\n
<b>IMeshSelectData *imsd = GetMeshSelectDataInterface(anim);</b>\n\n
This return value will either be NULL or a pointer to a valid Mesh Select Data
interface. */
class IMeshSelectData: public MaxHeapOperators {
public:
/*! \remarks Returns a <b>BitArray</b> that reflects the current vertex
selection. There is one bit for each vertex. Bits that are 1 indicate the
vertex is selected. */
virtual BitArray GetVertSel()=0;
/*! \remarks Returns a <b>BitArray</b> that reflects the current face
selection. There is one bit for each face. Bits that are 1 indicate the
face is selected. */
virtual BitArray GetFaceSel()=0;
/*! \remarks Returns a <b>BitArray</b> that reflects the current edge
selection. There is one bit for each edge. Bits that are 1 indicate the
edge is selected. */
virtual BitArray GetEdgeSel()=0;
/*! \remarks Sets the vertex selection of the modifier.
\par Parameters:
<b>BitArray \&set</b>\n\n
There is one bit for each vertex. Bits that are 1 indicate the vertex is
selected.\n\n
<b>IMeshSelect *imod</b>\n\n
This parameter is available in release 3.0 and later only.\n\n
Points to the IMeshSelect instance (generally this is a modifier).\n\n
<b>TimeValue t</b>\n\n
This parameter is available in release 3.0 and later only.\n\n
The current time at which the call is made. */
virtual void SetVertSel(BitArray &set, IMeshSelect *imod, TimeValue t)=0;
/*! \remarks Sets the face selection of the modifier.
\par Parameters:
<b>BitArray \&set</b>\n\n
There is one bit for each face. Bits that are 1 indicate the face is
selected.\n\n
<b>IMeshSelect *imod</b>\n\n
This parameter is available in release 3.0 and later only.\n\n
Points to the IMeshSelect instance (generally this is a modifier).\n\n
<b>TimeValue t</b>\n\n
This parameter is available in release 3.0 and later only.\n\n
The current time at which the call is made. */
virtual void SetFaceSel(BitArray &set, IMeshSelect *imod, TimeValue t)=0;
/*! \remarks Sets the edge selection of the modifier.
\par Parameters:
<b>BitArray \&set</b>\n\n
There is one bit for each edge. Bits that are 1 indicate the edge is
selected.\n\n
<b>IMeshSelect *imod</b>\n\n
This parameter is available in release 3.0 and later only.\n\n
Points to the IMeshSelect instance (generally this is a modifier).\n\n
<b>TimeValue t</b>\n\n
This parameter is available in release 3.0 and later only.\n\n
The current time at which the call is made. */
virtual void SetEdgeSel(BitArray &set, IMeshSelect *imod, TimeValue t)=0;
/*! \remarks Returns a reference to an instance of <b>GenericNamedSelSetList</b> used
for storing vertex level named selection sets. This class provides access
to and the ability to manipulate a list of named selection sets. */
virtual GenericNamedSelSetList & GetNamedVertSelList ()=0;
/*! \remarks Returns a reference to an instance of <b>GenericNamedSelSetList</b> used
for storing edge level named selection sets. This class provides access to
and the ability to manipulate a list of named selection sets. */
virtual GenericNamedSelSetList & GetNamedEdgeSelList ()=0;
/*! \remarks Returns a reference to an instance of <b>GenericNamedSelSetList</b> used
for storing face level named selection sets. This class provides access to
and the ability to manipulate a list of named selection sets. */
virtual GenericNamedSelSetList & GetNamedFaceSelList ()=0;
/*! \remarks Retrieves the weighted vertex selections data (Soft Selection data).
\par Parameters:
<b>int nv</b>\n\n
The number of vertices.\n\n
<b>float *sel</b>\n\n
An array of floats to store the results.
\par Default Implementation:
<b>{}</b> */
virtual void GetWeightedVertSel (int nv, float *sel) {}
/*! \remarks Sets the weighted vertex selection data (Soft Selection data) to the values
passed.
\par Parameters:
<b>int nv</b>\n\n
The number of vertices.\n\n
<b>float *sel</b>\n\n
An array of floats with the data.\n\n
<b>IMeshSelect *imod</b>\n\n
Points to the IMeshSelect object.\n\n
<b>TimeValue t</b>\n\n
The time at which to set the data.
\par Default Implementation:
<b>{}</b> */
virtual void SetWeightedVertSel (int nv, float *sel, IMeshSelect *imod, TimeValue t) {}
};
//-------------------------------------------------------------
// Access to spline selections and operations in SplineShape and EditSplineMod
//
// selection levels defined in splshape.h
/*! \sa Class Animatable, <a href="ms-its:3dsmaxsdk.chm::/shps_shapes_and_splines.html">Working with Shapes and Splines</a>.\n\n
\par Description:
This class is available in release 3.0 and later only.\n\n
This class provides an interface to the Spline Select Modifer. To obtain a
pointer to this class use the method <b>Animatable::GetInterface()</b> passing
<b>I_SPLINESELECT</b>.\n\n
For example:\n\n
<b>ISplineSelect *iss =
(ISplineSelect*)anim-\>GetInterface(I_SPLINESELECT));</b>\n\n
<b>DWORD sl = iss-\>GetSelLevel();</b> */
class ISplineSelect: public MaxHeapOperators // accessed via GetInterface(I_SPLINESELECT)
{
public:
/*! \remarks Returns a value indicating the current selection level of the
modifier. One of the following values:\n\n
<b>SS_VERTEX</b>\n\n
<b>SS_SEGMENT</b>\n\n
<b>SS_SPLINE</b>\n\n
<b>SS_OBJECT</b> */
virtual DWORD GetSelLevel()=0;
/*! \remarks Sets the current level of selection of the modifier.
\par Parameters:
<b>DWORD level</b>\n\n
The level to set. One of the following values:\n\n
<b>SS_VERTEX</b>\n\n
<b>SS_SEGMENT</b>\n\n
<b>SS_SPLINE</b>\n\n
<b>SS_OBJECT</b> */
virtual void SetSelLevel(DWORD level)=0;
/*! \remarks This method must be called when the selection level of the
modifier is changed. Developers can use the methods of <b>ISplineSelect</b>
to get and set the actual selection data. When a developers does set any of
these selection sets this method must be called when done. */
virtual void LocalDataChanged()=0;
};
/*! \sa Class ISplineSelect, Class Animatable, Class BitArray, <a href="ms-its:3dsmaxsdk.chm::/shps_shapes_and_splines.html">Working with Shapes and Splines</a>, Class GenericNamedSelSetList.\n\n
\par Description:
This class is available in release 3.0 and later only.\n\n
When a developer gets the <b>LocalModData</b> from the <b>ModContext</b> of the
Spline Select Modifier, they may cast it to this class and use these methods.
They may be used to get/set the vertex/segment/spline selection state of the
modifier as well as the named selection sets.\n\n
To obtain a pointer to this class use the method
<b>Animatable::GetInterface()</b> passing <b>I_SPLINESELECTDATA</b>.\n\n
For example:\n\n
<b>ISplineSelectData *iss =
(ISplineSelectData*)anim-\>GetInterface(I_SPLINESELECTDATA));</b>\n\n
<b>BitArray vs = iss-\>GetVertSel();</b> */
class ISplineSelectData: public MaxHeapOperators // accessed via GetInterface(I_SPLINESELECTDATA)
{
public:
// access spline sub-object selections, current & named
/*! \remarks Returns a <b>BitArray</b> that reflects the current vertex
selection. There is one bit for each vertex. Bits that are 1 indicate the
vertex is selected. */
virtual BitArray GetVertSel()=0;
/*! \remarks Returns a <b>BitArray</b> that reflects the current segment
selection. There is one bit for each segment. Bits that are 1 indicate the
segment is selected. */
virtual BitArray GetSegmentSel()=0;
/*! \remarks Returns a <b>BitArray</b> that reflects the current spline
selection. There is one bit for each spline. Bits that are 1 indicate the
spline is selected. */
virtual BitArray GetSplineSel()=0;
/*! \remarks Sets the vertex selection of the modifier.
\par Parameters:
<b>BitArray \&set</b>\n\n
There is one bit for each vertex. Bits that are 1 indicate the vertex
should be selected.\n\n
<b>ISplineSelect *imod</b>\n\n
Points to the ISplineSelect instance (generally this is a modifier).\n\n
<b>TimeValue t</b>\n\n
The current time at which the call is made. */
virtual void SetVertSel(BitArray &set, ISplineSelect *imod, TimeValue t)=0;
/*! \remarks Sets the segment selection of the modifier.
\par Parameters:
<b>BitArray \&set</b>\n\n
There is one bit for each vertex. Bits that are 1 indicate the segment
should be selected.\n\n
<b>ISplineSelect *imod</b>\n\n
Points to the ISplineSelect instance (generally this is a modifier).\n\n
<b>TimeValue t</b>\n\n
The current time at which the call is made. */
virtual void SetSegmentSel(BitArray &set, ISplineSelect *imod, TimeValue t)=0;
/*! \remarks Sets the spline selection of the modifier.
\par Parameters:
<b>BitArray \&set</b>\n\n
There is one bit for each spline. Bits that are 1 indicate the spline
should be selected.\n\n
<b>ISplineSelect *imod</b>\n\n
Points to the ISplineSelect instance (generally this is a modifier).\n\n
<b>TimeValue t</b>\n\n
The current time at which the call is made. */
virtual void SetSplineSel(BitArray &set, ISplineSelect *imod, TimeValue t)=0;
/*! \remarks Returns a reference to a class used for manipulating the
lists of vertex level named selection sets associated with this modifier.
*/
virtual GenericNamedSelSetList & GetNamedVertSelList ()=0;
/*! \remarks Returns a reference to a class used for manipulating the
lists of segment level named selection sets associated with this modifier.
*/
virtual GenericNamedSelSetList & GetNamedSegmentSelList ()=0;
/*! \remarks Returns a reference to a class used for manipulating the
lists of spline level named selection sets associated with this modifier.
*/
virtual GenericNamedSelSetList & GetNamedSplineSelList ()=0;
};
enum splineCommandMode { ScmCreateLine, ScmAttach, ScmInsert, ScmConnect, ScmRefine, ScmFillet, ScmChamfer,
ScmBind, ScmRefineConnect, ScmOutline, ScmTrim, ScmExtend, ScmCrossInsert,
ScmBreak, ScmUnion, ScmSubtract, ScmCrossSection, ScmCopyTangent, ScmPasteTangent, };
enum splineButtonOp { SopHide, SopUnhideAll, SopDelete, SopDetach, SopDivide, SopCycle,
SopUnbind, SopWeld, SopMakeFirst, SopAttachMultiple, SopExplode, SopReverse,
SopClose, SopIntersect, SopMirrorHoriz, SopMirrorVert,
SopMirrorBoth, SopSelectByID, SopFuse, };
// LAM: added 9/3/00
enum splineUIParam { };
/*! \sa Class ISplineSelect, Class Animatable, <a href="ms-its:3dsmaxsdk.chm::/shps_shapes_and_splines.html">Working with Shapes and Splines</a>.\n\n
\par Description:
This class is available in release 3.0 and later only.\n\n
This class provides an interface to the command modes and button press
operations of the Editable Spline object. To obtain a pointer to this class use
the method <b>Animatable::GetInterface()</b> passing <b>I_SPLINEOPS</b>.\n\n
For example:\n\n
<b>ISplineOps *iso = (ISplineOps*)anim-\>GetInterface(I_SPLINEOPS));</b>\n\n
<b>iso-\>StartCommandMode(ScmAttach);</b> */
class ISplineOps: public MaxHeapOperators // accessed via GetInterface(I_SPLINEOPS)
{
public:
// start up interactive command mode, uses mode enum above
/*! \remarks Begins the specified interactive command mode.
\par Parameters:
<b>splineCommandMode mode</b>\n\n
The mode to begin. One of the following values:\n\n
<b>ScmCreateLine</b>\n\n
<b>ScmAttach</b>\n\n
<b>ScmInsert</b>\n\n
<b>ScmConnect</b>\n\n
<b>ScmRefine</b>\n\n
<b>ScmFillet</b>\n\n
<b>ScmChamfer</b>\n\n
<b>ScmBind</b>\n\n
<b>ScmRefineConnect</b>\n\n
<b>ScmOutline</b>\n\n
<b>ScmTrim</b>\n\n
<b>ScmExtend</b>\n\n
<b>ScmBreak</b>\n\n
<b>ScmUnion</b>\n\n
<b>ScmCrossInsert</b> */
virtual void StartCommandMode(splineCommandMode mode)=0;
// perform button op, uses op enum above
/*! \remarks Performs the same operation as a button press inside the
Editable Spline UI.
\par Parameters:
<b>splineButtonOp opcode</b>\n\n
The button operation to execute. One of the following values:\n\n
<b>SopHide</b>\n\n
<b>SopUnhideAll</b>\n\n
<b>SopDelete</b>\n\n
<b>SopDetach</b>\n\n
<b>SopDivide</b>\n\n
<b>SopBreak</b>\n\n
<b>SopCycle</b>\n\n
<b>SopUnbind</b>\n\n
<b>SopWeld</b>\n\n
<b>SopMakeFirst</b>\n\n
<b>SopAttachMultiple</b>\n\n
<b>SopExplode</b>\n\n
<b>SopReverse</b>\n\n
<b>SopClose</b>\n\n
<b>SopUnion</b>\n\n
<b>SopSubstract</b>\n\n
<b>SopIntersect</b>\n\n
<b>SopMirrorHoriz</b>\n\n
<b>SopMirrorVert</b>\n\n
<b>SopMirrorBoth</b>\n\n
<b>SopSelectByID</b>\n\n
<b>SopFuse</b> */
virtual void ButtonOp(splineButtonOp opcode)=0;
// LAM: added 9/3/00
// UI controls access
/*! \remarks This method allows you to get the edit spline parameters from the command
panel. Currently not in use.
\par Parameters:
<b>splineUIParam uiCode</b>\n\n
This enum is currently empty.\n\n
<b>int \&ret</b>\n\n
The returned value.
\par Default Implementation:
<b>{ }</b> */
virtual void GetUIParam (splineUIParam uiCode, int & ret) { }
/*! \remarks This method allows you to set the edit spline parameters from the command
panel. Currently not in use.
\par Parameters:
<b>splineUIParam uiCode</b>\n\n
This enum is currently empty.\n\n
<b>int val</b>\n\n
The value to set.
\par Default Implementation:
<b>{ }</b> */
virtual void SetUIParam (splineUIParam uiCode, int val) { }
/*! \remarks This method allows you to get the edit spline parameters from the command
panel. Currently not in use.
\par Parameters:
<b>splineUIParam uiCode</b>\n\n
This enum is currently empty.\n\n
<b>float \&ret</b>\n\n
The returned value.
\par Default Implementation:
<b>{ }</b> */
virtual void GetUIParam (splineUIParam uiCode, float & ret) { }
/*! \remarks This method allows you to set the edit spline parameters from the command
panel. Currently not in use.
\par Parameters:
<b>splineUIParam uiCode</b>\n\n
This enum is currently empty.\n\n
<b>float val</b>\n\n
The value to set.
\par Default Implementation:
<b>{ }</b> */
virtual void SetUIParam (splineUIParam uiCode, float val) { }
};
//-------------------------------------------------------------
// Access to spline selections and operations in PatchObject and EditPatchMod
//
// selection levels defined in patchobj.h
/*! \sa Class Animatable, <a href="ms-its:3dsmaxsdk.chm::/patches_root.html">Working with Patches</a>.\n\n
\par Description:
This class is available in release 3.0 and later only.\n\n
This class provides an interface to the Patch Select Modifer. To obtain a
pointer to this class use the method <b>Animatable::GetInterface()</b> passing
<b>I_PATCHSELECT</b>.\n\n
For example:\n\n
<b>IPatchSelect *ips =
(IPatchSelect*)anim-\>GetInterface(I_PATCHSELECT));</b>\n\n
<b>DWORD sl = ips-\>GetSelLevel();</b> */
class IPatchSelect: public MaxHeapOperators // accessed via GetInterface(I_PATCHSELECT)
{
public:
/*! \remarks Returns a value indicating the current selection level of the
modifier. One of the following values:\n\n
<b>PO_VERTEX</b>\n\n
<b>PO_EDGE</b>\n\n
<b>PO_PATCH</b>\n\n
<b>PO_OBJECT</b> */
virtual DWORD GetSelLevel()=0;
/*! \remarks Sets the current level of selection of the modifier.
\par Parameters:
<b>DWORD level</b>\n\n
The level to set. One of the following values:\n\n
<b>PO_VERTEX</b>\n\n
<b>PO_EDGE</b>\n\n
<b>PO_PATCH</b>\n\n
<b>PO_OBJECT</b> */
virtual void SetSelLevel(DWORD level)=0;
/*! \remarks This method must be called when the selection level of the
modifier is changed. Developers can use the methods of this class to get
and set the actual selection data. When a developers does set any of these
selection sets this method must be called when done. */
virtual void LocalDataChanged()=0;
};
/*! \sa Class IPatchSelect, Class Animatable, Class BitArray, <a href="ms-its:3dsmaxsdk.chm::/patches_root.html">Working with Patches</a>, Class GenericNamedSelSetList.\n\n
\par Description:
This class is available in release 3.0 and later only.\n\n
When a developer gets the <b>LocalModData</b> from the <b>ModContext</b> of the
Patch Select Modifier, they may cast it to this class and use these methods.
They may be used to get/set the vertex/edge/patch sub-object selection state of
the modifier as well as the named selection sets.\n\n
To obtain a pointer to this class use the method
<b>Animatable::GetInterface()</b> passing <b>I_PATCHSELECTDATA</b>.\n\n
For example:\n\n
<b>IPatchSelectData *ips =
(IPatchSelectData*)anim-\>GetInterface(I_PATCHSELECTDATA));</b>\n\n
<b>BitArray vs = ips-\>GetVertSel();</b> */
class IPatchSelectData: public MaxHeapOperators // accessed via GetInterface(I_PATCHSELECTDATA)
{
public:
// access patch sub-object selections, current & named
virtual BitArray GetVecSel()=0;
/*! \remarks Returns a <b>BitArray</b> that reflects the current vertex
selection. There is one bit for each vertex. Bits that are 1 indicate the
vertex is selected. */
virtual BitArray GetVertSel()=0;
/*! \remarks Returns a <b>BitArray</b> that reflects the current edge
selection. There is one bit for each edge. Bits that are 1 indicate the
edge is selected. */
virtual BitArray GetEdgeSel()=0;
/*! \remarks Returns a <b>BitArray</b> that reflects the current patch
selection. There is one bit for each patch. Bits that are 1 indicate the
patch is selected. */
virtual BitArray GetPatchSel()=0;
virtual void SetVecSel(BitArray &set, IPatchSelect *imod, TimeValue t)=0;
/*! \remarks Sets the vertex selection of the modifier.
\par Parameters:
<b>BitArray \&set</b>\n\n
There is one bit for each vertex. Bits that are 1 indicate the vertex
should be selected.\n\n
<b>IPatchSelect *imod</b>\n\n
Points to the IPatchSelect instance (generally this is a modifier).\n\n
<b>TimeValue t</b>\n\n
The current time at which the call is made. */
virtual void SetVertSel(BitArray &set, IPatchSelect *imod, TimeValue t)=0;
/*! \remarks Sets the edge selection of the modifier.
\par Parameters:
<b>BitArray \&set</b>\n\n
There is one bit for each edge. Bits that are 1 indicate the edge should be
selected.\n\n
<b>IPatchSelect *imod</b>\n\n
Points to the IPatchSelect instance (generally this is a modifier).\n\n
<b>TimeValue t</b>\n\n
The current time at which the call is made. */
virtual void SetEdgeSel(BitArray &set, IPatchSelect *imod, TimeValue t)=0;
/*! \remarks Sets the patch selection of the modifier.
\par Parameters:
<b>BitArray \&set</b>\n\n
There is one bit for each patch. Bits that are 1 indicate the patch should
be selected.\n\n
<b>IPatchSelect *imod</b>\n\n
Points to the IPatchSelect instance (generally this is a modifier).\n\n
<b>TimeValue t</b>\n\n
The current time at which the call is made. */
virtual void SetPatchSel(BitArray &set, IPatchSelect *imod, TimeValue t)=0;
virtual GenericNamedSelSetList & GetNamedVecSelList ()=0;
/*! \remarks Returns a reference to a class used for manipulating the
lists of vertex level named selection sets associated with this modifier.
*/
virtual GenericNamedSelSetList & GetNamedVertSelList ()=0;
/*! \remarks Returns a reference to a class used for manipulating the
lists of edge level named selection sets associated with this modifier. */
virtual GenericNamedSelSetList & GetNamedEdgeSelList ()=0;
/*! \remarks Returns a reference to a class used for manipulating the
lists of patch level named selection sets associated with this modifier. */
virtual GenericNamedSelSetList & GetNamedPatchSelList ()=0;
};
enum patchCommandMode { PcmAttach, PcmExtrude, PcmBevel, PcmBind, PcmCreate, PcmWeldTarget,
PcmFlipNormal, PcmCopyTangent, PcmPasteTangent };
enum patchButtonOp { PopUnbind, PopHide, PopUnhideAll, PopWeld, PopDelete, PopSubdivide,
PopAddTri, PopAddQuad, PopDetach, PopSelectOpenEdges, PopBreak,
PopCreateShapeFromEdges, PopFlipNormal, PopUnifyNormal, PopSelectByID,
PopSelectBySG, PopClearAllSG, PopPatchSmooth, PopSelectionShrink, PopSelectionGrow,
PopEdgeRingSel, PopEdgeLoopSel, PopShadedFaceToggle };
// LAM: added 9/3/00
enum patchUIParam { };
/*! \sa Class Animatable, <a href="ms-its:3dsmaxsdk.chm::/patches_root.html">Working with Patches</a>.\n\n
\par Description:
This class is available in release 3.0 and later only.\n\n
This class provides an interface to the command modes and button press
operations of the Editable Patch object. To obtain a pointer to this class use
the method <b>Animatable::GetInterface()</b> passing <b>I_PATCHOPS</b>.\n\n
For example:\n\n
<b>IPatchOps *ipo = (IPatchOps*)anim-\>GetInterface(I_PATCHOPS));</b>\n\n
<b>ipo-\>StartCommandMode(PcmAttach);</b> */
class IPatchOps: public MaxHeapOperators // accessed via GetInterface(I_PATCHOPS)
{
public:
// start up interactive command mode, uses mode enum above
/*! \remarks Begins the specified interactive command mode.
\par Parameters:
<b>patchCommandMode mode</b>\n\n
<b>PcmAttach</b>\n\n
<b>PcmExtrude</b>\n\n
<b>PcmBevel</b>\n\n
<b>PcmCreate</b>\n\n
<b>PcmWeldTarget</b>\n\n
<b>PcmFlipNormal</b>\n\n
<b>PcmBind</b> */
virtual void StartCommandMode(patchCommandMode mode)=0;
// perform button op, uses op enum above
/*! \remarks Performs the same operation as a button press inside the
Editable Patch UI.
\par Parameters:
<b>patchButtonOp opcode</b>\n\n
The button operation to execute. One of the following values:\n\n
<b>PopBind</b>\n\n
<b>PopUnbind</b>\n\n
<b>PopHide</b>\n\n
<b>PopUnhideAll</b>\n\n
<b>PopWeld</b>\n\n
<b>PopDelete</b>\n\n
<b>PopSubdivide</b>\n\n
<b>PopAddTri</b>\n\n
<b>PopAddQuad</b>\n\n
<b>PopDetach</b> */
virtual void ButtonOp(patchButtonOp opcode)=0;
// LAM: added 9/3/00
// UI controls access
/*! \remarks This method allows you to get the edit patch parameters from the command
panel. Currently not in use.
\par Parameters:
<b>patchUIParam uiCode</b>\n\n
This enum is currently empty.\n\n
<b>int \&ret</b>\n\n
The returned value.
\par Default Implementation:
<b>{ }</b> */
virtual void GetUIParam (patchUIParam uiCode, int & ret) { }
/*! \remarks This method allows you to set the edit patch parameters from the command
panel. Currently not in use.
\par Parameters:
<b>patchUIParam uiCode</b>\n\n
This enum is currently empty.\n\n
<b>int val</b>\n\n
The value to set.
\par Default Implementation:
<b>{ }</b> */
virtual void SetUIParam (patchUIParam uiCode, int val) { }
/*! \remarks This method allows you to get the edit patch parameters from the command
panel. Currently not in use.
\par Parameters:
<b>patchUIParam uiCode</b>\n\n
This enum is currently empty.\n\n
<b>float \&ret</b>\n\n
The returned value.
\par Default Implementation:
<b>{ }</b> */
virtual void GetUIParam (patchUIParam uiCode, float & ret) { }
/*! \remarks This method allows you to set the edit patch parameters from the command
panel. Currently not in use.
\par Parameters:
<b>patchUIParam uiCode</b>\n\n
This enum is currently empty.\n\n
<b>float val</b>\n\n
The value to set.
\par Default Implementation:
<b>{ }</b> */
virtual void SetUIParam (patchUIParam uiCode, float val) { }
};
#pragma warning(pop)
//----------------------------------------------------------------
// Access to the new Assign Vertex Color utility - MAB - 6/04/03
#define APPLYVC_UTIL_CLASS_ID Class_ID(0x6e989195, 0x5dfb41b7)
#define IASSIGNVERTEXCOLORS_INTERFACE_ID Interface_ID(0x4f913fd8, 0x422a32af)
namespace LightingModel
{
enum LightingModel { //!< The lighting model to use when assigning vertex colors
kLightingOnly = 0, //!< Store lighting only
kShadedLighting = 1, //!< Store shaded color with lighting
kShadedOnly = 2 //!< Store shaded color without lighting
};
}
/*!
\brief The IAssignVertexColors is a static interface to the Assign Vertex Color utility.
It can be obtained as follows:
\code
IAssignVertexColors* avc = (IAssignVertexColors*)GetCOREInterface(IASSIGNVERTEXCOLORS_INTERFACE_ID);
\endcode
*/
class IAssignVertexColors : public FPStaticInterface {
public:
DECLARE_DESCRIPTOR( IAssignVertexColors );
typedef LightingModel::LightingModel LightingModel;
//! \brief The options used when calculating the vertex colors
struct Options: public MaxHeapOperators {
int mapChannel;
bool mixVertColors; //!< face colors is false, or mixed vertex colors if true
bool castShadows;
bool useMaps;
bool useRadiosity;
bool radiosityOnly;
LightingModel lightingModel;
};
//! \brief Performs a lighting calculation.
/*! The result is stored in the given VertexPaint modifier (if provided) or creates
a new modifier instanced across the given nodes.
\param[in, out] nodes A pointer to an array of nodes pointers to apply the iVertexPaint interface to.
This list of nodes will be filtered to include only nodes with geometry objects on return.
\param[in] iVertexPaint An instance of a ReferenceTarget derived class which supports the IVertexPaint interface.
If this parameter is null, an instance of the standard Max Vertex Paint modifier will be created and assigned to the nodes.
\return 0 if the vertex paint interface could not be applied, else 1. */
virtual int ApplyNodes( Tab<INode*>* nodes, ReferenceTarget* iVertexPaint=NULL ) = 0;
//! \brief The Get/SetOptions() methods control the parameters used for the lighting calculation, as shown in the UI of the utility.
virtual void GetOptions( Options& options ) = 0;
//! \brief The Get/SetOptions() methods control the parameters used for the lighting calculation, as shown in the UI of the utility.
virtual void SetOptions( Options& options ) = 0;
};
#define IASSIGNVERTEXCOLORS_R7_INTERFACE_ID Interface_ID(0x77870f30, 0x4ed82b62)
/*!
\brief This class extends IAssignVertexColors to include more options.
\sa Class IAssignVertexColors
Options2 has been extended to add the reuseillumination boolean, indicating
whether we reuse illumination or we render the direct lights.
*/
class IAssignVertexColors_R7 : public IAssignVertexColors {
public:
DECLARE_DESCRIPTOR( IAssignVertexColors_R7 );
//! \brief The options used when calculating the vertex colors
class Options2: public Options
{
public:
bool reuseIllumination; //!< Reuse Illumination or render direct lights
} ;
//! \brief The Get/SetOptions() methods control the parameters used for the lighting calculation, as shown in the UI of the utility.
virtual void GetOptions2( Options2& options ) = 0;
//! \brief The Get/SetOptions() methods control the parameters used for the lighting calculation, as shown in the UI of the utility.
virtual void SetOptions2( Options2& options ) = 0;
};
//----------------------------------------------------------------
// Access to the new Vertex Paint modifier in 3ds max 6 - MAB - 5/15/03
#define PAINTLAYERMOD_CLASS_ID Class_ID(0x7ebb4645, 0x7be2044b)
#define IVERTEXPAINT_INTERFACE_ID Interface_ID(0x3e262ef9, 0x220e7190)
/*!
\brief The IVertexPaint interface provides a way to set the vertex colors held in a VertexPaint modifier.
The interface can be obtained as follows:
\code
ReferenceTarget* vertexPaintMod = ...;
IVertexPaint* ivertexPaint = (IVertexPaint*)vertexPaintMod->GetInterface(IVERTEXPAINT_INTERFACE_ID);
\endcode
\note The class ID for the new VertexPaint in R6 and up is PAINTLAYERMOD_CLASS_ID, different from the
legacy modifier. The legacy modifier does not support IVertexPaint
*/
class IVertexPaint : public FPMixinInterface {
public:
struct FaceColor: public MaxHeapOperators { //!< Stores a color for each vertex of a triangle face.
Color colors[3];
};
typedef Tab<Color*> VertColorTab;
typedef Tab<FaceColor*> FaceColorTab;
typedef IAssignVertexColors::Options Options;
//! \brief Set the colors by providing one color per vert.
/*! If the vertex paint modifier is applied on a poly object, you should provide colors
based on the tri-mesh version of the object, as this is the object-type operated on by the modifier.
\param [in] node The node to apply the vertex painting to
\param [in] vertColors A table of colors, this should supply one for each vertex
\return 0 if the colors could not be applied, else 1 */
virtual int SetColors( INode* node, VertColorTab& vertColors ) = 0;
//! \brief Set colors by providing three colors per triangle.
/*! If the vertex paint modifier is applied on a poly object, you should provide colors
based on the tri-mesh version of the object, as this is the object-type operated on by the modifier.
\param [in] node The node to apply the vertex painting to
\param [in] faceColors A table of face colors, each with 3 colors for each vertex.
\return 0 if the colors could not be applied, else 1 */
virtual int SetColors( INode* node, FaceColorTab& faceColors ) = 0;
//! \brief The Get/SetOptions() methods control the parameters used for the lighting calculation, as shown in the UI of the utility.
virtual void GetOptions( Options& options ) = 0;
//! \brief The Get/SetOptions() methods control the parameters used for the lighting calculation, as shown in the UI of the utility.
virtual void SetOptions( Options& options ) = 0;
};
#define IVERTEXPAINT_R7_INTERFACE_ID Interface_ID(0x4ea42df5, 0x44a35866)
class IVertexPaint_R7 : public IVertexPaint {
public:
typedef IAssignVertexColors_R7::Options2 Options2;
// Assumes colors were calculated on the same object as seen by the modifier (converted to a tri-mesh)
virtual void GetOptions2( Options2& options ) = 0;
virtual void SetOptions2( Options2& options ) = 0;
};
// Interface for the TimeSlider
#define TIMESLIDER_INTERFACE Interface_ID(0x829e89e5, 0x878ef6e5)
//! \brief This class represents the interface for the time slider.
/*! This class is available in release 4.0 and later only.\n\n
The interface ID is
defined as <b>TIMESLIDER_INTERFACE</b>.\n\n
All methods of this class are Implemented by the System. */
class ITimeSlider : public FPStaticInterface {
public:
/*! \remarks This method allows you to set the visibility flags of the
time slider.
\par Parameters:
<b>BOOL bVisible</b>\n\n
TRUE to set the time slider visible, otherwise FALSE.\n\n
<b>BOOL bPersistent = TRUE</b>\n\n
If this parameter is set to TRUE the value will be written to the ini file
so the visibility switch will be persistent between sessions. Set this
parameter to FALSE if you wish to reset the visibility switch the next time
3ds Max starts. */
virtual void SetVisible(BOOL bVisible, BOOL bPersistent = TRUE) = 0;
/*! \remarks This method returns TRUE if the time slider is visible,
otherwise FALSE. */
virtual BOOL IsVisible() = 0;
};
// Interface for the StatusPanel
#define STATUSPANEL_INTERFACE Interface_ID(0x94357f0, 0x623e71c2)
class IStatusPanel : public FPStaticInterface {
public:
virtual void SetVisible(BOOL bVisible) = 0;
virtual BOOL IsVisible() = 0;
};
// Interface for the BMP I/O plug-in
#define BMPIO_INTERFACE Interface_ID(0x374f288f, 0x19e460d6)
// Valid types are, BMM_PALETTED, BMM_TRUE_24 and BMM_NO_TYPE (=BMM_TRUE_24)
//! \brief This class represents the interface for the Bitmap IO BMP format.
/*! This class is available in release 4.0 and later only.\n\n
All methods of this class are Implemented by the System.\n\n
The interfaceID is defined as <b>BMPIO_INTERFACE</b>. Through C++ you can access the
interface the following way:
\code
ClassEntry* ce = ip->GetDllDirectory()->ClassDir().FindClassEntry(BMM_IO_CLASS_ID, Class_ID(BMPCLASSID,0));
if (ce)
{
ClassDesc* cd = ce->FullCD();
if (cd) {
IBitmapIO_Bmp* ib = (IBitmapIO_Bmp*)cd->GetInterface(BMPIO_INTERFACE);
if (ib) {
int i = ib->GetType();
ib->SetType(i);
}
}
}
\endcode */
class IBitmapIO_Bmp : public FPStaticInterface {
public:
/*! \remarks This method returns the format type, which is one of the
following; <b>BMM_PALETTED</b>, <b>BMM_TRUE_24</b> and <b>BMM_NO_TYPE</b>
(which is equivalent to <b>BMM_TRUE_24</b>). */
virtual int GetType() = 0;
/*! \remarks This method allows you to set the format type.
\par Parameters:
<b>int type</b>\n\n
The type, which is one of the following; <b>BMM_PALETTED</b>,
<b>BMM_TRUE_24</b> and <b>BMM_NO_TYPE</b> (which is equivalent to
<b>BMM_TRUE_24</b>). */
virtual void SetType(int type) = 0;
};
// Interface for the JPeg I/O plug-in
#define JPEGIO_INTERFACE Interface_ID(0x466c7964, 0x2db94ff2)
/*! \sa Class FPStaticInterface\n\n
\par Description:
This class is available in release 4.0 and later only.\n\n
This class represents the interface for the Bitmap IO JPG format. The interface
ID is defined as <b>BMPIO_INTERFACE</b>.\n\n
All methods of this class are Implemented by the System. */
class IBitmapIO_Jpeg : public FPStaticInterface {
public:
/*! \remarks This method returns the quality level of the output image. */
virtual int GetQuality() = 0;
/*! \remarks This method allows you to set the quality level of the output
image.
\par Parameters:
<b>int quality</b>\n\n
The quality level. */
virtual void SetQuality(int quality) = 0;
/*! \remarks This method returns the smoothing level of the output image.
*/
virtual int GetSmoothing() = 0;
/*! \remarks This method allows you set the smoothing level of the output
image.
\par Parameters:
<b>int smoothing</b>\n\n
The smoothing level. */
virtual void SetSmoothing(int smoothing) = 0;
};
// Interface for the Png I/O plug-in
#define PNGIO_INTERFACE Interface_ID(0x1d7c41db, 0x328c1142)
/*! \sa Class FPStaticInterface\n\n
\par Description:
This class is available in release 4.0 and later only.\n\n
This class represents the interface for the Bitmap IO PNG format. The interface
ID is defined as <b>BMPIO_INTERFACE</b>.\n\n
All methods of this class are Implemented by the System. */
class IBitmapIO_Png : public FPStaticInterface {
public:
// Valid type are:
// BMM_PALETTED
// BMM_TRUE_24
// BMM_TRUE_48
// BMM_GRAY_8
// BMM_GRAY_16
/*! \remarks This method returns the bitmap type, which is one of the
following; <b>BMM_PALETTED, BMM_TRUE_24, BMM_TRUE_48, BMM_GRAY_8</b>, or
<b>BMM_GRAY_16</b>. */
virtual int GetType() = 0;
/*! \remarks This method allows you to set the bitmap type.
\par Parameters:
<b>int type</b>\n\n
One of the following; <b>BMM_PALETTED, BMM_TRUE_24, BMM_TRUE_48,
BMM_GRAY_8</b>, or <b>BMM_GRAY_16</b>. */
virtual void SetType(int type) = 0;
/*! \remarks This method returns TRUE if the alpha flag is set, otherwise
FALSE. */
virtual BOOL GetAlpha() = 0;
/*! \remarks This method allows you to set the alpha flag.
\par Parameters:
<b>BOOL alpha</b>\n\n
TRUE to set the alpha flag, otherwise FALSE. */
virtual void SetAlpha(BOOL alpha) = 0;
/*! \remarks This method returns TRUE if the interlaced flag is set,
otherwise FALSE. */
virtual BOOL GetInterlaced() = 0;
/*! \remarks This method allows you to set the interlaced flag.
\par Parameters:
<b>BOOL interlaced</b>\n\n
TRUE to set the interlaced flag, otherwise FALSE. */
virtual void SetInterlaced(BOOL interlaced) = 0;
};
// Interface for the Targa I/O plug-in
#define TGAIO_INTERFACE Interface_ID(0x21d673b7, 0x1d34198d)
/*! \sa Class FPStaticInterface, Class BitmapIO\n\n
\par Description:
This class is available in release 4.0 and later only.\n\n
This class represents the interface for the Bitmap IO TGA format. The interface
ID is defined as <b>BMPIO_INTERFACE</b>.\n\n
All methods of this class are Implemented by the System. */
class IBitmapIO_Tga : public FPStaticInterface {
public:
// 16, 24, 32
/*! \remarks This method returns the color depth, which would be 16, 24,
or 32. */
virtual int GetColorDepth() = 0;
/*! \remarks This method allows you to set the color depth.
\par Parameters:
<b>int bpp</b>\n\n
The color depth, being either 16, 24, or 32. */
virtual void SetColorDepth(int bpp) = 0;
/*! \remarks This method returns TRUE if the compression flag is set,
otherwise FALSE. */
virtual BOOL GetCompressed() = 0;
/*! \remarks This method allows you to set the compression flag.
\par Parameters:
<b>BOOL compressed</b>\n\n
TRUE to set the compression flag, otherwise FALSE. */
virtual void SetCompressed(BOOL compressed) = 0;
/*! \remarks This method returns TRUE if the alpha split flag is set,
otherwise FALSE. */
virtual BOOL GetAlphaSplit() = 0;
/*! \remarks This method allows you to set the alpha split flag.
\par Parameters:
<b>BOOL alphaSplit</b>\n\n
TRUE to set the alpha split flag, otherwise FALSE. */
virtual void SetAlphaSplit(BOOL alphaSplit) = 0;
/*! \remarks This method returns TRUE if the premultiplied alpha flag is
set, otherwise FALSE. */
virtual BOOL GetPreMultAlpha() = 0;
/*! \remarks This method allows you to set the premultiplied alpha flag.
\par Parameters:
<b>BOOL preMult</b>\n\n
TRUE to set the premultiplied alpha flag, otherwise FALSE. */
virtual void SetPreMultAlpha(BOOL preMult) = 0;
};
// Interface for the RLA I/O plug-in
//Fetching the interface using either RLAIO_INTERFACE or RPFIO_INTERFACE returns an object
//of the same class. But the object affects only the RLA or RPF settings accordingly.
//The "RPF-specific" methods have undefined behavior unless used with an RPFIO_INTERFACE object
#define RLAIO_INTERFACE Interface_ID(0x282c2f79, 0x68f7373d)
#define RPFIO_INTERFACE Interface_ID(0x25a87871, 0x2e265a49)
//! \brief The IBitmapIO_RLA class expands upon the previous IBitmapIO classes
/*! \sa Class IBitmapIO
\par Description:
The IBitmapIO_RLA class expands upon the previous IBitmapIO classes for .bmp,
.jpeg, .png and .tga. Like these others, it is a static interface; the code to
fetch the interface is given below. The interface does not directly change the
configuration of an existing BitmapIO. Instead, these methods set the default
values, which will be used the next time an RLA or RPF file is saved.
The defaults will also appear in the bitmap configuration dialog if the user saves
an RLA or RPF file.
\par Usage:
Both RLA and RPF have the same interface class, IBitmapIO_RLA, but some of the methods
of this class are RPF-specific, giving undefined behavior if used on an RLA instance
of the class.
\code
DllDir* dllDir = GetCOREInterface()->GetDllDirectory();
ClassDirectory& classDir = dllDir->ClassDir();
ClassEntry* classEntry = classDir.FindClassEntry( BMM_IO_CLASS_ID, Class_ID(RPFCLASSID,0));
ClassDesc* classDesc = classEntry->FullCD();
return classDesc->GetInterface( RPFIO_INTERFACE );
// You can substitute RLACLASSID and RLAIO_INTERFACE if you want the RLA interface.
\endcode
*/
class IBitmapIO_RLA : public FPStaticInterface {
public:
// 8, 16, 32
virtual int GetColorDepth() = 0;
virtual void SetColorDepth(int bpp) = 0;
virtual BOOL GetStoreAlpha() = 0;
virtual void SetStoreAlpha(BOOL storeAlpha) = 0;
virtual BOOL GetPremultAlpha() = 0;
virtual void SetPremultAlpha(BOOL preMult) = 0;
virtual MSTR GetDescription() = 0;
virtual void SetDescription(MSTR description) = 0;
virtual MSTR GetAuthor() = 0;
virtual void SetAuthor(MSTR author) = 0;
virtual BOOL GetZChannel() = 0;
virtual void SetZChannel(BOOL b) = 0;
virtual BOOL GetMtlIDChannel() = 0;
virtual void SetMtlIDChannel(BOOL b) = 0;
virtual BOOL GetNodeIDChannel() = 0;
virtual void SetNodeIDChannel(BOOL b) = 0;
virtual BOOL GetUVChannel() = 0;
virtual void SetUVChannel(BOOL b) = 0;
virtual BOOL GetNormalChannel() = 0;
virtual void SetNormalChannel(BOOL b) = 0;
virtual BOOL GetRealpixChannel() = 0;
virtual void SetRealpixChannel(BOOL b) = 0;
virtual BOOL GetCoverageChannel() = 0;
virtual void SetCoverageChannel(BOOL b) = 0;
// RPF-specific methods
virtual BOOL GetNodeRenderIDChannel() = 0;
virtual void SetNodeRenderIDChannel(BOOL b) = 0;
virtual BOOL GetColorChannel() = 0;
virtual void SetColorChannel(BOOL b) = 0;
virtual BOOL GetTranspChannel() = 0;
virtual void SetTranspChannel(BOOL b) = 0;
virtual BOOL GetVelocChannel() = 0;
virtual void SetVelocChannel(BOOL b) = 0;
virtual BOOL GetWeightChannel() = 0;
virtual void SetWeightChannel(BOOL b) = 0;
virtual BOOL GetMaskChannel() = 0;
virtual void SetMaskChannel(BOOL b) = 0;
};
//! \deprecated The new OpenEXR plug-in of 3ds Max 2011 no longer supports this interface.
//! Users could use MaxScript to configure the new OpenEXR plug-in.
//! Interface ID of the IBitmapIO_Exr interface.
#define EXRIO_INTERFACE Interface_ID(0x174f281f, 0x11e462d6)
#pragma deprecated("EXRIO_INTERFACE")
//! \deprecated The new OpenEXR plug-in of 3ds Max 2011 no longer supports this interface.
//! Users could use MaxScript to configure the new OpenEXR plug-in.
//! Interface for the OpenEXR I/O plug-in. This interface is used to query or
//! change the options that are used with the OpenEXR I/O plugin. Each of the
//! options corresponds to something in the load or save user interface.
//! You can get a pointer to this interface by calling GetInterface(EXRIO_INTERFACE)
//! on the class descriptor of the OpenEXR plugin (which has class ID 'MAXOPENEXR_CLASSID').
class MAX_DEPRECATED IBitmapIO_Exr : public FPStaticInterface
{
public:
//! Returns the exponent used when loading an OpenEXR file.
virtual float GetLoadExponent()=0;
//! Sets the exponent used when loading an OpenEXR file.
virtual void SetLoadExponent(float input)=0;
//! Returns the exponent used when saving an OpenEXR file.
virtual float GetSaveExponent()=0;
//! Sets the exponent used when saving an OpenEXR file.
virtual void SetSaveExponent(float input)=0;
//! Returns the state of the "Pre-Multiply Alpha" option used when saving an OpenEXR file.
virtual bool GetSavePreMultAlpha()=0;
//! Sets the state of the "Pre-Multiply Alpha" option used when saving an OpenEXR file.
virtual void SetSavePreMultAlpha(bool input)=0;
//! Returns the "Alpha" option which controls whether an alpha channel is saved to an OpenEXR file.
virtual bool GetSaveAlpha()=0;
//! Sets the "Alpha" option which controls whether an alpha channel is saved to an OpenEXR file.
virtual void SetSaveAlpha(bool input)=0;
//! Returns the "Red" option which controls whether an alpha channel is saved to an OpenEXR file.
virtual bool GetSaveRed()=0;
//! Sets the "Red" option which controls whether an alpha channel is saved to an OpenEXR file.
virtual void SetSaveRed(bool input)=0;
//! Returns the "Green" option which controls whether an alpha channel is saved to an OpenEXR file.
virtual bool GetSaveGreen()=0;
//! Sets the "Green" option which controls whether an alpha channel is saved to an OpenEXR file.
virtual void SetSaveGreen(bool input)=0;
//! Returns the "Blue" option which controls whether an alpha channel is saved to an OpenEXR file.
virtual bool GetSaveBlue()=0;
//! Sets the "Blue" option which controls whether an alpha channel is saved to an OpenEXR file.
virtual void SetSaveBlue(bool input)=0;
//! Returns the bit depth option used when saving an OpenEXR file.
//! 0 for 8bit integers;
//! 1 for half-float;
//! 2 for float
virtual int GetSaveBitDepth()=0;
//! Sets the bit depth option used when saving an OpenEXR file.
//! 0 for 8bit integers;
//! 1 for half-float;
//! 2 for float
virtual void SetSaveBitDepth(int input)=0;
//! Returns the state of the "Use Number of Frame Digits" option used when saving an OpenEXR file.
virtual bool GetSaveUseFrameNumDigits()=0;
//! Sets the state of the "Use Number of Frame Digits" option used when saving an OpenEXR file.
virtual void SetSaveUseFrameNumDigits(bool input)=0;
//! Returns the number of frame digits used when saving an OpenEXR file.
virtual int GetSaveFrameNumDigits()=0;
//! Sets the number of frame digits used when saving an OpenEXR file.
virtual void SetSaveFrameNumDigits(int input)=0;
//! Returns the compression type used when saving an OpenEXR file.
//! 0 = no compression;
//! 1 = RLE;
//! 2 = ZIP (1 scanline);
//! 3 = ZIP (16 scanlines);
//! 4 = PIZ
virtual int GetSaveCompressionType()=0;
//! Sets the compression type used when saving an OpenEXR file.
//! 0 = no compression;
//! 1 = RLE;
//! 2 = ZIP (1 scanline);
//! 3 = ZIP (16 scanlines);
//! 4 = PIZ
virtual void SetSaveCompressionType(int input)=0;
//! Returns the state of the "Use Exponent" option used when saving an OpenEXR file.
virtual bool GetSaveUseExponent()=0;
//! Sets the state of the "Use Exponent" option used when saving an OpenEXR file.
virtual void SetSaveUseExponent(bool input)=0;
//! Returns the state of the "Use RealPix RGB Data" option used when saving an OpenEXR file.
virtual bool GetSaveUseRealPix()=0;
//! Sets the state of the "Use RealPix RGB Data" option used when saving an OpenEXR file.
virtual void SetSaveUseRealPix(bool input)=0;
//! Returns the value of the "Black Point" option used when loading an OpenEXR file.
virtual float GetLoadBlackPoint()=0;
//! Sets the value of the "Black Point" option used when loading an OpenEXR file.
virtual void SetLoadBlackPoint(float input)=0;
//! Returns the value of the "White Point" option used when loading an OpenEXR file.
virtual float GetLoadWhitePoint()=0;
//! Sets the value of the "White Point" option used when loading an OpenEXR file.
virtual void SetLoadWhitePoint(float input)=0;
//! Returns the value of the "RGB Level" option used when loading an OpenEXR file.
virtual float GetLoadRGBLevel()=0;
//! Sets the value of the "RGB Level" option used when loading an OpenEXR file.
virtual void SetLoadRGBLevel(float input)=0;
//! Returns the value of the "RGB Offset" option used when loading an OpenEXR file.
virtual float GetLoadRGBOffset()=0;
//! Sets the value of the "RGB Offset" option used when loading an OpenEXR file.
virtual void SetLoadRGBOffset(float input)=0;
//! Returns the storage format used when loading an OpenEXR file.
virtual int GetLoadStorageFormat()=0;
//! Sets the storage format used when loading an OpenEXR file.
virtual void SetLoadStorageFormat(int input)=0;
//! Returns the status of the "Color Transform" option used when loading an OpenEXR file.
virtual bool GetLoadDoColorTransform()=0;
//! Sets the status of the "Color Transform" option used when loading an OpenEXR file.
virtual void SetLoadDoColorTransform(bool input)=0;
//! Returns the OpenEXR version used by the OpenEXR I/O plugin.
virtual float GetVersion()=0;
//! Returns whether the default Export/Save options are used, or whether the custom
//! options from the .ini files are used.
virtual bool GetExportUseDefaults()=0;
//! Sets whether the default Export/Save options are used, or whether the custom
//! options from the .ini files are used.
virtual void SetExportUseDefaults(bool input)=0;
//! Returns whether the default Import/Load options are used, or whether the custom
//! options from the .ini files are used.
virtual bool GetImportUseDefaults()=0;
//! Sets whether the default Import/Load options are used, or whether the custom
//! options from the .ini files are used.
virtual void SetImportUseDefaults(bool input)=0;
//! Returns whether the custom export/save options from the .ini file should override the default
//! options when doing a network render.
virtual bool GetNetServerExportOverrideParams()=0;
//! Sets whether the custom export/save options from the .ini file should override the default
//! options when doing a network render.
virtual void SetNetServerExportOverrideParams(bool input)=0;
//! Returns whether the custom import/load options from the .ini file should override the default
//! options when doing a network render.
virtual bool GetNetServerImportOverrideParams()=0;
//! Sets whether the custom import/load options from the .ini file should override the default
//! options when doing a network render.
virtual void SetNetServerImportOverrideParams(bool input)=0;
};
// Interface for the Rgb I/O plug-in
#define RGBIO_INTERFACE Interface_ID(0x096c2424, 0x21b84dae)
/*! \sa Class FPStaticInterface\n\n
\par Description:
This class is available in 3ds Max 2011 and later only.\n\n
This class represents the interface for the Bitmap IO RGB format. The interface
ID is defined as <b>BMPIO_INTERFACE</b>.\n\n
All methods of this class are Implemented by the System. */
class IBitmapIO_Rgb : public FPStaticInterface
{
public:
/*! \remarks This method returns the bytes per channel info of the output image. */
virtual int GetBytesPerChannel() = 0;
/*! \remarks This method allows you to set the bytes per channel of the output
image.
\par Parameters:
<b>int bytesPerChannel</b>\n\n
The bytesPerChannel can only be 1 or 2. */
virtual void SetBytesPerChannel(int bytesPerChannel) = 0;
/*! \remarks This method tells whether the output image should have an alpha channel or not
*/
virtual BOOL GetAlphaChannelState() = 0;
/*! \remarks This method allows you set whether the output image should have an alpha channel or not
\par Parameters:
<b>bool bHasAlpha</b>\n\n
true if with alpha channel, false otherwise */
virtual void SetAlphaChannelState(BOOL bHasAlpha) = 0;
/*! \remarks This method tells whether the output image should be compressed or not
*/
virtual BOOL GetCompressionState() = 0;
/*! \remarks This method allows you set whether the output image should be compressed or not
\par Parameters:
<b>bool bCompressed</b>\n\n
true if output image should be compressed, false otherwise */
virtual void SetCompressionState(BOOL bCompressed) = 0;
};
//IUnReplaceableControl --added 08/03/04 MZ. Added for exposetransform helper object.
//This interface serves 2 related functions. First, if this interface is present, pb2's and wires won't try to replace this controller
///Basically it's a backwards-compatabile fix for the fact that the 'IsReplaceable' control flag isn't used by PB2's. Secondly the class provides
//a function to replace it's default 'clone' method. This is currently also used in wiring when a wire is unconnected.
//! \brief IUnReplaceableControl is a new interface which if present lets the internal system know that the controller can't be replaced.
/*! \par Description:
This interface is mainly used by the wire controller UI. \n\n
For example, a controller that implements this interface can't be replaced by a wire controller, it can only participate
in one way wires where this controller is the master. In addition when the controller is replaced and collapsed the
Control returned by the GetReplacementClone function will be used to replace the wire.\n\n
The interface is retrieved by calling GetInterface(I_UNREPLACEABLECTL).
\par Examples:
The expose transform controller (see maxsdk\samples\objects\helpers\exposetransform) implements this interface.
*/
class IUnReplaceableControl: public MaxHeapOperators
{
public:
virtual ~IUnReplaceableControl(){};
virtual Control * GetReplacementClone()=0;
};
//! \brief IEulerControl is an interface for euler controllers so we can get/set their xyz ordering.
//! The interface is returned by calling GetInterface(I_EULERCTRL).
class IEulerControl: public MaxHeapOperators {
public:
//! \brief Get/Set the XYZ Order of the euler controller.
//! Returns the order of the xyz eulers as defined in euler.h
virtual int GetOrder()=0;
//! Sets the order of the xyz eulers as defined in euler.h
virtual void SetOrder(int newOrder)=0;
};
class AKey;
#define I_ATTACHCTRL Interface_ID(0x199a6b11, 0x5ca27621) // (IAttachControl*) - for attach controllers
//! \brief IAttachCtrl is an interface for getting/setting properties on the Attach controller.
/*! The interface is returned by calling GetInterface(I_ATTACHCTRL).
*/
class IAttachCtrl : public BaseInterface {
public:
//! \brief Set the Node to attach to
/*! \param[in] node The Node to attach to
\return True if the node could be set as the attached to node
*/
virtual BOOL SetObject(INode *node)=0;
//! \brief Get the Node to attached to
/*! \return The node attached to
*/
virtual INode* GetObject()=0;
//! \brief Get a Attach controller key
/*! \param[in] index The key index
\return The indexed Attach controller key, NULL if index invalid
*/
virtual AKey* GetKey(int index)=0;
//! \brief Set a attach controller key, creating the key if necessary
/*! \param[in] t The time of the key
\param[in] faceIndex The face index on the node's mesh to attach to
\param[in] bary The barycentric coordinates on the face
*/
virtual void SetKeyPos(TimeValue t, DWORD faceIndex, Point3 bary)=0;
//! \brief Get Attach controller Align property
/*! \return The Align state
*/
virtual BOOL GetAlign()=0;
//! \brief Set Attach controller Align property
/*! \param[in] align New Align state
*/
virtual void SetAlign(BOOL align)=0;
//! \brief Get Attach controller Manual Update property
/*! \return The Manual Update state
*/
virtual BOOL GetManualUpdate()=0;
//! \brief Set Attach controller Manual Update property
/*! \param[in] manUpdate New Manual Update state
*/
virtual void SetManualUpdate(BOOL manUpdate)=0;
//! \brief Invalidate the Attach controller and update its ui if displayed
/*! \param[in] forceUpdate If true, forces an update of the controller even if manual update is off.
*/
virtual void Invalidate(BOOL forceUpdate = FALSE)=0;
};
//! Interface for interactions between 'systems', in particular biped, and the max xref core.
//! This interface allows for xrefs to notify systems when key operations occur so they may act accordingly.
//! The interface ID is I_SYSTEM_XREF defined in AnimatableInterfaceIDs.h.
class ISystemXRef: public MaxHeapOperators {
public:
//! The system is created as an object xref.
virtual void SystemIsObjectXRef() = 0;
//! The system is no longer an object xref. Most likely because it has been merged into the scene.
virtual void SystemNoLongerObjectXRef() = 0;
//! The system is updated. Passed in this the head node of the system that's being xref'd in.
//! param[in] headNode - the first node returned from Animatable::GetSystemNodes
virtual void SystemUpdated(INode *headNode) = 0;
};
| {
"content_hash": "8575a8b0dd54b5109c95304e0967f256",
"timestamp": "",
"source": "github",
"line_count": 4652,
"max_line_length": 196,
"avg_line_length": 38.740326741186585,
"alnum_prop": 0.7169958939074464,
"repo_name": "LiangYue1981816/CrossEngine",
"id": "68d3c22ed008156d097c60a64dec839161f405ea",
"size": "180592",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Tools/MaxExporter/MaxSDKs/2011/include/istdplug.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "30761"
},
{
"name": "C",
"bytes": "84933432"
},
{
"name": "C++",
"bytes": "92458842"
},
{
"name": "CMake",
"bytes": "10937"
},
{
"name": "Cuda",
"bytes": "319314"
},
{
"name": "GLSL",
"bytes": "108168"
},
{
"name": "HTML",
"bytes": "174058"
},
{
"name": "Java",
"bytes": "563"
},
{
"name": "LLVM",
"bytes": "3292"
},
{
"name": "Makefile",
"bytes": "7764848"
},
{
"name": "Objective-C",
"bytes": "304372"
},
{
"name": "Objective-C++",
"bytes": "90267"
},
{
"name": "PAWN",
"bytes": "15882"
},
{
"name": "R",
"bytes": "14754"
},
{
"name": "Shell",
"bytes": "14659"
},
{
"name": "Visual Basic",
"bytes": "3046"
}
],
"symlink_target": ""
} |
class Irwi::Comparators::Spans::ChangedSpan
attr_accessor :action, :old_value, :new_value
def initialize( act, ov, nv )
@action = act
@old_value = ov
@new_value = nv
end
def to_s
s = ''
s << "<span class=\"removed\">#{@old_value}</span>" if @old_value
s << "<span class=\"added\">#{@new_value}</span>" if @new_value
s
end
end
| {
"content_hash": "517727706ddf03b74ac5b8ef4431278b",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 69,
"avg_line_length": 20.444444444444443,
"alnum_prop": 0.5760869565217391,
"repo_name": "fractaldirk/custom_wiki",
"id": "6c3cb416d70249a8a1bc4429c45f87a2cd5a07d7",
"size": "368",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/irwi/comparators/spans/changed_span.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "49393"
}
],
"symlink_target": ""
} |
using base::android::AttachCurrentThread;
using base::android::ScopedJavaLocalRef;
namespace content {
namespace {
const char kObjectIsGone[] = "Java object is gone";
const char kMethodNotFound[] = "Method not found";
const char kAccessToObjectGetClassIsBlocked[] =
"Access to java.lang.Object.getClass is blocked";
const char kJavaExceptionRaised[] =
"Java exception has been raised during method invocation";
// See frameworks/base/core/java/android/webkit/EventLogTags.logtags
const int kObjectGetClassInvocationAttemptLogTag = 70151;
} // namespace
GinJavaMethodInvocationHelper::GinJavaMethodInvocationHelper(
scoped_ptr<ObjectDelegate> object,
const std::string& method_name,
const base::ListValue& arguments)
: object_(object.Pass()),
method_name_(method_name),
arguments_(arguments.DeepCopy()) {
}
GinJavaMethodInvocationHelper::~GinJavaMethodInvocationHelper() {}
void GinJavaMethodInvocationHelper::Init(DispatcherDelegate* dispatcher) {
// Build on the UI thread a map of object_id -> WeakRef for Java objects from
// |arguments_|. Then we can use this map on the background thread without
// accessing |dispatcher|.
BuildObjectRefsFromListValue(dispatcher, arguments_.get());
}
// As V8ValueConverter has finite recursion depth when serializing
// JavaScript values, we don't bother about having a recursion threshold here.
void GinJavaMethodInvocationHelper::BuildObjectRefsFromListValue(
DispatcherDelegate* dispatcher,
const base::Value* list_value) {
DCHECK(list_value->IsType(base::Value::TYPE_LIST));
const base::ListValue* list;
list_value->GetAsList(&list);
for (base::ListValue::const_iterator iter = list->begin();
iter != list->end();
++iter) {
if (AppendObjectRef(dispatcher, *iter))
continue;
if ((*iter)->IsType(base::Value::TYPE_LIST)) {
BuildObjectRefsFromListValue(dispatcher, *iter);
} else if ((*iter)->IsType(base::Value::TYPE_DICTIONARY)) {
BuildObjectRefsFromDictionaryValue(dispatcher, *iter);
}
}
}
void GinJavaMethodInvocationHelper::BuildObjectRefsFromDictionaryValue(
DispatcherDelegate* dispatcher,
const base::Value* dict_value) {
DCHECK(dict_value->IsType(base::Value::TYPE_DICTIONARY));
const base::DictionaryValue* dict;
dict_value->GetAsDictionary(&dict);
for (base::DictionaryValue::Iterator iter(*dict);
!iter.IsAtEnd();
iter.Advance()) {
if (AppendObjectRef(dispatcher, &iter.value()))
continue;
if (iter.value().IsType(base::Value::TYPE_LIST)) {
BuildObjectRefsFromListValue(dispatcher, &iter.value());
} else if (iter.value().IsType(base::Value::TYPE_DICTIONARY)) {
BuildObjectRefsFromDictionaryValue(dispatcher, &iter.value());
}
}
}
bool GinJavaMethodInvocationHelper::AppendObjectRef(
DispatcherDelegate* dispatcher,
const base::Value* raw_value) {
if (!GinJavaBridgeValue::ContainsGinJavaBridgeValue(raw_value))
return false;
scoped_ptr<const GinJavaBridgeValue> value(
GinJavaBridgeValue::FromValue(raw_value));
if (!value->IsType(GinJavaBridgeValue::TYPE_OBJECT_ID))
return false;
GinJavaBoundObject::ObjectID object_id;
if (value->GetAsObjectID(&object_id)) {
ObjectRefs::iterator iter = object_refs_.find(object_id);
if (iter == object_refs_.end()) {
JavaObjectWeakGlobalRef object_ref(
dispatcher->GetObjectWeakRef(object_id));
if (!object_ref.is_empty()) {
object_refs_.insert(std::make_pair(object_id, object_ref));
}
}
}
return true;
}
void GinJavaMethodInvocationHelper::Invoke() {
JNIEnv* env = AttachCurrentThread();
const JavaMethod* method =
object_->FindMethod(method_name_, arguments_->GetSize());
if (!method) {
SetInvocationFailure(kMethodNotFound);
return;
}
if (object_->IsObjectGetClassMethod(method)) {
base::android::EventLogWriteInt(kObjectGetClassInvocationAttemptLogTag,
getuid());
SetInvocationFailure(kAccessToObjectGetClassIsBlocked);
return;
}
ScopedJavaLocalRef<jobject> obj;
ScopedJavaLocalRef<jclass> cls;
if (method->is_static()) {
cls = object_->GetLocalClassRef(env);
} else {
obj = object_->GetLocalRef(env);
}
if (obj.is_null() && cls.is_null()) {
SetInvocationFailure(kObjectIsGone);
return;
}
std::vector<jvalue> parameters(method->num_parameters());
for (size_t i = 0; i < method->num_parameters(); ++i) {
const base::Value* argument;
arguments_->Get(i, &argument);
parameters[i] = CoerceJavaScriptValueToJavaValue(
env, argument, method->parameter_type(i), true, object_refs_);
}
if (method->is_static()) {
InvokeMethod(
NULL, cls.obj(), method->return_type(), method->id(), ¶meters[0]);
} else {
InvokeMethod(
obj.obj(), NULL, method->return_type(), method->id(), ¶meters[0]);
}
// Now that we're done with the jvalue, release any local references created
// by CoerceJavaScriptValueToJavaValue().
for (size_t i = 0; i < method->num_parameters(); ++i) {
ReleaseJavaValueIfRequired(env, ¶meters[i], method->parameter_type(i));
}
}
void GinJavaMethodInvocationHelper::SetInvocationFailure(
const char* error_message) {
holds_primitive_result_ = true;
primitive_result_.reset(new base::ListValue());
error_message_ = error_message;
}
void GinJavaMethodInvocationHelper::SetPrimitiveResult(
const base::ListValue& result_wrapper) {
holds_primitive_result_ = true;
primitive_result_.reset(result_wrapper.DeepCopy());
}
void GinJavaMethodInvocationHelper::SetObjectResult(
const base::android::JavaRef<jobject>& object,
const base::android::JavaRef<jclass>& safe_annotation_clazz) {
holds_primitive_result_ = false;
object_result_.Reset(object);
safe_annotation_clazz_.Reset(safe_annotation_clazz);
}
bool GinJavaMethodInvocationHelper::HoldsPrimitiveResult() {
return holds_primitive_result_;
}
const base::ListValue& GinJavaMethodInvocationHelper::GetPrimitiveResult() {
return *primitive_result_.get();
}
const base::android::JavaRef<jobject>&
GinJavaMethodInvocationHelper::GetObjectResult() {
return object_result_;
}
const base::android::JavaRef<jclass>&
GinJavaMethodInvocationHelper::GetSafeAnnotationClass() {
return safe_annotation_clazz_;
}
const std::string& GinJavaMethodInvocationHelper::GetErrorMessage() {
return error_message_;
}
void GinJavaMethodInvocationHelper::InvokeMethod(jobject object,
jclass clazz,
const JavaType& return_type,
jmethodID id,
jvalue* parameters) {
DCHECK(object || clazz);
JNIEnv* env = AttachCurrentThread();
base::ListValue result_wrapper;
switch (return_type.type) {
case JavaType::TypeBoolean:
result_wrapper.AppendBoolean(
object ? env->CallBooleanMethodA(object, id, parameters)
: env->CallStaticBooleanMethodA(clazz, id, parameters));
break;
case JavaType::TypeByte:
result_wrapper.AppendInteger(
object ? env->CallByteMethodA(object, id, parameters)
: env->CallStaticByteMethodA(clazz, id, parameters));
break;
case JavaType::TypeChar:
result_wrapper.AppendInteger(
object ? env->CallCharMethodA(object, id, parameters)
: env->CallStaticCharMethodA(clazz, id, parameters));
break;
case JavaType::TypeShort:
result_wrapper.AppendInteger(
object ? env->CallShortMethodA(object, id, parameters)
: env->CallStaticShortMethodA(clazz, id, parameters));
break;
case JavaType::TypeInt:
result_wrapper.AppendInteger(
object ? env->CallIntMethodA(object, id, parameters)
: env->CallStaticIntMethodA(clazz, id, parameters));
break;
case JavaType::TypeLong:
result_wrapper.AppendDouble(
object ? env->CallLongMethodA(object, id, parameters)
: env->CallStaticLongMethodA(clazz, id, parameters));
break;
case JavaType::TypeFloat: {
float result = object
? env->CallFloatMethodA(object, id, parameters)
: env->CallStaticFloatMethodA(clazz, id, parameters);
if (base::IsFinite(result)) {
result_wrapper.AppendDouble(result);
} else {
result_wrapper.Append(
GinJavaBridgeValue::CreateNonFiniteValue(result).release());
}
break;
}
case JavaType::TypeDouble: {
double result = object
? env->CallDoubleMethodA(object, id, parameters)
: env->CallStaticDoubleMethodA(clazz, id, parameters);
if (base::IsFinite(result)) {
result_wrapper.AppendDouble(result);
} else {
result_wrapper.Append(
GinJavaBridgeValue::CreateNonFiniteValue(result).release());
}
break;
}
case JavaType::TypeVoid:
if (object)
env->CallVoidMethodA(object, id, parameters);
else
env->CallStaticVoidMethodA(clazz, id, parameters);
result_wrapper.Append(
GinJavaBridgeValue::CreateUndefinedValue().release());
break;
case JavaType::TypeArray:
// LIVECONNECT_COMPLIANCE: Existing behavior is to not call methods that
// return arrays. Spec requires calling the method and converting the
// result to a JavaScript array.
result_wrapper.Append(
GinJavaBridgeValue::CreateUndefinedValue().release());
break;
case JavaType::TypeString: {
jstring java_string = static_cast<jstring>(
object ? env->CallObjectMethodA(object, id, parameters)
: env->CallStaticObjectMethodA(clazz, id, parameters));
// If an exception was raised, we must clear it before calling most JNI
// methods. ScopedJavaLocalRef is liable to make such calls, so we test
// first.
if (base::android::ClearException(env)) {
SetInvocationFailure(kJavaExceptionRaised);
return;
}
ScopedJavaLocalRef<jstring> scoped_java_string(env, java_string);
if (!scoped_java_string.obj()) {
// LIVECONNECT_COMPLIANCE: Existing behavior is to return undefined.
// Spec requires returning a null string.
result_wrapper.Append(
GinJavaBridgeValue::CreateUndefinedValue().release());
break;
}
result_wrapper.AppendString(
base::android::ConvertJavaStringToUTF8(scoped_java_string));
break;
}
case JavaType::TypeObject: {
// If an exception was raised, we must clear it before calling most JNI
// methods. ScopedJavaLocalRef is liable to make such calls, so we test
// first.
jobject java_object =
object ? env->CallObjectMethodA(object, id, parameters)
: env->CallStaticObjectMethodA(clazz, id, parameters);
if (base::android::ClearException(env)) {
SetInvocationFailure(kJavaExceptionRaised);
return;
}
ScopedJavaLocalRef<jobject> scoped_java_object(env, java_object);
if (!scoped_java_object.obj()) {
result_wrapper.Append(base::Value::CreateNullValue());
break;
}
SetObjectResult(scoped_java_object, object_->GetSafeAnnotationClass());
return;
}
}
// This is for all cases except JavaType::TypeObject.
if (!base::android::ClearException(env)) {
SetPrimitiveResult(result_wrapper);
} else {
SetInvocationFailure(kJavaExceptionRaised);
}
}
} // namespace content
| {
"content_hash": "2d28fe83d6dcd7623a86f6647d3ac168",
"timestamp": "",
"source": "github",
"line_count": 323,
"max_line_length": 80,
"avg_line_length": 36.303405572755416,
"alnum_prop": 0.6679174484052532,
"repo_name": "andykimpe/chromium-test-npapi",
"id": "d3fb138654424771076277aa52edf517c2dbf8f1",
"size": "12452",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "content/browser/renderer_host/java/gin_java_method_invocation_helper.cc",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Assembly",
"bytes": "24741"
},
{
"name": "Batchfile",
"bytes": "6704"
},
{
"name": "C",
"bytes": "3578395"
},
{
"name": "C++",
"bytes": "197882186"
},
{
"name": "CSS",
"bytes": "774304"
},
{
"name": "HTML",
"bytes": "16781925"
},
{
"name": "Java",
"bytes": "5176812"
},
{
"name": "JavaScript",
"bytes": "9838003"
},
{
"name": "Makefile",
"bytes": "36405"
},
{
"name": "Objective-C",
"bytes": "1135377"
},
{
"name": "Objective-C++",
"bytes": "7082902"
},
{
"name": "PLpgSQL",
"bytes": "141320"
},
{
"name": "Perl",
"bytes": "69392"
},
{
"name": "Protocol Buffer",
"bytes": "360984"
},
{
"name": "Python",
"bytes": "5577847"
},
{
"name": "Rebol",
"bytes": "262"
},
{
"name": "Shell",
"bytes": "434741"
},
{
"name": "Standard ML",
"bytes": "1589"
},
{
"name": "nesC",
"bytes": "15206"
}
],
"symlink_target": ""
} |
[PostCSS]: https://github.com/postcss/postcss
[ci-img]: https://travis-ci.org/markgoodyear/postcss-pointer.svg?branch=master
[ci]: https://travis-ci.org/markgoodyear/postcss-pointer
A [PostCSS] plugin to replace `pointer: cursor` with `cursor: pointer`.
## Why?
Because of this Tweet: https://twitter.com/_dte/status/613396433748692992
## Example
Input:
```css
.elem {
pointer: cursor;
}
```
Output:
```css
.elem {
cursor: pointer;
}
```
## Usage
Install:
```
npm install postcss-pointer --save-dev
```
Then include the plugin:
```js
postcss([ require('postcss-pointer')(options) ])
```
See [PostCSS] docs for examples for your environment.
## Licence
Released under the MIT license.
| {
"content_hash": "147bfe66421bfbe778faa1813d1cc730",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 79,
"avg_line_length": 18.025641025641026,
"alnum_prop": 0.6984352773826458,
"repo_name": "markgoodyear/postcss-pointer",
"id": "6b5a715e0f4fd276cd0871e83561116853ea3c16",
"size": "751",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1350"
}
],
"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("WAADJwT-Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WAADJwT-Client")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("f62ca598-0ead-4e3c-b979-82cb3b10169e")]
// 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": "a31ab255c81ceaae79ef8426d7b04678",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 38.916666666666664,
"alnum_prop": 0.7444682369735903,
"repo_name": "matvelloso/AADNodeJWT",
"id": "9e6d346e34e7be68025e39c9752e3639e2c2d199",
"size": "1404",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "V2/WAADJwT-Client/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "4781"
},
{
"name": "CSS",
"bytes": "57526"
},
{
"name": "HTML",
"bytes": "75223"
},
{
"name": "JavaScript",
"bytes": "27567"
}
],
"symlink_target": ""
} |
class A {async foo(await) { }}; | {
"content_hash": "6b8f3e606a39510723be7c2c155fce30",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 31,
"avg_line_length": 31,
"alnum_prop": 0.6129032258064516,
"repo_name": "eslint/espree",
"id": "dac6531dbad4610f578a66475a94e07f81740ab5",
"size": "31",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "tests/fixtures/ecma-version/8/modules/invalid-async-method-await-param.src.js",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "JavaScript",
"bytes": "100083"
}
],
"symlink_target": ""
} |
package li.strolch.utils.collections;
import static li.strolch.utils.collections.SynchronizedCollections.synchronizedMapOfMaps;
import static org.junit.Assert.*;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SynchronizedMapOfMapsTest {
private static final Logger logger = LoggerFactory.getLogger(SynchronizedMapOfMapsTest.class);
private ExecutorService executorService;
@Before
public void before() {
this.executorService = Executors.newCachedThreadPool();
}
@Test
public void shouldForEach() throws ExecutionException, InterruptedException {
MapOfMaps<String, String, String> mapOfMaps = buildMapOfMaps();
AtomicBoolean run = new AtomicBoolean(false);
Callable<Boolean> addTask = () -> addToMap(mapOfMaps, run);
Callable<Boolean> iterateTask = () -> {
for (; ; ) {
if (run.get())
break;
}
while (run.get()) {
mapOfMaps.forEach(
(s, subTypeMap) -> subTypeMap.forEach((s1, s2) -> logger.info(s + " " + s1 + " " + s2)));
mapOfMaps.getMap("Resource").forEach((s1, s2) -> logger.info(" " + s1 + " " + s2));
}
return true;
};
runTest(addTask, iterateTask, run);
}
@Test
public void shouldIterate() throws ExecutionException, InterruptedException {
MapOfMaps<String, String, String> mapOfMaps = buildMapOfMaps();
AtomicBoolean run = new AtomicBoolean(false);
Callable<Boolean> addTask = () -> addToMap(mapOfMaps, run);
Callable<Boolean> iterateTask = () -> {
for (; ; ) {
if (run.get())
break;
}
while (run.get()) {
Set<String> types = mapOfMaps.keySet();
for (String type : types) {
Map<String, String> subTypeMap = mapOfMaps.getMap(type);
Set<String> subTypes = subTypeMap.keySet();
synchronized (mapOfMaps) {
for (String subType : subTypes) {
logger.info(type + " " + subType + " " + mapOfMaps.getElement(type, subType));
}
}
}
synchronized (mapOfMaps) {
Map<String, String> resources = mapOfMaps.getMap("Resource");
for (String value : resources.values()) {
logger.info("Resource: value: " + value);
}
}
}
return true;
};
runTest(addTask, iterateTask, run);
}
private void runTest(Callable<Boolean> addTask, Callable<Boolean> iterateTask, AtomicBoolean run)
throws InterruptedException, ExecutionException {
Future<Boolean> task0 = this.executorService.submit(addTask);
Future<Boolean> task1 = this.executorService.submit(iterateTask);
Future<Boolean> task2 = this.executorService.submit(iterateTask);
Future<Boolean> task3 = this.executorService.submit(iterateTask);
Future<Boolean> task4 = this.executorService.submit(iterateTask);
Future<Boolean> task5 = this.executorService.submit(iterateTask);
run.set(true);
Thread.sleep(20L);
run.set(false);
Boolean result0 = task0.get();
Boolean result1 = task1.get();
Boolean result2 = task2.get();
Boolean result3 = task3.get();
Boolean result4 = task4.get();
Boolean result5 = task5.get();
assertTrue(result0);
assertTrue(result1);
assertTrue(result2);
assertTrue(result3);
assertTrue(result4);
assertTrue(result5);
}
private Boolean addToMap(MapOfMaps<String, String, String> mapOfMaps, AtomicBoolean run) {
for (; ; ) {
if (run.get())
break;
}
while (run.get()) {
addElement(mapOfMaps, "Resource", "Ball", UUID.randomUUID().toString());
addElement(mapOfMaps, "Resource", "Car", UUID.randomUUID().toString());
addElement(mapOfMaps, "Order", "StockOrder", UUID.randomUUID().toString());
addElement(mapOfMaps, "Order", "ToStock", UUID.randomUUID().toString());
addElement(mapOfMaps, "Order", "FromStock", UUID.randomUUID().toString());
addElement(mapOfMaps, "Activity", "FromStock", UUID.randomUUID().toString());
addElement(mapOfMaps, "Activity", "ToStock", UUID.randomUUID().toString());
mapOfMaps.removeElement("Resource", "Ball");
mapOfMaps.removeElement("Order", "ToStock");
mapOfMaps.removeElement("Activity", "ToStock");
}
return true;
}
private void addElement(MapOfMaps<String, String, String> mapOfMaps, String type, String subType, String id) {
//logger.info("Adding " + type + " " + subType + " " + id);
mapOfMaps.addElement(type, subType, id);
}
private MapOfMaps<String, String, String> buildMapOfMaps() {
MapOfMaps<String, String, String> mapOfMaps = synchronizedMapOfMaps(new MapOfMaps<>(true));
mapOfMaps.addElement("Resource", "Ball", "yellow");
mapOfMaps.addElement("Resource", "Car", "car1");
mapOfMaps.addElement("Order", "StockOrder", "stockOrder1");
mapOfMaps.addElement("Order", "ToStock", "toStock1");
mapOfMaps.addElement("Order", "FromStock", "fromStock1");
mapOfMaps.addElement("Activity", "FromStock", "fromStock1");
mapOfMaps.addElement("Activity", "ToStock", "toStock1");
assertEquals("yellow", mapOfMaps.getElement("Resource", "Ball"));
assertNull(mapOfMaps.getMap("xxx"));
return mapOfMaps;
}
}
| {
"content_hash": "58a79c619c047e0e1dda36996d5f643e",
"timestamp": "",
"source": "github",
"line_count": 162,
"max_line_length": 111,
"avg_line_length": 31.666666666666668,
"alnum_prop": 0.6953216374269006,
"repo_name": "4treesCH/strolch",
"id": "13e3dee950e7bc16f1137149bdcb6efc7e79c503",
"size": "5130",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "li.strolch.utils/src/test/java/li/strolch/utils/collections/SynchronizedMapOfMapsTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "2003"
},
{
"name": "CSS",
"bytes": "2486"
},
{
"name": "HTML",
"bytes": "383752"
},
{
"name": "Java",
"bytes": "4122045"
},
{
"name": "JavaScript",
"bytes": "2831"
},
{
"name": "PLSQL",
"bytes": "3323"
},
{
"name": "Shell",
"bytes": "14167"
},
{
"name": "Smarty",
"bytes": "878"
},
{
"name": "TSQL",
"bytes": "29111"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.apigateway.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.apigateway.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* GetStageResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetStageResultJsonUnmarshaller implements Unmarshaller<GetStageResult, JsonUnmarshallerContext> {
public GetStageResult unmarshall(JsonUnmarshallerContext context) throws Exception {
GetStageResult getStageResult = new GetStageResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return getStageResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("deploymentId", targetDepth)) {
context.nextToken();
getStageResult.setDeploymentId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("clientCertificateId", targetDepth)) {
context.nextToken();
getStageResult.setClientCertificateId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("stageName", targetDepth)) {
context.nextToken();
getStageResult.setStageName(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("description", targetDepth)) {
context.nextToken();
getStageResult.setDescription(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("cacheClusterEnabled", targetDepth)) {
context.nextToken();
getStageResult.setCacheClusterEnabled(context.getUnmarshaller(Boolean.class).unmarshall(context));
}
if (context.testExpression("cacheClusterSize", targetDepth)) {
context.nextToken();
getStageResult.setCacheClusterSize(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("cacheClusterStatus", targetDepth)) {
context.nextToken();
getStageResult.setCacheClusterStatus(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("methodSettings", targetDepth)) {
context.nextToken();
getStageResult.setMethodSettings(new MapUnmarshaller<String, MethodSetting>(context.getUnmarshaller(String.class),
MethodSettingJsonUnmarshaller.getInstance()).unmarshall(context));
}
if (context.testExpression("variables", targetDepth)) {
context.nextToken();
getStageResult.setVariables(new MapUnmarshaller<String, String>(context.getUnmarshaller(String.class), context
.getUnmarshaller(String.class)).unmarshall(context));
}
if (context.testExpression("documentationVersion", targetDepth)) {
context.nextToken();
getStageResult.setDocumentationVersion(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("accessLogSettings", targetDepth)) {
context.nextToken();
getStageResult.setAccessLogSettings(AccessLogSettingsJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("canarySettings", targetDepth)) {
context.nextToken();
getStageResult.setCanarySettings(CanarySettingsJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("tracingEnabled", targetDepth)) {
context.nextToken();
getStageResult.setTracingEnabled(context.getUnmarshaller(Boolean.class).unmarshall(context));
}
if (context.testExpression("webAclArn", targetDepth)) {
context.nextToken();
getStageResult.setWebAclArn(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("tags", targetDepth)) {
context.nextToken();
getStageResult.setTags(new MapUnmarshaller<String, String>(context.getUnmarshaller(String.class), context.getUnmarshaller(String.class))
.unmarshall(context));
}
if (context.testExpression("createdDate", targetDepth)) {
context.nextToken();
getStageResult.setCreatedDate(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
}
if (context.testExpression("lastUpdatedDate", targetDepth)) {
context.nextToken();
getStageResult.setLastUpdatedDate(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return getStageResult;
}
private static GetStageResultJsonUnmarshaller instance;
public static GetStageResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new GetStageResultJsonUnmarshaller();
return instance;
}
}
| {
"content_hash": "f97f798023afc0a50ca27dbb864d4ea9",
"timestamp": "",
"source": "github",
"line_count": 130,
"max_line_length": 156,
"avg_line_length": 50.2,
"alnum_prop": 0.6089488201041986,
"repo_name": "aws/aws-sdk-java",
"id": "4f1a0a44e13203e5be0de3ceb2b05fd4b28293f0",
"size": "7106",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/transform/GetStageResultJsonUnmarshaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
REGION = 'eu-west-1'
PROFILE_NAME = 'InstanceLister'
TERMINAL = 'xfce4-terminal -H'
SSH_CERTIFICATE = ['/home/lorenzo/.certificates/david-1.pem', '/home/lorenzo/.certificates/david-1-pocket-sell-app.pem']
UPDATE_COMMAND = ' && '.join([
'sudo apt-get update',
'sudo apt-get upgrade',
'sudo apt-get clean',
'sudo apt-get autoclean',
'sudo apt-get autoremove',
'if [ -f /var/run/reboot-required ]; then echo; echo "=== SYSTEM REBOOT REQUIRED! ==="; read -p "Do you want to reboot now (y|n)? " -r; if [[ $REPLY =~ ^[Yy] ]]; then sudo shutdown -r now; fi; echo; fi',
'bash'
])
###
import os
import subprocess
from boto import ec2
from colorama import Fore, Back, Style
execfile(os.path.abspath(os.path.dirname(__file__)) + '/commons.py')
printTitle('EC2 INSTANCES UPDATE', 'Runs apt-get to update instances, excluding ones with tag NoUpdate=1')
print
connection = ec2.connect_to_region(REGION, profile_name = PROFILE_NAME)
# Ask which instances
instances = []
for instance in connection.get_only_instances():
if instance.state == 'running' and instance.tags.get('NoUpdate', '0') != '1' and instance.platform != 'windows':
instance_name = instance.tags.get('Name', '(no name)')
if questionYN('Do you want to update instance ' + Style.BRIGHT + '{}' + Style.RESET_ALL + ' ({})', instance_name, instance.id):
instances.append({ 'instance': instance, 'instance_name': instance_name })
if len(instances) > 0:
# Escape command
UPDATE_COMMAND = UPDATE_COMMAND.replace("\\", "\\\\").replace("'", "'\\''").replace('"', '\\"')
# SSH certificates
certificates = (SSH_CERTIFICATE if isinstance(SSH_CERTIFICATE, list) else [SSH_CERTIFICATE])
certificates_command = ' '.join(['-i "' + path + '"' for path in certificates])
# Start SSH on instances
for instance in instances:
instance_dns = instance['instance'].public_dns_name
instance_ip = instance['instance'].ip_address.strip()
terminal_title = instance['instance_name'] + ' UPDATE (' + (instance_ip or instance_dns) + ')'
subprocess.call(TERMINAL + ' --title="' + terminal_title + '" --command=\'ssh -t ' + certificates_command + ' ubuntu@' + (instance_ip or instance_dns) + ' "' + UPDATE_COMMAND + '"\'', shell=True)
| {
"content_hash": "693c0a09526c968519a1488ef48c2068",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 204,
"avg_line_length": 43.07843137254902,
"alnum_prop": 0.6718252162039144,
"repo_name": "lorenzos/AWSInteractiveUtils",
"id": "7c410f1fa3c2068ef09df6b3df6884a5ac390eaf",
"size": "2397",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "update_servers.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "9178"
}
],
"symlink_target": ""
} |
package com.tesshu.subsonic.client.fx.command.logic;
import com.tesshu.subsonic.client.fx.command.InitializeComponentWithParamLogic;
import com.tesshu.subsonic.client.fx.command.param.SimpleObjectParam;
import com.tesshu.subsonic.client.fx.view.annotation.ChronoContainer;
import com.tesshu.subsonic.client.model.MusicFolder;
public interface InitializeChronoContainerLogic
extends InitializeComponentWithParamLogic<ChronoContainer, SimpleObjectParam<MusicFolder>> {
}
| {
"content_hash": "9f1e7e17c09845c855fb9bd4f43209f3",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 96,
"avg_line_length": 39.75,
"alnum_prop": 0.8553459119496856,
"repo_name": "tesshucom/subsonic-fx-player",
"id": "ae828675fb3f282efdb1801b9e518bd4b9aad009",
"size": "1097",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "subsonic-fx-player-api/src/main/java/com/tesshu/subsonic/client/fx/command/logic/InitializeChronoContainerLogic.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "37252"
},
{
"name": "Java",
"bytes": "1130820"
}
],
"symlink_target": ""
} |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome to CodeIgniter</title>
<style type="text/css">
::selection { background-color: #E13300; color: white; }
::-moz-selection { background-color: #E13300; color: white; }
body {
background-color: #fff;
margin: 40px;
font: 13px/20px normal Helvetica, Arial, sans-serif;
color: #4F5155;
}
a {
color: #003399;
background-color: transparent;
font-weight: normal;
}
h1 {
color: #444;
background-color: transparent;
border-bottom: 1px solid #D0D0D0;
font-size: 19px;
font-weight: normal;
margin: 0 0 14px 0;
padding: 14px 15px 10px 15px;
}
code {
font-family: Consolas, Monaco, Courier New, Courier, monospace;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
#body {
margin: 0 15px 0 15px;
}
p.footer {
text-align: right;
font-size: 11px;
border-top: 1px solid #D0D0D0;
line-height: 32px;
padding: 0 10px 0 10px;
margin: 20px 0 0 0;
}
#container {
margin: 10px;
border: 1px solid #D0D0D0;
box-shadow: 0 0 8px #D0D0D0;
}
</style>
</head>
<body>
<div id="container">
<h1>Bienvenido to CodeIgniter!</h1>
<div id="body">
<p>The page you are looking at is being generated dynamically by CodeIgniter.</p>
<p>If you would like to edit this page you'll find it located at:</p>
<code>application/views/welcome_message.php</code>
<p>The corresponding controller for this page is found at:</p>
<code>application/controllers/Welcome.php</code>
<p>If you are exploring CodeIgniter for the very first time, you should start by reading the <a href="user_guide/">User Guide</a>.</p>
</div>
<p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds. <?php echo (ENVIRONMENT === 'development') ? 'CodeIgniter Version <strong>' . CI_VERSION . '</strong>' : '' ?></p>
</div>
</body>
</html> | {
"content_hash": "471021bc057057e14e3a00fcaffd4b7f",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 193,
"avg_line_length": 23.078651685393258,
"alnum_prop": 0.6699123661148978,
"repo_name": "pniebla/test-repo-console",
"id": "faff3d32d49382a617c4939df69febb6dfcdb102",
"size": "2054",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/views/welcome_message2.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "2095"
},
{
"name": "C",
"bytes": "4638094"
},
{
"name": "C++",
"bytes": "225573"
},
{
"name": "CSS",
"bytes": "810198"
},
{
"name": "Emacs Lisp",
"bytes": "86984"
},
{
"name": "Go",
"bytes": "15064"
},
{
"name": "Groff",
"bytes": "26859"
},
{
"name": "HTML",
"bytes": "5436579"
},
{
"name": "JavaScript",
"bytes": "1533072"
},
{
"name": "Makefile",
"bytes": "112078"
},
{
"name": "Objective-C",
"bytes": "504"
},
{
"name": "PHP",
"bytes": "2152692"
},
{
"name": "Perl",
"bytes": "1099544"
},
{
"name": "Python",
"bytes": "297820"
},
{
"name": "Shell",
"bytes": "3606350"
},
{
"name": "Tcl",
"bytes": "751684"
}
],
"symlink_target": ""
} |
"""Contains utilities for downloading and converting datasets."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import tarfile
from six.moves import urllib
import tensorflow as tf
LABELS_FILENAME = 'labels.txt'
def int64_feature(value):
"""Wrapper for inserting int64 features into Example proto.
"""
if not isinstance(value, list):
value = [value]
return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
def float_feature(value):
"""Wrapper for inserting float features into Example proto.
"""
if not isinstance(value, list):
value = [value]
return tf.train.Feature(float_list=tf.train.FloatList(value=value))
def bytes_feature(value):
"""Wrapper for inserting bytes features into Example proto.
"""
if not isinstance(value, list):
value = [value]
return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))
def image_to_tfexample(image_data, image_format, height, width, class_id):
return tf.train.Example(features=tf.train.Features(feature={
'image/encoded': bytes_feature(image_data),
'image/format': bytes_feature(image_format),
'image/class/label': int64_feature(class_id),
'image/height': int64_feature(height),
'image/width': int64_feature(width),
}))
def download_and_uncompress_tarball(tarball_url, dataset_dir):
"""Downloads the `tarball_url` and uncompresses it locally.
Args:
tarball_url: The URL of a tarball file.
dataset_dir: The directory where the temporary files are stored.
"""
filename = tarball_url.split('/')[-1]
filepath = os.path.join(dataset_dir, filename)
def _progress(count, block_size, total_size):
sys.stdout.write('\r>> Downloading %s %.1f%%' % (
filename, float(count * block_size) / float(total_size) * 100.0))
sys.stdout.flush()
filepath, _ = urllib.request.urlretrieve(tarball_url, filepath, _progress)
print()
statinfo = os.stat(filepath)
print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')
tarfile.open(filepath, 'r:gz').extractall(dataset_dir)
def write_label_file(labels_to_class_names, dataset_dir,
filename=LABELS_FILENAME):
"""Writes a file with the list of class names.
Args:
labels_to_class_names: A map of (integer) labels to class names.
dataset_dir: The directory in which the labels file should be written.
filename: The filename where the class names are written.
"""
labels_filename = os.path.join(dataset_dir, filename)
with tf.gfile.Open(labels_filename, 'w') as f:
for label in labels_to_class_names:
class_name = labels_to_class_names[label]
f.write('%d:%s\n' % (label, class_name))
def has_labels(dataset_dir, filename=LABELS_FILENAME):
"""Specifies whether or not the dataset directory contains a label map file.
Args:
dataset_dir: The directory in which the labels file is found.
filename: The filename where the class names are written.
Returns:
`True` if the labels file exists and `False` otherwise.
"""
return tf.gfile.Exists(os.path.join(dataset_dir, filename))
def read_label_file(dataset_dir, filename=LABELS_FILENAME):
"""Reads the labels file and returns a mapping from ID to class name.
Args:
dataset_dir: The directory in which the labels file is found.
filename: The filename where the class names are written.
Returns:
A map from a label (integer) to class name.
"""
labels_filename = os.path.join(dataset_dir, filename)
with tf.gfile.Open(labels_filename, 'rb') as f:
lines = f.read()
lines = lines.split(b'\n')
lines = filter(None, lines)
labels_to_class_names = {}
for line in lines:
index = line.index(b':')
labels_to_class_names[int(line[:index])] = line[index+1:]
return labels_to_class_names | {
"content_hash": "f648c0dc464f44909fc8d4cf2437717d",
"timestamp": "",
"source": "github",
"line_count": 114,
"max_line_length": 80,
"avg_line_length": 35.08771929824562,
"alnum_prop": 0.67625,
"repo_name": "nghiattran/self-steering",
"id": "79ad75196c97f6a8398426a06528cd8ed14f51b7",
"size": "4689",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "data_utils.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "49272"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace Sonata\Component\Product;
interface DeliveryInterface
{
/**
* Set product.
*/
public function setProduct(ProductInterface $product);
/**
* Get product.
*
* @return ProductInterface
*/
public function getProduct();
/**
* Set class_name.
*
* @param string $code
*/
public function setCode($code);
/**
* Get class_name.
*
* @return string $className
*/
public function getCode();
/**
* Set per_item.
*
* @param bool $perItem
*/
public function setPerItem($perItem);
/**
* Get per_item.
*
* @return bool $perItem
*/
public function getPerItem();
/**
* Set country code.
*
* @param string $countryCode
*/
public function setCountryCode($countryCode);
/**
* Get country.
*
* @return string $country
*/
public function getCountryCode();
/**
* Set zone.
*
* @param string $zone
*/
public function setZone($zone);
/**
* Get zone.
*
* @return string $zone
*/
public function getZone();
/**
* Set enabled.
*
* @param bool $enabled
*/
public function setEnabled($enabled);
/**
* Get enabled.
*
* @return bool $enabled
*/
public function getEnabled();
/**
* Set updatedAt.
*
* @param \Datetime $updatedAt
*/
public function setUpdatedAt(?\DateTime $updatedAt = null);
/**
* Get updatedAt.
*
* @return \Datetime $updatedAt
*/
public function getUpdatedAt();
/**
* Set createdAt.
*
* @param \Datetime $createdAt
*/
public function setCreatedAt(?\DateTime $createdAt = null);
/**
* Get createdAt.
*
* @return \Datetime $createdAt
*/
public function getCreatedAt();
/**
* Returns Delivery base data as an array.
*
* @return array
*/
public function toArray();
/**
* Populate entity from an array.
*
* @param array $array
*/
public function fromArray($array);
}
| {
"content_hash": "8014503294a247ac2478a850e7e27a09",
"timestamp": "",
"source": "github",
"line_count": 134,
"max_line_length": 63,
"avg_line_length": 16.425373134328357,
"alnum_prop": 0.5238527941844616,
"repo_name": "sonata-project/ecommerce",
"id": "5414653d2307bc4ad0e71dbc6690a14839e49b4f",
"size": "2448",
"binary": false,
"copies": "1",
"ref": "refs/heads/3.x",
"path": "src/Component/Product/DeliveryInterface.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "921"
},
{
"name": "HTML",
"bytes": "123098"
},
{
"name": "JavaScript",
"bytes": "4012"
},
{
"name": "Makefile",
"bytes": "1475"
},
{
"name": "PHP",
"bytes": "1303179"
},
{
"name": "Shell",
"bytes": "1097"
}
],
"symlink_target": ""
} |
package org.softuni;
import java.util.Arrays;
import java.util.Scanner;
public class _01_SortArrayNumbers {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numberCount = in.nextInt();
int[] numberArray = new int[numberCount];
for (int i = 0; i < numberCount; i++) {
numberArray[i] = in.nextInt();
}
Arrays.sort(numberArray);
Arrays.stream(numberArray).forEachOrdered(number -> System.out.printf("%d ", number));
}
}
| {
"content_hash": "251a17b5091728b8d2458c8102af6f06",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 94,
"avg_line_length": 26.55,
"alnum_prop": 0.6139359698681732,
"repo_name": "sholev/SoftUni",
"id": "4d2ea7a935585f6ac63ae5265bf0f63917cf8939",
"size": "531",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Fundamentals-2.0/JavaFundamentals/Homework/JavaCollections/src/org/softuni/_01_SortArrayNumbers.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1570212"
},
{
"name": "HTML",
"bytes": "600"
},
{
"name": "Java",
"bytes": "350008"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
Mascagnia amazonica Nied.
### Remarks
null | {
"content_hash": "a88778efa5669daa42abf44e866d893e",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 11.307692307692308,
"alnum_prop": 0.7278911564625851,
"repo_name": "mdoering/backbone",
"id": "95c0c9086f636edc4dd36784ad6627bbd0db9f68",
"size": "210",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Malpighiaceae/Amorimia/Amorimia amazonica/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
\pageId{usecases}
There are a healthy number of tools which have functionality related to SnuggleTeX,
which can make it hard to decide which tool bits fits your given requirements.
Like all tools, SnuggleTeX has its relative strengths and weaknesses that you
should consider:
\begin{itemize}
\item
SnuggleTeX was originally developed to support our
\href[Aardvark Content Management System]{http://www.ph.ed.ac.uk/elearning/projects/aardvark/}
in order to facilitate the conversion of fragments of LaTeX written by
academics into XML tree branches. Another example of this type of use
might be a kind of LaTeX-based Wiki, where SnuggleTeX could be plugged in and
used at some point in the LaTeX to XHTML conversion pipeline.
\item
SnuggleTeX is 100\% Java with minimal (usually no) dependencies on
other libraries so can be easily integrated into a Java software
development project as a library for converting LaTeX to XML.
\item
SnuggleTeX can also be used to generate
\href[``legacy'' web pages]{docs://legacyWebPages}
where mathematical formulae are represented by HTML + CSS (if suitably
simple) and/or images. (This uses the open-source
\href[JEuclid]{http://jeuclid.sourceforge.net} library.)
\item
SnuggleTeX was \emph{not} intended to be a standalone tool that you
could throw complete LaTeX documents at and have them converted into web
pages. Other tools do this type of thing very well, such as
\href[TeX4ht]{http://www.cse.ohio-state.edu/~gurari/TeX4ht/}.
\item
SnuggleTeX supports a pragmatic subset of LaTeX but does not include anything
that is particularly paper- or page-specific. It also currently doesn't
do cross-referencing or numbering as it could be argued that this is better
done at a higher level. Other tools might therefore be a better fit for these
types of requirements.
\item
SnuggleTeX's parser pretends that TeX never happened and may behave slightly
differently to what experienced LaTeX users might expect. Alternatively,
novice LaTeX users will not notice any difference and might actually find the
error messages provided here more helpful!
\item
SnuggleTeX's web page outputs are highly configurable and make it relatively
easy to create MathML-enabled pages that will work across a range of
browser platforms. Hooks are available to customise the web page outputs to
more exacting requirements; these require a knowledge of XSLT.
\item
The new (and slightly experimental) features introduced in SnuggleTeX 1.1.0
for converting LaTeX to Content MathML and Maxima were added for the
\href[JISC MathAssess Project]{http://mathassess.ecs.soton.ac.uk/}
in order to ``understand'' responses made by students to test questions. These
features might have applications for similar projects.
\item
A quick summary on the types of problem that SnuggleTeX (and related
packages) attempt to address can be found in some
\href[slides on conversion of Mathematical Content]{http://physics-elearning.blogspot.com/2009/10/some-slides-on-conversion-of.html}.
\end{itemize}
| {
"content_hash": "299f951788f79075c4ab2a5c38f8a27a",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 135,
"avg_line_length": 46.04477611940298,
"alnum_prop": 0.7834683954619125,
"repo_name": "kduske-n4/snuggletex",
"id": "68795a05240cae2510129e98183877af5c94feff",
"size": "3085",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "snuggletex-webapp/src/main/webapp/WEB-INF/docs/use-cases.tex",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "14653"
},
{
"name": "Java",
"bytes": "1113418"
},
{
"name": "JavaScript",
"bytes": "68568"
},
{
"name": "TeX",
"bytes": "381581"
},
{
"name": "XSLT",
"bytes": "287838"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ngClassifieds</title>
<link rel="stylesheet" href="node_modules/angular-material/angular-material.css">
<link rel="stylesheet" href="node_modules/mdi/css/materialdesignicons.min.css" media="all" type="text/css">
<link rel="stylesheet" href="css/style.css">
</head>
<body ng-app="ngClassifieds" ng-controller='classifiedsCtrl'>
<md-toolbar>
<div class="md-toolbar-tools">
<p>
<stront>ngClassifieds</stront>
</p>
<md-button ng-click="openSidebar()">
<md-icon class="mdi mdi-plus-circle"></md-icon>
New Classified
</md-button>
</div>
</md-toolbar>
<md-sidenav class="md-sidenav-left md-whiteframe-z2" md-component-id="left">
<md-toolbar>
<h1 class="md-toolbar-tools">Add a Classifieds</h1>
</md-toolbar>
<md-content layout-padding>
<form action="">
<md-input-container>
<label for="title">Title</label>
<input type="text" id="title" ng-model="classified.title" md-autofocus/>
</md-input-container>
<md-input-container>
<label for="price">Price</label>
<input type="text" id="price" ng-model="classified.price"/>
</md-input-container>
<md-input-container>
<label for="desciption">Description</label>
<textarea type="textarea" id="description" ng-model="classified.description"></textarea>
</md-input-container>
<md-input-container>
<label for="image">Image Link</label>
<input type="text" id="image" ng-model="classified.image" />
</md-input-container>
<md-button ng-if="!editing" class="md-primary" ng-click="saveClassified(classified)">Save</md-button>
<md-button ng-click="saveEdit()" ng-if="editing" class="md-primary">Save Edit</md-button>
<md-button class="md-warn" ng-click="closeSidebar()">Cancel</md-button>
<pre>{{ classified | json }}</pre>
</form>
</md-content>
</md-sidenav>
<md-content class="md-padding" layout="row" layout-wrap>
<md-card ng-repeat="classified in classifieds" flex="30">
<img ng-src={{classified.image}} alt="">
<md-card-content>
<div class="classified-info" ng-show="!showContact">
<h2 class="md-title">{{classified.title}}</h2>
<h2>{{classified.posted | date}}</h2>
<h3>{{classified.price | currency}}</h3>
<p>{{classified.description}}</p>
<!-- <pre>{{classified | json}}</pre> -->
</div>
</md-card-content>
<div class="classified-contact" ng-show="showContact">
<p><md-icon class="mdi mdi-account"></md-icon>{{classified.contact.name}}</p>
<p><md-icon class="mdi mdi-phone"></md-icon>{{classified.contact.phone}}</p>
<p><md-icon class="mdi mdi-email"></md-icon>{{classified.contact.email}}</p>
</div>
<div layout="row">
<md-button ng-show="!showContact" ng-click="showContact = true">Contact</md-button>
<md-button ng-show="showContact" ng-click="showContact = false">Details</md-button>
<md-button ng-show="!showAdmin" ng-click="showAdmin = true">Admin</md-button>
<md-button ng-show="showAdmin" ng-click="showAdmin = false">Close</md-button>
</div>
<div class="classified-admin" ng-if="showAdmin">
<h3>Admin</h3>
<div layout="row">
<md-button ng-click="editClassified(classified)" class="md-primary">Edit</md-button>
<md-button ng-click="deleteClassified($event, classified)" class="md-warn">Delete</md-button>
</div>
</div>
</md-card>
</md-content>
<script src="node_modules/angular/angular.js"></script>
<script src="node_modules/angular-animate/angular-animate.min.js"></script>
<script src="node_modules/angular-aria/angular-aria.min.js"></script>
<script src="node_modules/angular-material/angular-material.min.js"></script>
<script src="scripts/app.js"></script>
<script src="components/classifieds.ctr.js"></script>
<script src="components/classifieds.fac.js"></script>
</body>
</html> | {
"content_hash": "be82aced86ef964ffc8804d38cc76f38",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 109,
"avg_line_length": 37.640776699029125,
"alnum_prop": 0.6615940159917462,
"repo_name": "yoavgecht/yoavgecht.github.io",
"id": "e7ac54587cb100fee2bc31c046b06d95a20f64f7",
"size": "3877",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "classifieds/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12723"
},
{
"name": "HTML",
"bytes": "17548"
},
{
"name": "JavaScript",
"bytes": "4596"
}
],
"symlink_target": ""
} |
<aside class="menu" *ngIf="menu" style="height: 100%; overflow-y: auto">
<div *ngFor="let item of menu.items">
<div class="menu-label">{{item.name}}</div>
<ul class="menu-list">
<li *ngFor="let child of item.items">
<a [routerLink]="child.url" routerLinkActive="is-active">{{child.name}}</a>
</li>
</ul>
</div>
</aside> | {
"content_hash": "4fe71154dedfde2ed051596f144cd524",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 85,
"avg_line_length": 36.7,
"alnum_prop": 0.5694822888283378,
"repo_name": "akhellas/iris2",
"id": "727acd45a4612ee8ce5d03689ff26e43076b91c7",
"size": "367",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/src/app/core/sidenav/sidenav.component.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1076"
},
{
"name": "HTML",
"bytes": "5986"
},
{
"name": "JavaScript",
"bytes": "1645"
},
{
"name": "TypeScript",
"bytes": "26716"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="utf-8" />
<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 rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700%7CRoboto+Mono:400,500,700&display=fallback">
<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.genmod.families.links.CDFLink.deriv2 — 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/material.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/language_data.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/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.genmod.families.links.CDFLink.inverse" href="statsmodels.genmod.families.links.CDFLink.inverse.html" />
<link rel="prev" title="statsmodels.genmod.families.links.CDFLink.deriv" href="statsmodels.genmod.families.links.CDFLink.deriv.html" />
<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>
</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.genmod.families.links.CDFLink.deriv2" 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 0.11.0</span>
<span class="md-header-nav__topic"> statsmodels.genmod.families.links.CDFLink.deriv2 </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>
</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="../glm.html" class="md-tabs__link">Generalized Linear Models</a></li>
<li class="md-tabs__item"><a href="statsmodels.genmod.families.links.CDFLink.html" class="md-tabs__link">statsmodels.genmod.families.links.CDFLink</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 0.11.0</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>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../regression.html" class="md-nav__link">Linear Regression</a>
</li>
<li class="md-nav__item">
<a href="../glm.html" class="md-nav__link">Generalized Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../gee.html" class="md-nav__link">Generalized Estimating Equations</a>
</li>
<li class="md-nav__item">
<a href="../gam.html" class="md-nav__link">Generalized Additive Models (GAM)</a>
</li>
<li class="md-nav__item">
<a href="../rlm.html" class="md-nav__link">Robust Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../mixed_linear.html" class="md-nav__link">Linear Mixed Effects Models</a>
</li>
<li class="md-nav__item">
<a href="../discretemod.html" class="md-nav__link">Regression with Discrete Dependent Variable</a>
</li>
<li class="md-nav__item">
<a href="../mixed_glm.html" class="md-nav__link">Generalized Linear Mixed Effects Models</a>
</li>
<li class="md-nav__item">
<a href="../anova.html" class="md-nav__link">ANOVA</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
</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.genmod.families.links.CDFLink.deriv2.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-genmod-families-links-cdflink-deriv2--page-root">statsmodels.genmod.families.links.CDFLink.deriv2<a class="headerlink" href="#generated-statsmodels-genmod-families-links-cdflink-deriv2--page-root" title="Permalink to this headline">¶</a></h1>
<dl class="method">
<dt id="statsmodels.genmod.families.links.CDFLink.deriv2">
<code class="sig-prename descclassname">CDFLink.</code><code class="sig-name descname">deriv2</code><span class="sig-paren">(</span><em class="sig-param">p</em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/genmod/families/links.html#CDFLink.deriv2"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.genmod.families.links.CDFLink.deriv2" title="Permalink to this definition">¶</a></dt>
<dd><p>Second derivative of the link function g’’(p)</p>
<p>implemented through numerical differentiation</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.genmod.families.links.CDFLink.deriv.html" title="Material"
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.genmod.families.links.CDFLink.deriv </span>
</div>
</a>
<a href="statsmodels.genmod.families.links.CDFLink.inverse.html" title="Admonition"
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.genmod.families.links.CDFLink.inverse </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
Jan 22, 2020.
<br/>
Created using
<a href="http://sphinx-doc.org/">Sphinx</a> 2.3.1.
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": "02372655a4cc0c43cc5eb1726c675d49",
"timestamp": "",
"source": "github",
"line_count": 442,
"max_line_length": 999,
"avg_line_length": 41.01809954751131,
"alnum_prop": 0.6011583011583012,
"repo_name": "statsmodels/statsmodels.github.io",
"id": "077e19d96886672aed04e8c63cc07b49ab33dd75",
"size": "18138",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "v0.11.0/generated/statsmodels.genmod.families.links.CDFLink.deriv2.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<?php
namespace tests\TestCases;
use tests\Model\UserModel;
use tests\Model\PostModel;
/**
* SQL查询条件测试
*
* @author Lumeng <[email protected]>
*/
class SQLConditionTest extends BaseDatabaseTestCase {
protected function getDataSet() {
$xmlFileArray = array(
TEST_ROOT . '/resources/sql-condition-fixture.xml',
);
return $this->createCompositeMySQLXMLDataSet($xmlFileArray);
}
public function testBetween() {
$userModel = new UserModel();
$conditions = array(
'uid' => ['between', 2, 5],
);
$users = $userModel->where($conditions)->findAll();
$this->assertCount(3, $users);
}
public function testNotBetween() {
$userModel = new UserModel();
$conditions = array(
'uid' => ['not between', 2, 5],
);
$users = $userModel->where($conditions)->findAll();
$this->assertCount(1, $users);
}
public function testNotEqual() {
$postModel = new PostModel();
//找出除了李雷之外,其他人发的所有帖子
$conditions = array(
'uid' => ['neq', 2],
);
$posts = $postModel->where($conditions)->findAll();
$this->assertCount(3, $posts);
$this->assertEquals('呵呵', $posts[0]['content']);
}
public function testExists() {
$userModel = new UserModel();
//找出发过帖子的所有用户
$condition = [
'_string' => 'EXISTS (SELECT * FROM bbs_post p WHERE p.uid = u.uid)',
];
$users = $userModel->alias('u')->select('u.uid,u.nickname')
->where($condition)
->findAll();
//沉默寡言的张三
$taciturnUser = array(
'uid' => '4',
'nickname' => '张三',
);
$this->assertCount(3, $users);
$this->assertNotContains($taciturnUser, $users);
}
public function testNotExists() {
$userModel = new UserModel();
//找出尚未发过帖子的所有用户
$condition = [
'_string' => 'NOT EXISTS(SELECT * FROM bbs_post p WHERE p.uid = u.uid)',
];
$taciturnUsers = $userModel->alias('u')->select('u.uid,u.nickname')
->where($condition)
->findAll();
$this->assertCount(1, $taciturnUsers);
$this->assertEquals('张三', $taciturnUsers[0]['nickname']);
}
public function testGreaterThan() {
$userModel = new UserModel();
//找出uid大于2的所有用户
$conditions = array(
'uid' => ['gt', 2],
);
$users = $userModel->where($conditions)->findAll();
$this->assertCount(2, $users);
$this->assertEquals('韩梅梅', $users[0]['nickname']);
}
public function testLessEqualThan() {
$userModel = new UserModel();
//找出uid小于或等于2的所有用户
$conditions = array(
'uid' => ['lte', 2],
);
$users = $userModel->where($conditions)->findAll();
$this->assertCount(2, $users);
$this->assertEquals('李雷', $users[1]['nickname']);
}
public function testIn() {
$postModel = new PostModel();
//找出李雷和韩梅梅发的所有帖子
$conditions = array(
'uid' => ['in', [2, 3]],
);
$posts = $postModel->where($conditions)->findAll();
$this->assertCount(5, $posts);
$this->assertEquals('睡了', $posts[4]['content']);
}
public function testLike() {
$postModel = new PostModel();
//找出标题里包含"韩梅梅"的所有帖子
$conditions = array(
'title' => ['like', '%韩梅梅%'],
);
$posts = $postModel->where($conditions)->findAll();
$this->assertCount(3, $posts);
$this->assertEquals('“呵呵”是啥意思?', $posts[2]['content']);
}
}
| {
"content_hash": "572d904d568c83932bf22a4de08bc792",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 84,
"avg_line_length": 25.71034482758621,
"alnum_prop": 0.5209227467811158,
"repo_name": "zhengb302/LumengPHP-Db",
"id": "c155ea9ebed67b870f94340d1b8d993654241f0e",
"size": "3988",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/TestCases/SQLConditionTest.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "93007"
},
{
"name": "Shell",
"bytes": "428"
}
],
"symlink_target": ""
} |
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "AddressableRecord" do
describe "having ActiveRecord extensions" do
it "should respond to address" do
ActiveRecord::Base.respond_to?( :address ).should be_true
end
it "should respond to addresses" do
ActiveRecord::Base.respond_to?( :addresses ).should be_true
end
end
describe "having models descending from ActiveRecord" do
before :each do
@address_attributes = ADDRESS_ATTRIBUTES
@user = User.new( :name => 'John Smith', :address => AddressableRecord::Address.new( @address_attributes ) )
@user.save!
end
it "should respond to address" do
@user.respond_to?( :address ).should be_true
end
it "should be an AddressableRecord::Address" do
@user.address.is_a?( AddressableRecord::Address ).should be_true
end
it "should agree that the size of streets is 2" do
@user.address.streets.size.should eql( 2 )
end
it "should agree that the street address is 123 Jones Street, Suite 540" do
@user.address.street.should eql( '123 Jones Street, Suite 540' )
end
it "should agree that the city is Atlanta" do
@user.address.city.should eql( 'Atlanta' )
end
it "should agree that the state is GA" do
@user.address.state.should eql( 'GA' )
end
it "should agree that the zip_code is 33333-1111" do
@user.address.zip_code.should eql( '33333-1111' )
end
it "should agree that the country is U.S.A." do
@user.address.country.should eql( 'U.S.A.' )
end
# describe "when creating with a string of address elements" do
# before :each do
# attributes = ADDRESS_ATTRIBUTES
# @address_attributes =
# [attributes[:raw_street],attributes[:city],attributes[:state_or_province],attributes[:raw_zip_code],attributes[:country]]
# @klass = AddressableRecord::Address
# @instance = AddressableRecord::Address.new( @address_attributes.join( ', ' ) )
# end
#
# it "should create an address record" do
# @instance.is_a?( @klass ).should be_true
# end
# end
describe "when creating with a Hash of address elements" do
before :each do
@user = User.new( :name => 'John Smith', :address => @address_attributes )
@user.save!
end
it "should respond to address" do
@user.respond_to?( :address ).should be_true
end
it "should be an AddressableRecord::Address" do
@user.address.is_a?( AddressableRecord::Address ).should be_true
end
it "should agree that the size of streets is 2" do
@user.address.streets.size.should eql( 2 )
end
it "should agree that the street address is 123 Jones Street, Suite 540" do
@user.address.street.should eql( '123 Jones Street, Suite 540' )
end
it "should agree that the city is Atlanta" do
@user.address.city.should eql( 'Atlanta' )
end
it "should agree that the state is GA" do
@user.address.state.should eql( 'GA' )
end
it "should agree that the zip_code is 33333-1111" do
@user.address.zip_code.should eql( '33333-1111' )
end
it "should agree that the country is U.S.A." do
@user.address.country.should eql( 'U.S.A.' )
end
it "should handle a 5 digit zip code" do
@user = User.new( :name => 'John Smith', :address => @address_attributes.merge( :raw_zip_code => '31234' ) )
@user.save!
@user.address.zip_code.should eql( '31234' )
end
end
end
describe "when used through an association" do
before :each do
@address_attributes = ADDRESS_ATTRIBUTES
@person = Person.new( :name => 'John Smith' )
@person.save!
end
describe "creating through the association" do
before :each do
@address = AddressableRecord::Address.new( @address_attributes )
@person.contact_addresses.build( :address => @address )
@person.save!
end
it "should agree that the address street is 123 Jones Street, Suite 540" do
@address.street.should eql( '123 Jones Street, Suite 540' )
end
it "should agree that the associated street is 123 Jones Street, Suite 540" do
@person.contact_addresses.first.address.street.should eql( '123 Jones Street, Suite 540' )
end
it "should agree that the address city is Atlanta" do
@address.city.should eql( 'Atlanta' )
end
it "should agree that the associated street is Atlanta" do
@person.contact_addresses.first.address.city.should eql( 'Atlanta' )
end
it "should agree that the address state is GA" do
@address.state.should eql( 'GA' )
end
it "should agree that the associated state is GA" do
@person.contact_addresses.first.address.state.should eql( 'GA' )
end
it "should agree that the address zip code is 33333-1111" do
@address.zip_code.should eql( '33333-1111' )
end
it "should agree that the associated zip code is 33333-1111" do
@person.contact_addresses.first.address.zip_code.should eql( '33333-1111' )
end
it "should agree that the address country is U.S.A." do
@address.country.should eql( 'U.S.A.' )
end
it "should agree that the associated country is U.S.A." do
@person.contact_addresses.first.address.country.should eql( 'U.S.A.' )
end
end
end
end
| {
"content_hash": "56c978a451c7fe6f4a4ee2e40b7521a0",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 133,
"avg_line_length": 32.904761904761905,
"alnum_prop": 0.6360347322720694,
"repo_name": "midas/addressable_record",
"id": "45ae878fcd1f9e9fa226f28845627a57556c7b81",
"size": "5528",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/addressable_record_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "38170"
}
],
"symlink_target": ""
} |
/********************** tine translations of ActiveSync**********************/
Locale.Gettext.prototype._msgs['./LC_MESSAGES/ActiveSync'] = new Locale.Gettext.PO(({
""
: "Project-Id-Version: Tine 2.0\nPOT-Creation-Date: 2008-05-17 22:12+0100\nPO-Revision-Date: 2012-10-08 15:55+0000\nLast-Translator: Gurney <[email protected]>\nLanguage-Team: French (http://www.transifex.com/projects/p/tine20/language/fr/)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=UTF-8\nContent-Transfer-Encoding: 8bit\nLanguage: fr\nPlural-Forms: nplurals=2; plural=(n > 1);\nX-Poedit-Country: GB\nX-Poedit-Language: en\nX-Poedit-SourceCharset: utf-8\n"
, "Default policy for new devices"
: "Politique par défaut pour les nouveaux appareils"
, "Enter the id of the policy to apply to newly created devices."
: "Entrez le numéro de la politique qui s'appliquera aux appareils nouvellement enregistrés"
, "Active Sync"
: "ActiveSync"
, "Select a Device"
: "Sélectionnez un appareil"
, "No ActiveSync Device registered"
: "Aucun appareil ActiveSync enregistré"
, "Set as {0} Filter"
: "Définir en tant que filtre {0}"
, "Resetted Sync Filter"
: "Filtre de synchronisations réinitialisé"
, "{0} filter for device \"{1}\" is now \"{2}\""
: "Le filtre {0} pour l'appareil \"{1}\" est désormais \"{2}\""
, "resetted"
: "réinitialisé"
, "Set Sync Filter"
: "Définir le filtre de synchronisation"
, "Device, Devices"
: [
"Appareil"
,"Appareils"
]
, "Devices"
: "Appareils"
, "Default Addressbook"
: "Carnet d'adresses par défaut"
, "The default addressbook to create new contacts in."
: "Carnet d'adresse où seront créés par défaut les nouveaux contacts."
, "Default Calendar"
: "Agenda par défaut"
, "The default calendar to create new events in."
: "Calendrier où seront créés par défaut les nouveaux évènements."
, "Default Task List"
: "Liste des tâches par défaut"
, "The default task list to create new tasks in."
: "Liste où seront créés par défaut les nouvelles tâches."
, "Default Policy"
: "Règle par défaut"
, "Default Policy installed during setup"
: "Politique par défaut configurée durant l'installation"
, "Device"
: "Appareil"
}));
| {
"content_hash": "5b756cf30a97e522d8250393e95bdbc9",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 476,
"avg_line_length": 29.958333333333332,
"alnum_prop": 0.7070004636068614,
"repo_name": "jodier/tmpdddf",
"id": "2d88533a666f62c14462a53e85aaf0393189a9a1",
"size": "2192",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web/private/tine20/ActiveSync/js/ActiveSync-lang-fr-debug.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "44010"
},
{
"name": "Perl",
"bytes": "794"
},
{
"name": "Shell",
"bytes": "286"
}
],
"symlink_target": ""
} |
package loader
import (
"context"
"fmt"
"os"
"time"
"github.com/cilium/cilium/pkg/datapath/linux/config"
"github.com/cilium/cilium/pkg/testutils"
. "gopkg.in/check.v1"
)
func (s *LoaderTestSuite) TestobjectCache(c *C) {
tmpDir, err := os.MkdirTemp("", "cilium_test")
c.Assert(err, IsNil)
defer os.RemoveAll(tmpDir)
ctx, cancel := context.WithTimeout(context.Background(), contextTimeout)
defer cancel()
cache := newObjectCache(&config.HeaderfileWriter{}, nil, tmpDir)
realEP := testutils.NewTestEndpoint()
// First run should compile and generate the object.
_, isNew, err := cache.fetchOrCompile(ctx, &realEP, nil)
c.Assert(err, IsNil)
c.Assert(isNew, Equals, true)
// Same EP should not be compiled twice.
_, isNew, err = cache.fetchOrCompile(ctx, &realEP, nil)
c.Assert(err, IsNil)
c.Assert(isNew, Equals, false)
// Changing the ID should not generate a new object.
realEP.Id++
_, isNew, err = cache.fetchOrCompile(ctx, &realEP, nil)
c.Assert(err, IsNil)
c.Assert(isNew, Equals, false)
// Changing a setting on the EP should generate a new object.
realEP.Opts.SetBool("foo", true)
_, isNew, err = cache.fetchOrCompile(ctx, &realEP, nil)
c.Assert(err, IsNil)
c.Assert(isNew, Equals, true)
}
type buildResult struct {
goroutine int
path string
compiled bool
err error
}
func receiveResult(c *C, results chan buildResult) (*buildResult, error) {
select {
case result := <-results:
if result.err != nil {
return nil, result.err
}
return &result, nil
case <-time.After(contextTimeout):
return nil, fmt.Errorf("Timed out waiting for goroutines to return")
}
}
func (s *LoaderTestSuite) TestobjectCacheParallel(c *C) {
tmpDir, err := os.MkdirTemp("", "cilium_test")
c.Assert(err, IsNil)
defer os.RemoveAll(tmpDir)
ctx, cancel := context.WithTimeout(context.Background(), contextTimeout)
defer cancel()
tests := []struct {
description string
builds int
divisor int
}{
{
description: "One build, multiple blocking goroutines",
builds: 8,
divisor: 8,
},
{
description: "Eight builds, half compile, half block",
builds: 8,
divisor: 2,
},
{
description: "Eight unique builds",
builds: 8,
divisor: 1,
},
}
for _, t := range tests {
c.Logf(" %s", t.description)
results := make(chan buildResult, t.builds)
cache := newObjectCache(&config.HeaderfileWriter{}, nil, tmpDir)
for i := 0; i < t.builds; i++ {
go func(i int) {
ep := testutils.NewTestEndpoint()
opt := fmt.Sprintf("OPT%d", i/t.divisor)
ep.Opts.SetBool(opt, true)
path, isNew, err := cache.fetchOrCompile(ctx, &ep, nil)
results <- buildResult{
goroutine: i,
path: path,
compiled: isNew,
err: err,
}
}(i)
}
// First result will always be a compilation for the new set of options
compiled := make(map[string]int, t.builds)
used := make(map[string]int, t.builds)
for i := 0; i < t.builds; i++ {
result, err := receiveResult(c, results)
c.Assert(err, IsNil)
used[result.path] = used[result.path] + 1
if result.compiled {
compiled[result.path] = compiled[result.path] + 1
}
}
c.Assert(len(compiled), Equals, t.builds/t.divisor)
c.Assert(len(used), Equals, t.builds/t.divisor)
for _, templateCompileCount := range compiled {
// Only one goroutine compiles each template
c.Assert(templateCompileCount, Equals, 1)
}
for _, templateUseCount := range used {
// Based on the test parameters, a number of goroutines
// may share the same template.
c.Assert(templateUseCount, Equals, t.divisor)
}
}
}
| {
"content_hash": "98b20e9d4608532551d76b3b5cc163ba",
"timestamp": "",
"source": "github",
"line_count": 143,
"max_line_length": 74,
"avg_line_length": 25.44055944055944,
"alnum_prop": 0.6610775151181968,
"repo_name": "tklauser/cilium",
"id": "48717630d83f8e6432fbc7a9fbf1450b1ae802a8",
"size": "3770",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pkg/datapath/loader/cache_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "939774"
},
{
"name": "Dockerfile",
"bytes": "27555"
},
{
"name": "Go",
"bytes": "9502023"
},
{
"name": "HCL",
"bytes": "1394"
},
{
"name": "Makefile",
"bytes": "76523"
},
{
"name": "Mustache",
"bytes": "1457"
},
{
"name": "Python",
"bytes": "11097"
},
{
"name": "Ruby",
"bytes": "394"
},
{
"name": "Shell",
"bytes": "349188"
},
{
"name": "SmPL",
"bytes": "6540"
},
{
"name": "Smarty",
"bytes": "10430"
},
{
"name": "TeX",
"bytes": "416"
},
{
"name": "sed",
"bytes": "2642"
}
],
"symlink_target": ""
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* @author Moqsad
*/
public class Notices {
private final Connection dbconnection;
private final Statement statement;
private ResultSet resultSet = null;
public static int noOfNotices;
public static String uploaderIdArray[] = new String[500];
public static String titleArray[] = new String[500];
public static String descriptionArray[] = new String[500];
public static String importancyArray[] = new String[500];
public static String dateArray[] = new String[500];
public static String fileNameArray[] = new String[500];
public static String categoryArray[] = new String[500];
//for marquee
public static int marqueeNoOfNotices;
public static String marqueeTitleArray[] = new String[5];
public static String marqueeDescriptionArray[] = new String[5];
public static String marqueeDateArray[] = new String[5];
public static String marqueeFileNameArray[] = new String[5];
public static String marqueeCategoryArray[] = new String[5];
public Notices() throws SQLException, ClassNotFoundException {
System.out.println("before");
Class.forName("com.mysql.jdbc.Driver");
dbconnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/enotice", "root", "1234");
statement = dbconnection.createStatement();
System.out.println("after");
}
public void allNotices(String category, String search) {
try {
resultSet = statement.executeQuery("SELECT * FROM enotice.notice ORDER BY date DESC;");
noOfNotices = 0;
search = search.toLowerCase();
search = search.replaceAll(" ", "");
System.out.println(">>>>>>>>>>>>>>>>>>" + search + "<<<<<<<<<<<<<<<<<<");
System.out.println("Priniting Notice Array.........");
while (resultSet.next()) {
if (resultSet.getString("category").equals(category) || category.equals("All")) {
String title = resultSet.getString("title");
title = title.toLowerCase().replaceAll(" ", "");
System.out.println(">>>>>>>>>>>>>>>>>>-------" + title + "-------<<<<<<<<<<<<<<<<<<");
if (title.contains(search)) {
uploaderIdArray[noOfNotices] = resultSet.getString("uploader_id");
titleArray[noOfNotices] = resultSet.getString("title");
descriptionArray[noOfNotices] = resultSet.getString("description");
importancyArray[noOfNotices] = resultSet.getString("importancy");
dateArray[noOfNotices] = resultSet.getString("date");
fileNameArray[noOfNotices] = resultSet.getString("filename");
categoryArray[noOfNotices] = resultSet.getString("category");
System.out.println("Uploader Id : " + uploaderIdArray[noOfNotices]);
System.out.println("Title : " + titleArray[noOfNotices]);
System.out.println("Description : " + descriptionArray[noOfNotices]);
System.out.println("Importancy : " + importancyArray[noOfNotices]);
System.out.println("Date : " + dateArray[noOfNotices]);
System.out.println("File : " + fileNameArray[noOfNotices]);
System.out.println("Category : " + categoryArray[noOfNotices]);
++noOfNotices;
}
}
}
System.out.println("Notice Array Printing is completed.........");
marqueeNotices();
} catch (Exception e) {
System.out.println("Exception in allNotices() of Notices");
e.printStackTrace();
}
}
private void marqueeNotices() {
try {
System.out.println("In marqueeNotices()");
resultSet = statement.executeQuery("SELECT * FROM enotice.notice ORDER BY importancy DESC, date DESC limit 5;");
marqueeNoOfNotices = 0;
while (resultSet.next()) {
marqueeTitleArray[marqueeNoOfNotices] = resultSet.getString("title");
marqueeDescriptionArray[marqueeNoOfNotices] = resultSet.getString("description");
marqueeDateArray[marqueeNoOfNotices] = resultSet.getString("date");
marqueeFileNameArray[marqueeNoOfNotices] = resultSet.getString("filename");
marqueeCategoryArray[marqueeNoOfNotices] = resultSet.getString("category");
++marqueeNoOfNotices;
}
} catch (Exception e) {
System.out.println("Exception in marqueNotices() of Notices");
e.printStackTrace();
}
}
}
| {
"content_hash": "510ee368ebca857265c58b1b08fe766d",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 124,
"avg_line_length": 41.24409448818898,
"alnum_prop": 0.5874379534173348,
"repo_name": "bd-king/E-notice",
"id": "d0404cfe170f0a8eec467962c9ee6b75448cbe3a",
"size": "5238",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/Database/Notices.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8508"
},
{
"name": "Java",
"bytes": "243521"
},
{
"name": "JavaScript",
"bytes": "2710"
}
],
"symlink_target": ""
} |
interface IMenuHeader {
TextColor: string;
BackgroundColor: string;
} | {
"content_hash": "53de4464ff3b6049dcbffb9a0ece9e92",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 28,
"avg_line_length": 19.5,
"alnum_prop": 0.717948717948718,
"repo_name": "ImAliveApp/HumanoidCharacter",
"id": "06f5e97560389e4bf30e53bc412db673c72ee448",
"size": "80",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "HumanoidCharacter/AliveEnvironmentObjects/MenuInterfaces/IMenuHeader.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "302"
},
{
"name": "JavaScript",
"bytes": "305"
},
{
"name": "TypeScript",
"bytes": "145244"
}
],
"symlink_target": ""
} |
<component name="libraryTable">
<library name="support-annotations-22.2.0">
<CLASSES>
<root url="jar://$USER_HOME$/Desktop/android/extras/android/m2repository/com/android/support/support-annotations/22.2.0/support-annotations-22.2.0.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$USER_HOME$/Desktop/android/extras/android/m2repository/com/android/support/support-annotations/22.2.0/support-annotations-22.2.0-sources.jar!/" />
</SOURCES>
</library>
</component> | {
"content_hash": "39f42029c099e9d3cd324dd041c9bea5",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 170,
"avg_line_length": 46.45454545454545,
"alnum_prop": 0.700587084148728,
"repo_name": "shwetaagrawal15/AssignmentReminder",
"id": "16078ef532858d8cabd6fcdb48e8b3015c2ad5b8",
"size": "511",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/libraries/support_annotations_22_2_0.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "48228"
}
],
"symlink_target": ""
} |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const catchError = (matcher) => (e) => matcher.test(e.message) ? undefined :
assert.fail(e.message, matcher.toString(), `Invalid error: ${e.message}`);
exports.catchInvalidOpcode = catchError(/invalid opcode/);
const catchOutOfGas = catchError(/out of gas/);
const catchThrow = exports.catchInvalidOpcode; // Invalid opcode renders as a throw
const catchInvalidJump = catchOutOfGas; // Out of gas renders as invalid jump
exports.assert_throws = (p, message) => p
.then(_ => assert.fail(undefined, undefined, message || "Expected contract to throw"))
.catch(exports.catchInvalidOpcode);
| {
"content_hash": "c087ef00374b0c44b398714e412541b0",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 90,
"avg_line_length": 61.36363636363637,
"alnum_prop": 0.7274074074074074,
"repo_name": "ProBonoPublicoWorld/ico-contracts",
"id": "8f8171dcfc915c41daaa069ffeaf77aca5a51e6a",
"size": "675",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/utils/assert_throws.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "66655"
},
{
"name": "Shell",
"bytes": "1981"
},
{
"name": "TypeScript",
"bytes": "70658"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>V8 API Reference Guide for node.js v0.10.27 - v0.10.28: File List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">V8 API Reference Guide for node.js v0.10.27 - v0.10.28
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.9.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li class="current"><a href="files.html"><span>File List</span></a></li>
</ul>
</div>
</div><!-- top -->
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">File List</div> </div>
</div><!--header-->
<div class="contents">
<div class="textblock">Here is a list of all documented files with brief descriptions:</div><div class="directory">
<div class="levels">[detail level <span onclick="javascript:toggleLevel(1);">1</span><span onclick="javascript:toggleLevel(2);">2</span><span onclick="javascript:toggleLevel(3);">3</span><span onclick="javascript:toggleLevel(4);">4</span>]</div><table class="directory">
<tr id="row_0_" class="even"><td class="entry"><span style="width:0px;display:inline-block;"> </span><span id="arr_0_" class="arrow" onclick="toggleFolder('0_')">▼</span><span id="img_0_" class="iconfopen" onclick="toggleFolder('0_')"> </span><a class="el" href="dir_94a36784afa54c0b50996002372b429e.html" target="_self">deps</a></td><td class="desc"></td></tr>
<tr id="row_0_0_"><td class="entry"><span style="width:16px;display:inline-block;"> </span><span id="arr_0_0_" class="arrow" onclick="toggleFolder('0_0_')">▼</span><span id="img_0_0_" class="iconfopen" onclick="toggleFolder('0_0_')"> </span><a class="el" href="dir_7edecdc49f3d0e5b35ff20670f3bf33e.html" target="_self">v8</a></td><td class="desc"></td></tr>
<tr id="row_0_0_0_" class="even"><td class="entry"><span style="width:32px;display:inline-block;"> </span><span id="arr_0_0_0_" class="arrow" onclick="toggleFolder('0_0_0_')">▼</span><span id="img_0_0_0_" class="iconfopen" onclick="toggleFolder('0_0_0_')"> </span><a class="el" href="dir_3debe4bd29323c1699f247c91661804b.html" target="_self">include</a></td><td class="desc"></td></tr>
<tr id="row_0_0_0_0_"><td class="entry"><span style="width:64px;display:inline-block;"> </span><a href="v8-debug_8h_source.html"><span class="icondoc"></span></a><b>v8-debug.h</b></td><td class="desc"></td></tr>
<tr id="row_0_0_0_1_" class="even"><td class="entry"><span style="width:64px;display:inline-block;"> </span><a href="v8-preparser_8h_source.html"><span class="icondoc"></span></a><b>v8-preparser.h</b></td><td class="desc"></td></tr>
<tr id="row_0_0_0_2_"><td class="entry"><span style="width:64px;display:inline-block;"> </span><a href="v8-profiler_8h_source.html"><span class="icondoc"></span></a><b>v8-profiler.h</b></td><td class="desc"></td></tr>
<tr id="row_0_0_0_3_" class="even"><td class="entry"><span style="width:64px;display:inline-block;"> </span><a href="v8-testing_8h_source.html"><span class="icondoc"></span></a><b>v8-testing.h</b></td><td class="desc"></td></tr>
<tr id="row_0_0_0_4_"><td class="entry"><span style="width:64px;display:inline-block;"> </span><a href="v8_8h_source.html"><span class="icondoc"></span></a><b>v8.h</b></td><td class="desc"></td></tr>
<tr id="row_0_0_0_5_" class="even"><td class="entry"><span style="width:64px;display:inline-block;"> </span><a href="v8stdint_8h_source.html"><span class="icondoc"></span></a><b>v8stdint.h</b></td><td class="desc"></td></tr>
</table>
</div><!-- directory -->
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Tue Aug 11 2015 23:45:14 for V8 API Reference Guide for node.js v0.10.27 - v0.10.28 by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.9.1
</small></address>
</body>
</html>
| {
"content_hash": "febe5dbd48558ee4a539c68273c5eacd",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 401,
"avg_line_length": 62.1651376146789,
"alnum_prop": 0.6508264462809917,
"repo_name": "v8-dox/v8-dox.github.io",
"id": "fa09ae95d03fc507e6aafda41d311ba76eee12fe",
"size": "6776",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "3f3a71e/html/files.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
<bean id="webAppDispatcherServlet" class="yourwebproject2.servlet.YourWebAppDispatcherServlet"/>
</beans> | {
"content_hash": "e6d8dbf5c7781edea6dbe11910dbcda8",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 100,
"avg_line_length": 42.333333333333336,
"alnum_prop": 0.7349081364829396,
"repo_name": "ykameshrao/spring-angularjs-hibernate-twitter-bootstrap-java-single-page-webapp-with-jwt-auth-rest-api",
"id": "2a1e5ca006460b46b3594432f0e2a3d48e275379",
"size": "381",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/resources/config/spring/appContext-servlet.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "263"
},
{
"name": "HTML",
"bytes": "10905"
},
{
"name": "Java",
"bytes": "118713"
},
{
"name": "JavaScript",
"bytes": "16827"
}
],
"symlink_target": ""
} |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2013 Illuminati developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "db.h"
#include "net.h"
#include "init.h"
#include "addrman.h"
#include "ui_interface.h"
#include "script.h"
#ifdef WIN32
#include <string.h>
#endif
#ifdef USE_UPNP
#include <miniupnpc/miniwget.h>
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
#endif
// period dump peer.dat in second
const unsigned int dump_addresses_interval = 900;
using namespace std;
using namespace boost;
static const int MAX_OUTBOUND_CONNECTIONS = 24;
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
struct LocalServiceInfo {
int nScore;
int nPort;
};
//
// Global state variables
//
bool fDiscover = true;
uint64 nLocalServices = NODE_NETWORK;
static CCriticalSection cs_mapLocalHost;
static map<CNetAddr, LocalServiceInfo> mapLocalHost;
static bool vfReachable[NET_MAX] = {};
static bool vfLimited[NET_MAX] = {};
static CNode* pnodeLocalHost = NULL;
static CNode* pnodeSync = NULL;
uint64 nLocalHostNonce = 0;
static std::vector<SOCKET> vhListenSocket;
CAddrMan addrman;
int nMaxConnections = 125;
vector<CNode*> vNodes;
CCriticalSection cs_vNodes;
map<CInv, CDataStream> mapRelay;
deque<pair<int64, CInv> > vRelayExpiration;
CCriticalSection cs_mapRelay;
limitedmap<CInv, int64> mapAlreadyAskedFor(MAX_INV_SZ);
static deque<string> vOneShots;
CCriticalSection cs_vOneShots;
set<CNetAddr> setservAddNodeAddresses;
CCriticalSection cs_setservAddNodeAddresses;
vector<std::string> vAddedNodes;
CCriticalSection cs_vAddedNodes;
static CSemaphore *semOutbound = NULL;
void AddOneShot(string strDest)
{
LOCK(cs_vOneShots);
vOneShots.push_back(strDest);
}
unsigned short GetListenPort()
{
return (unsigned short)(GetArg("-port", GetDefaultPort()));
}
void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd)
{
// Filter out duplicate requests
if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd)
return;
pindexLastGetBlocksBegin = pindexBegin;
hashLastGetBlocksEnd = hashEnd;
PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);
}
// find 'best' local address for a particular peer
bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
{
if (fNoListen)
return false;
int nBestScore = -1;
int nBestReachability = -1;
{
LOCK(cs_mapLocalHost);
for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
{
int nScore = (*it).second.nScore;
int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
{
addr = CService((*it).first, (*it).second.nPort);
nBestReachability = nReachability;
nBestScore = nScore;
}
}
}
return nBestScore >= 0;
}
// get best local address for a particular peer as a CAddress
CAddress GetLocalAddress(const CNetAddr *paddrPeer)
{
CAddress ret(CService("0.0.0.0",0),0);
CService addr;
if (GetLocal(addr, paddrPeer))
{
ret = CAddress(addr);
ret.nServices = nLocalServices;
ret.nTime = GetAdjustedTime();
}
return ret;
}
bool RecvLine(SOCKET hSocket, string& strLine)
{
strLine = "";
loop
{
char c;
int nBytes = recv(hSocket, &c, 1, 0);
if (nBytes > 0)
{
if (c == '\n')
continue;
if (c == '\r')
return true;
strLine += c;
if (strLine.size() >= 9000)
return true;
}
else if (nBytes <= 0)
{
boost::this_thread::interruption_point();
if (nBytes < 0)
{
int nErr = WSAGetLastError();
if (nErr == WSAEMSGSIZE)
continue;
if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS)
{
MilliSleep(10);
continue;
}
}
if (!strLine.empty())
return true;
if (nBytes == 0)
{
// socket closed
printf("socket closed\n");
return false;
}
else
{
// socket error
int nErr = WSAGetLastError();
printf("recv failed: %d\n", nErr);
return false;
}
}
}
}
// used when scores of local addresses may have changed
// pushes better local address to peers
void static AdvertizeLocal()
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->fSuccessfullyConnected)
{
CAddress addrLocal = GetLocalAddress(&pnode->addr);
if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal)
{
pnode->PushAddress(addrLocal);
pnode->addrLocal = addrLocal;
}
}
}
}
void SetReachable(enum Network net, bool fFlag)
{
LOCK(cs_mapLocalHost);
vfReachable[net] = fFlag;
if (net == NET_IPV6 && fFlag)
vfReachable[NET_IPV4] = true;
}
// learn a new local address
bool AddLocal(const CService& addr, int nScore)
{
if (!addr.IsRoutable())
return false;
if (!fDiscover && nScore < LOCAL_MANUAL)
return false;
if (IsLimited(addr))
return false;
printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore);
{
LOCK(cs_mapLocalHost);
bool fAlready = mapLocalHost.count(addr) > 0;
LocalServiceInfo &info = mapLocalHost[addr];
if (!fAlready || nScore >= info.nScore) {
info.nScore = nScore + (fAlready ? 1 : 0);
info.nPort = addr.GetPort();
}
SetReachable(addr.GetNetwork());
}
AdvertizeLocal();
return true;
}
bool AddLocal(const CNetAddr &addr, int nScore)
{
return AddLocal(CService(addr, GetListenPort()), nScore);
}
/** Make a particular network entirely off-limits (no automatic connects to it) */
void SetLimited(enum Network net, bool fLimited)
{
if (net == NET_UNROUTABLE)
return;
LOCK(cs_mapLocalHost);
vfLimited[net] = fLimited;
}
bool IsLimited(enum Network net)
{
LOCK(cs_mapLocalHost);
return vfLimited[net];
}
bool IsLimited(const CNetAddr &addr)
{
return IsLimited(addr.GetNetwork());
}
/** vote for a local address */
bool SeenLocal(const CService& addr)
{
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == 0)
return false;
mapLocalHost[addr].nScore++;
}
AdvertizeLocal();
return true;
}
/** check whether a given address is potentially local */
bool IsLocal(const CService& addr)
{
LOCK(cs_mapLocalHost);
return mapLocalHost.count(addr) > 0;
}
/** check whether a given address is in a network we can probably connect to */
bool IsReachable(const CNetAddr& addr)
{
LOCK(cs_mapLocalHost);
enum Network net = addr.GetNetwork();
return vfReachable[net] && !vfLimited[net];
}
bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
{
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());
send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
string strLine;
while (RecvLine(hSocket, strLine))
{
if (strLine.empty()) // HTTP response is separated from headers by blank line
{
loop
{
if (!RecvLine(hSocket, strLine))
{
closesocket(hSocket);
return false;
}
if (pszKeyword == NULL)
break;
if (strLine.find(pszKeyword) != string::npos)
{
strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
break;
}
}
closesocket(hSocket);
if (strLine.find("<") != string::npos)
strLine = strLine.substr(0, strLine.find("<"));
strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
strLine.resize(strLine.size()-1);
CService addr(strLine,0,true);
printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
if (!addr.IsValid() || !addr.IsRoutable())
return false;
ipRet.SetIP(addr);
return true;
}
}
closesocket(hSocket);
return error("GetMyExternalIP() : connection closed");
}
bool GetMyExternalIP(CNetAddr& ipRet)
{
CService addrConnect;
const char* pszGet;
const char* pszKeyword;
for (int nLookup = 0; nLookup <= 1; nLookup++)
for (int nHost = 1; nHost <= 2; nHost++)
{
// We should be phasing out our use of sites like these. If we need
// replacements, we should ask for volunteers to put this simple
// php file on their web server that prints the client IP:
// <?php echo $_SERVER["REMOTE_ADDR"]; ?>
if (nHost == 1)
{
addrConnect = CService("91.198.22.70", 80); // checkip.dyndns.org
if (nLookup == 1)
{
CService addrIP("checkip.dyndns.org", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}
pszGet = "GET / HTTP/1.1\r\n"
"Host: checkip.dyndns.org\r\n"
"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
"Connection: close\r\n"
"\r\n";
pszKeyword = "Address:";
}
else if (nHost == 2)
{
addrConnect = CService("212.117.175.194", 80); // www.showmyip.com
if (nLookup == 1)
{
CService addrIP("www.showmyip.com", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}
pszGet = "GET /simple/ HTTP/1.1\r\n"
"Host: www.showmyip.com\r\n"
"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
"Connection: close\r\n"
"\r\n";
pszKeyword = NULL; // Returns just IP address
}
if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
return true;
}
return false;
}
void ThreadGetMyExternalIP(void* parg)
{
// Make this thread recognisable as the external IP detection thread
RenameThread("bitcoin-ext-ip");
CNetAddr addrLocalHost;
if (GetMyExternalIP(addrLocalHost))
{
printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());
AddLocal(addrLocalHost, LOCAL_HTTP);
}
}
void AddressCurrentlyConnected(const CService& addr)
{
addrman.Connected(addr);
}
CNode* FindNode(const CNetAddr& ip)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CNetAddr)pnode->addr == ip)
return (pnode);
return NULL;
}
CNode* FindNode(std::string addrName)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->addrName == addrName)
return (pnode);
return NULL;
}
CNode* FindNode(const CService& addr)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CService)pnode->addr == addr)
return (pnode);
return NULL;
}
CNode* ConnectNode(CAddress addrConnect, const char *pszDest)
{
if (pszDest == NULL) {
if (IsLocal(addrConnect))
return NULL;
// Look for an existing connection
CNode* pnode = FindNode((CService)addrConnect);
if (pnode)
{
pnode->AddRef();
return pnode;
}
}
/// debug print
printf("trying connection %s lastseen=%.1fhrs\n",
pszDest ? pszDest : addrConnect.ToString().c_str(),
pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
// Connect
SOCKET hSocket;
if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket))
{
addrman.Attempt(addrConnect);
/// debug print
printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str());
// Set to non-blocking
#ifdef WIN32
u_long nOne = 1;
if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
printf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError());
#else
if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
printf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno);
#endif
// Add node
CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
pnode->nTimeConnected = GetTime();
return pnode;
}
else
{
return NULL;
}
}
void CNode::CloseSocketDisconnect()
{
fDisconnect = true;
if (hSocket != INVALID_SOCKET)
{
printf("disconnecting node %s\n", addrName.c_str());
closesocket(hSocket);
hSocket = INVALID_SOCKET;
}
// in case this fails, we'll empty the recv buffer when the CNode is deleted
TRY_LOCK(cs_vRecvMsg, lockRecv);
if (lockRecv)
vRecvMsg.clear();
// if this was the sync node, we'll need a new one
if (this == pnodeSync)
pnodeSync = NULL;
}
void CNode::Cleanup()
{
}
void CNode::PushVersion()
{
/// when NTP implemented, change to just nTime = GetAdjustedTime()
int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
CAddress addrMe = GetLocalAddress(&addr);
RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str());
PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight);
}
std::map<CNetAddr, int64> CNode::setBanned;
CCriticalSection CNode::cs_setBanned;
void CNode::ClearBanned()
{
setBanned.clear();
}
bool CNode::IsBanned(CNetAddr ip)
{
bool fResult = false;
{
LOCK(cs_setBanned);
std::map<CNetAddr, int64>::iterator i = setBanned.find(ip);
if (i != setBanned.end())
{
int64 t = (*i).second;
if (GetTime() < t)
fResult = true;
}
}
return fResult;
}
bool CNode::Misbehaving(int howmuch)
{
if (addr.IsLocal())
{
printf("Warning: Local node %s misbehaving (delta: %d)!\n", addrName.c_str(), howmuch);
return false;
}
nMisbehavior += howmuch;
if (nMisbehavior >= GetArg("-banscore", 100))
{
int64 banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban
printf("Misbehaving: %s (%d -> %d) DISCONNECTING\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
{
LOCK(cs_setBanned);
if (setBanned[addr] < banTime)
setBanned[addr] = banTime;
}
CloseSocketDisconnect();
return true;
} else
printf("Misbehaving: %s (%d -> %d)\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
return false;
}
#undef X
#define X(name) stats.name = name
void CNode::copyStats(CNodeStats &stats)
{
X(nServices);
X(nLastSend);
X(nLastRecv);
X(nTimeConnected);
X(addrName);
X(nVersion);
X(strSubVer);
X(fInbound);
X(nStartingHeight);
X(nMisbehavior);
X(nSendBytes);
X(nRecvBytes);
stats.fSyncNode = (this == pnodeSync);
}
#undef X
// requires LOCK(cs_vRecvMsg)
bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes)
{
while (nBytes > 0) {
// get current incomplete message, or create a new one
if (vRecvMsg.empty() ||
vRecvMsg.back().complete())
vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion));
CNetMessage& msg = vRecvMsg.back();
// absorb network data
int handled;
if (!msg.in_data)
handled = msg.readHeader(pch, nBytes);
else
handled = msg.readData(pch, nBytes);
if (handled < 0)
return false;
pch += handled;
nBytes -= handled;
}
return true;
}
int CNetMessage::readHeader(const char *pch, unsigned int nBytes)
{
// copy data to temporary parsing buffer
unsigned int nRemaining = 24 - nHdrPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
memcpy(&hdrbuf[nHdrPos], pch, nCopy);
nHdrPos += nCopy;
// if header incomplete, exit
if (nHdrPos < 24)
return nCopy;
// deserialize to CMessageHeader
try {
hdrbuf >> hdr;
}
catch (std::exception &e) {
return -1;
}
// reject messages larger than MAX_SIZE
if (hdr.nMessageSize > MAX_SIZE)
return -1;
// switch state to reading message data
in_data = true;
vRecv.resize(hdr.nMessageSize);
return nCopy;
}
int CNetMessage::readData(const char *pch, unsigned int nBytes)
{
unsigned int nRemaining = hdr.nMessageSize - nDataPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
memcpy(&vRecv[nDataPos], pch, nCopy);
nDataPos += nCopy;
return nCopy;
}
// requires LOCK(cs_vSend)
void SocketSendData(CNode *pnode)
{
std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin();
while (it != pnode->vSendMsg.end()) {
const CSerializeData &data = *it;
assert(data.size() > pnode->nSendOffset);
int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
if (nBytes > 0) {
pnode->nLastSend = GetTime();
pnode->nSendBytes += nBytes;
pnode->nSendOffset += nBytes;
if (pnode->nSendOffset == data.size()) {
pnode->nSendOffset = 0;
pnode->nSendSize -= data.size();
it++;
} else {
// could not send full message; stop sending more
break;
}
} else {
if (nBytes < 0) {
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
printf("socket send error %d\n", nErr);
pnode->CloseSocketDisconnect();
}
}
// couldn't send anything at all
break;
}
}
if (it == pnode->vSendMsg.end()) {
assert(pnode->nSendOffset == 0);
assert(pnode->nSendSize == 0);
}
pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
}
static list<CNode*> vNodesDisconnected;
void ThreadSocketHandler()
{
unsigned int nPrevNodeCount = 0;
loop
{
//
// Disconnect nodes
//
{
LOCK(cs_vNodes);
// Disconnect unused nodes
vector<CNode*> vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (pnode->fDisconnect ||
(pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty()))
{
// remove from vNodes
vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
// release outbound grant (if any)
pnode->grantOutbound.Release();
// close socket and cleanup
pnode->CloseSocketDisconnect();
pnode->Cleanup();
// hold in disconnected pool until all refs are released
if (pnode->fNetworkNode || pnode->fInbound)
pnode->Release();
vNodesDisconnected.push_back(pnode);
}
}
// Delete disconnected nodes
list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
{
// wait until threads are done using it
if (pnode->GetRefCount() <= 0)
{
bool fDelete = false;
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv)
{
TRY_LOCK(pnode->cs_inventory, lockInv);
if (lockInv)
fDelete = true;
}
}
}
if (fDelete)
{
vNodesDisconnected.remove(pnode);
delete pnode;
}
}
}
}
if (vNodes.size() != nPrevNodeCount)
{
nPrevNodeCount = vNodes.size();
uiInterface.NotifyNumConnectionsChanged(vNodes.size());
}
//
// Find which sockets have data to receive
//
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 50000; // frequency to poll pnode->vSend
fd_set fdsetRecv;
fd_set fdsetSend;
fd_set fdsetError;
FD_ZERO(&fdsetRecv);
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
SOCKET hSocketMax = 0;
bool have_fds = false;
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
FD_SET(hListenSocket, &fdsetRecv);
hSocketMax = max(hSocketMax, hListenSocket);
have_fds = true;
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->hSocket == INVALID_SOCKET)
continue;
FD_SET(pnode->hSocket, &fdsetError);
hSocketMax = max(hSocketMax, pnode->hSocket);
have_fds = true;
// Implement the following logic:
// * If there is data to send, select() for sending data. As this only
// happens when optimistic write failed, we choose to first drain the
// write buffer in this case before receiving more. This avoids
// needlessly queueing received data, if the remote peer is not themselves
// receiving data. This means properly utilizing TCP flow control signalling.
// * Otherwise, if there is no (complete) message in the receive buffer,
// or there is space left in the buffer, select() for receiving data.
// * (if neither of the above applies, there is certainly one message
// in the receiver buffer ready to be processed).
// Together, that means that at least one of the following is always possible,
// so we don't deadlock:
// * We send some data.
// * We wait for data to be received (and disconnect after timeout).
// * We process a message in the buffer (message handler thread).
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend && !pnode->vSendMsg.empty()) {
FD_SET(pnode->hSocket, &fdsetSend);
continue;
}
}
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv && (
pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() ||
pnode->GetTotalRecvSize() <= ReceiveFloodSize()))
FD_SET(pnode->hSocket, &fdsetRecv);
}
}
}
int nSelect = select(have_fds ? hSocketMax + 1 : 0,
&fdsetRecv, &fdsetSend, &fdsetError, &timeout);
boost::this_thread::interruption_point();
if (nSelect == SOCKET_ERROR)
{
if (have_fds)
{
int nErr = WSAGetLastError();
printf("socket select error %d\n", nErr);
for (unsigned int i = 0; i <= hSocketMax; i++)
FD_SET(i, &fdsetRecv);
}
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
MilliSleep(timeout.tv_usec/1000);
}
//
// Accept new connections
//
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
{
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
CAddress addr;
int nInbound = 0;
if (hSocket != INVALID_SOCKET)
if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
printf("Warning: Unknown socket family\n");
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->fInbound)
nInbound++;
}
if (hSocket == INVALID_SOCKET)
{
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK)
printf("socket error accept failed: %d\n", nErr);
}
else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS)
{
{
LOCK(cs_setservAddNodeAddresses);
if (!setservAddNodeAddresses.count(addr))
closesocket(hSocket);
}
}
else if (CNode::IsBanned(addr))
{
printf("connection from %s dropped (banned)\n", addr.ToString().c_str());
closesocket(hSocket);
}
else
{
printf("accepted connection %s\n", addr.ToString().c_str());
CNode* pnode = new CNode(hSocket, addr, "", true);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
}
}
//
// Service each socket
//
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->AddRef();
}
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
boost::this_thread::interruption_point();
//
// Receive
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv)
{
{
// typical socket buffer is 8K-64K
char pchBuf[0x10000];
int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
if (nBytes > 0)
{
if (!pnode->ReceiveMsgBytes(pchBuf, nBytes))
pnode->CloseSocketDisconnect();
pnode->nLastRecv = GetTime();
pnode->nRecvBytes += nBytes;
}
else if (nBytes == 0)
{
// socket closed gracefully
if (!pnode->fDisconnect)
printf("socket closed\n");
pnode->CloseSocketDisconnect();
}
else if (nBytes < 0)
{
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
if (!pnode->fDisconnect)
printf("socket recv error %d\n", nErr);
pnode->CloseSocketDisconnect();
}
}
}
}
}
//
// Send
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetSend))
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
SocketSendData(pnode);
}
//
// Inactivity checking
//
if (pnode->vSendMsg.empty())
pnode->nLastSendEmpty = GetTime();
if (GetTime() - pnode->nTimeConnected > 60)
{
if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
{
printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
{
printf("socket not sending\n");
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastRecv > 90*60)
{
printf("socket inactivity timeout\n");
pnode->fDisconnect = true;
}
}
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
MilliSleep(10);
}
}
#ifdef USE_UPNP
void ThreadMapPort()
{
std::string port = strprintf("%u", GetListenPort());
const char * multicastif = 0;
const char * minissdpdpath = 0;
struct UPNPDev * devlist = 0;
char lanaddr[64];
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
#else
/* miniupnpc 1.6 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
#endif
struct UPNPUrls urls;
struct IGDdatas data;
int r;
r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
if (r == 1)
{
if (fDiscover) {
char externalIPAddress[40];
r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
if(r != UPNPCOMMAND_SUCCESS)
printf("UPnP: GetExternalIPAddress() returned %d\n", r);
else
{
if(externalIPAddress[0])
{
printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
}
else
printf("UPnP: GetExternalIPAddress failed.\n");
}
}
string strDesc = "Bitcoin " + FormatFullVersion();
try {
loop {
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
#else
/* miniupnpc 1.6 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
#endif
if(r!=UPNPCOMMAND_SUCCESS)
printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
else
printf("UPnP Port Mapping successful.\n");;
MilliSleep(20*60*1000); // Refresh every 20 minutes
}
}
catch (boost::thread_interrupted)
{
r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
printf("UPNP_DeletePortMapping() returned : %d\n", r);
freeUPNPDevlist(devlist); devlist = 0;
FreeUPNPUrls(&urls);
throw;
}
} else {
printf("No valid UPnP IGDs found\n");
freeUPNPDevlist(devlist); devlist = 0;
if (r != 0)
FreeUPNPUrls(&urls);
}
}
void MapPort(bool fUseUPnP)
{
static boost::thread* upnp_thread = NULL;
if (fUseUPnP)
{
if (upnp_thread) {
upnp_thread->interrupt();
upnp_thread->join();
delete upnp_thread;
}
upnp_thread = new boost::thread(boost::bind(&TraceThread<boost::function<void()> >, "upnp", &ThreadMapPort));
}
else if (upnp_thread) {
upnp_thread->interrupt();
upnp_thread->join();
delete upnp_thread;
upnp_thread = NULL;
}
}
#else
void MapPort(bool)
{
// Intentionally left blank.
}
#endif
// DNS seeds
// Each pair gives a source name and a seed name.
// The first name is used as information source for addrman.
// The second name should resolve to a list of seed addresses.
static const char *strMainNetDNSSeed[][2] = {
{"69.90.132.162", "69.90.132.162"},
{NULL, NULL}
};
static const char *strTestNetDNSSeed[][2] = {
{NULL, NULL}
};
void ThreadDNSAddressSeed()
{
static const char *(*strDNSSeed)[2] = fTestNet ? strTestNetDNSSeed : strMainNetDNSSeed;
int found = 0;
printf("Loading addresses from DNS seeds (could take a while)\n");
for (unsigned int seed_idx = 0; strDNSSeed[seed_idx][0] != NULL; seed_idx++) {
if (HaveNameProxy()) {
AddOneShot(strDNSSeed[seed_idx][1]);
} else {
vector<CNetAddr> vaddr;
vector<CAddress> vAdd;
if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
{
BOOST_FOREACH(CNetAddr& ip, vaddr)
{
int nOneDay = 24*3600;
CAddress addr = CAddress(CService(ip, GetDefaultPort()));
addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
vAdd.push_back(addr);
found++;
}
}
addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true));
}
}
printf("%d addresses found from DNS seeds\n", found);
}
unsigned int pnSeed[] =
{
0x01020304
};
void DumpAddresses()
{
int64 nStart = GetTimeMillis();
CAddrDB adb;
adb.Write(addrman);
printf("Flushed %d addresses to peers.dat %"PRI64d"ms\n",
addrman.size(), GetTimeMillis() - nStart);
}
void static ProcessOneShot()
{
string strDest;
{
LOCK(cs_vOneShots);
if (vOneShots.empty())
return;
strDest = vOneShots.front();
vOneShots.pop_front();
}
CAddress addr;
CSemaphoreGrant grant(*semOutbound, true);
if (grant) {
if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
AddOneShot(strDest);
}
}
void ThreadOpenConnections()
{
// Connect to specific addresses
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0)
{
for (int64 nLoop = 0;; nLoop++)
{
ProcessOneShot();
BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
{
CAddress addr;
OpenNetworkConnection(addr, NULL, strAddr.c_str());
for (int i = 0; i < 10 && i < nLoop; i++)
{
MilliSleep(500);
}
}
MilliSleep(500);
}
}
// Initiate network connections
int64 nStart = GetTime();
loop
{
ProcessOneShot();
MilliSleep(500);
CSemaphoreGrant grant(*semOutbound);
boost::this_thread::interruption_point();
// Add seed nodes if IRC isn't working
if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet)
{
std::vector<CAddress> vAdd;
for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64 nOneWeek = 7*24*60*60;
struct in_addr ip;
memcpy(&ip, &pnSeed[i], sizeof(ip));
CAddress addr(CService(ip, GetDefaultPort()));
addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
vAdd.push_back(addr);
}
addrman.Add(vAdd, CNetAddr("127.0.0.1"));
}
//
// Choose an address to connect to based on most recently seen
//
CAddress addrConnect;
// Only connect out to one peer per network group (/16 for IPv4).
// Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
int nOutbound = 0;
set<vector<unsigned char> > setConnected;
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes) {
if (!pnode->fInbound) {
setConnected.insert(pnode->addr.GetGroup());
nOutbound++;
}
}
}
int64 nANow = GetAdjustedTime();
int nTries = 0;
loop
{
// use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
// if we selected an invalid address, restart
if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
break;
// If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
// stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
// already-connected network ranges, ...) before trying new addrman addresses.
nTries++;
if (nTries > 100)
break;
if (IsLimited(addr))
continue;
// only consider very recently tried nodes after 30 failed attempts
if (nANow - addr.nLastTry < 600 && nTries < 30)
continue;
// do not allow non-default ports, unless after 50 invalid addresses selected already
if (addr.GetPort() != GetDefaultPort() && nTries < 50)
continue;
addrConnect = addr;
break;
}
if (addrConnect.IsValid())
OpenNetworkConnection(addrConnect, &grant);
}
}
void ThreadOpenAddedConnections()
{
{
LOCK(cs_vAddedNodes);
vAddedNodes = mapMultiArgs["-addnode"];
}
if (HaveNameProxy()) {
while(true) {
list<string> lAddresses(0);
{
LOCK(cs_vAddedNodes);
BOOST_FOREACH(string& strAddNode, vAddedNodes)
lAddresses.push_back(strAddNode);
}
BOOST_FOREACH(string& strAddNode, lAddresses) {
CAddress addr;
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(addr, &grant, strAddNode.c_str());
MilliSleep(500);
}
MilliSleep(120000); // Retry every 2 minutes
}
}
for (unsigned int i = 0; true; i++)
{
list<string> lAddresses(0);
{
LOCK(cs_vAddedNodes);
BOOST_FOREACH(string& strAddNode, vAddedNodes)
lAddresses.push_back(strAddNode);
}
list<vector<CService> > lservAddressesToAdd(0);
BOOST_FOREACH(string& strAddNode, lAddresses)
{
vector<CService> vservNode(0);
if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
{
lservAddressesToAdd.push_back(vservNode);
{
LOCK(cs_setservAddNodeAddresses);
BOOST_FOREACH(CService& serv, vservNode)
setservAddNodeAddresses.insert(serv);
}
}
}
// Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
// (keeping in mind that addnode entries can have many IPs if fNameLookup)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++)
BOOST_FOREACH(CService& addrNode, *(it))
if (pnode->addr == addrNode)
{
it = lservAddressesToAdd.erase(it);
it--;
break;
}
}
BOOST_FOREACH(vector<CService>& vserv, lservAddressesToAdd)
{
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant);
MilliSleep(500);
}
MilliSleep(120000); // Retry every 2 minutes
}
}
// if successful, this moves the passed grant to the constructed node
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
{
//
// Initiate outbound network connection
//
boost::this_thread::interruption_point();
if (!strDest)
if (IsLocal(addrConnect) ||
FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
FindNode(addrConnect.ToStringIPPort().c_str()))
return false;
if (strDest && FindNode(strDest))
return false;
CNode* pnode = ConnectNode(addrConnect, strDest);
boost::this_thread::interruption_point();
if (!pnode)
return false;
if (grantOutbound)
grantOutbound->MoveTo(pnode->grantOutbound);
pnode->fNetworkNode = true;
if (fOneShot)
pnode->fOneShot = true;
return true;
}
// for now, use a very simple selection metric: the node from which we received
// most recently
double static NodeSyncScore(const CNode *pnode) {
return -pnode->nLastRecv;
}
void static StartSync(const vector<CNode*> &vNodes) {
CNode *pnodeNewSync = NULL;
double dBestScore = 0;
// fImporting and fReindex are accessed out of cs_main here, but only
// as an optimization - they are checked again in SendMessages.
if (fImporting || fReindex)
return;
// Iterate over all nodes
BOOST_FOREACH(CNode* pnode, vNodes) {
// check preconditions for allowing a sync
if (!pnode->fClient && !pnode->fOneShot &&
!pnode->fDisconnect && pnode->fSuccessfullyConnected &&
(pnode->nStartingHeight > (nBestHeight - 144)) &&
(pnode->nVersion < NOBLKS_VERSION_START || pnode->nVersion >= NOBLKS_VERSION_END)) {
// if ok, compare node's score with the best so far
double dScore = NodeSyncScore(pnode);
if (pnodeNewSync == NULL || dScore > dBestScore) {
pnodeNewSync = pnode;
dBestScore = dScore;
}
}
}
// if a new sync candidate was found, start sync!
if (pnodeNewSync) {
pnodeNewSync->fStartSync = true;
pnodeSync = pnodeNewSync;
}
}
void ThreadMessageHandler()
{
SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
while (true)
{
bool fHaveSyncNode = false;
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy) {
pnode->AddRef();
if (pnode == pnodeSync)
fHaveSyncNode = true;
}
}
if (!fHaveSyncNode)
StartSync(vNodesCopy);
// Poll the connected nodes for messages
CNode* pnodeTrickle = NULL;
if (!vNodesCopy.empty())
pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (pnode->fDisconnect)
continue;
// Receive messages
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv)
if (!ProcessMessages(pnode))
pnode->CloseSocketDisconnect();
}
boost::this_thread::interruption_point();
// Send messages
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
SendMessages(pnode, pnode == pnodeTrickle);
}
boost::this_thread::interruption_point();
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
MilliSleep(100);
}
}
bool BindListenPort(const CService &addrBind, string& strError)
{
strError = "";
int nOne = 1;
// Create socket for listening for incoming connections
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
{
strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
printf("%s\n", strError.c_str());
return false;
}
SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hListenSocket == INVALID_SOCKET)
{
strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
#ifdef SO_NOSIGPIPE
// Different way of disabling SIGPIPE on BSD
setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
#endif
#ifndef WIN32
// Allow binding if the port is still in TIME_WAIT state after
// the program was closed and restarted. Not an issue on windows.
setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
#endif
#ifdef WIN32
// Set to non-blocking, incoming connections will also inherit this
if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
#else
if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
#endif
{
strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
#ifdef USE_IPV6
// some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
// and enable it by default or not. Try to enable it, if possible.
if (addrBind.IsIPv6()) {
#ifdef IPV6_V6ONLY
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
#endif
#ifdef WIN32
int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
// this call is allowed to fail
setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
#endif
}
#endif
if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
{
int nErr = WSAGetLastError();
if (nErr == WSAEADDRINUSE)
strError = strprintf(_("Unable to bind to %s on this computer. Bitcoin is probably already running."), addrBind.ToString().c_str());
else
strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
printf("%s\n", strError.c_str());
return false;
}
printf("Bound to %s\n", addrBind.ToString().c_str());
// Listen for incoming connections
if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
{
strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
vhListenSocket.push_back(hListenSocket);
if (addrBind.IsRoutable() && fDiscover)
AddLocal(addrBind, LOCAL_BIND);
return true;
}
void static Discover()
{
if (!fDiscover)
return;
#ifdef WIN32
// Get local host IP
char pszHostName[1000] = "";
if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
{
vector<CNetAddr> vaddr;
if (LookupHost(pszHostName, vaddr))
{
BOOST_FOREACH (const CNetAddr &addr, vaddr)
{
AddLocal(addr, LOCAL_IF);
}
}
}
#else
// Get local host ip
struct ifaddrs* myaddrs;
if (getifaddrs(&myaddrs) == 0)
{
for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr == NULL) continue;
if ((ifa->ifa_flags & IFF_UP) == 0) continue;
if (strcmp(ifa->ifa_name, "lo") == 0) continue;
if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
if (ifa->ifa_addr->sa_family == AF_INET)
{
struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
CNetAddr addr(s4->sin_addr);
if (AddLocal(addr, LOCAL_IF))
printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
}
#ifdef USE_IPV6
else if (ifa->ifa_addr->sa_family == AF_INET6)
{
struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
CNetAddr addr(s6->sin6_addr);
if (AddLocal(addr, LOCAL_IF))
printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
}
#endif
}
freeifaddrs(myaddrs);
}
#endif
// Don't use external IPv4 discovery, when -onlynet="IPv6"
if (!IsLimited(NET_IPV4))
NewThread(ThreadGetMyExternalIP, NULL);
}
void StartNode(boost::thread_group& threadGroup)
{
if (semOutbound == NULL) {
// initialize semaphore
int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections);
semOutbound = new CSemaphore(nMaxOutbound);
}
if (pnodeLocalHost == NULL)
pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
Discover();
//
// Start threads
//
if (!GetBoolArg("-dnsseed", true))
printf("DNS seeding disabled\n");
else
threadGroup.create_thread(boost::bind(&TraceThread<boost::function<void()> >, "dnsseed", &ThreadDNSAddressSeed));
#ifdef USE_UPNP
// Map ports with UPnP
MapPort(GetBoolArg("-upnp", USE_UPNP));
#endif
// Send and receive from sockets, accept connections
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler));
// Initiate outbound connections from -addnode
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections));
// Initiate outbound connections
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections));
// Process messages
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler));
// Dump network addresses
threadGroup.create_thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, 1000 * dump_addresses_interval));
}
bool StopNode()
{
printf("StopNode()\n");
GenerateBitcoins(false, NULL);
MapPort(false);
nTransactionsUpdated++;
if (semOutbound)
for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
semOutbound->post();
MilliSleep(50);
DumpAddresses();
return true;
}
class CNetCleanup
{
public:
CNetCleanup()
{
}
~CNetCleanup()
{
// Close sockets
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->hSocket != INVALID_SOCKET)
closesocket(pnode->hSocket);
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET)
if (closesocket(hListenSocket) == SOCKET_ERROR)
printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
// clean up some globals (to help leak detection)
BOOST_FOREACH(CNode *pnode, vNodes)
delete pnode;
BOOST_FOREACH(CNode *pnode, vNodesDisconnected)
delete pnode;
vNodes.clear();
vNodesDisconnected.clear();
delete semOutbound;
semOutbound = NULL;
delete pnodeLocalHost;
pnodeLocalHost = NULL;
#ifdef WIN32
// Shutdown Windows Sockets
WSACleanup();
#endif
}
}
instance_of_cnetcleanup;
void RelayTransaction(const CTransaction& tx, const uint256& hash)
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(10000);
ss << tx;
RelayTransaction(tx, hash, ss);
}
void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss)
{
CInv inv(MSG_TX, hash);
{
LOCK(cs_mapRelay);
// Expire old relay messages
while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
{
mapRelay.erase(vRelayExpiration.front().second);
vRelayExpiration.pop_front();
}
// Save original serialized message so newer versions are preserved
mapRelay.insert(std::make_pair(inv, ss));
vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
}
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if(!pnode->fRelayTxes)
continue;
LOCK(pnode->cs_filter);
if (pnode->pfilter)
{
if (pnode->pfilter->IsRelevantAndUpdate(tx, hash))
pnode->PushInventory(inv);
} else
pnode->PushInventory(inv);
}
}
| {
"content_hash": "b4b8910dbb46e7ee4716da32c8444ef0",
"timestamp": "",
"source": "github",
"line_count": 1881,
"max_line_length": 196,
"avg_line_length": 30.045720361509836,
"alnum_prop": 0.5448014721494798,
"repo_name": "illuminaticorporation/ICR",
"id": "0491d9f087ff79965bb344b98bb326f468af661d",
"size": "56516",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/net.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "526933"
},
{
"name": "C++",
"bytes": "2422405"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "Objective-C++",
"bytes": "2656"
},
{
"name": "Python",
"bytes": "3773"
},
{
"name": "Shell",
"bytes": "7980"
},
{
"name": "TypeScript",
"bytes": "5244759"
}
],
"symlink_target": ""
} |
using System;
namespace PizzaCalories
{
public class Dough
{
private string flourType;
private string bakingTechnique;
private double weight;
private double calories;
public Dough(string flourType, string bakingTechnique, double weight)
{
this.FlourType = flourType;
this.BakingTechnique = bakingTechnique;
this.Weight = weight;
this.Calories = calories;
}
public double Calories
{
get { return this.calories; }
set { this.calories = GetCalories(this.weight, this.flourType, this.bakingTechnique); }
}
private string FlourType
{
set
{
if (!value.ToLowerInvariant().Equals("white")
&& !value.ToLowerInvariant().Equals("wholegrain"))
{
throw new ArgumentException("Invalid type of dough.");
}
this.flourType = value;
}
}
private string BakingTechnique
{
set
{
if (!value.ToLowerInvariant().Equals("crispy")
&& !value.ToLowerInvariant().Equals("chewy")
&& !value.ToLowerInvariant().Equals("homemade"))
{
throw new ArgumentException("Invalid type of dough.");
}
this.bakingTechnique = value;
}
}
private double Weight
{
set
{
if (value < 1 || value > 200)
{
throw new ArgumentException("Dough weight should be in the range [1..200].");
}
this.weight = value;
}
}
private double GetCalories(double weight, string flourType, string bakingTechnique)
{
if (flourType.ToLower() == "white") //White 1.5
{
switch (bakingTechnique.ToLower())
{
case "crispy":
return (2.0 * weight) * 1.5 * 0.9;
break;
case "chewy":
return (2.0 * weight) * 1.5 * 1.1;
break;
case "homemade":
return (2.0 * weight) * 1.5 * 1.0;
break;
}
}
else if (flourType.ToLower() == "wholegrain")
{
switch (bakingTechnique.ToLower())
{
case "crispy":
return (2.0 * weight) * 1.0 * 0.9;
break;
case "chewy":
return (2.0 * weight) * 1.0 * 1.1;
break;
case "homemade":
return (2.0 * weight) * 1.0 * 1.0;
break;
}
}
return 0;
}
}
} | {
"content_hash": "d024a952ac90804309555ecbd15aec91",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 99,
"avg_line_length": 29.737864077669904,
"alnum_prop": 0.41266731962128633,
"repo_name": "George221b/SoftUni-Tasks",
"id": "1e2bba1710323649465221692f84fa61385bd556",
"size": "3065",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "C#OOP-Basics/02.Encapsulation-Exercise/PizzaCalories/Dough.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1410133"
},
{
"name": "CSS",
"bytes": "18697"
},
{
"name": "HTML",
"bytes": "83506"
},
{
"name": "JavaScript",
"bytes": "273632"
}
],
"symlink_target": ""
} |
package org.apache.avro.mapred;
import java.io.IOException;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.conf.Configured;
/** A reducer for Avro data.
*
* <p>Applications should subclass this class and pass their subclass to {@link
* AvroJob#setReducerClass} and perhaps {@link AvroJob#setCombinerClass}.
* Subclasses override {@link #reduce}.
*/
public class AvroReducer<K,V,OUT> extends Configured {
private Pair<K,V> outputPair;
/** Called with all map output values with a given key. By default, pairs
* key with each value, collecting {@link Pair} instances. */
@SuppressWarnings("unchecked")
public void reduce(K key, Iterable<V> values,
AvroCollector<OUT> collector,
Reporter reporter) throws IOException {
if (outputPair == null)
outputPair = new Pair<K,V>(AvroJob.getOutputSchema(getConf()));
for (V value : values) {
outputPair.set(key, value);
collector.collect((OUT)outputPair);
}
}
}
| {
"content_hash": "4fd8f9a18e883b728b4f566e43cc19fd",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 79,
"avg_line_length": 29.114285714285714,
"alnum_prop": 0.6859666339548577,
"repo_name": "pwendell/Avro",
"id": "12585909c340470ddda685edb8cf76a55523b9d9",
"size": "1825",
"binary": false,
"copies": "2",
"ref": "refs/heads/trace-filestorage",
"path": "lang/java/src/java/org/apache/avro/mapred/AvroReducer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "383507"
},
{
"name": "C++",
"bytes": "271534"
},
{
"name": "Java",
"bytes": "1084478"
},
{
"name": "JavaScript",
"bytes": "144301"
},
{
"name": "Python",
"bytes": "219483"
},
{
"name": "Ruby",
"bytes": "105061"
},
{
"name": "Shell",
"bytes": "17952"
}
],
"symlink_target": ""
} |
define(function(require, exports){
var trackingServiceUrl = 'http://online-dnbard.rhcloud.com/',
// http://online-dnbard.rhcloud.com/ is an address of default tracking service
// Change it if you use self-hosting instance of online tracking service
appToken = <PLACE APPLICATION TOKEN HERE>,
// read https://github.com/dnbard/brackets-extension-rating/wiki/Online-and-max-users-counters-in-this-extension
// to learn on how to obtain an application token for your extension
mins60 = 60 * 60 * 1000,
mins5 = 5 * 60 * 1000,
keyId = 'ext-online-id';
function tick(){
var userId = getUserId(appToken, keyId),
url;
if (userId){
url = trackingServiceUrl + 'tick/' + appToken + '/' + userId;
} else {
url = trackingServiceUrl + 'tick/' + appToken;
}
$.ajax({ url: url })
.success(function(data){
//TODO: create complex model of data in local storage to support any number of extensions
if (data && data !== 'OK' && data !== 'ERROR'){
saveUserId(data, appToken, keyId);
}
}).error(function(){
console.log('Can\'t track online status, retry in 5 mins');
setTimeout(tick, mins5);
});
}
function init(){
tick();
setInterval(tick, mins60);
}
function getUserId(appToken, keyId){
if (typeof appToken !== 'string' || typeof keyId !== 'string'){
throw new Error('Invalid argument');
}
return JSON.parse(localStorage.getItem(keyId) || '{ }')[appToken];
}
function saveUserId(id, appToken, keyId){
if (typeof id !== 'string' || typeof appToken !== 'string' || typeof keyId !== 'string'){
throw new Error('Invalid argument');
}
var obj = JSON.parse(localStorage.getItem(keyId) || '{ }');
obj[appToken] = id;
localStorage.setItem(keyId, JSON.stringify(obj));
}
exports.init = init;
});
| {
"content_hash": "b6da965b22b855c4262ca1fbfc7c4be5",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 120,
"avg_line_length": 36.13793103448276,
"alnum_prop": 0.558206106870229,
"repo_name": "dnbard/brackets-extension-rating",
"id": "0465a554f21e42ef141be9605c2d74fb0d1b9249",
"size": "2356",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/onlineTrackingClient.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6135"
},
{
"name": "HTML",
"bytes": "2127"
},
{
"name": "JavaScript",
"bytes": "146991"
}
],
"symlink_target": ""
} |
#include "codegen/llvm/Codegen.hpp"
#ifdef HAVE_LLVM
namespace codegen { namespace llvm_ {
Codegen::Codegen ()
{
_cur_bb = NULL;
_cur_func = NULL;
_exit_block = NULL;
_module = NULL;
_st = NULL;
llvm::InitializeNativeTarget();
}
llvm::Value*
Codegen::_castLlvmValue (llvm::Value* val, mem::st::Type* src_ty, mem::st::Type* dest_ty)
{
// Casting between two integer types
if (src_ty->isIntType() && dest_ty->isIntType())
{
if (src_ty->ByteSize() == dest_ty->ByteSize())
{
// Don't do anything
}
// Extending (SAFE)
if (src_ty->ByteSize() < dest_ty->ByteSize())
{
val = new llvm::SExtInst(val, _type_maker.get(dest_ty), "", _cur_bb);
}
// Truncating (UNSAFE)
else if (src_ty->ByteSize() > dest_ty->ByteSize())
{
val = new llvm::TruncInst(val, _type_maker.get(dest_ty), "", _cur_bb);
}
}
// Casting between two pointer types
else if (src_ty->isPointerType() && dest_ty->isPointerType())
{
if (!_st->isVoidType(mem::st::castToPointerType(dest_ty)->PointedType()))
{
val = new llvm::BitCastInst(val, _type_maker.get(dest_ty), "", _cur_bb);
}
}
DEBUG_ENSURE (val != NULL);
return val;
}
std::string
Codegen::_getLlvmTypeName (llvm::Type* ty)
{
std::stringstream name;
if (ty != NULL)
{
if (ty->isStructTy())
{
name << llvm::cast<llvm::StructType>(ty)->getName().str();
}
else if (ty->isPointerTy())
{
name << _getLlvmTypeName(llvm::cast<llvm::PointerType>(ty)->getElementType()) + "*";
}
else if (ty->isPrimitiveType())
{
name << "Primitive";
}
else if (ty->isArrayTy())
{
name << "[" + _getLlvmTypeName(llvm::cast<llvm::ArrayType>(ty)->getElementType()) + "]";
}
else if (ty->isVectorTy())
{
name << "<>";
}
else if (ty->isFunctionTy())
{
name << "Func";
}
else if (ty->isIntegerTy())
{
name << "i" << static_cast<llvm::IntegerType*>(ty)->getBitWidth();
}
else
{
name << "UnknownType";
}
}
else
{
name << "NULL";
}
return name.str();
}
llvm::GetElementPtrInst*
Codegen::_createGepInst(llvm::Value* base, std::vector<llvm::Value*> idx)
{
DEBUG_REQUIRE (base != NULL);
#if 1
llvm::Type* base_ty = base->getType();
std::string base_ty_name;
if (base_ty != NULL)
{
base_ty_name = _getLlvmTypeName(base_ty);
}
std::string idx_name = "";
for (size_t i = 0; i < idx.size(); ++i)
{
idx_name += "[";
idx_name += _getLlvmTypeName(idx[i]->getType());
idx_name += "]";
}
DEBUG_PRINTF("GEP %s%s\n", base_ty_name.c_str(), idx_name.c_str());
#endif
llvm::GetElementPtrInst* gep_inst = llvm::GetElementPtrInst::Create(base, idx, "", _cur_bb);
DEBUG_ENSURE (gep_inst != NULL && "Failed to create GEP instruction");
return gep_inst;
}
std::string
Codegen::_getCodegenFuncName (mem::st::Func* func)
{
std::string name = "";
if (func->IsExternal())
{
name = func->Name();
}
else
{
name = func->gQualifiedName();
}
return name;
}
mem::st::Type*
Codegen::_getLowestCommonType (mem::st::Symbol* left_ty, mem::st::Symbol* right_ty)
{
mem::st::Type* common_ty = NULL;
if (!left_ty->isPointerType())
{
common_ty = mem::st::castToType(left_ty);
}
else if (!right_ty->isPointerType())
{
common_ty = mem::st::castToType(right_ty);
}
// Both operands are pointers
else
{
common_ty = mem::st::util::getPointerBaseType(mem::st::castToPointerType(left_ty));
}
return common_ty;
}
std::vector<llvm::Type*>
Codegen::_getFuncParamsTy (mem::st::Func* func)
{
std::vector<llvm::Type*> params_ty;
llvm::Type* cur_ty = NULL;
for (size_t i = 0; i < func->ParamCount(); ++i)
{
cur_ty = _type_maker.get(func->getParam(i)->Type());
assert (cur_ty != NULL);
params_ty.push_back(cur_ty);
}
return params_ty;
}
llvm::Type*
Codegen::_getFuncReturnTy (mem::ast::node::Func* func)
{
llvm::Type* ty = NULL;
if (func->ReturnTypeNode() != NULL)
{
ty = _type_maker.get(func->ExprType());
}
else
{
ty = _type_maker.makeVoidType();
}
IF_DEBUG
{
if (ty == NULL)
{
DEBUG_PRINTF("Function <%s> : cannot find return type <%s>\n",
func->ValueCstr(),
func->ExprType()->gQualifiedNameCstr());
}
}
assert(ty != NULL);
return ty;
}
bool
Codegen::_mustBeLoaded (mem::ast::node::Node* node)
{
if (node->hasBoundSymbol())
{
if (!node->BoundSymbol()->isAnyConstant()
&& !node->BoundSymbol()->isFuncSymbol())
{
return true;
}
}
if (node->hasExprType())
{
//return true;
}
if (node->isKind(mem::ast::node::Kind::BRACKET_OP))
{
return true;
}
/*
switch (node->Kind())
{
case mem::ast::node::Kind::FINAL_ID:
if (
node->BoundSymbol()->isFuncSymbol()
|| node->BoundSymbol()->isAnyConstant())
{
return false;
}
return true;
break;
case mem::ast::node::Kind::GROUP:
return _mustBeLoaded(node->getChild(0));
case mem::ast::node::Kind::BRACKET_OP:
case mem::ast::node::Kind::DEREF:
case mem::ast::node::Kind::DOT:
case mem::ast::node::Kind::TUPLE:
return true;
}
*/
return false;
}
void
Codegen::gen (mem::ast::node::Node* root)
{
assert (_st != NULL);
_module = new llvm::Module("top", llvm::getGlobalContext());
_type_maker.setModule(_module);
_type_maker.setStack(&_stack);
_type_maker.setSymbolTable(_st);
mem::st::PointerType* void_ptr = mem::st::util::getPointerType(_st->_core_types.VoidTy());
_type_maker.bind(void_ptr, _type_maker.makeVoidPointerType());
_stack.push();
_stack.set(_st->_core_types._null, llvm::ConstantPointerNull::get(_type_maker.makeVoidPointerType()));
//codegenTupleTypes();
codegenMemoryFunctions();
codegenFunctionDeclarations();
codegenFunctionBodies(static_cast<mem::ast::node::Root*>(root));
}
llvm::Value*
Codegen::cgAmpersandExpr (mem::ast::node::Node* node)
{
assert(node != NULL);
assert(node->isAmpersandNode());
std::string amp_label = "Amp";
llvm::Value* base_val = cgExpr(node->getChild(0));
return base_val;
}
llvm::Value*
Codegen::cgBinaryExpr (mem::ast::node::Node* node)
{
DEBUG_REQUIRE (node != NULL);
llvm::Value* val = NULL;
mem::ast::node::Node* left_node = node->getChild(0);
mem::ast::node::Node* right_node = node->getChild(1);
llvm::Value* left_val = cgExprAndLoad(left_node, node->ExprType());
llvm::Value* right_val = cgExprAndLoad(right_node, node->ExprType());
llvm::Instruction::BinaryOps op;
switch (node->Kind())
{
case mem::ast::node::Kind::OP_BIT_OR: op = llvm::Instruction::Or; break;
case mem::ast::node::Kind::OP_BIT_AND: op = llvm::Instruction::And; break;
case mem::ast::node::Kind::OP_XOR: op = llvm::Instruction::Xor; break;
case mem::ast::node::Kind::OP_LSHIFT: op = llvm::Instruction::Shl; break;
case mem::ast::node::Kind::OP_RSHIFT: op = llvm::Instruction::LShr; break;
case mem::ast::node::Kind::OP_PLUS: op = llvm::Instruction::Add; break;
case mem::ast::node::Kind::OP_MINUS: op = llvm::Instruction::Sub; break;
case mem::ast::node::Kind::OP_MODULO: op = llvm::Instruction::SRem; break;
case mem::ast::node::Kind::OP_MUL: op = llvm::Instruction::Mul; break;
case mem::ast::node::Kind::OP_DIV: op = llvm::Instruction::SDiv; break;
default:
DEBUG_PRINTF("Unsupported arithmetic operation : %s\n",
node->KindName().c_str());
assert (false);
}
val = llvm::BinaryOperator::Create(op, left_val,
right_val, "", _cur_bb);
DEBUG_ENSURE (val != NULL);
return val;
}
void
Codegen::cgBlock (mem::ast::node::Block* block)
{
assert (block != NULL);
_stack.push();
for (size_t i = 0; i < block->ChildCount(); ++i)
{
cgExpr(block->getChild(i));
}
_stack.pop();
}
llvm::Value*
Codegen::cgBracketOpExpr (mem::ast::node::BracketOp* n)
{
DEBUG_REQUIRE (n != NULL);
// -------
// VALUE
// -------
mem::ast::node::Node* value_node = n->ValueNode();
llvm::Value* val = cgExpr(value_node);
assert (val != NULL);
// -------
// INDEX
// -------
llvm::Value* index = cgExprAndLoad(n->IndexNode(), _st->gCoreTypes().IntTy());
assert (index != NULL);
/*
// If this is a pointer we have to dereference as much as
// (indirection_level - 1)
if (value_ty->isPointerType())
{
for (int i = 0; i < mem::st::castToPointerType(value_ty)->IndirectionLevel(); ++i)
{
val = new llvm::LoadInst(val, "", _cur_bb);
}
}
*/
// FIXME What ?
std::vector<llvm::Value*> idx;
if (0)//value_ty->isArrayType())
{
idx.push_back(_createInt32Constant(0));
}
idx.push_back(index);
// Compute address
llvm::GetElementPtrInst* inst = _createGepInst(val, idx);
inst->setIsInBounds(true);
DEBUG_ENSURE (inst != NULL);
return inst;
}
llvm::Value*
Codegen::cgCallExpr (mem::ast::node::Call* node)
{
DEBUG_REQUIRE (node != NULL);
DEBUG_REQUIRE (node->CallerNode() != NULL);
llvm::Value* callee = NULL;
mem::st::Type* caller_node_ty = node->CallerNode()->ExprType();
mem::st::FunctionType* func_ty = NULL;
// Calling a classic function
if (caller_node_ty->isFunctionType())
{
mem::st::Func* func = mem::st::castToFunc(node->CallerNode()->BoundSymbol());
func_ty = static_cast<mem::st::FunctionType*>(caller_node_ty);
callee = _functions[_getCodegenFuncName(func)];
}
// Calling a functor
else if (mem::st::util::isFunctorType(caller_node_ty))
{
mem::st::PointerType* fctor = mem::st::castToPointerType(caller_node_ty);
func_ty = static_cast<mem::st::FunctionType*>(fctor->getNonPointerParent());
callee = cgExprAndLoad(node->CallerNode(), func_ty);
}
else
{
assert(false);
}
assert(func_ty->isFunctionType());
std::vector<llvm::Value*> params;
// -----------------
// With parameters
// -----------------
if (node->ParamsNode() != NULL)
{
mem::ast::node::Node* cur_param_node = NULL;
llvm::Value* param_value = NULL;
for (size_t i = 0; i < node->ParamsNode()->ChildCount(); ++i)
{
cur_param_node = node->ParamsNode()->getChild(i);
param_value = cgExpr(cur_param_node);//, func_ty->getArgument(i));
if (_mustBeLoaded(cur_param_node))
{
param_value = new llvm::LoadInst(param_value, "", _cur_bb);
}
param_value = _castLlvmValue(param_value, cur_param_node->ExprType(), func_ty->getArgument(i));
params.push_back(param_value);
}
}
llvm::CallInst* call = llvm::CallInst::Create(callee, params, "", _cur_bb);
if (call != NULL && !_st->isVoidType(func_ty->ReturnType()))
{
call->setDoesNotReturn(true);
}
DEBUG_ENSURE (call != NULL);
return call;
}
llvm::Value*
Codegen::cgCastExpr (mem::ast::node::CastOp* n)
{
DEBUG_REQUIRE (n != NULL);
llvm::Value* src_val = cgExprAndLoad(n->ValueNode());
mem::st::Type* src_ty = n->ValueNode()->ExprType();
mem::st::Type* dest_ty = n->ExprType();
llvm::Value* val = _castLlvmValue(src_val, src_ty, dest_ty);
/*
// Casting between two integer types
if (src_ty->isIntType() && dest_ty->isIntType())
{
// Extending (SAFE)
if (src_ty->ByteSize() < dest_ty->ByteSize())
{
val = new llvm::SExtInst(src_val, _type_maker.get(dest_ty), "", _cur_bb);
}
// Truncating (UNSAFE)
else if (src_ty->ByteSize() > dest_ty->ByteSize())
{
val = new llvm::TruncInst(src_val, _type_maker.get(dest_ty), "", _cur_bb);
}
else
{
// No casting required
val = src_val;
}
}
// Casting between two pointer types
else if (src_ty->isPointerType() && dest_ty->isPointerType())
{
if (static_cast<mem::st::PointerType*>(dest_ty)->PointedType()->Name() == "void")
{
val = new llvm::BitCastInst(src_val, _type_maker.get(dest_ty), "", _cur_bb);
}
}
*/
DEBUG_ENSURE (val != NULL);
return val;
}
llvm::Value*
Codegen::cgCompOp (mem::ast::node::BinaryOp* n)
{
assert (n != NULL);
assert (_cur_bb != NULL);
mem::ast::node::Node* left_val_node = n->LeftNode();
mem::ast::node::Node* right_val_node = n->RightNode();
mem::st::Type* left_ty = left_val_node->ExprType();
mem::st::Type* right_ty = right_val_node->ExprType();
mem::st::Type* expected_operand_ty = NULL;
if (left_ty->isIntType() && right_ty->isIntType())
{
expected_operand_ty = mem::st::util::getBiggestIntType(
mem::st::castToIntType(left_ty),
mem::st::castToIntType(right_ty));
}
llvm::Value* left_val = cgExprAndLoad(left_val_node, expected_operand_ty);
llvm::Value* right_val = cgExprAndLoad(right_val_node, expected_operand_ty);
llvm::ICmpInst::Predicate pred;
switch (n->Kind())
{
case mem::ast::node::Kind::OP_NE: pred = llvm::ICmpInst::ICMP_NE; break;
case mem::ast::node::Kind::OP_EQ_EQ: pred = llvm::ICmpInst::ICMP_EQ; break;
case mem::ast::node::Kind::OP_LT: pred = llvm::ICmpInst::ICMP_SLT; break;
case mem::ast::node::Kind::OP_LTE: pred = llvm::ICmpInst::ICMP_SLE; break;
case mem::ast::node::Kind::OP_GT: pred = llvm::ICmpInst::ICMP_SGT; break;
case mem::ast::node::Kind::OP_GTE: pred = llvm::ICmpInst::ICMP_SGE; break;
default:
DEBUG_PRINTF("Unsupported comparison operator (%s)\n",
n->KindName().c_str());
assert(false);
}
llvm::CmpInst* comp_inst = new llvm::ICmpInst(*_cur_bb, pred, left_val,
right_val, "");
return comp_inst;
}
llvm::Value*
Codegen::cgDotExpr (mem::ast::node::BinaryOp* node)
{
DEBUG_REQUIRE (node != NULL);
DEBUG_REQUIRE (mem::ast::node::canCastToDot(node->Kind()));
llvm::Value* left_node = NULL;
// We can't rely on cgExpr here because it would load the left node and we
// wouldn't be able to have a pointer to use GetElementPtr on.
if (mem::ast::node::canCastToDot(node->LeftNode()->Kind()))
{
left_node = cgDotExpr(mem::ast::node::cast<mem::ast::node::BinaryOp>(node->LeftNode()));
}
else
{
left_node = cgFinalIdExpr(mem::ast::node::cast<mem::ast::node::Text>(node->LeftNode()));
}
std::vector<llvm::Value*> idx;
int indirection_level = 0;
if (node->LeftNode()->ExprType()->isPointerType())
{
mem::st::PointerType* ptr_ty = mem::st::castToPointerType(node->LeftNode()->ExprType());
indirection_level = ptr_ty->IndirectionLevel();
}
for (int i = 0; i < indirection_level; ++i)
{
left_node = new llvm::LoadInst(left_node, "", _cur_bb);
idx.push_back(_createInt32Constant(0));
assert(left_node != NULL);
}
// Compute the field index in the whole type hierarchy
mem::st::Field* field = static_cast<mem::st::Field*>(node->BoundSymbol());
mem::st::Class* cls_ty = mem::st::castToClassType(field->Parent());
int field_index = cls_ty->getFieldAbsoluteIndex(field->FieldIndex());
idx.push_back(_createInt32Constant(field_index));
llvm::Value* gep_inst = _createGepInst(left_node, idx);
DEBUG_ENSURE (gep_inst!= NULL);
return gep_inst;
}
llvm::Value*
Codegen::cgExpr (mem::ast::node::Node* node)
{
assert (node != NULL);
llvm::Value* res = NULL;
switch (node->Kind())
{
case mem::ast::node::Kind::AMPERSAND:
res = cgAmpersandExpr (node);
break;
case mem::ast::node::Kind::BRACKET_OP:
res = cgBracketOpExpr(static_cast<mem::ast::node::BracketOp*>(node));
break;
case mem::ast::node::Kind::CALL:
res = cgCallExpr(static_cast<mem::ast::node::Call*>(node));
break;
case mem::ast::node::Kind::DOT:
res = cgDotExpr(mem::ast::node::cast<mem::ast::node::BinaryOp>(node));
break;
case mem::ast::node::Kind::OP_NE:
case mem::ast::node::Kind::OP_EQ_EQ:
case mem::ast::node::Kind::OP_LT:
case mem::ast::node::Kind::OP_LTE:
case mem::ast::node::Kind::OP_GT:
case mem::ast::node::Kind::OP_GTE:
res = cgCompOp(static_cast<mem::ast::node::BinaryOp*>(node));
break;
case mem::ast::node::Kind::OP_CAST:
res = cgCastExpr (static_cast<mem::ast::node::CastOp*>(node));
break;
case mem::ast::node::Kind::GROUP:
res = cgExpr(node->getChild(0));
break;
case mem::ast::node::Kind::IF:
cgIfStatement(static_cast<mem::ast::node::If*>(node));
break;
case mem::ast::node::Kind::FINAL_ID:
res = cgFinalIdExpr(static_cast<mem::ast::node::FinalId*>(node));
break;
case mem::ast::node::Kind::FOR:
cgForStatement(static_cast<mem::ast::node::For*>(node));
break;
case mem::ast::node::Kind::NEW:
res = cgNewExpr(static_cast<mem::ast::node::New*>(node));
break;
case mem::ast::node::Kind::NUMBER:
res = cgNumberExpr(static_cast<mem::ast::node::Number*>(node));
assert (res != NULL);
break;
case mem::ast::node::Kind::OP_BIT_AND:
case mem::ast::node::Kind::OP_BIT_OR:
case mem::ast::node::Kind::OP_DIV:
case mem::ast::node::Kind::OP_LSHIFT:
case mem::ast::node::Kind::OP_RSHIFT:
case mem::ast::node::Kind::OP_MINUS:
case mem::ast::node::Kind::OP_MODULO:
case mem::ast::node::Kind::OP_MUL:
case mem::ast::node::Kind::OP_PLUS:
case mem::ast::node::Kind::OP_XOR:
res = cgBinaryExpr(node);
break;
case mem::ast::node::Kind::DEREF:
res = cgDerefExpr(node);
break;
case mem::ast::node::Kind::RETURN:
cgReturnStatement (static_cast<mem::ast::node::Return*>(node));
break;
case mem::ast::node::Kind::TUPLE:
res = codegenTuple (static_cast<mem::ast::node::Tuple*>(node));
break;
case mem::ast::node::Kind::STRING:
res = cgString(static_cast<mem::ast::node::String*>(node));
break;
case mem::ast::node::Kind::VARIABLE_ASSIGNMENT:
cgVarAssignStatement (static_cast<mem::ast::node::VarAssign*>(node));
break;
case mem::ast::node::Kind::VARIABLE_DECLARATION:
cgVarDeclStatement (static_cast<mem::ast::node::VarDecl*>(node));
break;
case mem::ast::node::Kind::WHILE:
cgWhileStatement (static_cast<mem::ast::node::While*>(node));
break;
default:
DEBUG_PRINTF("Unsupported node type (%s)\n", node->KindName().c_str());
assert(false);
}
return res;
}
llvm::Value*
Codegen::cgExprAndLoad (mem::ast::node::Node* node)
{
llvm::Value* val = cgExpr(node);
bool must_load = false;
if (val != NULL)
{
must_load = _mustBeLoaded(node);
}
if (must_load)
{
val = new llvm::LoadInst(val, "", _cur_bb);
}
return val;
}
llvm::Value*
Codegen::cgExprAndLoad (mem::ast::node::Node* node, mem::st::Type* dest_ty)
{
llvm::Value* val = NULL;
if (dest_ty->isIntType() && mem::ast::node::isa<mem::ast::node::Number>(node))
{
val = _type_maker.makeConstant(static_cast<mem::st::Constant*>(node->BoundSymbol()));
}
else
{
val = cgExpr(node);
}
if (val != NULL)
{
if (_mustBeLoaded(node))
{
val = new llvm::LoadInst(val, "", _cur_bb);
}
}
return val;
}
void
Codegen::cgFile (mem::ast::node::File* file_node)
{
mem::ast::node::Node* node = NULL;
// Codegen function bodies
for (size_t i = 0 ; i < file_node->ChildCount(); ++i)
{
node = file_node->getChild(i);
if (mem::ast::node::isa<mem::ast::node::Func>(node))
{
cgFunctionBody(mem::ast::node::cast<mem::ast::node::Func>(node));
}
}
}
llvm::Value*
Codegen::cgFinalIdExpr (mem::ast::node::Text* node)
{
DEBUG_REQUIRE (node != NULL);
DEBUG_REQUIRE (node->hasExprType());
llvm::Value* ty = _stack.get(node->BoundSymbol());
if (node->ExprType()->isArrayType())
{
std::vector<llvm::Value*> idx;
idx.push_back(_createInt32Constant(0));
idx.push_back(_createInt32Constant(0));
ty = _createGepInst(ty, idx);
}
IF_DEBUG
{
if (ty == NULL)
{
DEBUG_PRINTF("Cannot find final id `%s' in the stack\n",
node->ValueCstr());
}
}
return ty;
}
void
Codegen::cgForStatement (mem::ast::node::For* n)
{
assert (n != NULL);
cgExpr(n->InitializationNode());
llvm::BasicBlock* body_block = llvm::BasicBlock::Create(
llvm::getGlobalContext(), "for_block", _cur_func);
llvm::BasicBlock* after_block = llvm::BasicBlock::Create(
llvm::getGlobalContext(), "for_after", _cur_func);
llvm::BasicBlock* cond_block = llvm::BasicBlock::Create(
llvm::getGlobalContext(), "for_cond", _cur_func);
_cur_bb->getInstList().push_back(llvm::BranchInst::Create(cond_block));
_cur_bb = body_block;
cgBlock(static_cast<mem::ast::node::Block*>(n->BlockNode()));
cgExpr(n->IterationNode());
body_block->getInstList().push_back(llvm::BranchInst::Create(cond_block));
_cur_bb = cond_block;
llvm::Value* cond = cgExpr(n->ConditionNode());
llvm::BranchInst::Create(body_block, after_block, cond, _cur_bb);
_cur_bb = after_block;
}
void
Codegen::cgFunctionBody (mem::ast::node::Func* func_node)
{
assert(mem::ast::node::isa<mem::ast::node::Func>(func_node));
// Don't try to generate body for a virtual function
if (func_node->BodyNode() != NULL)
{
mem::st::Func* func_sym = mem::st::castToFunc(func_node->BoundSymbol());
assert (func_sym != NULL);
llvm::Function* func = _functions[_getCodegenFuncName(func_sym)];
assert (func != NULL);
llvm::BasicBlock& block = func->getEntryBlock();
_cur_bb = █
_exit_block = NULL;
_cur_func = func;
_stack.push();
// Set parameters
// We set this here instead of cgFunctionDef because we can append the
// parameters to the stack of the body of the function.
llvm::Function::arg_iterator i;
int j;
mem::st::Var* func_param = NULL;
llvm::Value* alloc = NULL;
llvm::Type* param_lty = NULL;
for (i = func->arg_begin(), j=0; i != func->arg_end(); ++i, ++j)
{
func_param = func_sym->getParam(j);
if (func_param != NULL)
{
i->setName(func_param->Name());
param_lty = _type_maker.get(func_param->Type());
alloc = new llvm::AllocaInst(param_lty, 0, "", _cur_bb);
new llvm::StoreInst(&*i, alloc, false, _cur_bb);
_stack.set(func_param, alloc);
}
}
cgBlock(func_node->BodyNode());
_stack.pop();
if (func_sym->ReturnType() == _st->_core_types.VoidTy())
{
llvm::ReturnInst::Create(_module->getContext(), NULL, _cur_bb);
}
}
_cur_bb = NULL;
}
void
Codegen::cgFunctionDef (mem::ast::node::Func* func_node)
{
mem::st::Func* func_sym = mem::st::castToFunc(func_node->BoundSymbol());
std::vector<llvm::Type*> func_ty_args;
std::string func_name;
if (func_sym->IsEntryPoint())
{
func_name = "main";
}
else
{
func_name = _getCodegenFuncName(func_sym);
}
// External function
std::vector<llvm::Type*> params;
if (func_sym->IsExternal())
{
mem::st::Var* func_param = NULL;
for (size_t i = 0; i < func_sym->ParamCount(); ++i)
{
func_param = func_sym->_params[i];
params.push_back(_type_maker.get(func_param->Type()));
assert (params[i] != NULL);
}
}
llvm::FunctionType* func_ty = llvm::FunctionType::get(
_getFuncReturnTy(func_node), params, false);
llvm::GlobalValue::LinkageTypes func_link = llvm::GlobalValue::ExternalLinkage;
llvm::Function* func = llvm::Function::Create(func_ty,
func_link,
func_name,
_module);
func->setCallingConv(llvm::CallingConv::C);
_cur_func = func;
// Don't codegen a body for a virtual/external function
if (func_node->BodyNode() != NULL)
{
llvm::BasicBlock::Create(llvm::getGlobalContext(), "entry", func);
}
_functions[_getCodegenFuncName(func_sym)] = func;
_stack.set(func_sym, func);
}
void
Codegen::cgIfStatement (mem::ast::node::If* node)
{
assert (node != NULL);
assert (_cur_bb != NULL);
// ---------------
// Create blocks
// ---------------
llvm::BasicBlock* true_block = _createBasicBlock("if_true");
llvm::BasicBlock* false_block = NULL;
if (node->ElseBlockNode() != NULL)
{
false_block = _createBasicBlock("if_false");
}
llvm::BasicBlock* after_block = _createBasicBlock("if_after");
// -----------
// Condition
// -----------
llvm::Value* cond = cgExpr(node->ConditionNode());
_pushNewCondBranchInst(_cur_bb, cond, true_block, after_block);
// ------------
// TRUE block
// ------------
_cur_bb = true_block;
_exit_block = true_block;
cgBlock(node->IfBlockNode());
_pushNewBranchInst(_cur_bb, after_block);
// -------------
// FALSE block
// -------------
if (false_block != NULL)
{
_cur_bb = false_block;
_exit_block = after_block;
cgBlock(node->ElseBlockNode());
}
_cur_bb = after_block;
}
void
Codegen::codegenMemoryFunctions ()
{
// MALLOC
std::vector<llvm::Type*> malloc_tys;
malloc_tys.push_back(llvm::Type::getInt32Ty(_module->getContext()));
llvm::FunctionType* malloc_ty = llvm::FunctionType::get(
_type_maker.makeVoidPointerType(),
malloc_tys,
/*isVarArg=*/false);
llvm::Function* malloc = llvm::Function::Create(malloc_ty,
llvm::GlobalValue::ExternalLinkage,
"malloc",
_module);
_functions["malloc"] = malloc;
}
llvm::Value*
Codegen::cgNewExpr (mem::ast::node::New* node)
{
llvm::Value* byte_size = NULL;
mem::ast::node::Node* type_node = node->TypeNode();
mem::st::Type* obj_ty = mem::st::castToType(type_node->BoundSymbol());
// FIXME Spaghetti code !
// Allocating an array
if (mem::ast::node::isa<mem::ast::node::ArrayType>(type_node))
{
mem::ast::node::ArrayType* arr_n = mem::ast::node::cast<mem::ast::node::ArrayType>(type_node);
// Array item
mem::ast::node::Node* arr_ty_n = arr_n->TypeNode();
mem::ast::node::Node* length_n = arr_n->LengthNode();
mem::st::Type* arr_ty_ty = mem::st::castToType(arr_ty_n->BoundSymbol());
// Array length
llvm::Value* num_obj = cgExprAndLoad(length_n, _st->_core_types.IntTy());
llvm::Value* obj_size = _createInt32Constant(arr_ty_ty->ByteSize());
// Compute array byte length
byte_size = llvm::BinaryOperator::Create(llvm::Instruction::Mul, num_obj, obj_size, "", _cur_bb);
}
else
{
int type_byte_size = mem::st::castToType(obj_ty)->ByteSize();
byte_size = llvm::ConstantInt::get(_type_maker.get(_st->_core_types.IntTy()), type_byte_size);
}
// -------------
// Malloc call
// -------------
llvm::Value* malloc_call = llvm::CallInst::Create(_functions["malloc"],
byte_size, "", _cur_bb);
assert(malloc_call != NULL);
// Cast the return pointer to the appropriate pointer type
assert (_type_maker.get(node->ExprType()) != NULL);
llvm::Value* ret = new llvm::BitCastInst(malloc_call, _type_maker.get(
node->ExprType()), "new_cast", _cur_bb);
// ------------------
// Constructor call
// ------------------
if (obj_ty->isClassType())
{
initializeValue(mem::st::castToClassType(obj_ty), ret);
}
else if (obj_ty->isArrayType())
{
mem::st::ArrayType* arr_ty = mem::st::castToArrayType(obj_ty);
initializeArrayOfClassInstances(arr_ty, ret, false);
}
else
{
// TODO Do something for primitive types ?
}
assert (ret != NULL);
return ret;
}
llvm::Value*
Codegen::cgNumberExpr (mem::ast::node::Number* node)
{
DEBUG_REQUIRE (node != NULL);
DEBUG_REQUIRE (node->BoundSymbol() != NULL);
DEBUG_REQUIRE (node->BoundSymbol()->isIntConstant());
// FIXME This works only for signed integers
mem::st::IntConstant* i_const = mem::st::castToIntConstant(node->BoundSymbol());
llvm::Value* val = llvm::ConstantInt::get(llvm::getGlobalContext(),
llvm::APInt(node->BoundSymbol()->ByteSize() * 8, i_const->getSignedValue(), false));
DEBUG_ENSURE (val != NULL);
return val;
}
llvm::Value*
Codegen::cgDerefExpr (mem::ast::node::Node* node)
{
mem::ast::node::Node* val_n = node->getChild(0);
llvm::Value* val = cgExpr(val_n);
#if 1
mem::st::Type* node_ty = val_n->ExprType();
if (node_ty->isPointerType() && mem::st::castToPointerType(node_ty)->isPointerToArray())
{
std::vector<llvm::Value*> idx;
idx.push_back(_createInt32Constant(0));
val = _createGepInst(val, idx);
}
#endif
return new llvm::LoadInst(val, "", _cur_bb);
}
void
Codegen::cgReturnStatement (mem::ast::node::Return* node)
{
DEBUG_REQUIRE (node != NULL);
DEBUG_REQUIRE (node->ValueNode() != NULL);
llvm::Value* val = cgExprAndLoad(node->ValueNode(), node->ExprType());
assert(val != NULL);
llvm::ReturnInst::Create(_module->getContext(), val, _cur_bb);
}
llvm::Value*
Codegen::cgString (mem::ast::node::String* n)
{
mem::st::Type* mem_ty = mem::st::util::lookupArrayType(_st->System(), "char", n->Value().size() + 1);
assert(mem_ty != NULL);
llvm::Type* llvm_ty = _type_maker.get(mem_ty);
assert(llvm_ty != NULL);
llvm::Constant* str_val = llvm::ConstantArray::get(_module->getContext(), n->Value().c_str(), true);
llvm::GlobalVariable* cons = new llvm::GlobalVariable(*_module, llvm_ty, true,
llvm::GlobalValue::PrivateLinkage, str_val, "");
std::vector<llvm::Constant*> idx;
idx.push_back(_createInt32Constant(0));
idx.push_back(_createInt32Constant(0));
llvm::Value* ret = llvm::ConstantExpr::getGetElementPtr(cons, idx);
return ret;
}
void
Codegen::cgVarAssignStatement (mem::ast::node::VarAssign* node)
{
llvm::Value* left_val = cgExpr(node->NameNode());
llvm::Value* right_val = cgExprAndLoad(node->ValueNode(), node->ExprType());
new llvm::StoreInst(right_val, left_val, _cur_bb);
}
void
Codegen::cgVarDeclStatement (mem::ast::node::VarDecl* node)
{
DEBUG_REQUIRE (node != NULL);
DEBUG_REQUIRE (mem::ast::node::isa<mem::ast::node::VarDecl>(node));
DEBUG_REQUIRE (node->hasExprType());
llvm::Type* var_ty = NULL;
llvm::Value* var_len = NULL;
if (mem::ast::node::isa<mem::ast::node::ArrayType>(node->TypeNode()))
{
mem::ast::node::ArrayType* arr = mem::ast::node::cast<mem::ast::node::ArrayType>(node->TypeNode());
assert (arr->LengthNode() != NULL);
var_ty = _type_maker.get(node->TypeNode()->BoundSymbol());
}
else
{
var_ty = _type_maker.get(node->ExprType());
}
assert(var_ty != NULL);
llvm::Value* var = new llvm::AllocaInst(var_ty, var_len,
node->Name(), _cur_bb);
if (node->ValueNode() != NULL)
{
llvm::Value* var_val = cgExprAndLoad(node->ValueNode(), node->ExprType());
assert (var_val != NULL);
new llvm::StoreInst(var_val, var, _cur_bb);
}
// ------------------
// Constructor call
// ------------------
mem::st::Type* obj_ty = mem::st::castToType(node->TypeNode()->BoundSymbol());
// Single object static allocation
if (obj_ty->isClassType() && node->ValueNode() == NULL)
{
mem::st::Class* cls_ty = mem::st::castToClassType(obj_ty);
if (cls_ty->DefaultCtor() != NULL)
{
initializeValue(cls_ty, var);
}
}
// Array static allocation
else if (obj_ty->isArrayType() && node->ValueNode() == NULL)
{
mem::st::ArrayType* arr_ty = mem::st::castToArrayType(obj_ty);
if (arr_ty->isArrayOfClassInstances())
{
//llvm::Value* var = new llvm::LoadInst(var, "", _cur_bb);
initializeArrayOfClassInstances(arr_ty, var, true);
}
}
_stack.set(node->BoundSymbol(), var);
}
void
Codegen::cgWhileStatement (mem::ast::node::While* n)
{
DEBUG_REQUIRE (n != NULL);
llvm::BasicBlock* while_cond = _createBasicBlock("while_head");
llvm::BasicBlock* while_body = _createBasicBlock("while_body");
llvm::BasicBlock* while_after = _createBasicBlock("while_after");
// Branch to the condition block (from the current block)
_pushNewBranchInst(_cur_bb, while_cond);
// -----------
// Condition
// -----------
_cur_bb = while_cond;
llvm::Value* cond_val = cgExpr(n->ConditionNode());
assert(cond_val != NULL);
// Either branch the loop block or skip the loop
_pushNewCondBranchInst(while_cond, cond_val, while_body, while_after);
// ------------
// While body
// ------------
_cur_bb = while_body;
cgBlock(mem::ast::node::cast<mem::ast::node::Block>(n->BlockNode()));
// Branch to the condition block
_pushNewBranchInst(_cur_bb, while_cond);
_cur_bb = while_after;
}
void
Codegen::codegenFunctionDeclarations ()
{
mem::st::Func* func = _st->FunctionLinkedListHead();
while (func != NULL)
{
codegenFunctionType (func);
func = func->NextFunction();
}
}
void
Codegen::codegenFunctionBodies (mem::ast::node::Root* root_n)
{
mem::ast::node::File* file_node = NULL;
mem::ast::node::Func* func_node = NULL;
for (size_t i = 0; i < root_n->ChildCount(); ++i)
{
file_node = static_cast<mem::ast::node::File*>(root_n->getChild(i));
func_node = file_node->FunctionLinkedListHead();
while (func_node != NULL)
{
cgFunctionBody(func_node);
func_node = func_node->NextFunction();
}
}
}
void
Codegen::codegenFunctionType (mem::st::Func* func_ty)
{
std::vector<llvm::Type*> func_ty_args;
std::string func_name;
if (func_ty->IsEntryPoint())
{
func_name = "main";
}
else
{
func_name = _getCodegenFuncName(func_ty);
}
// ------------
// PARAMETERS
// ------------
std::vector<llvm::Type*> params;
mem::st::Var* func_param = NULL;
// We will set their names in ::codegenFunctionBody so that we append
// them to the stack
for (size_t i = 0; i < func_ty->ParamCount(); ++i)
{
func_param = func_ty->_params[i];
params.push_back(_type_maker.get(func_param->Type()));
assert (params[i] != NULL);
}
// -------------
// RETURN TYPE
// -------------
llvm::FunctionType* func_lty = NULL;
mem::st::Type* return_ty = func_ty->ReturnType();
llvm::Type* return_lty = NULL;
if (!_st->isVoidType(return_ty))
{
return_lty = _type_maker.get(return_ty);
}
else
{
return_lty = _type_maker.makeVoidType();
}
assert (return_lty != NULL);
func_lty = llvm::FunctionType::get(return_lty, params, false);
assert (func_lty != NULL);
llvm::GlobalValue::LinkageTypes func_link;
if (func_ty->IsExternal())
{
func_link = llvm::GlobalValue::ExternalLinkage;
}
else
{
func_link = llvm::GlobalValue::ExternalLinkage;
}
llvm::Function* func = llvm::Function::Create(func_lty,
func_link,
func_name,
_module);
func->setCallingConv(llvm::CallingConv::C);
_cur_func = func;
// Don't codegen a body for a virtual/external function
if (func_ty->HasBody())
{
llvm::BasicBlock::Create(llvm::getGlobalContext(), "entry", func);
}
_functions[_getCodegenFuncName(func_ty)] = func;
_stack.set(func_ty, func);
}
llvm::Value*
Codegen::codegenTuple (mem::ast::node::Tuple* n)
{
DEBUG_REQUIRE (n != NULL);
mem::st::TupleType* tuple_ty = mem::st::castToTupleType(n->ExprType());
llvm::Type* tuple_lty = _type_maker.get(tuple_ty);
llvm::AllocaInst* var = new llvm::AllocaInst(tuple_lty, 0, "", _cur_bb);
llvm::Value* field = NULL;
llvm::Value* field_val = NULL;
std::vector<llvm::Value*> field_idx;
field_idx.push_back(_createInt32Constant(0));
field_idx.push_back(NULL); // Reserved for the field index
for (size_t i = 0; i < n->ChildCount(); ++i)
{
field_idx[1] = _createInt32Constant(i);
field = _createGepInst(var, field_idx);
field_val = cgExprAndLoad(n->getChild(i), tuple_ty->Subtypes()[i]);
new llvm::StoreInst(field_val, field, "", _cur_bb);
}
return var;
}
std::string
Codegen::getLlvmByteCode ()
{
#if 0
// Don't delete that !
//
// I seem to be on the right track but, for some reason, no code is emited
const llvm::Target* target = NULL;
for (llvm::TargetRegistry::iterator it = llvm::TargetRegistry::begin(),
ie = llvm::TargetRegistry::end(); it != ie; ++it)
{
if (strcmp(it->getName(),"x86")==0)
{
target = &*it;
}
}
if (target != NULL)
{
std::string err;
llvm::raw_fd_ostream obj_file("/home/thomas/test.s", err);
llvm::formatted_raw_ostream out(obj_file);
DEBUG_PRINTF("Errors ? %s\n", err.c_str());
llvm::TargetMachine* t = target->createTargetMachine(_module->getTargetTriple(), "", "");
assert (t != NULL);
llvm::PassManager pm;
pm.add(new llvm::TargetData(_module));
t->addPassesToEmitFile(pm, out, llvm::TargetMachine::CGFT_AssemblyFile,llvm::CodeGenOpt::Less);
pm.run(*_module);
}
else
{
DEBUG_PRINT("Architecture not supported\n");
}
#endif
std::string bc;
llvm::raw_string_ostream stream(bc);
_module->print(stream, NULL);
return bc;
}
void
Codegen::initializeValue (mem::st::Type* ty, llvm::Value* val)
{
if (ty->isClassType())
{
mem::st::Class* cls_ty = mem::st::castToClassType(ty);
// 0 initialize
llvm::Constant* init = llvm::ConstantAggregateZero::get(_type_maker.get(cls_ty));
new llvm::StoreInst(init, val, "", _cur_bb);
// Call constructor
if (cls_ty->DefaultCtor() != NULL)
{
llvm::CallInst::Create(
_functions[cls_ty->DefaultCtor()->gQualifiedName()],
val, "", _cur_bb);
}
}
else if (ty->isIntType())
{
mem::st::IntType* int_ty = mem::st::castToIntType(ty);
llvm::Constant* init = llvm::ConstantInt::get(_type_maker.get(int_ty), 0, true);
new llvm::StoreInst(init, val, "", _cur_bb);
}
}
void
Codegen::initializeArrayOfClassInstances (mem::st::ArrayType* arr_ty, llvm::Value* arr, bool is_static)
{
DEBUG_REQUIRE (arr_ty != NULL);
DEBUG_REQUIRE (arr_ty->isArrayType());
DEBUG_REQUIRE (arr_ty->ItemType() != NULL);
DEBUG_REQUIRE (arr_ty->ItemType()->isAnyType());
DEBUG_REQUIRE (arr != NULL);
llvm::BasicBlock* cond_bb = _createBasicBlock("ctor.cond");
llvm::BasicBlock* body_bb = _createBasicBlock("ctor.body");
llvm::BasicBlock* after_bb = _createBasicBlock("ctor.after");
llvm::AllocaInst* counter_var = new llvm::AllocaInst(
_type_maker.get(_st->_core_types.IntTy()), 0, "ctor.i", _cur_bb);
new llvm::StoreInst(_createInt32Constant(0), counter_var, false, _cur_bb);
llvm::AllocaInst* counter_max = new llvm::AllocaInst(
_type_maker.get(_st->_core_types.IntTy()), 0, "ctor.i_max", _cur_bb);
new llvm::StoreInst(_createInt32Constant(arr_ty->ArrayLength()), counter_max, false, _cur_bb);
// --------
// Before
// --------
llvm::BranchInst::Create(cond_bb, _cur_bb);
// -----------
// Condition
// -----------
llvm::Value* cond_value = new llvm::ICmpInst(*cond_bb, llvm::ICmpInst::ICMP_SLT, counter_var, counter_max);
llvm::BranchInst::Create(body_bb, after_bb, cond_value, cond_bb);
// ------
// Body
// ------
llvm::Value* counter_val = new llvm::LoadInst(counter_var, "", body_bb);
std::vector<llvm::Value*> gep_idx;
if (is_static) gep_idx.push_back(_createInt32Constant(0));
gep_idx.push_back(counter_val);
llvm::Value* item_val = llvm::GetElementPtrInst::Create(arr, gep_idx,
"", body_bb);
_cur_bb = body_bb;
initializeValue(arr_ty->ItemType(), item_val);
llvm::BranchInst::Create(cond_bb, body_bb);
_cur_bb = after_bb;
}
void
Codegen::tearDown ()
{
llvm::llvm_shutdown();
}
} }
#endif // HAVE_LLVM
| {
"content_hash": "6f75ad1394297b6549e4008cc239e454",
"timestamp": "",
"source": "github",
"line_count": 1501,
"max_line_length": 110,
"avg_line_length": 27.007994670219855,
"alnum_prop": 0.5847702212684082,
"repo_name": "ThQ/memc",
"id": "58224cfaa840026e595d0e5d0f6d5a6e0c89fbd9",
"size": "40539",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/codegen/llvm/Codegen.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "801700"
},
{
"name": "C++",
"bytes": "948529"
},
{
"name": "Python",
"bytes": "26891"
},
{
"name": "Shell",
"bytes": "762"
}
],
"symlink_target": ""
} |
namespace RestaurantProject
{
partial class Form5
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.label1 = new System.Windows.Forms.Label();
this.dataGridView2 = new System.Windows.Forms.DataGridView();
this.button1 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.buttonMenu = new System.Windows.Forms.Button();
this.buttonLogout = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dataGridView2)).BeginInit();
this.SuspendLayout();
//
// dataGridView1
//
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.AllowUserToDeleteRows = false;
this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
this.dataGridView1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.dataGridView1.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.Raised;
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(29, 43);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.ReadOnly = true;
this.dataGridView1.Size = new System.Drawing.Size(530, 480);
this.dataGridView1.TabIndex = 0;
this.dataGridView1.CellMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dataGridView1_CellMouseClick);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Bold);
this.label1.Location = new System.Drawing.Point(26, 24);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(79, 16);
this.label1.TabIndex = 1;
this.label1.Text = "Select Dish";
//
// dataGridView2
//
this.dataGridView2.AllowUserToAddRows = false;
this.dataGridView2.AllowUserToDeleteRows = false;
this.dataGridView2.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
this.dataGridView2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.dataGridView2.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.Raised;
this.dataGridView2.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView2.Location = new System.Drawing.Point(585, 43);
this.dataGridView2.Name = "dataGridView2";
this.dataGridView2.ReadOnly = true;
this.dataGridView2.Size = new System.Drawing.Size(530, 480);
this.dataGridView2.TabIndex = 2;
this.dataGridView2.CellMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dataGridView2_CellMouseClick_1);
//
// button1
//
this.button1.Font = new System.Drawing.Font("Arial", 9F);
this.button1.Location = new System.Drawing.Point(1028, 548);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(87, 26);
this.button1.TabIndex = 3;
this.button1.Text = "New Order";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(958, 548);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(53, 21);
this.textBox1.TabIndex = 4;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Bold);
this.label2.Location = new System.Drawing.Point(855, 550);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(97, 16);
this.label2.TabIndex = 5;
this.label2.Text = "Table Number";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Bold);
this.label3.Location = new System.Drawing.Point(582, 24);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(113, 16);
this.label3.TabIndex = 6;
this.label3.Text = "Select Beverage";
//
// buttonMenu
//
this.buttonMenu.Font = new System.Drawing.Font("Verdana", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.buttonMenu.Location = new System.Drawing.Point(975, 7);
this.buttonMenu.Name = "buttonMenu";
this.buttonMenu.Size = new System.Drawing.Size(79, 26);
this.buttonMenu.TabIndex = 44;
this.buttonMenu.Text = "Menu";
this.buttonMenu.UseVisualStyleBackColor = true;
this.buttonMenu.Click += new System.EventHandler(this.buttonMenu_Click);
//
// buttonLogout
//
this.buttonLogout.Font = new System.Drawing.Font("Verdana", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.buttonLogout.Location = new System.Drawing.Point(1060, 7);
this.buttonLogout.Name = "buttonLogout";
this.buttonLogout.Size = new System.Drawing.Size(79, 26);
this.buttonLogout.TabIndex = 43;
this.buttonLogout.Text = "Logout";
this.buttonLogout.UseVisualStyleBackColor = true;
this.buttonLogout.Click += new System.EventHandler(this.buttonLogout_Click);
//
// Form5
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1147, 590);
this.Controls.Add(this.buttonMenu);
this.Controls.Add(this.buttonLogout);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button1);
this.Controls.Add(this.dataGridView2);
this.Controls.Add(this.label1);
this.Controls.Add(this.dataGridView1);
this.Font = new System.Drawing.Font("Arial", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Name = "Form5";
this.Text = "New Order";
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form5_FormClosed);
this.Load += new System.EventHandler(this.Form5_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dataGridView2)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.DataGridView dataGridView2;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button buttonMenu;
private System.Windows.Forms.Button buttonLogout;
}
} | {
"content_hash": "016c9b6ef102c0e2efde53c45cb3f7e2",
"timestamp": "",
"source": "github",
"line_count": 182,
"max_line_length": 159,
"avg_line_length": 51.2967032967033,
"alnum_prop": 0.6066838046272494,
"repo_name": "pablokintopp/Restaurant",
"id": "a3fffd42540e0da44729024c31d52e955407099a",
"size": "9338",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "RestaurantProject/RestaurantProject/Form5.Designer.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "37073"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace Artisanry\Database\Traits\Repositories\Decorators\Cache;
trait AggregateTrait
{
public function count()
{
$key = $this->buildCacheKey(['count']);
if ($records = $this->getFromCache($key)) {
return $records;
}
$records = $this->repository->count();
return $this->put($key, $records);
}
public function max($column)
{
$key = $this->buildCacheKey(['max', $column]);
if ($records = $this->getFromCache($key)) {
return $records;
}
$records = $this->repository->max($column);
return $this->put($key, $records);
}
public function min($column)
{
$key = $this->buildCacheKey(['min', $column]);
if ($records = $this->getFromCache($key)) {
return $records;
}
$records = $this->repository->min($column);
return $this->put($key, $records);
}
public function avg($column)
{
$key = $this->buildCacheKey(['avg', $column]);
if ($records = $this->getFromCache($key)) {
return $records;
}
$records = $this->repository->avg($column);
return $this->put($key, $records);
}
public function sum($column)
{
$key = $this->buildCacheKey(['sum', $column]);
if ($records = $this->getFromCache($key)) {
return $records;
}
$records = $this->repository->sum($column);
return $this->put($key, $records);
}
}
| {
"content_hash": "e90333023087d4b0f7ffc821305c17bf",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 66,
"avg_line_length": 20.8,
"alnum_prop": 0.5243589743589744,
"repo_name": "DraperStudio/Laravel-Database",
"id": "d99762e8d762eed0c18a038cd45de2ecf07fc7c6",
"size": "1780",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Traits/Repositories/Decorators/Cache/AggregateTrait.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "131571"
}
],
"symlink_target": ""
} |
struct sys_var {
unsigned name_length;
bool no_support_one_shot;
sys_var() {}
};
struct sys_var_thd : public sys_var {
};
extern sys_var_thd sys_auto_is_null;
sys_var *getsys_variables() {
return &sys_auto_is_null;
}
sys_var *sys_variables = &sys_auto_is_null;
| {
"content_hash": "e5b54f178d7746c87f5a6e390cc1b068",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 43,
"avg_line_length": 11.708333333333334,
"alnum_prop": 0.6476868327402135,
"repo_name": "wrmsr/lljvm",
"id": "365c8e80fbf5f9fe2e7ebaadb4a4530a64fa0262",
"size": "331",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "thirdparty/llvm/test/FrontendC++/2006-11-30-ConstantExprCrash.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "4870"
},
{
"name": "C++",
"bytes": "91265"
},
{
"name": "Java",
"bytes": "149125"
},
{
"name": "Lua",
"bytes": "177"
},
{
"name": "Makefile",
"bytes": "21245"
},
{
"name": "Python",
"bytes": "8641"
},
{
"name": "Shell",
"bytes": "218"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE36_Absolute_Path_Traversal__char_file_ifstream_18.cpp
Label Definition File: CWE36_Absolute_Path_Traversal.label.xml
Template File: sources-sink-18.tmpl.cpp
*/
/*
* @description
* CWE: 36 Absolute Path Traversal
* BadSource: file Read input from a file
* GoodSource: Full path and file name
* Sink: ifstream
* BadSink : Open the file named in data using ifstream::open()
* Flow Variant: 18 Control flow: goto statements
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
#ifdef _WIN32
#define FILENAME "C:\\temp\\file.txt"
#else
#define FILENAME "/tmp/file.txt"
#endif
#include <fstream>
using namespace std;
namespace CWE36_Absolute_Path_Traversal__char_file_ifstream_18
{
#ifndef OMITBAD
void bad()
{
char * data;
char dataBuffer[FILENAME_MAX] = "";
data = dataBuffer;
goto source;
source:
{
/* Read input from a file */
size_t dataLen = strlen(data);
FILE * pFile;
/* if there is room in data, attempt to read the input from a file */
if (FILENAME_MAX-dataLen > 1)
{
pFile = fopen(FILENAME, "r");
if (pFile != NULL)
{
/* POTENTIAL FLAW: Read data from a file */
if (fgets(data+dataLen, (int)(FILENAME_MAX-dataLen), pFile) == NULL)
{
printLine("fgets() failed");
/* Restore NUL terminator if fgets fails */
data[dataLen] = '\0';
}
fclose(pFile);
}
}
}
{
ifstream inputFile;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
inputFile.open((char *)data);
inputFile.close();
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() - use goodsource and badsink by reversing the blocks on the goto statement */
static void goodG2B()
{
char * data;
char dataBuffer[FILENAME_MAX] = "";
data = dataBuffer;
goto source;
source:
#ifdef _WIN32
/* FIX: Use a fixed, full path and file name */
strcat(data, "c:\\temp\\file.txt");
#else
/* FIX: Use a fixed, full path and file name */
strcat(data, "/tmp/file.txt");
#endif
{
ifstream inputFile;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
inputFile.open((char *)data);
inputFile.close();
}
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE36_Absolute_Path_Traversal__char_file_ifstream_18; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| {
"content_hash": "41a9585c9def9c07d1eaf769a5f21582",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 114,
"avg_line_length": 25.807407407407407,
"alnum_prop": 0.5898392652123995,
"repo_name": "JianpingZeng/xcc",
"id": "e887559bd065c9d6a4f7f07ac45af0c8ef273d7d",
"size": "3484",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "xcc/test/juliet/testcases/CWE36_Absolute_Path_Traversal/s02/CWE36_Absolute_Path_Traversal__char_file_ifstream_18.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
include KeywordExtractorAnalyzer
describe KeywordExtractor do
context 'uninitialize' do
describe '#initialize' do
context 'when call' do
it 'CountAnalyzer' do
extractor = KeywordExtractor.new
analyzer = extractor.instance_eval('@analyzer')
analyzer.instance_of?(CountAnalyzer).should be_truthy
end
end
end
end
context 'initialized' do
before(:each) do
@extractor = KeywordExtractor.new
end
describe '#to_count' do
context 'when call' do
it 'CountAnalyzer' do
@extractor.to_count
analyzer = @extractor.instance_eval('@analyzer')
analyzer.instance_of?(CountAnalyzer).should be_truthy
end
end
end
describe '#to_tf_idf' do
context 'when corpus input' do
it 'TfIdfAnalyzer' do
corpus = ['test corpus1', 'test corpus2']
@extractor.to_tf_idf(corpus)
analyzer = @extractor.instance_eval('@analyzer')
analyzer.instance_of?(TfIdfAnalyzer).should be_truthy
end
end
end
describe '#analyze' do
context 'when doc input' do
it 'call analyzer#get_keyword_list' do
doc = 'test doc 01'
analyzer = double('analyzer')
analyzer.should_receive(:get_keyword_list).with(doc)
@extractor.instance_variable_set('@analyzer', analyzer)
@extractor.analyze(doc)
end
end
end
end
end
| {
"content_hash": "d54d1c0130d3ea7631b34bb6c71ffaf0",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 65,
"avg_line_length": 27.5,
"alnum_prop": 0.6116883116883117,
"repo_name": "yukihir0/keyword_extractor",
"id": "23f79838b03c5ad45faa9100df8a343cca2d0b40",
"size": "1556",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/keyword_extractor_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "12822"
},
{
"name": "Shell",
"bytes": "510"
}
],
"symlink_target": ""
} |
package com.mbrlabs.mundus.commons.g3d;
import com.badlogic.gdx.assets.loaders.FileHandleResolver;
import com.badlogic.gdx.assets.loaders.ModelLoader;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.g3d.model.data.ModelAnimation;
import com.badlogic.gdx.graphics.g3d.model.data.ModelData;
import com.badlogic.gdx.graphics.g3d.model.data.ModelMaterial;
import com.badlogic.gdx.graphics.g3d.model.data.ModelMesh;
import com.badlogic.gdx.graphics.g3d.model.data.ModelMeshPart;
import com.badlogic.gdx.graphics.g3d.model.data.ModelNode;
import com.badlogic.gdx.graphics.g3d.model.data.ModelNodeAnimation;
import com.badlogic.gdx.graphics.g3d.model.data.ModelNodeKeyframe;
import com.badlogic.gdx.graphics.g3d.model.data.ModelNodePart;
import com.badlogic.gdx.graphics.g3d.model.data.ModelTexture;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Quaternion;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ArrayMap;
import com.badlogic.gdx.utils.BaseJsonReader;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.JsonValue;
/**
* This is a modified version of the libGDX MG3dModelLoader.
*
* It ignores all textures, set in the model. This is because, one should be
* able to assign materials (textures, colors) from the editor.
*
* @author Marcus Brummer
* @version 04-10-2016
*/
public class MG3dModelLoader extends ModelLoader<ModelLoader.ModelParameters> {
public static final short VERSION_HI = 0;
public static final short VERSION_LO = 1;
protected final BaseJsonReader reader;
public MG3dModelLoader(final BaseJsonReader reader) {
this(reader, null);
}
public MG3dModelLoader(BaseJsonReader reader, FileHandleResolver resolver) {
super(resolver);
this.reader = reader;
}
@Override
public ModelData loadModelData(FileHandle fileHandle, ModelLoader.ModelParameters parameters) {
return parseModel(fileHandle);
}
public ModelData parseModel(FileHandle handle) {
JsonValue json = reader.parse(handle);
ModelData model = new ModelData();
JsonValue version = json.require("version");
model.version[0] = version.getShort(0);
model.version[1] = version.getShort(1);
if (model.version[0] != VERSION_HI || model.version[1] != VERSION_LO)
throw new GdxRuntimeException("Model version not supported");
model.id = json.getString("id", "");
parseMeshes(model, json);
parseMaterials(model, json, handle.parent().path());
parseNodes(model, json);
parseAnimations(model, json);
return model;
}
private void parseMeshes(ModelData model, JsonValue json) {
JsonValue meshes = json.get("meshes");
if (meshes != null) {
model.meshes.ensureCapacity(meshes.size);
for (JsonValue mesh = meshes.child; mesh != null; mesh = mesh.next) {
ModelMesh jsonMesh = new ModelMesh();
String id = mesh.getString("id", "");
jsonMesh.id = id;
JsonValue attributes = mesh.require("attributes");
jsonMesh.attributes = parseAttributes(attributes);
jsonMesh.vertices = mesh.require("vertices").asFloatArray();
JsonValue meshParts = mesh.require("parts");
Array<ModelMeshPart> parts = new Array<ModelMeshPart>();
for (JsonValue meshPart = meshParts.child; meshPart != null; meshPart = meshPart.next) {
ModelMeshPart jsonPart = new ModelMeshPart();
String partId = meshPart.getString("id", null);
if (partId == null) {
throw new GdxRuntimeException("Not id given for mesh part");
}
for (ModelMeshPart other : parts) {
if (other.id.equals(partId)) {
throw new GdxRuntimeException("Mesh part with id '" + partId + "' already in defined");
}
}
jsonPart.id = partId;
String type = meshPart.getString("type", null);
if (type == null) {
throw new GdxRuntimeException("No primitive type given for mesh part '" + partId + "'");
}
jsonPart.primitiveType = parseType(type);
jsonPart.indices = meshPart.require("indices").asShortArray();
parts.add(jsonPart);
}
jsonMesh.parts = parts.toArray(ModelMeshPart.class);
model.meshes.add(jsonMesh);
}
}
}
private int parseType(String type) {
if (type.equals("TRIANGLES")) {
return GL20.GL_TRIANGLES;
} else if (type.equals("LINES")) {
return GL20.GL_LINES;
} else if (type.equals("POINTS")) {
return GL20.GL_POINTS;
} else if (type.equals("TRIANGLE_STRIP")) {
return GL20.GL_TRIANGLE_STRIP;
} else if (type.equals("LINE_STRIP")) {
return GL20.GL_LINE_STRIP;
} else {
throw new GdxRuntimeException("Unknown primitive type '" + type
+ "', should be one of triangle, trianglestrip, line, linestrip, lineloop or point");
}
}
private VertexAttribute[] parseAttributes(JsonValue attributes) {
Array<VertexAttribute> vertexAttributes = new Array<VertexAttribute>();
int unit = 0;
int blendWeightCount = 0;
for (JsonValue value = attributes.child; value != null; value = value.next) {
String attribute = value.asString();
String attr = (String) attribute;
if (attr.equals("POSITION")) {
vertexAttributes.add(VertexAttribute.Position());
} else if (attr.equals("NORMAL")) {
vertexAttributes.add(VertexAttribute.Normal());
} else if (attr.equals("COLOR")) {
vertexAttributes.add(VertexAttribute.ColorUnpacked());
} else if (attr.equals("COLORPACKED")) {
vertexAttributes.add(VertexAttribute.ColorPacked());
} else if (attr.equals("TANGENT")) {
vertexAttributes.add(VertexAttribute.Tangent());
} else if (attr.equals("BINORMAL")) {
vertexAttributes.add(VertexAttribute.Binormal());
} else if (attr.startsWith("TEXCOORD")) {
vertexAttributes.add(VertexAttribute.TexCoords(unit++));
} else if (attr.startsWith("BLENDWEIGHT")) {
vertexAttributes.add(VertexAttribute.BoneWeight(blendWeightCount++));
} else {
throw new GdxRuntimeException("Unknown vertex attribute '" + attr
+ "', should be one of position, normal, uv, tangent or binormal");
}
}
return vertexAttributes.toArray(VertexAttribute.class);
}
private void parseMaterials(ModelData model, JsonValue json, String materialDir) {
JsonValue materials = json.get("materials");
if (materials == null) {
// we should probably create some default material in this case
} else {
model.materials.ensureCapacity(materials.size);
for (JsonValue material = materials.child; material != null; material = material.next) {
ModelMaterial jsonMaterial = new ModelMaterial();
String id = material.getString("id", null);
if (id == null) throw new GdxRuntimeException("Material needs an id.");
jsonMaterial.id = id;
// Read material colors
final JsonValue diffuse = material.get("diffuse");
if (diffuse != null) jsonMaterial.diffuse = parseColor(diffuse);
final JsonValue ambient = material.get("ambient");
if (ambient != null) jsonMaterial.ambient = parseColor(ambient);
final JsonValue emissive = material.get("emissive");
if (emissive != null) jsonMaterial.emissive = parseColor(emissive);
final JsonValue specular = material.get("specular");
if (specular != null) jsonMaterial.specular = parseColor(specular);
final JsonValue reflection = material.get("reflection");
if (reflection != null) jsonMaterial.reflection = parseColor(reflection);
// Read shininess
jsonMaterial.shininess = material.getFloat("shininess", 0.0f);
// Read opacity
jsonMaterial.opacity = material.getFloat("opacity", 1.0f);
// Read textures
// JsonValue textures = material.get("textures");
// if (textures != null) {
// for (JsonValue texture = textures.child; texture != null;
// texture = texture.next) {
// ModelTexture jsonTexture = new ModelTexture();
//
// String textureId = texture.getString("id", null);
// if (textureId == null) throw new GdxRuntimeException("Texture
// has no id.");
// jsonTexture.id = textureId;
//
// String fileName = texture.getString("filename", null);
// if (fileName == null) throw new GdxRuntimeException("Texture
// needs filename.");
// jsonTexture.fileName = materialDir + (materialDir.length() ==
// 0 || materialDir.endsWith("/") ? "" : "/")
// + fileName;
//
// jsonTexture.uvTranslation =
// readVector2(texture.get("uvTranslation"), 0f, 0f);
// jsonTexture.uvScaling = readVector2(texture.get("uvScaling"),
// 1f, 1f);
//
// String textureType = texture.getString("type", null);
// if (textureType == null) throw new
// GdxRuntimeException("Texture needs type.");
//
// jsonTexture.usage = parseTextureUsage(textureType);
//
// if (jsonMaterial.textures == null) jsonMaterial.textures =
// new Array<ModelTexture>();
// jsonMaterial.textures.add(jsonTexture);
// }
// }
model.materials.add(jsonMaterial);
}
}
}
private int parseTextureUsage(final String value) {
if (value.equalsIgnoreCase("AMBIENT"))
return ModelTexture.USAGE_AMBIENT;
else if (value.equalsIgnoreCase("BUMP"))
return ModelTexture.USAGE_BUMP;
else if (value.equalsIgnoreCase("DIFFUSE"))
return ModelTexture.USAGE_DIFFUSE;
else if (value.equalsIgnoreCase("EMISSIVE"))
return ModelTexture.USAGE_EMISSIVE;
else if (value.equalsIgnoreCase("NONE"))
return ModelTexture.USAGE_NONE;
else if (value.equalsIgnoreCase("NORMAL"))
return ModelTexture.USAGE_NORMAL;
else if (value.equalsIgnoreCase("REFLECTION"))
return ModelTexture.USAGE_REFLECTION;
else if (value.equalsIgnoreCase("SHININESS"))
return ModelTexture.USAGE_SHININESS;
else if (value.equalsIgnoreCase("SPECULAR"))
return ModelTexture.USAGE_SPECULAR;
else if (value.equalsIgnoreCase("TRANSPARENCY")) return ModelTexture.USAGE_TRANSPARENCY;
return ModelTexture.USAGE_UNKNOWN;
}
private Color parseColor(JsonValue colorArray) {
if (colorArray.size >= 3)
return new Color(colorArray.getFloat(0), colorArray.getFloat(1), colorArray.getFloat(2), 1.0f);
else
throw new GdxRuntimeException("Expected Color values <> than three.");
}
private Vector2 readVector2(JsonValue vectorArray, float x, float y) {
if (vectorArray == null)
return new Vector2(x, y);
else if (vectorArray.size == 2)
return new Vector2(vectorArray.getFloat(0), vectorArray.getFloat(1));
else
throw new GdxRuntimeException("Expected Vector2 values <> than two.");
}
private Array<ModelNode> parseNodes(ModelData model, JsonValue json) {
JsonValue nodes = json.get("nodes");
if (nodes != null) {
model.nodes.ensureCapacity(nodes.size);
for (JsonValue node = nodes.child; node != null; node = node.next) {
model.nodes.add(parseNodesRecursively(node));
}
}
return model.nodes;
}
private final Quaternion tempQ = new Quaternion();
private ModelNode parseNodesRecursively(JsonValue json) {
ModelNode jsonNode = new ModelNode();
String id = json.getString("id", null);
if (id == null) throw new GdxRuntimeException("Node id missing.");
jsonNode.id = id;
JsonValue translation = json.get("translation");
if (translation != null && translation.size != 3) throw new GdxRuntimeException("Node translation incomplete");
jsonNode.translation = translation == null ? null
: new Vector3(translation.getFloat(0), translation.getFloat(1), translation.getFloat(2));
JsonValue rotation = json.get("rotation");
if (rotation != null && rotation.size != 4) throw new GdxRuntimeException("Node rotation incomplete");
jsonNode.rotation = rotation == null ? null
: new Quaternion(rotation.getFloat(0), rotation.getFloat(1), rotation.getFloat(2),
rotation.getFloat(3));
JsonValue scale = json.get("scale");
if (scale != null && scale.size != 3) throw new GdxRuntimeException("Node scale incomplete");
jsonNode.scale = scale == null ? null : new Vector3(scale.getFloat(0), scale.getFloat(1), scale.getFloat(2));
String meshId = json.getString("mesh", null);
if (meshId != null) jsonNode.meshId = meshId;
JsonValue materials = json.get("parts");
if (materials != null) {
jsonNode.parts = new ModelNodePart[materials.size];
int i = 0;
for (JsonValue material = materials.child; material != null; material = material.next, i++) {
ModelNodePart nodePart = new ModelNodePart();
String meshPartId = material.getString("meshpartid", null);
String materialId = material.getString("materialid", null);
if (meshPartId == null || materialId == null) {
throw new GdxRuntimeException("Node " + id + " part is missing meshPartId or materialId");
}
nodePart.materialId = materialId;
nodePart.meshPartId = meshPartId;
JsonValue bones = material.get("bones");
if (bones != null) {
nodePart.bones = new ArrayMap<String, Matrix4>(true, bones.size, String.class, Matrix4.class);
int j = 0;
for (JsonValue bone = bones.child; bone != null; bone = bone.next, j++) {
String nodeId = bone.getString("node", null);
if (nodeId == null) throw new GdxRuntimeException("Bone node ID missing");
Matrix4 transform = new Matrix4();
JsonValue val = bone.get("translation");
if (val != null && val.size >= 3)
transform.translate(val.getFloat(0), val.getFloat(1), val.getFloat(2));
val = bone.get("rotation");
if (val != null && val.size >= 4) transform
.rotate(tempQ.set(val.getFloat(0), val.getFloat(1), val.getFloat(2), val.getFloat(3)));
val = bone.get("scale");
if (val != null && val.size >= 3)
transform.scale(val.getFloat(0), val.getFloat(1), val.getFloat(2));
nodePart.bones.put(nodeId, transform);
}
}
jsonNode.parts[i] = nodePart;
}
}
JsonValue children = json.get("children");
if (children != null) {
jsonNode.children = new ModelNode[children.size];
int i = 0;
for (JsonValue child = children.child; child != null; child = child.next, i++) {
jsonNode.children[i] = parseNodesRecursively(child);
}
}
return jsonNode;
}
private void parseAnimations(ModelData model, JsonValue json) {
JsonValue animations = json.get("animations");
if (animations == null) return;
model.animations.ensureCapacity(animations.size);
for (JsonValue anim = animations.child; anim != null; anim = anim.next) {
JsonValue nodes = anim.get("bones");
if (nodes == null) continue;
ModelAnimation animation = new ModelAnimation();
model.animations.add(animation);
animation.nodeAnimations.ensureCapacity(nodes.size);
animation.id = anim.getString("id");
for (JsonValue node = nodes.child; node != null; node = node.next) {
ModelNodeAnimation nodeAnim = new ModelNodeAnimation();
animation.nodeAnimations.add(nodeAnim);
nodeAnim.nodeId = node.getString("boneId");
// For backwards compatibility (version 0.1):
JsonValue keyframes = node.get("keyframes");
if (keyframes != null && keyframes.isArray()) {
for (JsonValue keyframe = keyframes.child; keyframe != null; keyframe = keyframe.next) {
final float keytime = keyframe.getFloat("keytime", 0f) / 1000.f;
JsonValue translation = keyframe.get("translation");
if (translation != null && translation.size == 3) {
if (nodeAnim.translation == null)
nodeAnim.translation = new Array<ModelNodeKeyframe<Vector3>>();
ModelNodeKeyframe<Vector3> tkf = new ModelNodeKeyframe<Vector3>();
tkf.keytime = keytime;
tkf.value = new Vector3(translation.getFloat(0), translation.getFloat(1),
translation.getFloat(2));
nodeAnim.translation.add(tkf);
}
JsonValue rotation = keyframe.get("rotation");
if (rotation != null && rotation.size == 4) {
if (nodeAnim.rotation == null)
nodeAnim.rotation = new Array<ModelNodeKeyframe<Quaternion>>();
ModelNodeKeyframe<Quaternion> rkf = new ModelNodeKeyframe<Quaternion>();
rkf.keytime = keytime;
rkf.value = new Quaternion(rotation.getFloat(0), rotation.getFloat(1), rotation.getFloat(2),
rotation.getFloat(3));
nodeAnim.rotation.add(rkf);
}
JsonValue scale = keyframe.get("scale");
if (scale != null && scale.size == 3) {
if (nodeAnim.scaling == null) nodeAnim.scaling = new Array<ModelNodeKeyframe<Vector3>>();
ModelNodeKeyframe<Vector3> skf = new ModelNodeKeyframe();
skf.keytime = keytime;
skf.value = new Vector3(scale.getFloat(0), scale.getFloat(1), scale.getFloat(2));
nodeAnim.scaling.add(skf);
}
}
} else { // Version 0.2:
JsonValue translationKF = node.get("translation");
if (translationKF != null && translationKF.isArray()) {
nodeAnim.translation = new Array<ModelNodeKeyframe<Vector3>>();
nodeAnim.translation.ensureCapacity(translationKF.size);
for (JsonValue keyframe = translationKF.child; keyframe != null; keyframe = keyframe.next) {
ModelNodeKeyframe<Vector3> kf = new ModelNodeKeyframe<Vector3>();
nodeAnim.translation.add(kf);
kf.keytime = keyframe.getFloat("keytime", 0f) / 1000.f;
JsonValue translation = keyframe.get("value");
if (translation != null && translation.size >= 3)
kf.value = new Vector3(translation.getFloat(0), translation.getFloat(1),
translation.getFloat(2));
}
}
JsonValue rotationKF = node.get("rotation");
if (rotationKF != null && rotationKF.isArray()) {
nodeAnim.rotation = new Array<ModelNodeKeyframe<Quaternion>>();
nodeAnim.rotation.ensureCapacity(rotationKF.size);
for (JsonValue keyframe = rotationKF.child; keyframe != null; keyframe = keyframe.next) {
ModelNodeKeyframe<Quaternion> kf = new ModelNodeKeyframe<Quaternion>();
nodeAnim.rotation.add(kf);
kf.keytime = keyframe.getFloat("keytime", 0f) / 1000.f;
JsonValue rotation = keyframe.get("value");
if (rotation != null && rotation.size >= 4) kf.value = new Quaternion(rotation.getFloat(0),
rotation.getFloat(1), rotation.getFloat(2), rotation.getFloat(3));
}
}
JsonValue scalingKF = node.get("scaling");
if (scalingKF != null && scalingKF.isArray()) {
nodeAnim.scaling = new Array<ModelNodeKeyframe<Vector3>>();
nodeAnim.scaling.ensureCapacity(scalingKF.size);
for (JsonValue keyframe = scalingKF.child; keyframe != null; keyframe = keyframe.next) {
ModelNodeKeyframe<Vector3> kf = new ModelNodeKeyframe<Vector3>();
nodeAnim.scaling.add(kf);
kf.keytime = keyframe.getFloat("keytime", 0f) / 1000.f;
JsonValue scaling = keyframe.get("value");
if (scaling != null && scaling.size >= 3)
kf.value = new Vector3(scaling.getFloat(0), scaling.getFloat(1), scaling.getFloat(2));
}
}
}
}
}
}
}
| {
"content_hash": "187efbb84d8bac311371169021fbd7b6",
"timestamp": "",
"source": "github",
"line_count": 475,
"max_line_length": 120,
"avg_line_length": 49.03578947368421,
"alnum_prop": 0.5609651382448909,
"repo_name": "mbrlabs/Mundus",
"id": "87ecd4a42a52383375af27bbf31eb4efd4ff4022",
"size": "23898",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "commons/src/main/com/mbrlabs/mundus/commons/g3d/MG3dModelLoader.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "12998"
},
{
"name": "Java",
"bytes": "446745"
},
{
"name": "Kotlin",
"bytes": "334799"
}
],
"symlink_target": ""
} |
require 'test/unit'
# Require and include test helpers
#
Dir[File.join(File.dirname(__FILE__), 'helpers', '*_test_helper.rb')].each do |helper|
require helper
/(.*?)_test_helper\.rb/.match File.basename(helper)
class_name = $1.split('_').collect{ |name| name.downcase.capitalize }.join('') + 'TestHelper'
Test::Unit::TestCase.send :include, Object.const_get(class_name) if Object.const_defined?(class_name)
end
# Load ActiveRecord
#
require 'rubygems'
gem 'activerecord'
require 'active_record'
ActiveRecord::Base.establish_connection :adapter => 'sqlite3', :dbfile => ':memory:'
# Load ActionPack
#
gem 'actionpack'
require 'action_pack'
require 'action_controller'
require 'action_controller/routing'
require 'action_controller/assertions'
require 'action_controller/test_process'
# Routing
#
class ActionController::Routing::RouteSet
def append
yield Mapper.new(self)
install_helpers
end
end
# Include Huberry::Authentication::ControllerMethods mock to test AuthenticationPatch
#
module Huberry
module Authentication
module ControllerMethods
module InstanceMethods
def self.included(base)
base.class_eval do
cattr_accessor :authentication_options
self.authentication_options = { :model => 'User' }
attr_accessor :current_user
end
end
def authentication_session_field
:user_id
end
end
end
end
end
ActionController::Base.send :include, Huberry::Authentication::ControllerMethods::InstanceMethods
# Require the main init.rb for the plugin
#
require File.join(File.dirname(File.dirname(__FILE__)), 'init') | {
"content_hash": "6e427d6d2bdd94f7ea60307c1c900dfe",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 103,
"avg_line_length": 26.79032258064516,
"alnum_prop": 0.7013847080072245,
"repo_name": "shuber/subdomain_account",
"id": "b819681d6db01b5352bee1547e64bbad27bc7f6e",
"size": "1661",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/init.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "7299"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "300bffd8c19f51a65e8794a9460e4d32",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "3bd4a789074c62cb4bce6c6dd8e8fbbb1829626c",
"size": "188",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Apiales/Apiaceae/Libanotis/Libanotis condensata/ Syn. Seseli condensatum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import urllib
import urllib2
class Pushco(object):
def __init__(self, api_key, api_secret, message, url=None, latitude=None, longitude=None, view_type = None):
self.api_key = api_key
self.api_secret = api_secret
self.message = message
self.url = url
self.latitude = latitude
self.longitude = longitude
self.view_type = view_type
def push(self):
params = {
'api_key':self.api_key,
'api_secret':self.api_secret,
'message':self.message
}
if self.url:
params['url']= self.url
params['view_type']= 1
elif self.latitude:
params['latitude']=self.latitude
params['longitude']=self.longitude
params['view_type']= 2
print self.url
req = urllib2.Request('https://api.push.co/1.0/push', urllib.urlencode(params))
try:
response = urllib2.urlopen(req)
return response.getcode()
except urllib2.URLError, e:
if e.code == 422:
return ' %s Message too long' %e.code
if e.code == 401:
return '%s - Not authorised' %e.code
if e.code == 500:
return '%s - Internal server error' %e.code
else:
return '%s - HTTP error' %e.code
| {
"content_hash": "55bc1e656cf97130b317713ae3febeec",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 112,
"avg_line_length": 31.695652173913043,
"alnum_prop": 0.49588477366255146,
"repo_name": "obrasco/pushco",
"id": "2c3c5f59b30c0beca07b7c355920117349fdfe7c",
"size": "1458",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pushco/pushco.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "2817"
}
],
"symlink_target": ""
} |
module.exports = function(exports) {
// ************************
// Request Methods
// ************************
var vars = exports.vars;
/**
* Request funds from a source user for the user associated with the authorized access token.
* https://www.dwolla.com/developers/endpoints/transactions/request
*
* Optional params:
*
* - sourceType
* - facilitatorAmount
* - notes
*
* @param {Number} pin
* @param {String} sourceId
* @param {String} amount
* @param {Function} fn
*/
exports.request = function(sourceId, amount, params, fn) {
// params are optional
if (!fn || typeof params === 'function') {
fn = params;
params = {};
}
if (!sourceId) { throw new Error('Missing arg sourceId'); }
if (!amount) { throw new Error('Missing arg amount'); }
var path = '/requests/';
var data = Object.assign({ sourceId, amount}, params | {});
exports._post({ path, data, fn});
};
/**
* Use this method to retrieve a list of pending money requests for the user associated with the authorized access token.
* https://developers.dwolla.com/dev/docs/requests/pending
*
* Optional params:
*
* - startDate
* - endDate
* - skip
* - limit
*
* @param {Function} fn
*/
exports.requests = function(params, fn) {
// params are optional
if (!fn || typeof params === 'function') {
fn = params;
params = {};
}
var path = '/requests/';
var query = params || {};
exports._request({ path, query, fn });
};
/**
* Use this method to fetch detailed information about a money request, identified by a specific request ID.
* https://www.dwolla.com/developers/endpoints/transactions/request
*
* @param {String} request_id
* @param {Function} fn
*/
exports.requestById = function(request_id, fn) {
if (!request_id) { throw new Error('Missing arg request_id'); }
var path = `/requests/${request_id}`;
exports._request({ path, fn });
};
/**
* Use this method to cancel (i.e. "reject") a money request from the user with the associated access token.
* https://developers.dwolla.com/dev/docs/requests/cancel
*
* @param {String} request_id
* @param {Function} fn
*/
exports.cancelRequest = function(request_id, fn) {
if (typeof fn !== 'function') { throw new Error('Missing callback'); }
if (!request_id) { throw new Error('Missing arg request_id'); }
var path = `/requests/${request_id}/cancel`;
var callback = function(err, res) {
if (err) { return fn(err); }
else {
// since the actual API response is an empty string
// in the case of a successful cancel, and that is
// terrible, we will return true, instead.
fn(null, true);
}
}
exports._post({ path, fn: callback });
};
/**
* Use this method to fulfill (i.e. "pay") a money request from the user with the associated access token.
* https://developers.dwolla.com/dev/docs/requests/fulfill
*
* Optional params:
*
* - notes
* - fundsSource
* - assumeCosts
*
* @param {Number} pin
* @param {String} request_id
* @param {String} amount
* @param {Function} fn
*/
exports.fulfillRequest = function(pin, request_id, amount, params, fn) {
// params are optional
if (!fn || typeof params === 'function') {
fn = params;
params = {};
}
if (!pin) { throw new Error('Missing arg pin'); }
if (!request_id) { throw new Error('Missing arg request_id'); }
if (!amount) { throw new Error('Missing arg amount'); }
var path = `/requests/${request_id}/fulfill`
var data = Object.assign({ pin, request_id, amount }, params || {});
exports._post({ path, data, fn });
};
};
| {
"content_hash": "bdd9bb1411344db199ed1dcba8f3aeb7",
"timestamp": "",
"source": "github",
"line_count": 130,
"max_line_length": 125,
"avg_line_length": 32.96923076923077,
"alnum_prop": 0.5242650489967335,
"repo_name": "Dwolla/dwolla-node",
"id": "8eaf078c7062b4440402ddbd14781cd83580cc42",
"size": "4286",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/requests.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "130588"
}
],
"symlink_target": ""
} |
set -o errexit
set -o nounset
set -o pipefail
# Avalanchego root folder
AVALANCHE_PATH=$( cd "$( dirname "${BASH_SOURCE[0]}" )"; cd .. && pwd )
# Load the versions
source "$AVALANCHE_PATH"/scripts/versions.sh
# Load the constants
source "$AVALANCHE_PATH"/scripts/constants.sh
# Download dependencies
echo "Downloading dependencies..."
go mod download
# Build avalanchego
"$AVALANCHE_PATH"/scripts/build_avalanche.sh
# Build coreth
"$AVALANCHE_PATH"/scripts/build_coreth.sh
# Exit build successfully if the binaries are created
if [[ -f "$avalanchego_path" && -f "$evm_path" ]]; then
echo "Build Successful"
exit 0
else
echo "Build failure" >&2
exit 1
fi
| {
"content_hash": "9bd8e832485708ca73499563b866efb8",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 71,
"avg_line_length": 23.82758620689655,
"alnum_prop": 0.6931982633863966,
"repo_name": "ava-labs/avalanchego",
"id": "a427058c3424ee3725e2609ae3821f8b1e51601f",
"size": "712",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts/build.sh",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "Dockerfile",
"bytes": "1695"
},
{
"name": "Go",
"bytes": "5973389"
},
{
"name": "Shell",
"bytes": "29536"
}
],
"symlink_target": ""
} |
require 'spec_helper'
require "amatista.rb"
describe Amatista do
before(:all) do
@fraccion1 = Amatista::Fraccion.new(-50,60)
@fraccion2 = Amatista::Fraccion.new(2,7)
puts @fraccion1.to_s << " + " << @fraccion2.to_s << " == (" << (@fraccion1 + @fraccion2).to_s << ")"
puts @fraccion1.to_s << " - " << @fraccion2.to_s << " == (" << (@fraccion1 - @fraccion2).to_s << ")"
puts @fraccion1.to_s << " * " << @fraccion2.to_s << " == (" << (@fraccion1 * @fraccion2).to_s << ")"
puts @fraccion1.to_s << " : " << @fraccion2.to_s << " == (" << (@fraccion1 / @fraccion2).to_s << ")"
@solucion1 = Amatista::Fraccion.new(-23,42)
@solucion2 = Amatista::Fraccion.new(-47,42)
@solucion3 = Amatista::Fraccion.new(-5,21)
@solucion4 = Amatista::Fraccion.new(-35,12)
end
describe " Expectativas Clase Fracción" do
it " Expectativa Instacia Fraccion " do
expect(@fraccion1).to be_truthy
end
it " Expectativa acceso atributos de la clase Fraccion" do
expect(@fraccion1).to be_instance_of(Amatista::Fraccion)
expect(@fraccion1).to respond_to(:numerador)
expect(@fraccion1).to respond_to(:denominador)
end
it " Expectativa mostrar fracción " do
expect(@fraccion1).to respond_to(:to_s)
end
it " Expectativa sumar fracción " do
expect(@fraccion1).to respond_to(:+)
end
it " Expectativa multiplicar fracción " do
expect(@fraccion1).to respond_to(:*)
end
it " Expectativa restar fracción " do
expect(@fraccion1).to respond_to(:-)
end
it " Expectativa dividir fracción " do
expect(@fraccion1).to respond_to(:/)
end
it " Expectativa simplificar fracción " do
expect(@fraccion1).to respond_to(:simplificar)
end
it " Expectativas verificar los valores de las operaciones " do
expect(@fraccion1 + @fraccion2).to eq(@solucion1)
expect(@fraccion1 - @fraccion2).to eq(@solucion2)
expect(@fraccion1 * @fraccion2).to eq(@solucion3)
expect(@fraccion1 / @fraccion2).to eq(@solucion4)
end
end
end
| {
"content_hash": "fd8ccfa192810d3948ef6c94766a5b42",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 105,
"avg_line_length": 33.81666666666667,
"alnum_prop": 0.6372597338590439,
"repo_name": "alu0100721805/prct05",
"id": "709816a35ebc1c476b80a490d7c3becdf777aaac",
"size": "2036",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/amatista_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "12332"
},
{
"name": "Shell",
"bytes": "115"
}
],
"symlink_target": ""
} |
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use CivilServices;
use MetaTag;
use Bugsnag;
class MyElectedOfficialsController extends Controller
{
/**
* @return mixed
*/
public function index()
{
// Setup Meta Tags
MetaTag::set('title', 'Find My Elected Officials');
MetaTag::set('description', 'Get Contact Information & Political History for members of the 117th United States Congress');
MetaTag::set('image', asset('img/header/lady-justice.jpg'));
MetaTag::set('keywords', 'Find My Officials, Contact Information, Elected Officials, Political History, Location, Address');
return view('my-elected-officials.index');
}
/**
* @return mixed
*/
public function redirect()
{
return redirect('my-elected-officials');
}
/**
* @param $zipcode
* @return mixed
*/
public function byZipCode($zipcode)
{
try {
$geolocation = CivilServices::searchGovernment([
'zipcode' => $zipcode
]);
// Setup Meta Tags
MetaTag::set('title', 'Elected Officials for Zip Code ' . $zipcode);
MetaTag::set('description', 'Elected Officials for Zip Code ' . $zipcode);
MetaTag::set('image', $geolocation->state->skyline->size_1280x720);
MetaTag::set('keywords', 'Elected Officials, Zip Code, ' . $zipcode . ', ' . $geolocation->state->state_name);
return view('my-elected-officials.results')
->with('representatives', $geolocation->house)
->with('senators', $geolocation->senate)
->with('state', $geolocation->state)
->with('subtitle', $geolocation->state)
->with('breadcrumb', (object) array(
'name' => $zipcode,
'url' => 'zipcode/' . $zipcode
));
} catch (\Exception $exception) {
Bugsnag::notifyException($exception);
Log::error($exception);
abort(404, 'Unable to find ' . titleCase($zipcode));
}
}
/**
* @param $latitude
* @param $longitude
* @return mixed
*/
public function byGeolocation($latitude, $longitude)
{
try {
$geolocation = CivilServices::searchGovernment([
'latitude' => $latitude,
'longitude' => $longitude
]);
// Setup Meta Tags
MetaTag::set('title', 'Elected Officials for ' . $geolocation->state->state_name . ' (' . $latitude . ', ' . $longitude . ')');
MetaTag::set('description', 'Elected Officials for ' . $geolocation->state->state_name . ' (' . $latitude . ', ' . $longitude . ')');
MetaTag::set('image', $geolocation->state->skyline->size_1280x720);
MetaTag::set('keywords', 'Elected Officials, GPS, Location, ' . $latitude . ', ' . $longitude . ', ' . $geolocation->state->state_name);
return view('my-elected-officials.results')
->with('representatives', $geolocation->house)
->with('senators', $geolocation->senate)
->with('breadcrumb', (object) array(
'name' => 'Results',
'url' => 'geolocation/' . $latitude . '/' . $longitude
))
->with('state', $geolocation->state);
} catch (\Exception $exception) {
Bugsnag::notifyException($exception);
Log::error($exception);
abort(404, 'Unable to Detect Location');
}
}
}
| {
"content_hash": "a0521ebc28db85c8c195684eab5c8345",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 148,
"avg_line_length": 36.37623762376238,
"alnum_prop": 0.5459989112683723,
"repo_name": "CivilServiceUSA/website",
"id": "5d2803b0c8a064c40806d5d75685ab30a2cd5683",
"size": "3674",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/Http/Controllers/MyElectedOfficialsController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Blade",
"bytes": "254080"
},
{
"name": "JavaScript",
"bytes": "43144"
},
{
"name": "PHP",
"bytes": "427640"
},
{
"name": "Shell",
"bytes": "3143"
}
],
"symlink_target": ""
} |
# Copyright (C) 2008-2009 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA
package GenTest::Reporter::AriaDoubleRecovery;
require Exporter;
@ISA = qw(GenTest::Reporter);
use strict;
use DBI;
use GenTest;
use GenTest::Constants;
use GenTest::Reporter;
use GenTest::Comparator;
use Data::Dumper;
use IPC::Open2;
use POSIX;
my $first_reporter;
sub monitor {
my $reporter = shift;
# In case of two servers, we will be called twice.
# Only kill the first server and ignore the second call.
$first_reporter = $reporter if not defined $first_reporter;
return STATUS_OK if $reporter ne $first_reporter;
my $pid = $reporter->serverInfo('pid');
if (time() > $reporter->testEnd() - 19) {
say("Sending SIGKILL to server with pid $pid in order to force a recovery.");
kill(9, $pid);
return STATUS_SERVER_KILLED;
} else {
return STATUS_OK;
}
}
sub report {
my $reporter = shift;
#
# If there is a hang during recovery in one engine, another engine may continue to print
# periodic diagnostic output forever. This prevents PB2 timeout mechanisms from kicking in
# In order to avoid that, we set our own crude alarm as a stop-gap measure
#
alarm(3600);
$first_reporter = $reporter if not defined $first_reporter;
return STATUS_OK if $reporter ne $first_reporter;
my $binary = $reporter->serverInfo('binary');
my $language = $reporter->serverVariable('language');
my $lc_messages_dir = $reporter->serverVariable('lc_messages_dir');
my $datadir = $reporter->serverVariable('datadir');
$datadir =~ s{[\\/]$}{}sgio;
my $recovery_datadir = $datadir.'_recovery';
my $socket = $reporter->serverVariable('socket');
my $port = $reporter->serverVariable('port');
my $pid = $reporter->serverInfo('pid');
my $aria_block_size = $reporter->serverVariable('maria_block_size') || $reporter->serverVariable('aria_block_size');
my $plugin_dir = $reporter->serverVariable('plugin_dir');
my $plugins = $reporter->serverPlugins();
my $binlog_format = $reporter->serverVariable('binlog_format');
my $binlog_on = $reporter->serverVariable('log_bin');
my $engine = $reporter->serverVariable('storage_engine');
my $dbh_prev = DBI->connect($reporter->dsn());
if (defined $dbh_prev) {
# Server is still running, kill it.
$dbh_prev->disconnect();
say("Sending SIGKILL to server with pid $pid in order to force a recovery.");
kill(9, $pid);
sleep(5);
}
say("Copying datadir... (interrupting the copy operation may cause a false recovery failure to be reported below");
system("cp -r $datadir $recovery_datadir");
system("rm -f $recovery_datadir/core*"); # Remove cores from any previous crash
my $recovery_datadir_aria = $recovery_datadir.'-aria';
say("Attempting database recovery using aria_read_log ...");
say("Copying Aria log files from $datadir to $recovery_datadir_aria ...");
# Copy just the *aria* files in an empty location and create a test "database"
system("mkdir $recovery_datadir_aria");
system("cp $datadir/*aria_log* $recovery_datadir_aria");
system("mkdir $recovery_datadir_aria/test");
system("mkdir $recovery_datadir_aria/smf");
system("mkdir $recovery_datadir_aria/smf2");
say("Copying complete.");
my $aria_read_log_path;
if (-e $reporter->serverVariable('basedir')."/../storage/maria/aria_read_log") {
$aria_read_log_path = $reporter->serverVariable('basedir')."/../storage/maria/aria_read_log";
} else {
$aria_read_log_path = $reporter->serverVariable('basedir')."/../storage/maria/maria_read_log";
}
my $aria_chk_path;
if (-e $reporter->serverVariable('basedir')."/../storage/maria/aria_chk") {
$aria_chk_path = $reporter->serverVariable('basedir')."/../storage/maria/aria_chk";
} else {
$aria_chk_path = $reporter->serverVariable('basedir')."/../storage/maria/maria_chk";
}
chdir($recovery_datadir_aria);
my $aria_read_log_command = $aria_read_log_path." --aria-log-dir-path $recovery_datadir_aria --apply --check --silent";
my $recovery_pid;
my $recovery_duration = 4;
my $child_pid = fork();
if ($child_pid == 0) {
say("Executing first $aria_read_log_command");
exec($aria_read_log_command);
exit();
} else {
$recovery_pid = $child_pid;
say("Will kill the first aria_read_log via kill -9 $recovery_pid in $recovery_duration seconds");
local $SIG{ALRM} = sub { kill 9 , $recovery_pid } ;
alarm($recovery_duration);
sleep($recovery_duration);
}
alarm(0);
print "\n";
sleep(1);
say("Executing second $aria_read_log_command");
my $aria_read_log_result = system($aria_read_log_command);
return STATUS_RECOVERY_FAILURE if $aria_read_log_result > 0;
say("$aria_read_log_path apparently returned success");
my $aria_chk_result = system("$aria_chk_path --extend-check */*.MAI");
return STATUS_RECOVERY_FAILURE if $aria_chk_result > 0;
say("$aria_chk_path apparently returned success");
return STATUS_OK;
}
sub type {
return REPORTER_TYPE_ALWAYS | REPORTER_TYPE_PERIODIC;
}
1;
| {
"content_hash": "f45c87969120b1df375469909f7df8f6",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 120,
"avg_line_length": 33.66867469879518,
"alnum_prop": 0.7058507783145465,
"repo_name": "jonzobrist/Percona-Server-5.1",
"id": "1319676ba58bf81d0abb85c9de3668748ede2701",
"size": "5589",
"binary": false,
"copies": "25",
"ref": "refs/heads/master",
"path": "kewpie/randgen/lib/GenTest/Reporter/AriaDoubleRecovery.pm",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "63359"
},
{
"name": "C",
"bytes": "21629542"
},
{
"name": "C#",
"bytes": "186518"
},
{
"name": "C++",
"bytes": "26608206"
},
{
"name": "JavaScript",
"bytes": "34135"
},
{
"name": "Objective-C",
"bytes": "73098"
},
{
"name": "Perl",
"bytes": "2396066"
},
{
"name": "Puppet",
"bytes": "447114"
},
{
"name": "Python",
"bytes": "1181762"
},
{
"name": "R",
"bytes": "34454"
},
{
"name": "Racket",
"bytes": "2416"
},
{
"name": "Scilab",
"bytes": "7740"
},
{
"name": "Shell",
"bytes": "1287942"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!-- Copyright (C) 1988-2017 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with the
Invariant Sections being "Free Software" and "Free Software Needs
Free Documentation", with the Front-Cover Texts being "A GNU Manual,"
and with the Back-Cover Texts as in (a) below.
(a) The FSF's Back-Cover Text is: "You are free to copy and modify
this GNU Manual. Buying copies from GNU Press supports the FSF in
developing GNU and promoting software freedom." -->
<!-- Created by GNU Texinfo 5.2, http://www.gnu.org/software/texinfo/ -->
<head>
<title>Debugging with GDB: Arguments</title>
<meta name="description" content="Debugging with GDB: Arguments">
<meta name="keywords" content="Debugging with GDB: Arguments">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Concept-Index.html#Concept-Index" rel="index" title="Concept Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Running.html#Running" rel="up" title="Running">
<link href="Environment.html#Environment" rel="next" title="Environment">
<link href="Starting.html#Starting" rel="prev" title="Starting">
<style type="text/css">
<!--
a.summary-letter {text-decoration: none}
blockquote.smallquotation {font-size: smaller}
div.display {margin-left: 3.2em}
div.example {margin-left: 3.2em}
div.indentedblock {margin-left: 3.2em}
div.lisp {margin-left: 3.2em}
div.smalldisplay {margin-left: 3.2em}
div.smallexample {margin-left: 3.2em}
div.smallindentedblock {margin-left: 3.2em; font-size: smaller}
div.smalllisp {margin-left: 3.2em}
kbd {font-style:oblique}
pre.display {font-family: inherit}
pre.format {font-family: inherit}
pre.menu-comment {font-family: serif}
pre.menu-preformatted {font-family: serif}
pre.smalldisplay {font-family: inherit; font-size: smaller}
pre.smallexample {font-size: smaller}
pre.smallformat {font-family: inherit; font-size: smaller}
pre.smalllisp {font-size: smaller}
span.nocodebreak {white-space:nowrap}
span.nolinebreak {white-space:nowrap}
span.roman {font-family:serif; font-weight:normal}
span.sansserif {font-family:sans-serif; font-weight:normal}
ul.no-bullet {list-style: none}
-->
</style>
</head>
<body lang="en" bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000">
<a name="Arguments"></a>
<div class="header">
<p>
Next: <a href="Environment.html#Environment" accesskey="n" rel="next">Environment</a>, Previous: <a href="Starting.html#Starting" accesskey="p" rel="prev">Starting</a>, Up: <a href="Running.html#Running" accesskey="u" rel="up">Running</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Concept-Index.html#Concept-Index" title="Index" rel="index">Index</a>]</p>
</div>
<hr>
<a name="Your-Program_0027s-Arguments"></a>
<h3 class="section">4.3 Your Program’s Arguments</h3>
<a name="index-arguments-_0028to-your-program_0029"></a>
<p>The arguments to your program can be specified by the arguments of the
<code>run</code> command.
They are passed to a shell, which expands wildcard characters and
performs redirection of I/O, and thence to your program. Your
<code>SHELL</code> environment variable (if it exists) specifies what shell
<small>GDB</small> uses. If you do not define <code>SHELL</code>, <small>GDB</small> uses
the default shell (<samp>/bin/sh</samp> on Unix).
</p>
<p>On non-Unix systems, the program is usually invoked directly by
<small>GDB</small>, which emulates I/O redirection via the appropriate system
calls, and the wildcard characters are expanded by the startup code of
the program, not by the shell.
</p>
<p><code>run</code> with no arguments uses the same arguments used by the previous
<code>run</code>, or those set by the <code>set args</code> command.
</p>
<dl compact="compact">
<dd><a name="index-set-args"></a>
</dd>
<dt><code>set args</code></dt>
<dd><p>Specify the arguments to be used the next time your program is run. If
<code>set args</code> has no arguments, <code>run</code> executes your program
with no arguments. Once you have run your program with arguments,
using <code>set args</code> before the next <code>run</code> is the only way to run
it again without arguments.
</p>
<a name="index-show-args"></a>
</dd>
<dt><code>show args</code></dt>
<dd><p>Show the arguments to give your program when it is started.
</p></dd>
</dl>
</body>
</html>
| {
"content_hash": "ed1a61a65f6b105ff5856eb08e40f5ae",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 419,
"avg_line_length": 43.846846846846844,
"alnum_prop": 0.735771522498459,
"repo_name": "ATM-HSW/mbed_target",
"id": "571d90acc0a90aac53341cfa2b2a7158d858e732",
"size": "4867",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "buildtools/gcc-arm-none-eabi-6-2017-q2/share/doc/gcc-arm-none-eabi/html/gdb/Arguments.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "29493"
},
{
"name": "Batchfile",
"bytes": "948"
},
{
"name": "C",
"bytes": "3167609"
},
{
"name": "C++",
"bytes": "12419698"
},
{
"name": "HTML",
"bytes": "27891106"
},
{
"name": "MATLAB",
"bytes": "230413"
},
{
"name": "Makefile",
"bytes": "2798"
},
{
"name": "Python",
"bytes": "225136"
},
{
"name": "Shell",
"bytes": "50803"
},
{
"name": "XC",
"bytes": "9173"
},
{
"name": "XS",
"bytes": "9123"
}
],
"symlink_target": ""
} |
{
var listeners = listenersTable.get(currentTarget);
if (!listeners) return true;
var target = overrideTarget || eventRetargetting(eventPath, currentTarget);
if (target === currentTarget) {
if (phase === CAPTURING_PHASE) return true;
if (phase === BUBBLING_PHASE) phase = AT_TARGET;
} else if (phase === BUBBLING_PHASE && !event.bubbles) {
return true;
}
if ("relatedTarget" in event) {
var originalEvent = unwrap(event);
var unwrappedRelatedTarget = originalEvent.relatedTarget;
if (unwrappedRelatedTarget) {
if (
unwrappedRelatedTarget instanceof Object &&
unwrappedRelatedTarget.addEventListener
) {
var relatedTarget = wrap(unwrappedRelatedTarget);
var adjusted = relatedTargetResolution(
event,
currentTarget,
relatedTarget
);
if (adjusted === target) return true;
} else {
adjusted = null;
}
relatedTargetTable.set(event, adjusted);
}
}
eventPhaseTable.set(event, phase);
var type = event.type;
var anyRemoved = false;
targetTable.set(event, target);
currentTargetTable.set(event, currentTarget);
listeners.depth++;
for (var i = 0, len = listeners.length; i < len; i++) {
var listener = listeners[i];
if (listener.removed) {
anyRemoved = true;
continue;
}
if (
listener.type !== type ||
(!listener.capture && phase === CAPTURING_PHASE) ||
(listener.capture && phase === BUBBLING_PHASE)
) {
continue;
}
try {
if (typeof listener.handler === "function")
listener.handler.call(currentTarget, event);
else listener.handler.handleEvent(event);
if (stopImmediatePropagationTable.get(event)) return false;
} catch (ex) {
if (!pendingError) pendingError = ex;
}
}
listeners.depth--;
if (anyRemoved && listeners.depth === 0) {
var copy = listeners.slice();
listeners.length = 0;
for (var i = 0; i < copy.length; i++) {
if (!copy[i].removed) listeners.push(copy[i]);
}
}
return !stopPropagationTable.get(event);
}
| {
"content_hash": "aee27e1dbd7730506c9ecd6c587f38a4",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 77,
"avg_line_length": 26.01219512195122,
"alnum_prop": 0.6188466947960619,
"repo_name": "stas-vilchik/bdd-ml",
"id": "695b7e34e213b8ff307da2961827be1cb1113e38",
"size": "2133",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "data/6542.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "6666795"
},
{
"name": "Python",
"bytes": "3199"
}
],
"symlink_target": ""
} |
Interact with the Assembla API
## Installation
In hubot project repo, run:
`npm install hubot-assembla --save`
Then add **hubot-assembla** to your `external-scripts.json`:
```json
["hubot-assembla"]
```
## Config
HUBOT_ASSEMBLA_API_APP_ID - Create @ https://www.assembla.com/user/edit/manage_clients (leave website and redirect URLs blank)
HUBOT_ASSEMBLA_API_APP_SECRET
HUBOT_ASSEMBLA_SPACE - Assembla workspace that the script will interact with
HUBOT_ASSEMBLA_DEPLOY_ACTION_ID - SSH action id for your default deploy
## Commands
hubot deploy - deploy the default project
hubot deploy #<merge_req_number> - merge and close an MR then perform deploy via ssh_tool
hubot sshtool actions - list actions in the ssh tool
hubot sshtool action <ssh_tool_action_id_or_name> - look up a sshtool action by id or name
hubot sshtool run <ssh_tool_action_id_or_name> - run a sshtool action by id or name
hubot assembla pin <pin_code> - authenticate with a pin code
hubot forget my assembla auth - forget api token
hubot assembla whoami - who are you on assembla
hubot mr #<merge request> - show merge request
hubot merge request #<merge request> - show merge request
hubot merge_and_close merge request #<merge request> - merge and close merge request
hubot ignore merge request #<merge request> - ignore merge request
hubot create ticket <summary> - Creates a ticket on default space
hubot create ticket <summary> #in <space> - create a ticket on the space given
hubot assembla user <username_or_id> - display user
hubot space <space> - look up a space by id or wiki_name
ticket #<ticket> - show ticket on default space
| {
"content_hash": "5e04d9ac6dfe70b2d7b909962f0629fb",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 130,
"avg_line_length": 42.525,
"alnum_prop": 0.7272192827748384,
"repo_name": "benwtr/hubot-assembla",
"id": "eaca1dd559a7240d051213417a514744fbeb82d3",
"size": "1719",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "13340"
},
{
"name": "Shell",
"bytes": "438"
}
],
"symlink_target": ""
} |
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) > [puppeteer](./puppeteer.md) > [Protocol](./puppeteer.protocol.md) > [WebAudio](./puppeteer.protocol.webaudio.md) > [ContextCreatedEvent](./puppeteer.protocol.webaudio.contextcreatedevent.md) > [context](./puppeteer.protocol.webaudio.contextcreatedevent.context.md)
## Protocol.WebAudio.ContextCreatedEvent.context property
<b>Signature:</b>
```typescript
context: BaseAudioContext;
```
| {
"content_hash": "2126baa18c6a78b6abb254957641385f",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 300,
"avg_line_length": 47.09090909090909,
"alnum_prop": 0.7335907335907336,
"repo_name": "GoogleChrome/puppeteer",
"id": "4e740dfbf88943579aaa36e84b2a5b0c1505ba25",
"size": "518",
"binary": false,
"copies": "1",
"ref": "refs/heads/1060080_cross_origin_iframe",
"path": "new-docs/puppeteer.protocol.webaudio.contextcreatedevent.context.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "393"
},
{
"name": "HTML",
"bytes": "17624"
},
{
"name": "JavaScript",
"bytes": "1087838"
},
{
"name": "TypeScript",
"bytes": "8164"
}
],
"symlink_target": ""
} |
import sys
import os
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# Get the project root dir, which is the parent dir of this
cwd = os.getcwd()
project_root = os.path.dirname(cwd)
# Insert the project root dir as the first element in the PYTHONPATH.
# This lets us ensure that the source package is imported, and that its
# version is used.
sys.path.insert(0, project_root)
import jinja2_pluralize
# -- General configuration ---------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Jinja2 Pluralize'
copyright = u'2014, Audrey Roy'
# The version info for the project you're documenting, acts as replacement
# for |version| and |release|, also used in various other places throughout
# the built documents.
#
# The short X.Y version.
version = jinja2_pluralize.__version__
# The full version, including alpha/beta/rc tags.
release = jinja2_pluralize.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to
# some non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built
# documents.
#keep_warnings = False
# -- Options for HTML output -------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a
# theme further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as
# html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the
# top of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon
# of the docs. This file should be a Windows icon file (.ico) being
# 16x16 or 32x32 pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets)
# here, relative to this directory. They are copied after the builtin
# static files, so a file named "default.css" will overwrite the builtin
# "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names
# to template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer.
# Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer.
# Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages
# will contain a <link> tag referring to it. The value of this option
# must be the base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'jinja2_pluralizedoc'
# -- Options for LaTeX output ------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto/manual]).
latex_documents = [
('index', 'jinja2_pluralize.tex',
u'Jinja2 Pluralize Documentation',
u'Audrey Roy', 'manual'),
]
# The name of an image file (relative to this directory) to place at
# the top of the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings
# are parts, not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'jinja2_pluralize',
u'Jinja2 Pluralize Documentation',
[u'Audrey Roy'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ----------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'jinja2_pluralize',
u'Jinja2 Pluralize Documentation',
u'Audrey Roy',
'jinja2_pluralize',
'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False | {
"content_hash": "142fa797c447a173ff812e2ad47421aa",
"timestamp": "",
"source": "github",
"line_count": 260,
"max_line_length": 76,
"avg_line_length": 30.93846153846154,
"alnum_prop": 0.7042516161113874,
"repo_name": "audreyr/jinja2_pluralize",
"id": "040346e957da9566b42492e84f96cf0e919f12f5",
"size": "8489",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/conf.py",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "Makefile",
"bytes": "1342"
},
{
"name": "Python",
"bytes": "5784"
}
],
"symlink_target": ""
} |
foam.CLASS({
package: 'foam.dao',
name: 'StoreAndForwardDAO',
extends: 'foam.dao.ProxyDAO',
documentation: `Store-and-forward (i.e., store-and-retry) failed DAO
operations. Useful for DAOs that may flake, but eventually succeed.`,
requires: [ 'foam.dao.InternalException' ],
classes: [
{
name: 'DAOOperation',
properties: [
{
class: 'String',
documentation: 'DAO method name associated with operation.',
name: 'methodName',
},
{
documentation: 'Arguments object associated with operation.',
name: 'args',
},
{
name: 'promise_',
factory: function() {
var self = this;
var resolve;
var reject;
var promise = new Promise(function(res, rej) {
resolve = res;
reject = rej;
});
promise.resolveFunction_ = resolve;
promise.rejectFunction_ = reject;
return promise;
}
},
{
class: 'Function',
name: 'resolve_',
factory: function() {
return this.promise_.resolveFunction_;
}
},
{
class: 'Function',
name: 'reject_',
factory: function() {
return this.promise_.rejectFunction_;
}
}
],
methods: [
function getPromise() { return this.promise_; }
],
listeners: [
function resolve() { return this.resolve_.apply(this, arguments); },
function reject() { return this.reject_.apply(this, arguments); }
]
}
],
properties: [
{
name: 'delegate',
postSet: function(old, nu) {
if ( this.isForwarding_ )
this.__context__.warn('StoreAndForwardDAO: Delegate while flushing queue!');
this.forward_();
}
},
{
class: 'Function',
documentation: `Determine whether or not an error is sufficiently internal
to the DAO that it's worth retrying the operation that yeilded the
error. Default is to retry foam.dao.InternalException errors.`,
name: 'shouldRetry',
// TODO(markdittmer): These should be supported by function properties,
// but they're not.
/*
type: 'Boolean',
args: [
{
documentation: 'The error thrown by the delegate DAO.',
name: 'error',
type: 'Any',
},
],
*/
value: function(error) {
return this.InternalException.isInstance(error);
}
},
{
class: 'FObjectArray',
of: 'FObject',
// of: 'DAOOperation',
documentation: 'Queue for incomplete DAO operations.',
name: 'q_',
},
{
class: 'Boolean',
name: 'isForwarding_',
},
],
methods: [
function put_() { return this.store_(foam.dao.DOP.PUT_.label, arguments); },
function remove_() { return this.store_(foam.dao.DOP.REMOVE_.label, arguments); },
function find_() { return this.store_(foam.dao.DOP.FIND_.label, arguments); },
function select_() { return this.store_(foam.dao.DOP.SELECT_.label, arguments); },
function removeAll_() { return this.store_(foam.dao.DOP.REMOVE_ALL_.label, arguments); },
function store_(methodName, args) {
// Store DAO operations in order.
var op = this.DAOOperation.create({
methodName: methodName,
args: args,
});
this.q_.push(op);
// If no forwarding in progress then forward this op immediately.
// Otherwise, in-progress forwarding will get to it eventually.
if ( ! this.isForwarding_ ) this.forward_();
// Return Promise associated with completing operation.
return op.getPromise();
},
function forward_() {
// Guard against flush-to-(no delegate) or attempt to flush empty queue.
if ( ( ! this.delegate ) || this.q_.length === 0 ) {
this.isForwarding_ = false;
return;
}
this.isForwarding_ = true;
var op = this.q_[0];
this.delegate[op.methodName].apply(this.delegate, op.args)
.then(this.onComplete.bind(this, op))
.catch(this.onError.bind(this, op));
}
],
listeners: [
{
name: 'onQ',
documentation: `Attempt to forward failed operations no more frequently
than "mergeDelay"ms.`,
isMerged: 'true',
mergeDelay: 2000,
code: function() {
this.forward_();
}
},
{
name: 'onComplete',
documentation: `Operation, "op", just completed successfully, yielding
"result". Since order is presvered, "op" is at the head of "q_".
Dequeue "op" and resolve its promise.`,
code: function(op, result) {
// Dequeue and resolve completed op; attempt to forward next op.
this.q_.shift();
op.resolve(result);
this.forward_();
}
},
{
name: 'onError',
documentation: `Operation, "op", failed, yielding "error". If it should be
retried, tickle merged listener "onQ" to ensure that it is tried again
later. Otherwise, discard it from "q_" and reject its promise.`,
code: function(op, error) {
// Trigger merged listener to initiate another forwarding attempt.
if ( this.shouldRetry(error) ) {
this.isForwarding_ = false;
this.onQ();
return;
}
// Thrown error not retryable:
// Dequeue and reject op; attempt to forward next op.
this.q_.shift();
op.reject(error);
this.forward_();
}
}
]
});
| {
"content_hash": "3e102c351b77ac8bd5a469d80e02f4df",
"timestamp": "",
"source": "github",
"line_count": 194,
"max_line_length": 93,
"avg_line_length": 29.144329896907216,
"alnum_prop": 0.5550053059780686,
"repo_name": "foam-framework/foam2",
"id": "44863583542370eb803b345c0ccad1d67b05926d",
"size": "6288",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/foam/dao/StoreAndForwardDAO.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "20356"
},
{
"name": "HTML",
"bytes": "10220505"
},
{
"name": "Java",
"bytes": "977816"
},
{
"name": "JavaScript",
"bytes": "7065731"
},
{
"name": "Makefile",
"bytes": "7676"
},
{
"name": "Shell",
"bytes": "5963"
},
{
"name": "Swift",
"bytes": "19039"
}
],
"symlink_target": ""
} |
package Google::Ads::AdWords::v201406::PlaceHolder;
use strict;
use warnings;
__PACKAGE__->_set_element_form_qualified(1);
sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201406' };
our $XML_ATTRIBUTE_CLASS;
undef $XML_ATTRIBUTE_CLASS;
sub __get_attr_class {
return $XML_ATTRIBUTE_CLASS;
}
use Class::Std::Fast::Storable constructor => 'none';
use base qw(Google::Ads::SOAP::Typelib::ComplexType);
{ # BLOCK to scope variables
__PACKAGE__->_factory(
[ qw(
) ],
{
},
{
},
{
}
);
} # end BLOCK
1;
=pod
=head1 NAME
Google::Ads::AdWords::v201406::PlaceHolder
=head1 DESCRIPTION
Perl data type class for the XML Schema defined complexType
PlaceHolder from the namespace https://adwords.google.com/api/adwords/cm/v201406.
A place holder for a result which is not available.
=head2 PROPERTIES
The following properties may be accessed using get_PROPERTY / set_PROPERTY
methods:
=over
=back
=head1 METHODS
=head2 new
Constructor. The following data structure may be passed to new():
=head1 AUTHOR
Generated by SOAP::WSDL
=cut
| {
"content_hash": "e031bbd639dea851c4ac6b070c36f19f",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 81,
"avg_line_length": 12.366666666666667,
"alnum_prop": 0.6864330637915543,
"repo_name": "gitpan/Google-Ads-AdWords-Client",
"id": "93e0bb318918b18beeb6fbdfe624e67b1750a8fd",
"size": "1113",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/Google/Ads/AdWords/v201406/PlaceHolder.pm",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Perl",
"bytes": "18425492"
}
],
"symlink_target": ""
} |
homebrew-bbsite
===============
install emacs
-------------
brew install --with-cocoa --japanese smiyabe/bbsite/emacs
| {
"content_hash": "f2aa2b5496629f96dcd0c4229f213767",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 57,
"avg_line_length": 13.555555555555555,
"alnum_prop": 0.5901639344262295,
"repo_name": "smiyabe/homebrew-bbsite",
"id": "6488397f24964003ad3b87bb72a6da0aceadc937",
"size": "122",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Ruby",
"bytes": "5746"
}
],
"symlink_target": ""
} |
package vista.paneles.org;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ModificacionCarreraOrg extends JPanel {
private static final long serialVersionUID = 1L;
private JTextField txtDistancia;
private JTextField txtDesnivel;
private JTextField txtPrecio;
private JTextField txtFecha;
private JTextField txtLugar;
private JButton btnModificar, btnLimpiar;
private JComboBox<Object> comboCarreraModificar;
public JTextField getTxtDistancia() {
return txtDistancia;
}
public JTextField getTxtDesnivel() {
return txtDesnivel;
}
public JTextField getTxtPrecio() {
return txtPrecio;
}
public JTextField getTxtFecha() {
return txtFecha;
}
public JTextField getTxtLugar() {
return txtLugar;
}
public JButton getBtnModificar() {
return btnModificar;
}
public JButton getBtnLimpiar() {
return btnLimpiar;
}
public JComboBox<Object> getComboCarreraModificar() {
return comboCarreraModificar;
}
public ModificacionCarreraOrg() {
setMinimumSize(new Dimension(800, 600));
setMaximumSize(new Dimension(800, 600));
setBounds(100, 100, 582, 351);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[] { 65, 86, 134, 65, 0 };
gridBagLayout.rowHeights = new int[] { 60, 23, 20, 0, 0, 0, 0, 0, 0, 0, 60, 0 };
gridBagLayout.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE };
gridBagLayout.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
Double.MIN_VALUE };
setLayout(gridBagLayout);
JLabel lblCarreraAModificar = new JLabel("Carrera a modificar: ");
lblCarreraAModificar.setFont(new Font("Lucida Grande", Font.BOLD, 13));
lblCarreraAModificar.setBounds(29, 19, 147, 16);
GridBagConstraints gbc_lblCarreraAModificar = new GridBagConstraints();
gbc_lblCarreraAModificar.anchor = GridBagConstraints.EAST;
gbc_lblCarreraAModificar.insets = new Insets(0, 0, 5, 5);
gbc_lblCarreraAModificar.gridx = 1;
gbc_lblCarreraAModificar.gridy = 1;
add(lblCarreraAModificar, gbc_lblCarreraAModificar);
comboCarreraModificar = new JComboBox<>();
comboCarreraModificar.setBounds(188, 15, 203, 27);
GridBagConstraints gbc_comboCarreraModificar = new GridBagConstraints();
gbc_comboCarreraModificar.fill = GridBagConstraints.HORIZONTAL;
gbc_comboCarreraModificar.anchor = GridBagConstraints.NORTHWEST;
gbc_comboCarreraModificar.insets = new Insets(0, 0, 5, 5);
gbc_comboCarreraModificar.gridx = 2;
gbc_comboCarreraModificar.gridy = 1;
add(comboCarreraModificar, gbc_comboCarreraModificar);
JLabel lblNuevosDatos = new JLabel("Nuevos Datos: ");
lblNuevosDatos.setFont(new Font("Lucida Grande", Font.BOLD, 15));
lblNuevosDatos.setBounds(29, 63, 129, 27);
GridBagConstraints gbc_lblNuevosDatos = new GridBagConstraints();
gbc_lblNuevosDatos.anchor = GridBagConstraints.NORTHWEST;
gbc_lblNuevosDatos.insets = new Insets(0, 0, 5, 5);
gbc_lblNuevosDatos.gridx = 1;
gbc_lblNuevosDatos.gridy = 2;
add(lblNuevosDatos, gbc_lblNuevosDatos);
JLabel lblDistancia = new JLabel("Distancia: ");
lblDistancia.setBounds(59, 125, 78, 16);
GridBagConstraints gbc_lblDistancia = new GridBagConstraints();
gbc_lblDistancia.insets = new Insets(0, 0, 5, 5);
gbc_lblDistancia.gridx = 1;
gbc_lblDistancia.gridy = 3;
add(lblDistancia, gbc_lblDistancia);
txtDistancia = new JTextField();
txtDistancia.setBounds(149, 120, 130, 26);
GridBagConstraints gbc_txtDistancia = new GridBagConstraints();
gbc_txtDistancia.fill = GridBagConstraints.HORIZONTAL;
gbc_txtDistancia.anchor = GridBagConstraints.WEST;
gbc_txtDistancia.insets = new Insets(0, 0, 5, 5);
gbc_txtDistancia.gridx = 2;
gbc_txtDistancia.gridy = 3;
add(txtDistancia, gbc_txtDistancia);
txtDistancia.setColumns(10);
JLabel lblDesnivel = new JLabel("Desnivel: ");
lblDesnivel.setBounds(59, 168, 78, 16);
GridBagConstraints gbc_lblDesnivel = new GridBagConstraints();
gbc_lblDesnivel.insets = new Insets(0, 0, 5, 5);
gbc_lblDesnivel.gridx = 1;
gbc_lblDesnivel.gridy = 4;
add(lblDesnivel, gbc_lblDesnivel);
txtDesnivel = new JTextField();
txtDesnivel.setBounds(149, 163, 130, 26);
GridBagConstraints gbc_txtDesnivel = new GridBagConstraints();
gbc_txtDesnivel.fill = GridBagConstraints.HORIZONTAL;
gbc_txtDesnivel.anchor = GridBagConstraints.WEST;
gbc_txtDesnivel.insets = new Insets(0, 0, 5, 5);
gbc_txtDesnivel.gridx = 2;
gbc_txtDesnivel.gridy = 4;
add(txtDesnivel, gbc_txtDesnivel);
txtDesnivel.setColumns(10);
JLabel lblPrecio = new JLabel("Precio: ");
lblPrecio.setBounds(59, 214, 61, 16);
GridBagConstraints gbc_lblPrecio = new GridBagConstraints();
gbc_lblPrecio.insets = new Insets(0, 0, 5, 5);
gbc_lblPrecio.gridx = 1;
gbc_lblPrecio.gridy = 5;
add(lblPrecio, gbc_lblPrecio);
txtPrecio = new JTextField();
txtPrecio.setBounds(149, 209, 130, 26);
GridBagConstraints gbc_txtPrecio = new GridBagConstraints();
gbc_txtPrecio.fill = GridBagConstraints.HORIZONTAL;
gbc_txtPrecio.anchor = GridBagConstraints.WEST;
gbc_txtPrecio.insets = new Insets(0, 0, 5, 5);
gbc_txtPrecio.gridx = 2;
gbc_txtPrecio.gridy = 5;
add(txtPrecio, gbc_txtPrecio);
txtPrecio.setColumns(10);
JLabel lblFecha = new JLabel("Fecha: ");
lblFecha.setBounds(59, 261, 61, 16);
GridBagConstraints gbc_lblFecha = new GridBagConstraints();
gbc_lblFecha.insets = new Insets(0, 0, 5, 5);
gbc_lblFecha.gridx = 1;
gbc_lblFecha.gridy = 6;
add(lblFecha, gbc_lblFecha);
txtFecha = new JTextField();
txtFecha.setText("Ej. 1999-09-09");
txtFecha.setBounds(149, 256, 130, 26);
GridBagConstraints gbc_txtFecha = new GridBagConstraints();
gbc_txtFecha.fill = GridBagConstraints.HORIZONTAL;
gbc_txtFecha.anchor = GridBagConstraints.NORTH;
gbc_txtFecha.insets = new Insets(0, 0, 5, 5);
gbc_txtFecha.gridx = 2;
gbc_txtFecha.gridy = 6;
add(txtFecha, gbc_txtFecha);
JLabel lblLugar = new JLabel("Lugar: ");
lblLugar.setBounds(59, 309, 61, 16);
GridBagConstraints gbc_lblLugar = new GridBagConstraints();
gbc_lblLugar.insets = new Insets(0, 0, 5, 5);
gbc_lblLugar.gridx = 1;
gbc_lblLugar.gridy = 7;
add(lblLugar, gbc_lblLugar);
txtLugar = new JTextField();
txtLugar.setBounds(149, 304, 130, 26);
GridBagConstraints gbc_txtLugar = new GridBagConstraints();
gbc_txtLugar.fill = GridBagConstraints.HORIZONTAL;
gbc_txtLugar.anchor = GridBagConstraints.WEST;
gbc_txtLugar.insets = new Insets(0, 0, 5, 5);
gbc_txtLugar.gridx = 2;
gbc_txtLugar.gridy = 7;
add(txtLugar, gbc_txtLugar);
txtLugar.setColumns(10);
btnModificar = new JButton("Modificar");
btnModificar.setBounds(333, 120, 117, 29);
GridBagConstraints gbc_btnModificar = new GridBagConstraints();
gbc_btnModificar.insets = new Insets(0, 0, 5, 5);
gbc_btnModificar.gridx = 1;
gbc_btnModificar.gridy = 9;
add(btnModificar, gbc_btnModificar);
btnLimpiar = new JButton("Limpiar");
btnLimpiar.setBounds(333, 163, 117, 29);
GridBagConstraints gbc_btnLimpiar = new GridBagConstraints();
gbc_btnLimpiar.insets = new Insets(0, 0, 5, 5);
gbc_btnLimpiar.gridx = 2;
gbc_btnLimpiar.gridy = 9;
add(btnLimpiar, gbc_btnLimpiar);
}
}
| {
"content_hash": "bd6bd508cfd2221580b2a07013b1883f",
"timestamp": "",
"source": "github",
"line_count": 216,
"max_line_length": 98,
"avg_line_length": 34.236111111111114,
"alnum_prop": 0.7369844489519946,
"repo_name": "usainzg/RaceManager",
"id": "ea834b6e499fd800747eb20c71f8df7d41f8afd5",
"size": "7395",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ProyectoCarreras/src/vista/paneles/org/ModificacionCarreraOrg.java",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12842"
},
{
"name": "HTML",
"bytes": "1160325"
},
{
"name": "Java",
"bytes": "173007"
},
{
"name": "JavaScript",
"bytes": "827"
},
{
"name": "SQLPL",
"bytes": "38835"
}
],
"symlink_target": ""
} |
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Reflection;
namespace OpenSim.Region.CoreModules.Asset
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "CoreAssetCache")]
public class CoreAssetCache : ISharedRegionModule, IImprovedAssetCache
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private Cache m_Cache;
private bool m_Enabled;
public string Name
{
get { return "CoreAssetCache"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void AddRegion(Scene scene)
{
if (m_Enabled)
scene.RegisterModuleInterface<IImprovedAssetCache>(this);
}
public void Cache(AssetBase asset)
{
if (asset != null)
m_Cache.Store(asset.ID, asset);
}
////////////////////////////////////////////////////////////
// IImprovedAssetCache
//
public bool Check(string id)
{
// XXX This is probably not an efficient implementation.
return Get(id) != null;
}
public void Clear()
{
m_Cache.Clear();
}
public void Close()
{
}
public void Expire(string id)
{
m_Cache.Invalidate(id);
}
public AssetBase Get(string id)
{
return (AssetBase)m_Cache.Get(id);
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("AssetCaching");
//m_log.DebugFormat("[XXX] name = {0} (this module's name: {1}", name, Name);
if (name == Name)
{
IConfig assetConfig = source.Configs["AssetCache"];
if (assetConfig == null)
{
m_log.Error("[ASSET CACHE]: AssetCache missing from OpenSim.ini");
return;
}
m_Cache = new Cache(CacheMedium.Memory, CacheStrategy.Aggressive, CacheFlags.AllowUpdate);
m_Enabled = true;
m_log.Info("[ASSET CACHE]: Core asset cache enabled");
m_Cache.Size = assetConfig.GetInt("CacheBuckets", 32768);
}
}
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
}
}
} | {
"content_hash": "19a7a1e22f8b6453450368f11cb2ffe1",
"timestamp": "",
"source": "github",
"line_count": 114,
"max_line_length": 110,
"avg_line_length": 25.982456140350877,
"alnum_prop": 0.5060769750168805,
"repo_name": "ft-/opensim-optimizations-wip",
"id": "a479e8f645c9f61d04c37e7bd9194face34bd5a0",
"size": "4579",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "OpenSim/Region/CoreModules/Asset/CoreAssetCache.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C#",
"bytes": "16122272"
},
{
"name": "CSS",
"bytes": "1683"
},
{
"name": "JavaScript",
"bytes": "556"
},
{
"name": "Ruby",
"bytes": "1111"
},
{
"name": "Shell",
"bytes": "1715"
}
],
"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 -->
<title>com.centurylink.mdw.request (MDW 6 API JavaDocs)</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<h1 class="bar"><a href="../../../../com/centurylink/mdw/request/package-summary.html" target="classFrame">com.centurylink.mdw.request</a></h1>
<div class="indexContainer">
<h2 title="Interfaces">Interfaces</h2>
<ul title="Interfaces">
<li><a href="RequestHandler.html" title="interface in com.centurylink.mdw.request" target="classFrame"><span class="interfaceName">RequestHandler</span></a></li>
</ul>
<h2 title="Enums">Enums</h2>
<ul title="Enums">
<li><a href="RequestHandler.Routing.html" title="enum in com.centurylink.mdw.request" target="classFrame">RequestHandler.Routing</a></li>
</ul>
<h2 title="Exceptions">Exceptions</h2>
<ul title="Exceptions">
<li><a href="RequestHandlerException.html" title="class in com.centurylink.mdw.request" target="classFrame">RequestHandlerException</a></li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "a391697fac2918dbd96135a1834f8b52",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 161,
"avg_line_length": 45.888888888888886,
"alnum_prop": 0.7005649717514124,
"repo_name": "CenturyLinkCloud/mdw",
"id": "4a62a8af675312e21456ec172994360ff6e183dd",
"size": "1239",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/_docs/javadoc/com/centurylink/mdw/request/package-frame.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "213"
},
{
"name": "CSS",
"bytes": "360257"
},
{
"name": "Dockerfile",
"bytes": "1606"
},
{
"name": "Groovy",
"bytes": "1370"
},
{
"name": "HTML",
"bytes": "253602"
},
{
"name": "Java",
"bytes": "4874323"
},
{
"name": "JavaScript",
"bytes": "1588812"
},
{
"name": "Kotlin",
"bytes": "49698"
},
{
"name": "PLSQL",
"bytes": "34878"
},
{
"name": "Python",
"bytes": "1790"
},
{
"name": "Shell",
"bytes": "24146"
},
{
"name": "XSLT",
"bytes": "15751"
}
],
"symlink_target": ""
} |
<?php
namespace Backend\Modules\Location\Actions;
use Backend\Core\Engine\Authentication as BackendAuthentication;
use Backend\Core\Engine\Base\ActionEdit as BackendBaseActionEdit;
use Backend\Core\Engine\Form as BackendForm;
use Backend\Core\Language\Language as BL;
use Backend\Core\Engine\Model as BackendModel;
use Backend\Modules\Location\Engine\Model as BackendLocationModel;
use Symfony\Component\Intl\Intl as Intl;
/**
* This is the edit-action, it will display a form to create a new item
*/
class Edit extends BackendBaseActionEdit
{
/**
* @var array
*/
protected $settings = array();
/**
* The settings form
*
* @var BackendForm
*/
protected $settingsForm;
/**
* Execute the action
*/
public function execute()
{
$this->id = $this->getParameter('id', 'int');
// does the item exists
if ($this->id !== null && BackendLocationModel::exists($this->id)) {
parent::execute();
// define Google Maps API key
$apikey = $this->get('fork.settings')->get('Core', 'google_maps_key');
// check Google Maps API key, otherwise redirect to settings
if ($apikey === null) {
$this->redirect(BackendModel::createURLForAction('Index', 'Settings'));
}
// add js
$this->header->addJS('https://maps.googleapis.com/maps/api/js?key=' . $apikey, null, false, true, false);
$this->loadData();
$this->loadForm();
$this->validateForm();
$this->loadSettingsForm();
$this->parse();
$this->display();
} else {
$this->redirect(BackendModel::createURLForAction('Index') . '&error=non-existing');
}
}
/**
* Get the data
*/
private function loadData()
{
$this->record = (array) BackendLocationModel::get($this->id);
// no item found, throw an exceptions, because somebody is fucking with our URL
if (empty($this->record)) {
$this->redirect(BackendModel::createURLForAction('Index') . '&error=non-existing');
}
$this->settings = BackendLocationModel::getMapSettings($this->id);
// load the settings from the general settings
if (empty($this->settings)) {
$settings = $this->get('fork.settings')->getForModule('Location');
$this->settings['width'] = $settings['width_widget'];
$this->settings['height'] = $settings['height_widget'];
$this->settings['map_type'] = $settings['map_type_widget'];
$this->settings['zoom_level'] = $settings['zoom_level_widget'];
$this->settings['center']['lat'] = $this->record['lat'];
$this->settings['center']['lng'] = $this->record['lng'];
}
// no center point given yet, use the first occurrence
if (!isset($this->settings['center'])) {
$this->settings['center']['lat'] = $this->record['lat'];
$this->settings['center']['lng'] = $this->record['lng'];
}
$this->settings['full_url'] = (isset($this->settings['full_url'])) ? ($this->settings['full_url']) : false;
$this->settings['directions'] = (isset($this->settings['directions'])) ? ($this->settings['directions']) : false;
}
/**
* Load the form
*/
private function loadForm()
{
$this->frm = new BackendForm('edit');
$this->frm->addText('title', $this->record['title'], null, 'form-control title', 'form-control danger title');
$this->frm->addText('street', $this->record['street']);
$this->frm->addText('number', $this->record['number']);
$this->frm->addText('zip', $this->record['zip']);
$this->frm->addText('city', $this->record['city']);
$this->frm->addDropdown('country', Intl::getRegionBundle()->getCountryNames(BL::getInterfaceLanguage()), $this->record['country']);
$this->frm->addHidden('redirect', 'overview');
}
/**
* Load the settings form
*/
protected function loadSettingsForm()
{
$mapTypes = array(
'ROADMAP' => BL::lbl('Roadmap', $this->getModule()),
'SATELLITE' => BL::lbl('Satellite', $this->getModule()),
'HYBRID' => BL::lbl('Hybrid', $this->getModule()),
'TERRAIN' => BL::lbl('Terrain', $this->getModule()),
);
$zoomLevels = array_combine(
array_merge(array('auto'), range(1, 18)),
array_merge(array(BL::lbl('Auto', $this->getModule())), range(1, 18))
);
$this->settingsForm = new BackendForm('settings');
// add map info (overview map)
$this->settingsForm->addHidden('map_id', $this->id);
$this->settingsForm->addDropdown('zoom_level', $zoomLevels, $this->settings['zoom_level']);
$this->settingsForm->addText('width', $this->settings['width']);
$this->settingsForm->addText('height', $this->settings['height']);
$this->settingsForm->addDropdown('map_type', $mapTypes, $this->settings['map_type']);
$this->settingsForm->addCheckbox('full_url', $this->settings['full_url']);
$this->settingsForm->addCheckbox('directions', $this->settings['directions']);
$this->settingsForm->addCheckbox('marker_overview', ($this->record['show_overview'] == 'Y'));
}
/**
* Parse the form
*/
protected function parse()
{
parent::parse();
// assign to template
$this->tpl->assign('item', $this->record);
$this->tpl->assign('settings', $this->settings);
$this->tpl->assign('godUser', BackendAuthentication::getUser()->isGod());
$this->settingsForm->parse($this->tpl);
// assign message if address was not be geocoded
if ($this->record['lat'] == null || $this->record['lng'] == null) {
$this->tpl->assign('errorMessage', BL::err('AddressCouldNotBeGeocoded'));
}
}
/**
* Validate the form
*/
private function validateForm()
{
if ($this->frm->isSubmitted()) {
$this->frm->cleanupFields();
// validate fields
$this->frm->getField('title')->isFilled(BL::err('TitleIsRequired'));
$this->frm->getField('street')->isFilled(BL::err('FieldIsRequired'));
$this->frm->getField('number')->isFilled(BL::err('FieldIsRequired'));
$this->frm->getField('zip')->isFilled(BL::err('FieldIsRequired'));
$this->frm->getField('city')->isFilled(BL::err('FieldIsRequired'));
if ($this->frm->isCorrect()) {
// build item
$item['id'] = $this->id;
$item['language'] = BL::getWorkingLanguage();
$item['extra_id'] = $this->record['extra_id'];
$item['title'] = $this->frm->getField('title')->getValue();
$item['street'] = $this->frm->getField('street')->getValue();
$item['number'] = $this->frm->getField('number')->getValue();
$item['zip'] = $this->frm->getField('zip')->getValue();
$item['city'] = $this->frm->getField('city')->getValue();
$item['country'] = $this->frm->getField('country')->getValue();
// check if it's necessary to geocode again
if ($this->record['lat'] === null || $this->record['lng'] === null || $item['street'] != $this->record['street'] || $item['number'] != $this->record['number'] || $item['zip'] != $this->record['zip'] || $item['city'] != $this->record['city'] || $item['country'] != $this->record['country']) {
// define coordinates
$coordinates = BackendLocationModel::getCoordinates(
$item['street'],
$item['number'],
$item['city'],
$item['zip'],
$item['country']
);
// define latitude and longitude
$item['lat'] = $coordinates['latitude'];
$item['lng'] = $coordinates['longitude'];
} else {
$item['lat'] = $this->record['lat'];
$item['lng'] = $this->record['lng'];
}
// insert the item
BackendLocationModel::update($item);
// everything is saved, so redirect to the overview
if ($item['lat'] && $item['lng']) {
// trigger event
BackendModel::triggerEvent($this->getModule(), 'after_edit', array('item' => $item));
}
// redirect to the overview
if ($this->frm->getField('redirect')->getValue() == 'overview') {
$this->redirect(BackendModel::createURLForAction('Index') . '&report=edited&var=' . rawurlencode($item['title']) . '&highlight=row-' . $item['id']);
} else {
$this->redirect(BackendModel::createURLForAction('Edit') . '&id=' . $item['id'] . '&report=edited');
}
}
}
}
}
| {
"content_hash": "962c9d870af26c7b9759c9222acce9d8",
"timestamp": "",
"source": "github",
"line_count": 233,
"max_line_length": 307,
"avg_line_length": 39.587982832618025,
"alnum_prop": 0.5357762359063313,
"repo_name": "dmoerman/forkcms",
"id": "9a2346266566974b3ae9e89a52abcbddd6c6191b",
"size": "9394",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Backend/Modules/Location/Actions/Edit.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3424"
},
{
"name": "CSS",
"bytes": "166296"
},
{
"name": "HTML",
"bytes": "1146020"
},
{
"name": "JavaScript",
"bytes": "951079"
},
{
"name": "PHP",
"bytes": "3180211"
},
{
"name": "Smarty",
"bytes": "23315"
}
],
"symlink_target": ""
} |
import React from 'react'
import PropTypes from 'prop-types'
import {PatchEvent, set} from 'part:@sanity/form-builder/patch-event'
import styles from './CustomFontStringInput.module.css'
export default class CustomStringInput extends React.Component {
static propTypes = {
value: PropTypes.string,
type: PropTypes.object,
onChange: PropTypes.func,
}
handleChange = (event) => {
this.props.onChange(PatchEvent.from(set(event.target.value)))
}
render() {
const {value, type} = this.props
return (
<div>
<h3>{type.title}</h3>
<p>{type.description}</p>
<input
type="text"
className={styles.input}
placeholder={type.placeholder}
onChange={this.handleChange}
value={value}
/>
</div>
)
}
}
| {
"content_hash": "41515cf605833ae46e6e4d8ba4969d4b",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 69,
"avg_line_length": 25.59375,
"alnum_prop": 0.6227106227106227,
"repo_name": "sanity-io/sanity",
"id": "e3eebdc375a3f7f36d38bcf2094b90950f51c3c7",
"size": "819",
"binary": false,
"copies": "1",
"ref": "refs/heads/next",
"path": "dev/test-studio/schema/debug/components/CustomFontStringInput.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "235048"
},
{
"name": "HTML",
"bytes": "181261"
},
{
"name": "JavaScript",
"bytes": "1485414"
},
{
"name": "Shell",
"bytes": "1303"
},
{
"name": "TypeScript",
"bytes": "3980581"
}
],
"symlink_target": ""
} |
#ifndef API_MANAGER_AUTH_LIB_AUTH_TOKEN_H_
#define API_MANAGER_AUTH_LIB_AUTH_TOKEN_H_
#include <stddef.h>
namespace google {
namespace api_manager {
namespace auth {
// Parse a json secret and generate auth_token
// Returned pointer need to be freed by esp_grpc_free
char *esp_get_auth_token(const char *json_secret, const char *audience);
// Free a buffer allocated by gRPC library.
void esp_grpc_free(char *token);
// Parses a JSON service account auth token in the following format:
// {
// "access_token":" ... ",
// "expires_in":100,
// "token_type":"Bearer"
// }
// Returns true on success, false otherwise. On success, *token is set to the
// malloc'd auth token (value of 'access_token' JSON property) and *expires is
// set to the value of 'expires_in' property (token expiration in seconds.
bool esp_get_service_account_auth_token(char *input, size_t size, char **token,
int *expires);
} // namespace auth
} // namespace api_manager
} // namespace google
#endif // API_MANAGER_AUTH_LIB_AUTH_TOKEN_H_
| {
"content_hash": "316854fafcf6d5ded63684273f6f5504",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 79,
"avg_line_length": 31.41176470588235,
"alnum_prop": 0.6825842696629213,
"repo_name": "FirebasePrivate/proxy",
"id": "f17358d96b8bfa99dacf9d1663a5e2d26964b46a",
"size": "1679",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "contrib/endpoints/src/api_manager/auth/lib/auth_token.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "12193"
},
{
"name": "C++",
"bytes": "990189"
},
{
"name": "Go",
"bytes": "1697"
},
{
"name": "Makefile",
"bytes": "57"
},
{
"name": "Protocol Buffer",
"bytes": "8714"
},
{
"name": "Python",
"bytes": "67348"
},
{
"name": "Shell",
"bytes": "4141"
}
],
"symlink_target": ""
} |
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
namespace osu.Game.Rulesets.RP.Objects.Interface
{
public interface IHasRotation
{
float Rotation { get; set; }
}
}
| {
"content_hash": "847aea9d84aa7e5e86d7ae6752e3cea7",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 102,
"avg_line_length": 30.8,
"alnum_prop": 0.6785714285714286,
"repo_name": "osu-RP/osu-RP",
"id": "d19acc38cc7a61ea7ad7c1d255fd07a9c9fb89a6",
"size": "310",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "osu.Game.Rulesets.RP/Objects/Interface/IHasRotation.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "2990525"
}
],
"symlink_target": ""
} |
"""Provides a simple private telegram bot example.
Provides an example telegram-bot using
ownbot's authentication decorators.
"""
from telegram.ext import Updater, CommandHandler
from ownbot.auth import requires_usergroup, assign_first_to
from ownbot.admincommands import AdminCommands
TOKEN = open("token.txt").read().strip()
# The first client who sends the '/start' command will be added
# to the admin group.
@assign_first_to("admin")
# If a user wants to execute the '/start' command he has to be
# a member of the 'group1'or the 'group2' group. Otherwise the
# decorator will not execute the handler function.
@requires_usergroup("group1", "group2")
def start_handler(bot, update):
"""Handles the command '/start'.
Sends a Hello World message to the client.
"""
bot.sendMessage(chat_id=update.message.chat_id, text="Hello World")
def main():
"""
Simple private telegram bot example.
"""
# Set up logging to log to stdout
import logging
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
updater = Updater(TOKEN)
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler("start", start_handler))
# Enable admin commands for this bot
AdminCommands(dispatcher)
updater.start_polling()
updater.idle()
if __name__ == "__main__":
main()
| {
"content_hash": "2bed426d2acd6ba5f18c3de1c42b180a",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 71,
"avg_line_length": 27.403846153846153,
"alnum_prop": 0.6877192982456141,
"repo_name": "michaelimfeld/ownbot",
"id": "b81a4874879a38d5b5a693bdf540f2ced02899e5",
"size": "1467",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/simple.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "48665"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.