text
stringlengths 2
1.04M
| meta
dict |
---|---|
package log;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.time.LocalDateTime;
public class log implements Runnable {
private char label;
private List<String> lines;
public log(char label, EventType eventType, LocalDateTime localDateTime, String votedata) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String ts = localDateTime.format(formatter);
this.label = label;
this.lines = new ArrayList<>();
switch (eventType) {
case WRITE_SUCCESS:
this.lines.add("" + ts + ": Write operation success.");
break;
case WRITE_REQUEST_SUCCESS:
this.lines.add("" + ts + ": Write request success.");
break;
case WRITE_FAIL_WITH_NACK:
this.lines.add("" + ts + ": Write operation failed, since some other site is updating.");
break;
case WRITE_FAIL_NO_DISTINGUISH:
this.lines.add("" + ts + ": Write operation failed, since node not in distinguished partition.");
break;
case WRITE_ABORT:
this.lines.add("" + ts + ": Write operation aborted by coordinate node.");
break;
}
lines.add("\t\t " + votedata);
}
public void run() {
try {
Files.write(Paths.get(label + ".log"), this.lines,
StandardOpenOption.APPEND, StandardOpenOption.CREATE);
} catch (IOException e) {
System.err.println("\nError when add event to log file: " + e.getMessage());
}
}
}
| {
"content_hash": "84c7772e94d69ea323507a9d8d99f022",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 113,
"avg_line_length": 33.94444444444444,
"alnum_prop": 0.5886524822695035,
"repo_name": "hanlin-he/UTD",
"id": "7a787e6482159be549bf39efa871c1ddd2ec9899",
"size": "1833",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CS6378/Project3/src/log/log.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "100244"
},
{
"name": "Java",
"bytes": "346352"
},
{
"name": "Makefile",
"bytes": "475"
},
{
"name": "PLSQL",
"bytes": "23956"
},
{
"name": "PLpgSQL",
"bytes": "1112"
},
{
"name": "Python",
"bytes": "74873"
},
{
"name": "R",
"bytes": "23864"
},
{
"name": "Scala",
"bytes": "4906"
},
{
"name": "Shell",
"bytes": "3623"
},
{
"name": "TeX",
"bytes": "637376"
}
],
"symlink_target": ""
} |
layout: page
title: "NCT01633866"
---
<ul>
{% assign result = site.data[page.title] %}
<p> Title: {{ result.official_title }} </p>
<p> Source: {{ result.source }} </p>
<p> ID: {{ result.id }} </p>
<p> URL: {{ result.required_header.url }} </p>
<p> Start: {{ result.start_date }} </p>
<p> Completion: {{ result.completion_date.value }} </p>
<p> Eligibility: Gender {{ result.eligibility.gender }} From {{ result.eligibility.minimum_age }} to {{ result.eligibility.maximum_age }}</p>
<p> Status: {{ result.overall_status }} </p>
{% for treatment in result.intervention %}
<p> Intervention: {{ treatment.intervention_name }} </p>
{% endfor %}
<p>{{ result.eligibility.study_pop.textblock }} </p>
<p>{{ result.detailed_description.textblock }} </p>
</ul>
| {
"content_hash": "633799af75b3f1cf4861245ae9a6eae1",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 145,
"avg_line_length": 43.1578947368421,
"alnum_prop": 0.5878048780487805,
"repo_name": "caskethopper/caskethopper.github.io",
"id": "e3f1667285b603e42ec8d466abe010b825b0d15c",
"size": "824",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "NCT01633866/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "60475"
},
{
"name": "HTML",
"bytes": "158634"
},
{
"name": "JavaScript",
"bytes": "66307"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Thu Mar 08 14:17:33 MST 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>RoleSupplier (BOM: * : All 2018.3.3 API)</title>
<meta name="date" content="2018-03-08">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="RoleSupplier (BOM: * : All 2018.3.3 API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":6};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/RoleSupplier.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2018.3.3</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/RoleConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/RuntimeQueue.html" title="class in org.wildfly.swarm.config.messaging.activemq.server"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/messaging/activemq/server/RoleSupplier.html" target="_top">Frames</a></li>
<li><a href="RoleSupplier.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.wildfly.swarm.config.messaging.activemq.server</div>
<h2 title="Interface RoleSupplier" class="title">Interface RoleSupplier<T extends <a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/Role.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">Role</a>></h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Functional Interface:</dt>
<dd>This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.</dd>
</dl>
<hr>
<br>
<pre><a href="http://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html?is-external=true" title="class or interface in java.lang">@FunctionalInterface</a>
public interface <span class="typeNameLabel">RoleSupplier<T extends <a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/Role.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">Role</a>></span></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/Role.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">Role</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/RoleSupplier.html#get--">get</a></span>()</code>
<div class="block">Constructed instance of Role resource</div>
</td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="get--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>get</h4>
<pre><a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/Role.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">Role</a> get()</pre>
<div class="block">Constructed instance of Role resource</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The instance</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/RoleSupplier.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2018.3.3</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/RoleConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/RuntimeQueue.html" title="class in org.wildfly.swarm.config.messaging.activemq.server"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/messaging/activemq/server/RoleSupplier.html" target="_top">Frames</a></li>
<li><a href="RoleSupplier.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2018 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "af97dbff4e04450da4dfbad85551a59a",
"timestamp": "",
"source": "github",
"line_count": 237,
"max_line_length": 391,
"avg_line_length": 40.26160337552743,
"alnum_prop": 0.6344581848669042,
"repo_name": "wildfly-swarm/wildfly-swarm-javadocs",
"id": "2e5263fe2a6c5452464b231af271a89c55df96c5",
"size": "9542",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "2018.3.3/apidocs/org/wildfly/swarm/config/messaging/activemq/server/RoleSupplier.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
---
layout: default
---
<div class="post">
<h1 class="post-title">{{ page.title }}</h1>
<span class="post-date">{{ page.date | date_to_string }}</span>
{{ content }}
</div>
<div class="related">
<h2>Related Posts</h2>
<ul class="related-posts">
{% for post in site.related_posts limit:3 %}
<li>
<h3>
<a href="{{ post.url }}">
{{ post.title }}
<small>{{ post.date | date_to_string }}</small>
</a>
</h3>
</li>
{% endfor %}
</ul>
</div>
<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 = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
*/
var disqus_shortname = 'lucasdeabreugithubio';
var disqus_identifier = "{{ page.url }}";
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = '//lucasdeabreugithubio.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" rel="nofollow">comments powered by Disqus.</a></noscript>
| {
"content_hash": "59ddad2b55a3fd0649eefe858fc30991",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 147,
"avg_line_length": 30.618181818181817,
"alnum_prop": 0.5932304038004751,
"repo_name": "lucasdeabreu/lucasdeabreu.github.io",
"id": "5b75fb710b5e3e4b7469cd41ff751bd487afcfdf",
"size": "1684",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_layouts/post.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "20352"
},
{
"name": "HTML",
"bytes": "6375"
}
],
"symlink_target": ""
} |
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
Bundler.require(*Rails.groups)
require "devise_security_questions"
module RailsApp
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
end
end
| {
"content_hash": "b64578add5a8e312b8f802616a804d37",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 99,
"avg_line_length": 38.5,
"alnum_prop": 0.7272727272727273,
"repo_name": "apcomplete/devise_security_questions",
"id": "bc1f0136ebb4f8d5e1b69ac55ccdc72095d061ff",
"size": "1078",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "spec/rails_app/config/application.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "546"
},
{
"name": "JavaScript",
"bytes": "599"
},
{
"name": "Ruby",
"bytes": "39376"
}
],
"symlink_target": ""
} |
<?php defined('SYSPATH') or die('No direct script access.');
class YouTube_Playlist_Video_Data extends YouTube_Data {
protected $_playlist_id;
protected $_meta;
public function __construct($id, $order_by = 'published')
{
$this->_playlist_id = $id;
$this->_url = YouTube::API_URL.'playlists/'.$id.'?v=2&alt=jsonc&orderby='.$order_by;
$this->_result_type = YouTube::VIDEO_RESULT;
parent::__construct($id);
}
public function __sleep()
{
return Arr::merge(array('_playlist_id', '_meta'), parent::__sleep());
}
protected function _initialize()
{
$data = parent::_initialize();
$this->_meta = array(
'id' => $data->id,
'title' => $data->title,
'description' => $data->description
);
return $data;
}
} | {
"content_hash": "e954389f94ebfcddab0728fb72994d8f",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 92,
"avg_line_length": 25.324324324324323,
"alnum_prop": 0.49413020277481323,
"repo_name": "senj-gold/plantator.hol.es",
"id": "862f725c8a7cd4f68b3a80d51dcb87d975d641b3",
"size": "937",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/youtube/classes/youtube/playlist/video/data.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "48309"
},
{
"name": "CSS",
"bytes": "1615859"
},
{
"name": "Go",
"bytes": "7075"
},
{
"name": "JavaScript",
"bytes": "9686425"
},
{
"name": "PHP",
"bytes": "2220420"
},
{
"name": "Python",
"bytes": "5844"
},
{
"name": "Shell",
"bytes": "3678"
}
],
"symlink_target": ""
} |
configure_file("${PROJECT_SOURCE_DIR}/luavm/luavm.lua" "${CMAKE_INSTALL_PREFIX}/luavm/luavm.lua")
install(FILES "${PROJECT_SOURCE_DIR}/luavm/luavm.cmd" DESTINATION "${CMAKE_INSTALL_PREFIX}/luavm")
| {
"content_hash": "a04f469875ccb9c3aacb5702c51179fe",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 98,
"avg_line_length": 98.5,
"alnum_prop": 0.751269035532995,
"repo_name": "xpol/luainstaller",
"id": "e3c4e0af108485f148a2facb1bff05cea7ede34c",
"size": "197",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "cmake/luavm.cmake",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "76369"
},
{
"name": "C",
"bytes": "5922481"
},
{
"name": "C++",
"bytes": "108595"
},
{
"name": "CMake",
"bytes": "12713"
},
{
"name": "CSS",
"bytes": "22682"
},
{
"name": "Groff",
"bytes": "22398"
},
{
"name": "HTML",
"bytes": "1488369"
},
{
"name": "Inno Setup",
"bytes": "2886"
},
{
"name": "Lua",
"bytes": "1281258"
},
{
"name": "Makefile",
"bytes": "91637"
},
{
"name": "Shell",
"bytes": "30315"
},
{
"name": "Terra",
"bytes": "481"
}
],
"symlink_target": ""
} |
import React from 'react'
import Markdown from '../../../components/Markdown'
const TOC = () => (
<Markdown
source='
# TOC
- Details
- Intro
- Legend
- Verbatim Transcript + Notes
'
/>
)
export default TOC
| {
"content_hash": "b42cb07341cbd25b062bd3b41ba6b1b4",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 51,
"avg_line_length": 12.764705882352942,
"alnum_prop": 0.6359447004608295,
"repo_name": "goldylucks/adamgoldman.me",
"id": "42c29e83350474cdd7bb6452551743e770d2291d",
"size": "217",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/routes/blogPost/components/TOC.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "25457"
},
{
"name": "Dockerfile",
"bytes": "331"
},
{
"name": "JavaScript",
"bytes": "1212895"
},
{
"name": "Shell",
"bytes": "452"
}
],
"symlink_target": ""
} |
/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, $, brackets */
/** Simple extension that adds a "File > Hello World" menu item. Inserts "Hello, world!" at cursor pos. */
define(function(require, exports, module) {
"use strict";
var CommandManager = brackets.getModule("command/CommandManager"),
EditorManager = brackets.getModule("editor/EditorManager"),
Menus = brackets.getModule("command/Menus");
var windowsCommand = {
key: 'Opt-Cmd-B',
platform: 'win'
};
var macCommand = {
key: 'Opt-Cmd-B',
platform: 'mac'
};
var command = [windowsCommand, macCommand];
// Function to run when the menu item is clicked
function handleJSBeautify() {
var editor = EditorManager.getFocusedEditor();
if (editor) {
var insertionPos = editor.getCursorPos();
editor.document.replaceRange("Hello, world!", insertionPos);
}
}
// First, register a command - a UI-less object associating an id to a handler
var COMMAND_ID = "donwalling.jsbeautify"; // package-style naming to avoid collisions
CommandManager.register("Run JSBeautify", COMMAND_ID, handleJSBeautify);
// Then create a menu item bound to the command
// The label of the menu item is the name we gave the command (see above)
var menu = Menus.getMenu(Menus.AppMenuBar.EDIT_MENU);
//var menu = Menus.getMenu(Menus.AppMenuBar.FILE_MENU);Hello, world!
menu.addMenuDivider();
menu.addMenuItem(COMMAND_ID, command);
});
| {
"content_hash": "f6e301e50ad31d32d3be59ada24687e9",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 106,
"avg_line_length": 38.23809523809524,
"alnum_prop": 0.6581569115815691,
"repo_name": "donwalling/brackets-jsbeautify",
"id": "a04847a8c4779c39135357aa3bf3bb9991ec2b0d",
"size": "1606",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "main.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "1606"
}
],
"symlink_target": ""
} |
class StatsPolicy < ApplicationPolicy
end
| {
"content_hash": "44949a48670dbab02789106bdbd5a579",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 37,
"avg_line_length": 21,
"alnum_prop": 0.8571428571428571,
"repo_name": "thoughtbot/administrate",
"id": "76e9342b812bae20137bfc39b715c7cd53c54768",
"size": "42",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "spec/example_app/app/policies/stats_policy.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "686"
},
{
"name": "HTML",
"bytes": "59733"
},
{
"name": "JavaScript",
"bytes": "1719"
},
{
"name": "Procfile",
"bytes": "57"
},
{
"name": "Ruby",
"bytes": "344059"
},
{
"name": "SCSS",
"bytes": "21308"
},
{
"name": "Shell",
"bytes": "2200"
}
],
"symlink_target": ""
} |
package org.apache.geode.internal.cache.partitioned;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.Logger;
import org.apache.geode.cache.CacheClosedException;
import org.apache.geode.cache.CacheException;
import org.apache.geode.cache.execute.Function;
import org.apache.geode.cache.execute.FunctionException;
import org.apache.geode.cache.execute.FunctionInvocationTargetException;
import org.apache.geode.cache.execute.ResultCollector;
import org.apache.geode.distributed.DistributedMember;
import org.apache.geode.distributed.internal.DistributionManager;
import org.apache.geode.distributed.internal.DistributionMessage;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.distributed.internal.ReplyException;
import org.apache.geode.distributed.internal.ReplyProcessor21;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.cache.ForceReattemptException;
import org.apache.geode.internal.cache.PartitionedRegion;
import org.apache.geode.internal.cache.execute.AbstractExecution;
import org.apache.geode.internal.cache.execute.BucketMovedException;
import org.apache.geode.internal.cache.execute.CachedResultCollector;
import org.apache.geode.internal.cache.execute.FunctionStreamingResultCollector;
import org.apache.geode.internal.cache.execute.InternalFunctionException;
import org.apache.geode.internal.cache.execute.InternalFunctionInvocationTargetException;
import org.apache.geode.internal.cache.execute.LocalResultCollectorImpl;
import org.apache.geode.internal.cache.execute.PartitionedRegionFunctionExecutor;
import org.apache.geode.internal.cache.execute.PartitionedRegionFunctionResultWaiter;
import org.apache.geode.internal.cache.execute.ResultCollectorHolder;
import org.apache.geode.logging.internal.log4j.api.LogService;
public class PRFunctionStreamingResultCollector extends FunctionStreamingResultCollector
implements CachedResultCollector {
private static final Logger logger = LogService.getLogger();
private boolean hasResult = false;
private final PartitionedRegionFunctionResultWaiter waiter;
private final ResultCollectorHolder rcHolder;
/**
* Contract of {@link ReplyProcessor21#stillWaiting()} is that it never returns true after
* returning false.
*/
public PRFunctionStreamingResultCollector(
PartitionedRegionFunctionResultWaiter partitionedRegionFunctionResultWaiter,
InternalDistributedSystem system, Set<InternalDistributedMember> members, ResultCollector rc,
Function functionObject, PartitionedRegion pr, AbstractExecution execution) {
super(partitionedRegionFunctionResultWaiter, system, members, rc, functionObject, execution);
this.waiter = partitionedRegionFunctionResultWaiter;
this.hasResult = functionObject.hasResult();
rcHolder = new ResultCollectorHolder(this);
}
@Override
public void addResult(DistributedMember memId, Object resultOfSingleExecution) {
if (!this.endResultReceived) {
if (!(this.userRC instanceof LocalResultCollectorImpl)
&& resultOfSingleExecution instanceof InternalFunctionException) {
resultOfSingleExecution = ((InternalFunctionException) resultOfSingleExecution).getCause();
}
this.userRC.addResult(memId, resultOfSingleExecution);
}
}
@Override
public Object getResult() throws FunctionException {
return rcHolder.getResult();
}
@Override
public Object getResultInternal() throws FunctionException {
if (this.resultCollected) {
throw new FunctionException("Result already collected");
}
this.resultCollected = true;
if (this.hasResult) {
try {
this.waitForCacheOrFunctionException(0);
if (!this.execution.getFailedNodes().isEmpty() && !this.execution.isClientServerMode()) {
// end the rc and clear it
endResults();
clearResults();
this.execution = this.execution.setIsReExecute();
ResultCollector newRc = null;
if (execution.isFnSerializationReqd()) {
newRc = this.execution.execute(this.fn);
} else {
newRc = this.execution.execute(this.fn.getId());
}
return newRc.getResult();
}
if (!this.execution.getWaitOnExceptionFlag() && this.fites.size() > 0) {
throw new FunctionException(this.fites.get(0));
}
} catch (FunctionInvocationTargetException fite) {
// this is case of WrapperException which enforce the re execution of
// the function.
if (!execution.getWaitOnExceptionFlag()) {
if (!this.fn.isHA()) {
throw new FunctionException(fite);
} else if (execution.isClientServerMode()) {
clearResults();
FunctionInvocationTargetException iFITE = new InternalFunctionInvocationTargetException(
fite.getMessage(), this.execution.getFailedNodes());
throw new FunctionException(iFITE);
} else {
clearResults();
this.execution = this.execution.setIsReExecute();
ResultCollector newRc = null;
if (execution.isFnSerializationReqd()) {
newRc = this.execution.execute(this.fn);
} else {
newRc = this.execution.execute(this.fn.getId());
}
return newRc.getResult();
}
}
} catch (BucketMovedException e) {
if (!execution.getWaitOnExceptionFlag()) {
if (!this.fn.isHA()) {
// endResults();
FunctionInvocationTargetException fite =
new FunctionInvocationTargetException(e.getMessage());
throw new FunctionException(fite);
} else if (execution.isClientServerMode()) {
// endResults();
clearResults();
FunctionInvocationTargetException fite =
new InternalFunctionInvocationTargetException(e.getMessage());
throw new FunctionException(fite);
} else {
// endResults();
clearResults();
this.execution = this.execution.setIsReExecute();
ResultCollector newRc = null;
if (execution.isFnSerializationReqd()) {
newRc = this.execution.execute(this.fn);
} else {
newRc = this.execution.execute(this.fn.getId());
}
return newRc.getResult();
}
}
} catch (CacheClosedException e) {
if (!execution.getWaitOnExceptionFlag()) {
if (!this.fn.isHA()) {
// endResults();
FunctionInvocationTargetException fite =
new FunctionInvocationTargetException(e.getMessage());
throw new FunctionException(fite);
} else if (execution.isClientServerMode()) {
// endResults();
clearResults();
FunctionInvocationTargetException fite = new InternalFunctionInvocationTargetException(
e.getMessage(), this.execution.getFailedNodes());
throw new FunctionException(fite);
} else {
// endResults();
clearResults();
this.execution = this.execution.setIsReExecute();
ResultCollector newRc = null;
if (execution.isFnSerializationReqd()) {
newRc = this.execution.execute(this.fn);
} else {
newRc = this.execution.execute(this.fn.getId());
}
return newRc.getResult();
}
}
} catch (CacheException e) {
// endResults();
throw new FunctionException(e);
} catch (ForceReattemptException e) {
// this is case of WrapperException which enforce the re execution of
// the function.
if (!this.fn.isHA()) {
throw new FunctionException(e);
} else if (execution.isClientServerMode()) {
clearResults();
FunctionInvocationTargetException iFITE = new InternalFunctionInvocationTargetException(
e.getMessage(), this.execution.getFailedNodes());
throw new FunctionException(iFITE);
} else {
clearResults();
this.execution = this.execution.setIsReExecute();
ResultCollector newRc = null;
if (execution.isFnSerializationReqd()) {
newRc = this.execution.execute(this.fn);
} else {
newRc = this.execution.execute(this.fn.getId());
}
return newRc.getResult();
}
}
}
return this.userRC.getResult();
}
@Override
public Object getResult(long timeout, TimeUnit unit)
throws FunctionException, InterruptedException {
return rcHolder.getResult(timeout, unit);
}
@Override
public Object getResultInternal(long timeout, TimeUnit unit)
throws FunctionException, InterruptedException {
long timeoutInMillis = unit.toMillis(timeout);
if (this.resultCollected) {
throw new FunctionException("Result already collected");
}
this.resultCollected = true;
if (this.hasResult) {
try {
long timeBefore = System.currentTimeMillis();
if (!this.waitForCacheOrFunctionException(timeoutInMillis)) {
throw new FunctionException("All results not received in time provided.");
}
long timeAfter = System.currentTimeMillis();
timeoutInMillis = timeoutInMillis - (timeAfter - timeBefore);
if (timeoutInMillis < 0) {
timeoutInMillis = 0;
}
if (!this.execution.getFailedNodes().isEmpty() && !this.execution.isClientServerMode()) {
// end the rc and clear it
endResults();
clearResults();
this.execution = this.execution.setIsReExecute();
ResultCollector newRc = null;
if (execution.isFnSerializationReqd()) {
newRc = this.execution.execute(this.fn);
} else {
newRc = this.execution.execute(this.fn.getId());
}
return newRc.getResult(timeoutInMillis, unit);
}
if (!this.execution.getWaitOnExceptionFlag() && this.fites.size() > 0) {
throw new FunctionException(this.fites.get(0));
}
} catch (FunctionInvocationTargetException fite) {
if (!this.fn.isHA()) {
throw new FunctionException(fite);
} else if (execution.isClientServerMode()) {
clearResults();
FunctionInvocationTargetException fe = new InternalFunctionInvocationTargetException(
fite.getMessage(), this.execution.getFailedNodes());
throw new FunctionException(fe);
} else {
clearResults();
this.execution = this.execution.setIsReExecute();
ResultCollector newRc = null;
if (execution.isFnSerializationReqd()) {
newRc = this.execution.execute(this.fn);
} else {
newRc = this.execution.execute(this.fn.getId());
}
return newRc.getResult(timeoutInMillis, unit);
}
} catch (BucketMovedException e) {
if (!this.fn.isHA()) {
// endResults();
FunctionInvocationTargetException fite =
new FunctionInvocationTargetException(e.getMessage());
throw new FunctionException(fite);
} else if (execution.isClientServerMode()) {
// endResults();
clearResults();
FunctionInvocationTargetException fite =
new FunctionInvocationTargetException(e.getMessage());
throw new FunctionException(fite);
} else {
// endResults();
clearResults();
this.execution = this.execution.setIsReExecute();
ResultCollector newRc = null;
if (execution.isFnSerializationReqd()) {
newRc = this.execution.execute(this.fn);
} else {
newRc = this.execution.execute(this.fn.getId());
}
return newRc.getResult(timeoutInMillis, unit);
}
} catch (CacheClosedException e) {
if (!this.fn.isHA()) {
// endResults();
FunctionInvocationTargetException fite =
new FunctionInvocationTargetException(e.getMessage());
throw new FunctionException(fite);
} else if (execution.isClientServerMode()) {
// endResults();
clearResults();
FunctionInvocationTargetException fite = new InternalFunctionInvocationTargetException(
e.getMessage(), this.execution.getFailedNodes());
throw new FunctionException(fite);
} else {
// endResults();
clearResults();
this.execution = this.execution.setIsReExecute();
ResultCollector newRc = null;
if (execution.isFnSerializationReqd()) {
newRc = this.execution.execute(this.fn);
} else {
newRc = this.execution.execute(this.fn.getId());
}
return newRc.getResult(timeoutInMillis, unit);
}
} catch (CacheException e) {
// endResults();
throw new FunctionException(e);
} catch (ForceReattemptException e) {
// this is case of WrapperException which enforce the re execution of
// the function.
if (!this.fn.isHA()) {
throw new FunctionException(e);
} else if (execution.isClientServerMode()) {
clearResults();
FunctionInvocationTargetException iFITE = new InternalFunctionInvocationTargetException(
e.getMessage(), this.execution.getFailedNodes());
throw new FunctionException(iFITE);
} else {
clearResults();
this.execution = this.execution.setIsReExecute();
ResultCollector newRc = null;
if (execution.isFnSerializationReqd()) {
newRc = this.execution.execute(this.fn);
} else {
newRc = this.execution.execute(this.fn.getId());
}
return newRc.getResult();
}
}
}
return this.userRC.getResult(timeoutInMillis, unit); // As we have already waited for timeout
// earlier we expect results to be ready
}
@Override
public void memberDeparted(DistributionManager distributionManager,
final InternalDistributedMember id, final boolean crashed) {
FunctionInvocationTargetException fite;
if (id != null) {
synchronized (this.members) {
if (removeMember(id, true)) {
if (!this.fn.isHA()) {
fite = new FunctionInvocationTargetException(
String.format("memberDeparted event for < %s > crashed, %s",
new Object[] {id, Boolean.valueOf(crashed)}),
id);
} else {
fite = new InternalFunctionInvocationTargetException(
String.format("memberDeparted event for < %s > crashed, %s",
new Object[] {id, Boolean.valueOf(crashed)}),
id);
this.execution.addFailedNode(id.getId());
}
this.fites.add(fite);
}
checkIfDone();
}
} else {
Exception e = new Exception(
"memberDeparted got null memberId");
logger.info(String.format("memberDeparted got null memberId crashed=%s",
Boolean.valueOf(crashed)),
e);
}
}
@Override
protected synchronized void processException(DistributionMessage msg, ReplyException ex) {
logger.debug(
"StreamingPartitionResponseWithResultCollector received exception {} from member {}",
ex.getCause(), msg.getSender());
// we have already forwarded the exception, no need to keep it here
if (execution.isForwardExceptions() || execution.getWaitOnExceptionFlag()) {
return;
}
/*
* Below two cases should also be handled and not thrown exception Saving the exception
* ForeceReattempt can also be added here? Also, if multipel nodes throw exception, one may
* override another TODO: Wrap exception among each other or create a list of exceptions like
* this.fite.
*/
if (ex.getCause() instanceof CacheClosedException) {
((PartitionedRegionFunctionExecutor) this.execution).addFailedNode(msg.getSender().getId());
this.exception = ex;
} else if (ex.getCause() instanceof BucketMovedException) {
this.exception = ex;
} else if (!execution.getWaitOnExceptionFlag()) {
this.exception = ex;
}
}
}
| {
"content_hash": "4114fc8adddaa70ee82cb3944975eb37",
"timestamp": "",
"source": "github",
"line_count": 408,
"max_line_length": 100,
"avg_line_length": 40.745098039215684,
"alnum_prop": 0.6445500481231954,
"repo_name": "davinash/geode",
"id": "ca09a2d7117b0e3e8686b1109ca7e6110e3356cd",
"size": "17413",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "geode-core/src/main/java/org/apache/geode/internal/cache/partitioned/PRFunctionStreamingResultCollector.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "106707"
},
{
"name": "Go",
"bytes": "1205"
},
{
"name": "Groovy",
"bytes": "2783"
},
{
"name": "HTML",
"bytes": "3917327"
},
{
"name": "Java",
"bytes": "28126965"
},
{
"name": "JavaScript",
"bytes": "1781013"
},
{
"name": "Python",
"bytes": "5014"
},
{
"name": "Ruby",
"bytes": "6686"
},
{
"name": "Shell",
"bytes": "46841"
}
],
"symlink_target": ""
} |
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " applehelp to make an Apple Help Book"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " epub3 to make an epub3"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
@echo " coverage to run coverage check of the documentation (if enabled)"
@echo " dummy to check syntax errors of document sources"
.PHONY: clean
clean:
rm -rf $(BUILDDIR)/*
.PHONY: html
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
.PHONY: dirhtml
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
.PHONY: singlehtml
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
.PHONY: pickle
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
.PHONY: json
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
.PHONY: htmlhelp
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
.PHONY: qthelp
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/VMInspect.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/VMInspect.qhc"
.PHONY: applehelp
applehelp:
$(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp
@echo
@echo "Build finished. The help book is in $(BUILDDIR)/applehelp."
@echo "N.B. You won't be able to view it unless you put it in" \
"~/Library/Documentation/Help or install it in your application" \
"bundle."
.PHONY: devhelp
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/VMInspect"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/VMInspect"
@echo "# devhelp"
.PHONY: epub
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
.PHONY: epub3
epub3:
$(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3
@echo
@echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3."
.PHONY: latex
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
.PHONY: latexpdf
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
.PHONY: latexpdfja
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
.PHONY: text
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
.PHONY: man
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
.PHONY: texinfo
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
.PHONY: info
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
.PHONY: gettext
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
.PHONY: changes
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
.PHONY: linkcheck
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
.PHONY: doctest
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
.PHONY: coverage
coverage:
$(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage
@echo "Testing of coverage in the sources finished, look at the " \
"results in $(BUILDDIR)/coverage/python.txt."
.PHONY: xml
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
.PHONY: pseudoxml
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
.PHONY: dummy
dummy:
$(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy
@echo
@echo "Build finished. Dummy builder generates no files."
| {
"content_hash": "4cacc18f626cfa5d1a3534a4dca9d863",
"timestamp": "",
"source": "github",
"line_count": 221,
"max_line_length": 84,
"avg_line_length": 34.05429864253394,
"alnum_prop": 0.7022322614934893,
"repo_name": "noxdafox/vminspect",
"id": "e9c94240b980bd01334e74b1172657ec1ca485a0",
"size": "7618",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/Makefile",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "83757"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.github.sdaclin.jpok</groupId>
<artifactId>jpok</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>business</module>
<module>model</module>
<module>analyzer</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.source.version>1.7</project.source.version>
<project.target.version>1.7</project.target.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.github.sdaclin.jpok</groupId>
<artifactId>model</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>io.github.sdaclin.jpok</groupId>
<artifactId>analyzer</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.5</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${project.source.version}</source>
<target>${project.target.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project> | {
"content_hash": "999c89a9aaf9bb14e03e609b6993e5ed",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 108,
"avg_line_length": 34.36231884057971,
"alnum_prop": 0.5525094896668072,
"repo_name": "sdaclin/jPok",
"id": "25208a72872b9565419fe1d2df99d898f61911b2",
"size": "2371",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pom.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "63801"
}
],
"symlink_target": ""
} |
struct symrec;
//struct darray_symrec;
// "declaration" of hashtable and darray types
KHASH_MAP_INIT_INT(id, struct symrec*)
DARRAY_DEFINE(symrec, struct symrec*)
typedef enum { CONST, VAR, PROCEDURE, PARAM, PARAMLIST } species;
typedef struct symrec
{
species spec;
size_t id; // 2ndary token
int type; // Among T_BOOLEAN, T_INTEGER, T_REAL. Bite me.
YYSTYPE value; // This is never going to be a symrec
struct darray_symrec* parameter_list; // Dynamic array of function parameters.
char* code; // Mostly used to handle the pushing of expressions onto the stack;
int reg;
int bp_off;
} symrec;
symrec*
darray_find_id(darray_symrec* arr,
int id);
// END OF DARRAY FUNCTIONS
// This struct is basically a backwards linked list of hashtables. I thought of
// making a hashtable of hashtables, but decided this way was easier to work with
// and only marginally less performing since access is always from first to last.
typedef struct symbol_stack
{
khash_t(id)* kh_table_top;
struct symbol_stack* previous;
} symbol_stack;
void
print_symrec(symrec* s);
void
print_table();
symrec*
copy_symrec(symrec*);
void
add_to_scope(symrec*);
void
initialize_stack();
void
create_scope();
void
delete_scope();
symrec*
search_in_current_scope(int id);
symrec*
search_in_any_scope(int id);
symrec*
const_declare(int id,
YYSTYPE value,
int type);
symrec*
var_declare(int id,
int type);
symrec*
proc_declare(int id);
#endif
| {
"content_hash": "f4e10bfad2b9f7978ec3526d1fcc7af5",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 83,
"avg_line_length": 19.935064935064936,
"alnum_prop": 0.6866449511400652,
"repo_name": "rgeminas/gp--",
"id": "6895075add6f1daaa38fe03ed03487a9c8a45a19",
"size": "1681",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/scope/symrec.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "88040"
},
{
"name": "C++",
"bytes": "723"
},
{
"name": "Objective-C",
"bytes": "1631"
}
],
"symlink_target": ""
} |
package com.atlassian.sourcemap;
import java.io.IOException;
/**
* We encode our variable length numbers as base64 encoded strings with
* the least significant digit coming first. Each base64 digit encodes
* a 5-bit value (0-31) and a continuation bit. Signed values can be
* represented by using the least significant bit of the value as the
* sign bit.
*
* Code based on Google Closure Compiler https://code.google.com/p/closure-compiler
*/
class Base64VLQ {
// Utility class.
private Base64VLQ() {}
// A Base64 VLQ digit can represent 5 bits, so it is base-32.
private static final int VLQ_BASE_SHIFT = 5;
private static final int VLQ_BASE = 1 << VLQ_BASE_SHIFT;
// A mask of bits for a VLQ digit (11111), 31 decimal.
private static final int VLQ_BASE_MASK = VLQ_BASE-1;
// The continuation bit is the 6th bit.
private static final int VLQ_CONTINUATION_BIT = VLQ_BASE;
/**
* Converts from a two-complement value to a value where the sign bit is
* is placed in the least significant bit. For example, as decimals:
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
*/
private static int toVLQSigned(int value) {
return (value < 0) ? (((-value) << 1) + 1) : ((value << 1) + 0);
}
/**
* Converts to a two-complement value from a value where the sign bit is
* is placed in the least significant bit. For example, as decimals:
* 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
* 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
*/
private static int fromVLQSigned(int value) {
boolean negate = (value & 1) == 1;
value = value >> 1;
return negate ? -value : value;
}
/**
* Writes a VLQ encoded value to the provide appendable.
* @throws IOException
*/
public static void encode(Appendable out, int value) throws IOException {
value = toVLQSigned(value);
do {
int digit = value & VLQ_BASE_MASK;
value >>>= VLQ_BASE_SHIFT;
if (value > 0) digit |= VLQ_CONTINUATION_BIT;
out.append(Base64.toBase64(digit));
} while (value > 0);
}
/**
* A simple interface for advancing through a sequence of characters, that
* communicates that advance back to the source.
*/
interface CharIterator {
boolean hasNext();
char next();
}
/**
* Decodes the next VLQValue from the provided CharIterator.
*/
public static int decode(CharIterator in) {
int result = 0;
boolean continuation;
int shift = 0;
do {
char c = in.next();
int digit = Base64.fromBase64(c);
continuation = (digit & VLQ_CONTINUATION_BIT) != 0;
digit &= VLQ_BASE_MASK;
result = result + (digit << shift);
shift = shift + VLQ_BASE_SHIFT;
} while (continuation);
return fromVLQSigned(result);
}
}
| {
"content_hash": "4e08789f6e17240e91a3593ed603f6d1",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 83,
"avg_line_length": 33.54945054945055,
"alnum_prop": 0.6082541762201114,
"repo_name": "atlassian/sourcemap",
"id": "19b0f078e9b0c74c6ef6a8d56d3669e736180350",
"size": "3053",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/atlassian/sourcemap/Base64VLQ.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "59495"
}
],
"symlink_target": ""
} |
ST.namespace('ST.fieldDate.dayGrid');
ST.fieldDate.dayGrid.Layout = (function(){
var component = function(data)
{
this._data = data['object']['_data'];
this._object = data['object'];
this.isAdded = false;
this.dom = undefined;
};
component.prototype.commit = function()
{
this.createDOM();
this._data['wrapper'].innerHTML = '';
if(this.isAdded == false)
{
this._data['wrapper'].appendChild(this.dom.table);
this.isAdded = true;
};
};
component.prototype.createDOM = function()
{
this.dom = {};
this.dom.table = document.createElement('table');
this.dom.table.className = 'st-calendar-day-table';
var trH = document.createElement('tr');
this.dom.table.appendChild(trH);
var d = ['пн', 'вт', 'ср', 'чт', 'пт', 'cб','вс'];
for(var i = 0; i < d.length; i++)
{
var th = document.createElement('th');
th.className = 'st-calendar-day-th';
if(d[i] == 'cб' || d[i] == 'вс')
{
th.style.cssText = 'color: red;';
}
th.innerHTML = d[i];
trH.appendChild(th);
}
var dates = this._object.getDates();
var buildDate = this._object.getBuildDate();
var selDate = this._object.selectedDate;
var DATE_NOW = new Date(); //сегодняшняя дата
var style;
for(var i = 0; i < 6; i++)
{
var tr = document.createElement('tr');
this.dom.table.appendChild(tr);
for(var j = 0; j < 7; j++)
{
if(ST.fieldDate.compareDate(dates[i][j], DATE_NOW))
{
style='st-calendar-day-td st-calendar-day-tdToday';
if(ST.fieldDate.isWeekend(dates[i][j]))
style+= ' st-calendar-day-tdWeekend';
}
else if (ST.fieldDate.isPreviousOrNextMonth(dates[i][j], buildDate))
{
style='st-calendar-day-td st-calendar-day-tdprevNextMonth';
if(ST.fieldDate.isWeekend(dates[i][j]))
style+=' calendar-floating-tdWeekendNot';
}
else
{
style='st-calendar-day-td';
if(ST.fieldDate.isWeekend(dates[i][j]))
style+=' st-calendar-day-tdWeekend';
}
if (selDate!= undefined && ST.fieldDate.compareDate(dates[i][j], selDate))
{
style +=' st-calendar-floating-tdSelected';
}
// else if (ST.fieldDate.compareDate(dates[i][j], DATE_NOW))
// {
// style+=' st-calendar-day-tdNow';
// }
var self = this;
var td = document.createElement('td');
tr.appendChild(td);
var f = (function(){
var t = td;
return function() { self._object._data['handler']['click'].apply(self._object,[t.title]); }
})();
ST.addEventListener(td,'click',f);
td.className = style;
td.title = ST.fieldDate.getOutputDate(dates[i][j])+"."+ST.fieldDate.getOutputMonth(dates[i][j])+"."+dates[i][j].getFullYear()
td.innerHTML = dates[i][j].getDate();
}
}
this.table = this.dom.table;
};
component.prototype.reset = function()
{
if(ST.isUndefined(this.dom))
{
return;
};
if(this.isAdded == true)
{
this._data['wrapper'].removeChild(this.dom.table);
this.isAdded = false;
};
};
return component;
})(); | {
"content_hash": "7005d2d47f71a5f85525c75a92b32075",
"timestamp": "",
"source": "github",
"line_count": 141,
"max_line_length": 135,
"avg_line_length": 24.73049645390071,
"alnum_prop": 0.5202179523946086,
"repo_name": "abcd19/StorageUI",
"id": "bce40b9394733f5cb3e1ce38bf80919a6f71a828",
"size": "3518",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "st-field/st-fielddate/source/js/Calendar/DayGrid/Layout.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11928"
},
{
"name": "HTML",
"bytes": "68551"
},
{
"name": "JavaScript",
"bytes": "424393"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_24) on Tue May 01 09:56:12 CEST 2012 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class net.sourceforge.pmd.lang.rule.properties.MethodProperty (PMD 5.0.0 API)
</TITLE>
<META NAME="date" CONTENT="2012-05-01">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class net.sourceforge.pmd.lang.rule.properties.MethodProperty (PMD 5.0.0 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../net/sourceforge/pmd/lang/rule/properties/MethodProperty.html" title="class in net.sourceforge.pmd.lang.rule.properties"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?net/sourceforge/pmd/lang/rule/properties//class-useMethodProperty.html" target="_top"><B>FRAMES</B></A>
<A HREF="MethodProperty.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>net.sourceforge.pmd.lang.rule.properties.MethodProperty</B></H2>
</CENTER>
No usage of net.sourceforge.pmd.lang.rule.properties.MethodProperty
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../net/sourceforge/pmd/lang/rule/properties/MethodProperty.html" title="class in net.sourceforge.pmd.lang.rule.properties"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?net/sourceforge/pmd/lang/rule/properties//class-useMethodProperty.html" target="_top"><B>FRAMES</B></A>
<A HREF="MethodProperty.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2002-2012 <a href="http://pmd.sourceforge.net/">InfoEther</a>. All Rights Reserved.
</BODY>
</HTML>
| {
"content_hash": "1c0bd66cd2f43e0882ac9d1d39084867",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 258,
"avg_line_length": 43.97931034482759,
"alnum_prop": 0.6145522973184884,
"repo_name": "daejunpark/jsaf",
"id": "eaf1d6138ccb6225a0f9875973f86cde45175a57",
"size": "6377",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "third_party/pmd/docs/apidocs/net/sourceforge/pmd/lang/rule/properties/class-use/MethodProperty.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "379"
},
{
"name": "C",
"bytes": "59067"
},
{
"name": "C++",
"bytes": "13294"
},
{
"name": "CSS",
"bytes": "9351891"
},
{
"name": "Emacs Lisp",
"bytes": "9812"
},
{
"name": "HTML",
"bytes": "19106074"
},
{
"name": "Jasmin",
"bytes": "46"
},
{
"name": "Java",
"bytes": "375421"
},
{
"name": "JavaScript",
"bytes": "51177272"
},
{
"name": "Makefile",
"bytes": "3558"
},
{
"name": "Objective-C",
"bytes": "345276"
},
{
"name": "Objective-J",
"bytes": "4500028"
},
{
"name": "PHP",
"bytes": "12684"
},
{
"name": "Perl",
"bytes": "5278"
},
{
"name": "Python",
"bytes": "75059"
},
{
"name": "Ruby",
"bytes": "22932"
},
{
"name": "Scala",
"bytes": "5542753"
},
{
"name": "Shell",
"bytes": "91018"
},
{
"name": "VimL",
"bytes": "6985"
},
{
"name": "XML",
"bytes": "1288109"
}
],
"symlink_target": ""
} |
#ifndef BOOST_THREAD_FUTURE_HPP
#define BOOST_THREAD_FUTURE_HPP
#include <boost/thread/detail/config.hpp>
// boost::thread::future requires exception handling
// due to boost::exception::exception_ptr dependency
#ifndef BOOST_NO_EXCEPTIONS
#include <boost/core/scoped_enum.hpp>
#include <stdexcept>
#include <boost/thread/exceptional_ptr.hpp>
#include <boost/thread/detail/move.hpp>
#include <boost/thread/detail/invoker.hpp>
#include <boost/thread/thread_time.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/thread/lock_algorithms.hpp>
#include <boost/thread/lock_types.hpp>
#include <boost/exception_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/type_traits/is_fundamental.hpp>
#include <boost/thread/detail/is_convertible.hpp>
#include <boost/type_traits/decay.hpp>
#include <boost/type_traits/is_void.hpp>
#include <boost/type_traits/conditional.hpp>
#include <boost/config.hpp>
#include <boost/throw_exception.hpp>
#include <algorithm>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/core/ref.hpp>
#include <boost/scoped_array.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/core/enable_if.hpp>
#include <list>
#include <boost/next_prior.hpp>
#include <vector>
#include <boost/thread/future_error_code.hpp>
#ifdef BOOST_THREAD_USES_CHRONO
#include <boost/chrono/system_clocks.hpp>
#endif
#if defined BOOST_THREAD_PROVIDES_FUTURE_CTOR_ALLOCATORS
#include <boost/thread/detail/memory.hpp>
#include <boost/container/scoped_allocator.hpp>
#if ! defined BOOST_NO_CXX11_ALLOCATOR
#include <memory>
#endif
#endif
#include <boost/utility/result_of.hpp>
#include <boost/thread/thread_only.hpp>
#if defined BOOST_THREAD_PROVIDES_FUTURE_WHEN_ALL_WHEN_ANY
#include <boost/thread/csbl/tuple.hpp>
#include <boost/thread/csbl/vector.hpp>
#endif
#if defined BOOST_THREAD_PROVIDES_FUTURE
#define BOOST_THREAD_FUTURE future
#else
#define BOOST_THREAD_FUTURE unique_future
#endif
namespace boost
{
//enum class launch
BOOST_SCOPED_ENUM_DECLARE_BEGIN(launch)
{
none = 0,
async = 1,
deferred = 2,
#ifdef BOOST_THREAD_PROVIDES_EXECUTORS
executor = 4,
#endif
any = async | deferred
}
BOOST_SCOPED_ENUM_DECLARE_END(launch)
//enum class future_status
BOOST_SCOPED_ENUM_DECLARE_BEGIN(future_status)
{
ready,
timeout,
deferred
}
BOOST_SCOPED_ENUM_DECLARE_END(future_status)
class BOOST_SYMBOL_VISIBLE future_error
: public std::logic_error
{
system::error_code ec_;
public:
future_error(system::error_code ec)
: logic_error(ec.message()),
ec_(ec)
{
}
const system::error_code& code() const BOOST_NOEXCEPT
{
return ec_;
}
};
class BOOST_SYMBOL_VISIBLE future_uninitialized:
public future_error
{
public:
future_uninitialized() :
future_error(system::make_error_code(future_errc::no_state))
{}
};
class BOOST_SYMBOL_VISIBLE broken_promise:
public future_error
{
public:
broken_promise():
future_error(system::make_error_code(future_errc::broken_promise))
{}
};
class BOOST_SYMBOL_VISIBLE future_already_retrieved:
public future_error
{
public:
future_already_retrieved():
future_error(system::make_error_code(future_errc::future_already_retrieved))
{}
};
class BOOST_SYMBOL_VISIBLE promise_already_satisfied:
public future_error
{
public:
promise_already_satisfied():
future_error(system::make_error_code(future_errc::promise_already_satisfied))
{}
};
class BOOST_SYMBOL_VISIBLE task_already_started:
public future_error
{
public:
task_already_started():
future_error(system::make_error_code(future_errc::promise_already_satisfied))
{}
};
class BOOST_SYMBOL_VISIBLE task_moved:
public future_error
{
public:
task_moved():
future_error(system::make_error_code(future_errc::no_state))
{}
};
class promise_moved:
public future_error
{
public:
promise_moved():
future_error(system::make_error_code(future_errc::no_state))
{}
};
namespace future_state
{
enum state { uninitialized, waiting, ready, moved, deferred };
}
namespace detail
{
struct relocker
{
boost::unique_lock<boost::mutex>& lock_;
bool unlocked_;
relocker(boost::unique_lock<boost::mutex>& lk):
lock_(lk)
{
lock_.unlock();
unlocked_=true;
}
~relocker()
{
if (unlocked_) {
lock_.lock();
}
}
void lock() {
if (unlocked_) {
lock_.lock();
unlocked_=false;
}
}
private:
relocker& operator=(relocker const&);
};
struct shared_state_base : enable_shared_from_this<shared_state_base>
{
typedef std::list<boost::condition_variable_any*> waiter_list;
// This type should be only included conditionally if interruptions are allowed, but is included to maintain the same layout.
typedef shared_ptr<shared_state_base> continuation_ptr_type;
boost::exception_ptr exception;
bool done;
bool is_deferred_;
launch policy_;
bool is_constructed;
mutable boost::mutex mutex;
boost::condition_variable waiters;
waiter_list external_waiters;
boost::function<void()> callback;
// This declaration should be only included conditionally if interruptions are allowed, but is included to maintain the same layout.
bool thread_was_interrupted;
// This declaration should be only included conditionally, but is included to maintain the same layout.
continuation_ptr_type continuation_ptr;
// This declaration should be only included conditionally, but is included to maintain the same layout.
virtual void launch_continuation(boost::unique_lock<boost::mutex>&)
{
}
shared_state_base():
done(false),
is_deferred_(false),
policy_(launch::none),
is_constructed(false),
thread_was_interrupted(false),
continuation_ptr()
{}
virtual ~shared_state_base()
{}
void set_deferred()
{
is_deferred_ = true;
policy_ = launch::deferred;
}
void set_async()
{
is_deferred_ = false;
policy_ = launch::async;
}
#ifdef BOOST_THREAD_PROVIDES_EXECUTORS
void set_executor()
{
is_deferred_ = false;
policy_ = launch::executor;
}
#endif
waiter_list::iterator register_external_waiter(boost::condition_variable_any& cv)
{
boost::unique_lock<boost::mutex> lock(mutex);
do_callback(lock);
return external_waiters.insert(external_waiters.end(),&cv);
}
void remove_external_waiter(waiter_list::iterator it)
{
boost::lock_guard<boost::mutex> lock(mutex);
external_waiters.erase(it);
}
#if defined BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION
void do_continuation(boost::unique_lock<boost::mutex>& lock)
{
if (continuation_ptr) {
continuation_ptr_type this_continuation_ptr = continuation_ptr;
continuation_ptr.reset();
this_continuation_ptr->launch_continuation(lock);
//if (! lock.owns_lock())
// lock.lock();
}
}
#else
void do_continuation(boost::unique_lock<boost::mutex>&)
{
}
#endif
#if defined BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION
void set_continuation_ptr(continuation_ptr_type continuation, boost::unique_lock<boost::mutex>& lock)
{
continuation_ptr= continuation;
if (done) {
do_continuation(lock);
}
}
#endif
void mark_finished_internal(boost::unique_lock<boost::mutex>& lock)
{
done=true;
waiters.notify_all();
for(waiter_list::const_iterator it=external_waiters.begin(),
end=external_waiters.end();it!=end;++it)
{
(*it)->notify_all();
}
do_continuation(lock);
}
void make_ready()
{
boost::unique_lock<boost::mutex> lock(mutex);
mark_finished_internal(lock);
}
void do_callback(boost::unique_lock<boost::mutex>& lock)
{
if(callback && !done)
{
boost::function<void()> local_callback=callback;
relocker relock(lock);
local_callback();
}
}
void wait_internal(boost::unique_lock<boost::mutex> &lk, bool rethrow=true)
{
do_callback(lk);
//if (!done) // fixme why this doesn't work?
{
if (is_deferred_)
{
is_deferred_=false;
execute(lk);
//lk.unlock();
}
else
{
while(!done)
{
waiters.wait(lk);
}
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
if(rethrow && thread_was_interrupted)
{
throw boost::thread_interrupted();
}
#endif
if(rethrow && exception)
{
boost::rethrow_exception(exception);
}
}
}
}
virtual void wait(bool rethrow=true)
{
boost::unique_lock<boost::mutex> lock(mutex);
wait_internal(lock, rethrow);
}
#if defined BOOST_THREAD_USES_DATETIME
bool timed_wait_until(boost::system_time const& target_time)
{
boost::unique_lock<boost::mutex> lock(mutex);
if (is_deferred_)
return false;
do_callback(lock);
while(!done)
{
bool const success=waiters.timed_wait(lock,target_time);
if(!success && !done)
{
return false;
}
}
return true;
}
#endif
#ifdef BOOST_THREAD_USES_CHRONO
template <class Clock, class Duration>
future_status
wait_until(const chrono::time_point<Clock, Duration>& abs_time)
{
boost::unique_lock<boost::mutex> lock(mutex);
if (is_deferred_)
return future_status::deferred;
do_callback(lock);
while(!done)
{
cv_status const st=waiters.wait_until(lock,abs_time);
if(st==cv_status::timeout && !done)
{
return future_status::timeout;
}
}
return future_status::ready;
}
#endif
void mark_exceptional_finish_internal(boost::exception_ptr const& e, boost::unique_lock<boost::mutex>& lock)
{
exception=e;
mark_finished_internal(lock);
}
void mark_exceptional_finish()
{
boost::unique_lock<boost::mutex> lock(mutex);
mark_exceptional_finish_internal(boost::current_exception(), lock);
}
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
void mark_interrupted_finish()
{
boost::unique_lock<boost::mutex> lock(mutex);
thread_was_interrupted=true;
mark_finished_internal(lock);
}
void set_interrupted_at_thread_exit()
{
unique_lock<boost::mutex> lk(mutex);
thread_was_interrupted=true;
if (has_value(lk))
{
throw_exception(promise_already_satisfied());
}
detail::make_ready_at_thread_exit(shared_from_this());
}
#endif
void set_exception_at_thread_exit(exception_ptr e)
{
unique_lock<boost::mutex> lk(mutex);
if (has_value(lk))
{
throw_exception(promise_already_satisfied());
}
exception=e;
this->is_constructed = true;
detail::make_ready_at_thread_exit(shared_from_this());
}
bool has_value() const
{
boost::lock_guard<boost::mutex> lock(mutex);
return done && !(exception
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
|| thread_was_interrupted
#endif
);
}
bool has_value(unique_lock<boost::mutex>& ) const
{
return done && !(exception
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
|| thread_was_interrupted
#endif
);
}
bool has_exception() const
{
boost::lock_guard<boost::mutex> lock(mutex);
return done && (exception
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
|| thread_was_interrupted
#endif
);
}
bool has_exception(unique_lock<boost::mutex>&) const
{
return done && (exception
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
|| thread_was_interrupted
#endif
);
}
bool is_deferred(boost::lock_guard<boost::mutex>&) const {
return is_deferred_;
}
launch launch_policy(boost::unique_lock<boost::mutex>&) const
{
return policy_;
}
future_state::state get_state() const
{
boost::lock_guard<boost::mutex> guard(mutex);
if(!done)
{
return future_state::waiting;
}
else
{
return future_state::ready;
}
}
exception_ptr get_exception_ptr()
{
boost::unique_lock<boost::mutex> lock(mutex);
return get_exception_ptr(lock);
}
exception_ptr get_exception_ptr(boost::unique_lock<boost::mutex>& lock)
{
wait_internal(lock, false);
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
if(thread_was_interrupted)
{
return copy_exception(boost::thread_interrupted());
}
#endif
return exception;
}
template<typename F,typename U>
void set_wait_callback(F f,U* u)
{
boost::lock_guard<boost::mutex> lock(mutex);
callback=boost::bind(f,boost::ref(*u));
}
virtual void execute(boost::unique_lock<boost::mutex>&) {}
private:
shared_state_base(shared_state_base const&);
shared_state_base& operator=(shared_state_base const&);
};
template<typename T>
struct future_traits
{
typedef boost::scoped_ptr<T> storage_type;
struct dummy;
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
typedef T const& source_reference_type;
//typedef typename conditional<boost::is_fundamental<T>::value,dummy&,BOOST_THREAD_RV_REF(T)>::type rvalue_source_type;
typedef BOOST_THREAD_RV_REF(T) rvalue_source_type;
//typedef typename conditional<boost::is_fundamental<T>::value,T,BOOST_THREAD_RV_REF(T)>::type move_dest_type;
typedef T move_dest_type;
#elif defined BOOST_THREAD_USES_MOVE
typedef typename conditional<boost::is_fundamental<T>::value,T,T&>::type source_reference_type;
//typedef typename conditional<boost::is_fundamental<T>::value,T,BOOST_THREAD_RV_REF(T)>::type rvalue_source_type;
//typedef typename conditional<boost::enable_move_utility_emulation<T>::value,BOOST_THREAD_RV_REF(T),T>::type move_dest_type;
typedef BOOST_THREAD_RV_REF(T) rvalue_source_type;
typedef T move_dest_type;
#else
typedef T& source_reference_type;
typedef typename conditional<boost::thread_detail::is_convertible<T&,BOOST_THREAD_RV_REF(T) >::value, BOOST_THREAD_RV_REF(T),T const&>::type rvalue_source_type;
typedef typename conditional<boost::thread_detail::is_convertible<T&,BOOST_THREAD_RV_REF(T) >::value, BOOST_THREAD_RV_REF(T),T>::type move_dest_type;
#endif
typedef const T& shared_future_get_result_type;
static void init(storage_type& storage,source_reference_type t)
{
storage.reset(new T(t));
}
static void init(storage_type& storage,rvalue_source_type t)
{
#if ! defined BOOST_NO_CXX11_RVALUE_REFERENCES
storage.reset(new T(boost::forward<T>(t)));
#else
storage.reset(new T(static_cast<rvalue_source_type>(t)));
#endif
}
static void cleanup(storage_type& storage)
{
storage.reset();
}
};
template<typename T>
struct future_traits<T&>
{
typedef T* storage_type;
typedef T& source_reference_type;
//struct rvalue_source_type
//{};
typedef T& move_dest_type;
typedef T& shared_future_get_result_type;
static void init(storage_type& storage,T& t)
{
storage=&t;
}
static void cleanup(storage_type& storage)
{
storage=0;
}
};
template<>
struct future_traits<void>
{
typedef bool storage_type;
typedef void move_dest_type;
typedef void shared_future_get_result_type;
static void init(storage_type& storage)
{
storage=true;
}
static void cleanup(storage_type& storage)
{
storage=false;
}
};
// Used to create stand-alone futures
template<typename T>
struct shared_state:
detail::shared_state_base
{
typedef typename future_traits<T>::storage_type storage_type;
typedef typename future_traits<T>::source_reference_type source_reference_type;
typedef typename future_traits<T>::rvalue_source_type rvalue_source_type;
typedef typename future_traits<T>::move_dest_type move_dest_type;
typedef typename future_traits<T>::shared_future_get_result_type shared_future_get_result_type;
storage_type result;
shared_state():
result(0)
{}
~shared_state()
{}
void mark_finished_with_result_internal(source_reference_type result_, boost::unique_lock<boost::mutex>& lock)
{
future_traits<T>::init(result,result_);
this->mark_finished_internal(lock);
}
void mark_finished_with_result_internal(rvalue_source_type result_, boost::unique_lock<boost::mutex>& lock)
{
#if ! defined BOOST_NO_CXX11_RVALUE_REFERENCES
future_traits<T>::init(result,boost::forward<T>(result_));
#else
future_traits<T>::init(result,static_cast<rvalue_source_type>(result_));
#endif
this->mark_finished_internal(lock);
}
void mark_finished_with_result(source_reference_type result_)
{
boost::unique_lock<boost::mutex> lock(mutex);
this->mark_finished_with_result_internal(result_, lock);
}
void mark_finished_with_result(rvalue_source_type result_)
{
boost::unique_lock<boost::mutex> lock(mutex);
#if ! defined BOOST_NO_CXX11_RVALUE_REFERENCES
mark_finished_with_result_internal(boost::forward<T>(result_), lock);
#else
mark_finished_with_result_internal(static_cast<rvalue_source_type>(result_), lock);
#endif
}
virtual move_dest_type get()
{
boost::unique_lock<boost::mutex> lock(mutex);
wait_internal(lock);
return boost::move(*result);
}
virtual shared_future_get_result_type get_sh()
{
boost::unique_lock<boost::mutex> lock(mutex);
wait_internal(lock);
return *result;
}
//void set_value_at_thread_exit(const T & result_)
void set_value_at_thread_exit(source_reference_type result_)
{
unique_lock<boost::mutex> lk(this->mutex);
if (this->has_value(lk))
{
throw_exception(promise_already_satisfied());
}
//future_traits<T>::init(result,result_);
result.reset(new T(result_));
this->is_constructed = true;
detail::make_ready_at_thread_exit(shared_from_this());
}
//void set_value_at_thread_exit(BOOST_THREAD_RV_REF(T) result_)
void set_value_at_thread_exit(rvalue_source_type result_)
{
unique_lock<boost::mutex> lk(this->mutex);
if (this->has_value(lk))
throw_exception(promise_already_satisfied());
result.reset(new T(boost::move(result_)));
//future_traits<T>::init(result,static_cast<rvalue_source_type>(result_));
this->is_constructed = true;
detail::make_ready_at_thread_exit(shared_from_this());
}
private:
shared_state(shared_state const&);
shared_state& operator=(shared_state const&);
};
template<typename T>
struct shared_state<T&>:
detail::shared_state_base
{
typedef typename future_traits<T&>::storage_type storage_type;
typedef typename future_traits<T&>::source_reference_type source_reference_type;
typedef typename future_traits<T&>::move_dest_type move_dest_type;
typedef typename future_traits<T&>::shared_future_get_result_type shared_future_get_result_type;
T* result;
shared_state():
result(0)
{}
~shared_state()
{
}
void mark_finished_with_result_internal(source_reference_type result_, boost::unique_lock<boost::mutex>& lock)
{
//future_traits<T>::init(result,result_);
result= &result_;
mark_finished_internal(lock);
}
void mark_finished_with_result(source_reference_type result_)
{
boost::unique_lock<boost::mutex> lock(mutex);
mark_finished_with_result_internal(result_, lock);
}
virtual T& get()
{
boost::unique_lock<boost::mutex> lock(mutex);
wait_internal(lock);
return *result;
}
virtual T& get_sh()
{
boost::unique_lock<boost::mutex> lock(mutex);
wait_internal(lock);
return *result;
}
void set_value_at_thread_exit(T& result_)
{
unique_lock<boost::mutex> lk(this->mutex);
if (this->has_value(lk))
throw_exception(promise_already_satisfied());
//future_traits<T>::init(result,result_);
result= &result_;
this->is_constructed = true;
detail::make_ready_at_thread_exit(shared_from_this());
}
private:
shared_state(shared_state const&);
shared_state& operator=(shared_state const&);
};
template<>
struct shared_state<void>:
detail::shared_state_base
{
typedef void shared_future_get_result_type;
shared_state()
{}
void mark_finished_with_result_internal(boost::unique_lock<boost::mutex>& lock)
{
mark_finished_internal(lock);
}
void mark_finished_with_result()
{
boost::unique_lock<boost::mutex> lock(mutex);
mark_finished_with_result_internal(lock);
}
virtual void get()
{
boost::unique_lock<boost::mutex> lock(mutex);
this->wait_internal(lock);
}
virtual void get_sh()
{
boost::unique_lock<boost::mutex> lock(mutex);
this->wait_internal(lock);
}
void set_value_at_thread_exit()
{
unique_lock<boost::mutex> lk(this->mutex);
if (this->has_value(lk))
{
throw_exception(promise_already_satisfied());
}
this->is_constructed = true;
detail::make_ready_at_thread_exit(shared_from_this());
}
private:
shared_state(shared_state const&);
shared_state& operator=(shared_state const&);
};
/////////////////////////
/// future_async_shared_state_base
/////////////////////////
template<typename Rp>
struct future_async_shared_state_base: shared_state<Rp>
{
typedef shared_state<Rp> base_type;
protected:
boost::thread thr_;
void join()
{
if (thr_.joinable()) thr_.join();
}
public:
future_async_shared_state_base()
{
this->set_async();
}
explicit future_async_shared_state_base(BOOST_THREAD_RV_REF(boost::thread) th) :
thr_(boost::move(th))
{
this->set_async();
}
~future_async_shared_state_base()
{
join();
}
virtual void wait(bool rethrow)
{
join();
this->base_type::wait(rethrow);
}
};
/////////////////////////
/// future_async_shared_state
/////////////////////////
template<typename Rp, typename Fp>
struct future_async_shared_state: future_async_shared_state_base<Rp>
{
typedef future_async_shared_state_base<Rp> base_type;
public:
explicit future_async_shared_state(BOOST_THREAD_FWD_REF(Fp) f) :
base_type(thread(&future_async_shared_state::run, this, boost::forward<Fp>(f)))
{
}
static void run(future_async_shared_state* that, BOOST_THREAD_FWD_REF(Fp) f)
{
try
{
that->mark_finished_with_result(f());
}
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
catch(thread_interrupted& )
{
that->mark_interrupted_finish();
}
#endif
catch(...)
{
that->mark_exceptional_finish();
}
}
};
template<typename Fp>
struct future_async_shared_state<void, Fp>: public future_async_shared_state_base<void>
{
typedef future_async_shared_state_base<void> base_type;
public:
explicit future_async_shared_state(BOOST_THREAD_FWD_REF(Fp) f) :
base_type(thread(&future_async_shared_state::run, this, boost::forward<Fp>(f)))
{
}
static void run(future_async_shared_state* that, BOOST_THREAD_FWD_REF(Fp) f)
{
try
{
f();
that->mark_finished_with_result();
}
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
catch(thread_interrupted& )
{
that->mark_interrupted_finish();
}
#endif
catch(...)
{
that->mark_exceptional_finish();
}
}
};
template<typename Rp, typename Fp>
struct future_async_shared_state<Rp&, Fp>: future_async_shared_state_base<Rp&>
{
typedef future_async_shared_state_base<Rp&> base_type;
public:
explicit future_async_shared_state(BOOST_THREAD_FWD_REF(Fp) f) :
base_type(thread(&future_async_shared_state::run, this, boost::forward<Fp>(f)))
{
}
static void run(future_async_shared_state* that, BOOST_THREAD_FWD_REF(Fp) f)
{
try
{
that->mark_finished_with_result(f());
}
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
catch(thread_interrupted& )
{
that->mark_interrupted_finish();
}
#endif
catch(...)
{
that->mark_exceptional_finish();
}
}
};
//////////////////////////
/// future_deferred_shared_state
//////////////////////////
template<typename Rp, typename Fp>
struct future_deferred_shared_state: shared_state<Rp>
{
typedef shared_state<Rp> base_type;
Fp func_;
public:
explicit future_deferred_shared_state(BOOST_THREAD_FWD_REF(Fp) f)
: func_(boost::forward<Fp>(f))
{
this->set_deferred();
}
virtual void execute(boost::unique_lock<boost::mutex>& lck) {
try
{
Fp local_fuct=boost::move(func_);
relocker relock(lck);
Rp res = local_fuct();
relock.lock();
this->mark_finished_with_result_internal(boost::move(res), lck);
}
catch (...)
{
this->mark_exceptional_finish_internal(current_exception(), lck);
}
}
};
template<typename Rp, typename Fp>
struct future_deferred_shared_state<Rp&,Fp>: shared_state<Rp&>
{
typedef shared_state<Rp&> base_type;
Fp func_;
public:
explicit future_deferred_shared_state(BOOST_THREAD_FWD_REF(Fp) f)
: func_(boost::forward<Fp>(f))
{
this->set_deferred();
}
virtual void execute(boost::unique_lock<boost::mutex>& lck) {
try
{
this->mark_finished_with_result_internal(func_(), lck);
}
catch (...)
{
this->mark_exceptional_finish_internal(current_exception(), lck);
}
}
};
template<typename Fp>
struct future_deferred_shared_state<void,Fp>: shared_state<void>
{
typedef shared_state<void> base_type;
Fp func_;
public:
explicit future_deferred_shared_state(BOOST_THREAD_FWD_REF(Fp) f)
: func_(boost::forward<Fp>(f))
{
this->set_deferred();
}
virtual void execute(boost::unique_lock<boost::mutex>& lck) {
try
{
Fp local_fuct=boost::move(func_);
relocker relock(lck);
local_fuct();
relock.lock();
this->mark_finished_with_result_internal(lck);
}
catch (...)
{
this->mark_exceptional_finish_internal(current_exception(), lck);
}
}
};
// template<typename T, typename Allocator>
// struct shared_state_alloc: public shared_state<T>
// {
// typedef shared_state<T> base;
// Allocator alloc_;
//
// public:
// explicit shared_state_alloc(const Allocator& a)
// : alloc_(a) {}
//
// };
class future_waiter
{
struct registered_waiter;
typedef std::vector<int>::size_type count_type;
struct registered_waiter
{
boost::shared_ptr<detail::shared_state_base> future_;
detail::shared_state_base::waiter_list::iterator wait_iterator;
count_type index;
registered_waiter(boost::shared_ptr<detail::shared_state_base> const& a_future,
detail::shared_state_base::waiter_list::iterator wait_iterator_,
count_type index_):
future_(a_future),wait_iterator(wait_iterator_),index(index_)
{}
};
struct all_futures_lock
{
#ifdef _MANAGED
typedef std::ptrdiff_t count_type_portable;
#else
typedef count_type count_type_portable;
#endif
count_type_portable count;
boost::scoped_array<boost::unique_lock<boost::mutex> > locks;
all_futures_lock(std::vector<registered_waiter>& futures):
count(futures.size()),locks(new boost::unique_lock<boost::mutex>[count])
{
for(count_type_portable i=0;i<count;++i)
{
locks[i]=BOOST_THREAD_MAKE_RV_REF(boost::unique_lock<boost::mutex>(futures[i].future_->mutex));
}
}
void lock()
{
boost::lock(locks.get(),locks.get()+count);
}
void unlock()
{
for(count_type_portable i=0;i<count;++i)
{
locks[i].unlock();
}
}
};
boost::condition_variable_any cv;
std::vector<registered_waiter> futures;
count_type future_count;
public:
future_waiter():
future_count(0)
{}
template<typename F>
void add(F& f)
{
if(f.future_)
{
registered_waiter waiter(f.future_,f.future_->register_external_waiter(cv),future_count);
try {
futures.push_back(waiter);
} catch(...) {
f.future_->remove_external_waiter(waiter.wait_iterator);
throw;
}
}
++future_count;
}
#ifndef BOOST_NO_CXX11_VARIADIC_TEMPLATES
template<typename F1, typename... Fs>
void add(F1& f1, Fs&... fs)
{
add(f1); add(fs...);
}
#endif
count_type wait()
{
all_futures_lock lk(futures);
for(;;)
{
for(count_type i=0;i<futures.size();++i)
{
if(futures[i].future_->done)
{
return futures[i].index;
}
}
cv.wait(lk);
}
}
~future_waiter()
{
for(count_type i=0;i<futures.size();++i)
{
futures[i].future_->remove_external_waiter(futures[i].wait_iterator);
}
}
};
}
template <typename R>
class BOOST_THREAD_FUTURE;
template <typename R>
class shared_future;
template<typename T>
struct is_future_type
{
BOOST_STATIC_CONSTANT(bool, value=false);
typedef void type;
};
template<typename T>
struct is_future_type<BOOST_THREAD_FUTURE<T> >
{
BOOST_STATIC_CONSTANT(bool, value=true);
typedef T type;
};
template<typename T>
struct is_future_type<shared_future<T> >
{
BOOST_STATIC_CONSTANT(bool, value=true);
typedef T type;
};
template<typename Iterator>
typename boost::disable_if<is_future_type<Iterator>,void>::type wait_for_all(Iterator begin,Iterator end)
{
for(Iterator current=begin;current!=end;++current)
{
current->wait();
}
}
#ifdef BOOST_NO_CXX11_VARIADIC_TEMPLATES
template<typename F1,typename F2>
typename boost::enable_if<is_future_type<F1>,void>::type wait_for_all(F1& f1,F2& f2)
{
f1.wait();
f2.wait();
}
template<typename F1,typename F2,typename F3>
void wait_for_all(F1& f1,F2& f2,F3& f3)
{
f1.wait();
f2.wait();
f3.wait();
}
template<typename F1,typename F2,typename F3,typename F4>
void wait_for_all(F1& f1,F2& f2,F3& f3,F4& f4)
{
f1.wait();
f2.wait();
f3.wait();
f4.wait();
}
template<typename F1,typename F2,typename F3,typename F4,typename F5>
void wait_for_all(F1& f1,F2& f2,F3& f3,F4& f4,F5& f5)
{
f1.wait();
f2.wait();
f3.wait();
f4.wait();
f5.wait();
}
#else
template<typename F1, typename... Fs>
void wait_for_all(F1& f1, Fs&... fs)
{
bool dummy[] = { (f1.wait(), true), (fs.wait(), true)... };
// prevent unused parameter warning
(void) dummy;
}
#endif // !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
template<typename Iterator>
typename boost::disable_if<is_future_type<Iterator>,Iterator>::type wait_for_any(Iterator begin,Iterator end)
{
if(begin==end)
return end;
detail::future_waiter waiter;
for(Iterator current=begin;current!=end;++current)
{
waiter.add(*current);
}
return boost::next(begin,waiter.wait());
}
#ifdef BOOST_NO_CXX11_VARIADIC_TEMPLATES
template<typename F1,typename F2>
typename boost::enable_if<is_future_type<F1>,unsigned>::type wait_for_any(F1& f1,F2& f2)
{
detail::future_waiter waiter;
waiter.add(f1);
waiter.add(f2);
return waiter.wait();
}
template<typename F1,typename F2,typename F3>
unsigned wait_for_any(F1& f1,F2& f2,F3& f3)
{
detail::future_waiter waiter;
waiter.add(f1);
waiter.add(f2);
waiter.add(f3);
return waiter.wait();
}
template<typename F1,typename F2,typename F3,typename F4>
unsigned wait_for_any(F1& f1,F2& f2,F3& f3,F4& f4)
{
detail::future_waiter waiter;
waiter.add(f1);
waiter.add(f2);
waiter.add(f3);
waiter.add(f4);
return waiter.wait();
}
template<typename F1,typename F2,typename F3,typename F4,typename F5>
unsigned wait_for_any(F1& f1,F2& f2,F3& f3,F4& f4,F5& f5)
{
detail::future_waiter waiter;
waiter.add(f1);
waiter.add(f2);
waiter.add(f3);
waiter.add(f4);
waiter.add(f5);
return waiter.wait();
}
#else
template<typename F1, typename... Fs>
typename boost::enable_if<is_future_type<F1>, unsigned>::type wait_for_any(F1& f1, Fs&... fs)
{
detail::future_waiter waiter;
waiter.add(f1, fs...);
return waiter.wait();
}
#endif // !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
template <typename R>
class promise;
template <typename R>
class packaged_task;
namespace detail
{
/// Common implementation for all the futures independently of the return type
class base_future
{
//BOOST_THREAD_MOVABLE(base_future)
};
/// Common implementation for future and shared_future.
template <typename R>
class basic_future : public base_future
{
protected:
public:
typedef boost::shared_ptr<detail::shared_state<R> > future_ptr;
static //BOOST_CONSTEXPR
future_ptr make_exceptional_future_ptr(exceptional_ptr const& ex) {
promise<R> p;
p.set_exception(ex.ptr_);
return p.get_future().future_;
}
future_ptr future_;
basic_future(future_ptr a_future):
future_(a_future)
{
}
// Copy construction from a shared_future
explicit basic_future(const shared_future<R>&) BOOST_NOEXCEPT;
public:
typedef future_state::state state;
BOOST_THREAD_MOVABLE(basic_future)
basic_future(): future_() {}
//BOOST_CONSTEXPR
basic_future(exceptional_ptr const& ex)
: future_(make_exceptional_future_ptr(ex))
{
}
~basic_future() {}
basic_future(BOOST_THREAD_RV_REF(basic_future) other) BOOST_NOEXCEPT:
future_(BOOST_THREAD_RV(other).future_)
{
BOOST_THREAD_RV(other).future_.reset();
}
basic_future& operator=(BOOST_THREAD_RV_REF(basic_future) other) BOOST_NOEXCEPT
{
future_=BOOST_THREAD_RV(other).future_;
BOOST_THREAD_RV(other).future_.reset();
return *this;
}
void swap(basic_future& that) BOOST_NOEXCEPT
{
future_.swap(that.future_);
}
// functions to check state, and wait for ready
state get_state() const
{
if(!future_)
{
return future_state::uninitialized;
}
return future_->get_state();
}
bool is_ready() const
{
return get_state()==future_state::ready;
}
bool has_exception() const
{
return future_ && future_->has_exception();
}
bool has_value() const
{
return future_ && future_->has_value();
}
launch launch_policy(boost::unique_lock<boost::mutex>& lk) const
{
if ( future_ ) return future_->launch_policy(lk);
else return launch(launch::none);
}
exception_ptr get_exception_ptr()
{
return future_
? future_->get_exception_ptr()
: exception_ptr();
}
bool valid() const BOOST_NOEXCEPT
{
return future_ != 0;
}
void wait() const
{
if(!future_)
{
boost::throw_exception(future_uninitialized());
}
future_->wait(false);
}
#if defined BOOST_THREAD_USES_DATETIME
template<typename Duration>
bool timed_wait(Duration const& rel_time) const
{
return timed_wait_until(boost::get_system_time()+rel_time);
}
bool timed_wait_until(boost::system_time const& abs_time) const
{
if(!future_)
{
boost::throw_exception(future_uninitialized());
}
return future_->timed_wait_until(abs_time);
}
#endif
#ifdef BOOST_THREAD_USES_CHRONO
template <class Rep, class Period>
future_status
wait_for(const chrono::duration<Rep, Period>& rel_time) const
{
return wait_until(chrono::steady_clock::now() + rel_time);
}
template <class Clock, class Duration>
future_status
wait_until(const chrono::time_point<Clock, Duration>& abs_time) const
{
if(!future_)
{
boost::throw_exception(future_uninitialized());
}
return future_->wait_until(abs_time);
}
#endif
};
} // detail
BOOST_THREAD_DCL_MOVABLE_BEG(R) detail::basic_future<R> BOOST_THREAD_DCL_MOVABLE_END
namespace detail
{
#if (!defined _MSC_VER || _MSC_VER >= 1400) // _MSC_VER == 1400 on MSVC 2005
template <class Rp, class Fp>
BOOST_THREAD_FUTURE<Rp>
make_future_async_shared_state(BOOST_THREAD_FWD_REF(Fp) f);
template <class Rp, class Fp>
BOOST_THREAD_FUTURE<Rp>
make_future_deferred_shared_state(BOOST_THREAD_FWD_REF(Fp) f);
#endif // #if (!defined _MSC_VER || _MSC_VER >= 1400)
#if defined BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION
template<typename F, typename Rp, typename Fp>
struct future_deferred_continuation_shared_state;
template<typename F, typename Rp, typename Fp>
struct future_async_continuation_shared_state;
template <class F, class Rp, class Fp>
BOOST_THREAD_FUTURE<Rp>
make_future_async_continuation_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c);
template <class F, class Rp, class Fp>
BOOST_THREAD_FUTURE<Rp>
make_future_deferred_continuation_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c);
#endif
#if defined BOOST_THREAD_PROVIDES_FUTURE_UNWRAP
template<typename F, typename Rp>
struct future_unwrap_shared_state;
template <class F, class Rp>
inline BOOST_THREAD_FUTURE<Rp>
make_future_unwrap_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f);
#endif
}
template <typename R>
class BOOST_THREAD_FUTURE : public detail::basic_future<R>
{
private:
typedef detail::basic_future<R> base_type;
typedef typename base_type::future_ptr future_ptr;
friend class shared_future<R>;
friend class promise<R>;
#if defined BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION
template <typename, typename, typename>
friend struct detail::future_async_continuation_shared_state;
template <typename, typename, typename>
friend struct detail::future_deferred_continuation_shared_state;
template <class F, class Rp, class Fp>
friend BOOST_THREAD_FUTURE<Rp>
detail::make_future_async_continuation_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c);
template <class F, class Rp, class Fp>
friend BOOST_THREAD_FUTURE<Rp>
detail::make_future_deferred_continuation_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c);
#endif
#if defined BOOST_THREAD_PROVIDES_FUTURE_UNWRAP
template<typename F, typename Rp>
friend struct detail::future_unwrap_shared_state;
template <class F, class Rp>
friend BOOST_THREAD_FUTURE<Rp>
detail::make_future_unwrap_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f);
#endif
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
template <class> friend class packaged_task; // todo check if this works in windows
#else
friend class packaged_task<R>;
#endif
friend class detail::future_waiter;
template <class Rp, class Fp>
friend BOOST_THREAD_FUTURE<Rp>
detail::make_future_async_shared_state(BOOST_THREAD_FWD_REF(Fp) f);
template <class Rp, class Fp>
friend BOOST_THREAD_FUTURE<Rp>
detail::make_future_deferred_shared_state(BOOST_THREAD_FWD_REF(Fp) f);
typedef typename detail::future_traits<R>::move_dest_type move_dest_type;
public: // when_all
BOOST_THREAD_FUTURE(future_ptr a_future):
base_type(a_future)
{
}
public:
BOOST_THREAD_MOVABLE_ONLY(BOOST_THREAD_FUTURE)
typedef future_state::state state;
typedef R value_type; // EXTENSION
BOOST_CONSTEXPR BOOST_THREAD_FUTURE() {}
//BOOST_CONSTEXPR
BOOST_THREAD_FUTURE(exceptional_ptr const& ex):
base_type(ex) {}
~BOOST_THREAD_FUTURE() {}
BOOST_THREAD_FUTURE(BOOST_THREAD_RV_REF(BOOST_THREAD_FUTURE) other) BOOST_NOEXCEPT:
base_type(boost::move(static_cast<base_type&>(BOOST_THREAD_RV(other))))
{
}
inline BOOST_THREAD_FUTURE(BOOST_THREAD_RV_REF(BOOST_THREAD_FUTURE<BOOST_THREAD_FUTURE<R> >) other); // EXTENSION
BOOST_THREAD_FUTURE& operator=(BOOST_THREAD_RV_REF(BOOST_THREAD_FUTURE) other) BOOST_NOEXCEPT
{
this->base_type::operator=(boost::move(static_cast<base_type&>(BOOST_THREAD_RV(other))));
return *this;
}
// BOOST_THREAD_FUTURE& operator=(exceptional_ptr const& ex)
// {
// this->future_=base_type::make_exceptional_future_ptr(ex);
// return *this;
// }
shared_future<R> share()
{
return shared_future<R>(::boost::move(*this));
}
void swap(BOOST_THREAD_FUTURE& other)
{
static_cast<base_type*>(this)->swap(other);
}
// todo this function must be private and friendship provided to the internal users.
void set_async()
{
this->future_->set_async();
}
// todo this function must be private and friendship provided to the internal users.
void set_deferred()
{
this->future_->set_deferred();
}
// retrieving the value
move_dest_type get()
{
if(!this->future_)
{
boost::throw_exception(future_uninitialized());
}
future_ptr fut_=this->future_;
#ifdef BOOST_THREAD_PROVIDES_FUTURE_INVALID_AFTER_GET
this->future_.reset();
#endif
return fut_->get();
}
template <typename R2>
typename boost::disable_if< is_void<R2>, move_dest_type>::type
get_or(BOOST_THREAD_RV_REF(R2) v)
{
if(!this->future_)
{
boost::throw_exception(future_uninitialized());
}
this->future_->wait(false);
future_ptr fut_=this->future_;
#ifdef BOOST_THREAD_PROVIDES_FUTURE_INVALID_AFTER_GET
this->future_.reset();
#endif
if (fut_->has_value()) {
return fut_->get();
}
else {
return boost::move(v);
}
}
template <typename R2>
typename boost::disable_if< is_void<R2>, move_dest_type>::type
get_or(R2 const& v) // EXTENSION
{
if(!this->future_)
{
boost::throw_exception(future_uninitialized());
}
this->future_->wait(false);
future_ptr fut_=this->future_;
#ifdef BOOST_THREAD_PROVIDES_FUTURE_INVALID_AFTER_GET
this->future_.reset();
#endif
if (fut_->has_value()) {
return fut_->get();
}
else {
return v;
}
}
#if defined BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION
// template<typename F>
// auto then(F&& func) -> BOOST_THREAD_FUTURE<decltype(func(*this))>;
//#if defined(BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR)
// template<typename RF>
// inline BOOST_THREAD_FUTURE<RF> then(RF(*func)(BOOST_THREAD_FUTURE&));
// template<typename RF>
// inline BOOST_THREAD_FUTURE<RF> then(launch policy, RF(*func)(BOOST_THREAD_FUTURE&));
//#endif
template<typename F>
inline BOOST_THREAD_FUTURE<typename boost::result_of<F(BOOST_THREAD_FUTURE)>::type>
then(BOOST_THREAD_FWD_REF(F) func); // EXTENSION
template<typename F>
inline BOOST_THREAD_FUTURE<typename boost::result_of<F(BOOST_THREAD_FUTURE)>::type>
then(launch policy, BOOST_THREAD_FWD_REF(F) func); // EXTENSION
template <typename R2>
inline typename boost::disable_if< is_void<R2>, BOOST_THREAD_FUTURE<R> >::type
fallback_to(BOOST_THREAD_RV_REF(R2) v); // EXTENSION
template <typename R2>
inline typename boost::disable_if< is_void<R2>, BOOST_THREAD_FUTURE<R> >::type
fallback_to(R2 const& v); // EXTENSION
#endif
//#if defined BOOST_THREAD_PROVIDES_FUTURE_UNWRAP
// inline
// typename boost::enable_if<
// is_future_type<value_type>,
// value_type
// //BOOST_THREAD_FUTURE<typename is_future_type<value_type>::type>
// >::type
// unwrap();
//#endif
};
BOOST_THREAD_DCL_MOVABLE_BEG(T) BOOST_THREAD_FUTURE<T> BOOST_THREAD_DCL_MOVABLE_END
template <typename R2>
class BOOST_THREAD_FUTURE<BOOST_THREAD_FUTURE<R2> > : public detail::basic_future<BOOST_THREAD_FUTURE<R2> >
{
typedef BOOST_THREAD_FUTURE<R2> R;
private:
typedef detail::basic_future<R> base_type;
typedef typename base_type::future_ptr future_ptr;
friend class shared_future<R>;
friend class promise<R>;
#if defined BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION
template <typename, typename, typename>
friend struct detail::future_async_continuation_shared_state;
template <typename, typename, typename>
friend struct detail::future_deferred_continuation_shared_state;
template <class F, class Rp, class Fp>
friend BOOST_THREAD_FUTURE<Rp>
detail::make_future_async_continuation_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c);
template <class F, class Rp, class Fp>
friend BOOST_THREAD_FUTURE<Rp>
detail::make_future_deferred_continuation_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c);
#endif
#if defined BOOST_THREAD_PROVIDES_FUTURE_UNWRAP
template<typename F, typename Rp>
friend struct detail::future_unwrap_shared_state;
template <class F, class Rp>
friend BOOST_THREAD_FUTURE<Rp>
detail::make_future_unwrap_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f);
#endif
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
template <class> friend class packaged_task; // todo check if this works in windows
#else
friend class packaged_task<R>;
#endif
friend class detail::future_waiter;
template <class Rp, class Fp>
friend BOOST_THREAD_FUTURE<Rp>
detail::make_future_async_shared_state(BOOST_THREAD_FWD_REF(Fp) f);
template <class Rp, class Fp>
friend BOOST_THREAD_FUTURE<Rp>
detail::make_future_deferred_shared_state(BOOST_THREAD_FWD_REF(Fp) f);
typedef typename detail::future_traits<R>::move_dest_type move_dest_type;
BOOST_THREAD_FUTURE(future_ptr a_future):
base_type(a_future)
{
}
public:
BOOST_THREAD_MOVABLE_ONLY(BOOST_THREAD_FUTURE)
typedef future_state::state state;
typedef R value_type; // EXTENSION
BOOST_CONSTEXPR BOOST_THREAD_FUTURE() {}
//BOOST_CONSTEXPR
BOOST_THREAD_FUTURE(exceptional_ptr const& ex):
base_type(ex) {}
~BOOST_THREAD_FUTURE() {}
BOOST_THREAD_FUTURE(BOOST_THREAD_RV_REF(BOOST_THREAD_FUTURE) other) BOOST_NOEXCEPT:
base_type(boost::move(static_cast<base_type&>(BOOST_THREAD_RV(other))))
{
}
BOOST_THREAD_FUTURE& operator=(BOOST_THREAD_RV_REF(BOOST_THREAD_FUTURE) other) BOOST_NOEXCEPT
{
this->base_type::operator=(boost::move(static_cast<base_type&>(BOOST_THREAD_RV(other))));
return *this;
}
// BOOST_THREAD_FUTURE& operator=(exceptional_ptr const& ex)
// {
// this->future_=base_type::make_exceptional_future_ptr(ex);
// return *this;
// }
shared_future<R> share()
{
return shared_future<R>(::boost::move(*this));
}
void swap(BOOST_THREAD_FUTURE& other)
{
static_cast<base_type*>(this)->swap(other);
}
// todo this function must be private and friendship provided to the internal users.
void set_async()
{
this->future_->set_async();
}
// todo this function must be private and friendship provided to the internal users.
void set_deferred()
{
this->future_->set_deferred();
}
// retrieving the value
move_dest_type get()
{
if(!this->future_)
{
boost::throw_exception(future_uninitialized());
}
future_ptr fut_=this->future_;
#ifdef BOOST_THREAD_PROVIDES_FUTURE_INVALID_AFTER_GET
this->future_.reset();
#endif
return fut_->get();
}
move_dest_type get_or(BOOST_THREAD_RV_REF(R) v) // EXTENSION
{
if(!this->future_)
{
boost::throw_exception(future_uninitialized());
}
this->future_->wait(false);
future_ptr fut_=this->future_;
#ifdef BOOST_THREAD_PROVIDES_FUTURE_INVALID_AFTER_GET
this->future_.reset();
#endif
if (fut_->has_value()) return fut_->get();
else return boost::move(v);
}
move_dest_type get_or(R const& v) // EXTENSION
{
if(!this->future_)
{
boost::throw_exception(future_uninitialized());
}
this->future_->wait(false);
future_ptr fut_=this->future_;
#ifdef BOOST_THREAD_PROVIDES_FUTURE_INVALID_AFTER_GET
this->future_.reset();
#endif
if (fut_->has_value()) return fut_->get();
else return v;
}
#if defined BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION
// template<typename F>
// auto then(F&& func) -> BOOST_THREAD_FUTURE<decltype(func(*this))>;
//#if defined(BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR)
// template<typename RF>
// inline BOOST_THREAD_FUTURE<RF> then(RF(*func)(BOOST_THREAD_FUTURE&));
// template<typename RF>
// inline BOOST_THREAD_FUTURE<RF> then(launch policy, RF(*func)(BOOST_THREAD_FUTURE&));
//#endif
template<typename F>
inline BOOST_THREAD_FUTURE<typename boost::result_of<F(BOOST_THREAD_FUTURE)>::type>
then(BOOST_THREAD_FWD_REF(F) func); // EXTENSION
template<typename F>
inline BOOST_THREAD_FUTURE<typename boost::result_of<F(BOOST_THREAD_FUTURE)>::type>
then(launch policy, BOOST_THREAD_FWD_REF(F) func); // EXTENSION
#endif
#if defined BOOST_THREAD_PROVIDES_FUTURE_UNWRAP
inline
BOOST_THREAD_FUTURE<R2>
unwrap(); // EXTENSION
#endif
};
template <typename R>
class shared_future : public detail::basic_future<R>
{
typedef detail::basic_future<R> base_type;
typedef typename base_type::future_ptr future_ptr;
friend class detail::future_waiter;
friend class promise<R>;
#if defined BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION
template <typename, typename, typename>
friend struct detail::future_async_continuation_shared_state;
template <typename, typename, typename>
friend struct detail::future_deferred_continuation_shared_state;
template <class F, class Rp, class Fp>
friend BOOST_THREAD_FUTURE<Rp>
detail::make_future_async_continuation_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c);
template <class F, class Rp, class Fp>
friend BOOST_THREAD_FUTURE<Rp>
detail::make_future_deferred_continuation_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c);
#endif
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
template <class> friend class packaged_task;// todo check if this works in windows
#else
friend class packaged_task<R>;
#endif
shared_future(future_ptr a_future):
base_type(a_future)
{}
public:
BOOST_THREAD_MOVABLE(shared_future)
typedef R value_type; // EXTENSION
shared_future(shared_future const& other):
base_type(other)
{}
typedef future_state::state state;
BOOST_CONSTEXPR shared_future()
{}
//BOOST_CONSTEXPR
shared_future(exceptional_ptr const& ex):
base_type(ex) {}
~shared_future()
{}
shared_future& operator=(shared_future const& other)
{
shared_future(other).swap(*this);
return *this;
}
// shared_future& operator=(exceptional_ptr const& ex)
// {
// this->future_=base_type::make_exceptional_future_ptr(ex);
// return *this;
// }
shared_future(BOOST_THREAD_RV_REF(shared_future) other) BOOST_NOEXCEPT :
base_type(boost::move(static_cast<base_type&>(BOOST_THREAD_RV(other))))
{
BOOST_THREAD_RV(other).future_.reset();
}
shared_future(BOOST_THREAD_RV_REF( BOOST_THREAD_FUTURE<R> ) other) BOOST_NOEXCEPT :
base_type(boost::move(static_cast<base_type&>(BOOST_THREAD_RV(other))))
{
}
shared_future& operator=(BOOST_THREAD_RV_REF(shared_future) other) BOOST_NOEXCEPT
{
base_type::operator=(boost::move(static_cast<base_type&>(BOOST_THREAD_RV(other))));
return *this;
}
shared_future& operator=(BOOST_THREAD_RV_REF( BOOST_THREAD_FUTURE<R> ) other) BOOST_NOEXCEPT
{
base_type::operator=(boost::move(static_cast<base_type&>(BOOST_THREAD_RV(other))));
return *this;
}
void swap(shared_future& other) BOOST_NOEXCEPT
{
static_cast<base_type*>(this)->swap(other);
}
// retrieving the value
typename detail::shared_state<R>::shared_future_get_result_type get()
{
if(!this->future_)
{
boost::throw_exception(future_uninitialized());
}
return this->future_->get_sh();
}
template <typename R2>
typename boost::disable_if< is_void<R2>, typename detail::shared_state<R>::shared_future_get_result_type>::type
get_or(BOOST_THREAD_RV_REF(R2) v) // EXTENSION
{
if(!this->future_)
{
boost::throw_exception(future_uninitialized());
}
future_ptr fut_=this->future_;
fut_->wait();
if (fut_->has_value()) return fut_->get_sh();
else return boost::move(v);
}
#if defined BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION
// template<typename F>
// auto then(F&& func) -> BOOST_THREAD_FUTURE<decltype(func(*this))>;
// template<typename F>
// auto then(launch, F&& func) -> BOOST_THREAD_FUTURE<decltype(func(*this))>;
//#if defined(BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR)
// template<typename RF>
// inline BOOST_THREAD_FUTURE<RF> then(RF(*func)(shared_future&));
// template<typename RF>
// inline BOOST_THREAD_FUTURE<RF> then(launch policy, RF(*func)(shared_future&));
//#endif
template<typename F>
inline BOOST_THREAD_FUTURE<typename boost::result_of<F(shared_future)>::type>
then(BOOST_THREAD_FWD_REF(F) func); // EXTENSION
template<typename F>
inline BOOST_THREAD_FUTURE<typename boost::result_of<F(shared_future)>::type>
then(launch policy, BOOST_THREAD_FWD_REF(F) func); // EXTENSION
#endif
//#if defined BOOST_THREAD_PROVIDES_FUTURE_UNWRAP
// inline
// typename boost::enable_if_c<
// is_future_type<value_type>::value,
// BOOST_THREAD_FUTURE<typename is_future_type<value_type>::type>
// >::type
// unwrap();
//#endif
};
BOOST_THREAD_DCL_MOVABLE_BEG(T) shared_future<T> BOOST_THREAD_DCL_MOVABLE_END
namespace detail
{
/// Copy construction from a shared_future
template <typename R>
inline basic_future<R>::basic_future(const shared_future<R>& other) BOOST_NOEXCEPT
: future_(other.future_)
{
}
}
template <typename R>
class promise
{
typedef boost::shared_ptr<detail::shared_state<R> > future_ptr;
future_ptr future_;
bool future_obtained;
void lazy_init()
{
#if defined BOOST_THREAD_PROVIDES_PROMISE_LAZY
#include <boost/detail/atomic_undef_macros.hpp>
if(!atomic_load(&future_))
{
future_ptr blank;
atomic_compare_exchange(&future_,&blank,future_ptr(new detail::shared_state<R>));
}
#include <boost/detail/atomic_redef_macros.hpp>
#endif
}
public:
BOOST_THREAD_MOVABLE_ONLY(promise)
#if defined BOOST_THREAD_PROVIDES_FUTURE_CTOR_ALLOCATORS
template <class Allocator>
promise(boost::allocator_arg_t, Allocator a)
{
typedef typename Allocator::template rebind<detail::shared_state<R> >::other A2;
A2 a2(a);
typedef thread_detail::allocator_destructor<A2> D;
future_ = future_ptr(::new(a2.allocate(1)) detail::shared_state<R>(), D(a2, 1) );
future_obtained = false;
}
#endif
promise():
#if defined BOOST_THREAD_PROVIDES_PROMISE_LAZY
future_(),
#else
future_(new detail::shared_state<R>()),
#endif
future_obtained(false)
{}
~promise()
{
if(future_)
{
boost::unique_lock<boost::mutex> lock(future_->mutex);
if(!future_->done && !future_->is_constructed)
{
future_->mark_exceptional_finish_internal(boost::copy_exception(broken_promise()), lock);
}
}
}
// Assignment
promise(BOOST_THREAD_RV_REF(promise) rhs) BOOST_NOEXCEPT :
future_(BOOST_THREAD_RV(rhs).future_),future_obtained(BOOST_THREAD_RV(rhs).future_obtained)
{
BOOST_THREAD_RV(rhs).future_.reset();
BOOST_THREAD_RV(rhs).future_obtained=false;
}
promise & operator=(BOOST_THREAD_RV_REF(promise) rhs) BOOST_NOEXCEPT
{
future_=BOOST_THREAD_RV(rhs).future_;
future_obtained=BOOST_THREAD_RV(rhs).future_obtained;
BOOST_THREAD_RV(rhs).future_.reset();
BOOST_THREAD_RV(rhs).future_obtained=false;
return *this;
}
void swap(promise& other)
{
future_.swap(other.future_);
std::swap(future_obtained,other.future_obtained);
}
// Result retrieval
BOOST_THREAD_FUTURE<R> get_future()
{
lazy_init();
if (future_.get()==0)
{
boost::throw_exception(promise_moved());
}
if (future_obtained)
{
boost::throw_exception(future_already_retrieved());
}
future_obtained=true;
return BOOST_THREAD_FUTURE<R>(future_);
}
void set_value(typename detail::future_traits<R>::source_reference_type r)
{
lazy_init();
boost::unique_lock<boost::mutex> lock(future_->mutex);
if(future_->done)
{
boost::throw_exception(promise_already_satisfied());
}
future_->mark_finished_with_result_internal(r, lock);
}
// void set_value(R && r);
void set_value(typename detail::future_traits<R>::rvalue_source_type r)
{
lazy_init();
boost::unique_lock<boost::mutex> lock(future_->mutex);
if(future_->done)
{
boost::throw_exception(promise_already_satisfied());
}
#if ! defined BOOST_NO_CXX11_RVALUE_REFERENCES
future_->mark_finished_with_result_internal(boost::forward<R>(r), lock);
#else
future_->mark_finished_with_result_internal(static_cast<typename detail::future_traits<R>::rvalue_source_type>(r), lock);
#endif
}
void set_exception(boost::exception_ptr p)
{
lazy_init();
boost::unique_lock<boost::mutex> lock(future_->mutex);
if(future_->done)
{
boost::throw_exception(promise_already_satisfied());
}
future_->mark_exceptional_finish_internal(p, lock);
}
template <typename E>
void set_exception(E ex)
{
set_exception(copy_exception(ex));
}
// setting the result with deferred notification
void set_value_at_thread_exit(const R& r)
{
if (future_.get()==0)
{
boost::throw_exception(promise_moved());
}
future_->set_value_at_thread_exit(r);
}
void set_value_at_thread_exit(BOOST_THREAD_RV_REF(R) r)
{
if (future_.get()==0)
{
boost::throw_exception(promise_moved());
}
future_->set_value_at_thread_exit(boost::move(r));
}
void set_exception_at_thread_exit(exception_ptr e)
{
if (future_.get()==0)
{
boost::throw_exception(promise_moved());
}
future_->set_exception_at_thread_exit(e);
}
template <typename E>
void set_exception_at_thread_exit(E ex)
{
set_exception_at_thread_exit(copy_exception(ex));
}
template<typename F>
void set_wait_callback(F f)
{
lazy_init();
future_->set_wait_callback(f,this);
}
};
template <typename R>
class promise<R&>
{
typedef boost::shared_ptr<detail::shared_state<R&> > future_ptr;
future_ptr future_;
bool future_obtained;
void lazy_init()
{
#if defined BOOST_THREAD_PROVIDES_PROMISE_LAZY
#include <boost/detail/atomic_undef_macros.hpp>
if(!atomic_load(&future_))
{
future_ptr blank;
atomic_compare_exchange(&future_,&blank,future_ptr(new detail::shared_state<R&>));
}
#include <boost/detail/atomic_redef_macros.hpp>
#endif
}
public:
BOOST_THREAD_MOVABLE_ONLY(promise)
#if defined BOOST_THREAD_PROVIDES_FUTURE_CTOR_ALLOCATORS
template <class Allocator>
promise(boost::allocator_arg_t, Allocator a)
{
typedef typename Allocator::template rebind<detail::shared_state<R&> >::other A2;
A2 a2(a);
typedef thread_detail::allocator_destructor<A2> D;
future_ = future_ptr(::new(a2.allocate(1)) detail::shared_state<R&>(), D(a2, 1) );
future_obtained = false;
}
#endif
promise():
#if defined BOOST_THREAD_PROVIDES_PROMISE_LAZY
future_(),
#else
future_(new detail::shared_state<R&>()),
#endif
future_obtained(false)
{}
~promise()
{
if(future_)
{
boost::unique_lock<boost::mutex> lock(future_->mutex);
if(!future_->done && !future_->is_constructed)
{
future_->mark_exceptional_finish_internal(boost::copy_exception(broken_promise()), lock);
}
}
}
// Assignment
promise(BOOST_THREAD_RV_REF(promise) rhs) BOOST_NOEXCEPT :
future_(BOOST_THREAD_RV(rhs).future_),future_obtained(BOOST_THREAD_RV(rhs).future_obtained)
{
BOOST_THREAD_RV(rhs).future_.reset();
BOOST_THREAD_RV(rhs).future_obtained=false;
}
promise & operator=(BOOST_THREAD_RV_REF(promise) rhs) BOOST_NOEXCEPT
{
future_=BOOST_THREAD_RV(rhs).future_;
future_obtained=BOOST_THREAD_RV(rhs).future_obtained;
BOOST_THREAD_RV(rhs).future_.reset();
BOOST_THREAD_RV(rhs).future_obtained=false;
return *this;
}
void swap(promise& other)
{
future_.swap(other.future_);
std::swap(future_obtained,other.future_obtained);
}
// Result retrieval
BOOST_THREAD_FUTURE<R&> get_future()
{
lazy_init();
if (future_.get()==0)
{
boost::throw_exception(promise_moved());
}
if (future_obtained)
{
boost::throw_exception(future_already_retrieved());
}
future_obtained=true;
return BOOST_THREAD_FUTURE<R&>(future_);
}
void set_value(R& r)
{
lazy_init();
boost::unique_lock<boost::mutex> lock(future_->mutex);
if(future_->done)
{
boost::throw_exception(promise_already_satisfied());
}
future_->mark_finished_with_result_internal(r, lock);
}
void set_exception(boost::exception_ptr p)
{
lazy_init();
boost::unique_lock<boost::mutex> lock(future_->mutex);
if(future_->done)
{
boost::throw_exception(promise_already_satisfied());
}
future_->mark_exceptional_finish_internal(p, lock);
}
template <typename E>
void set_exception(E ex)
{
set_exception(copy_exception(ex));
}
// setting the result with deferred notification
void set_value_at_thread_exit(R& r)
{
if (future_.get()==0)
{
boost::throw_exception(promise_moved());
}
future_->set_value_at_thread_exit(r);
}
void set_exception_at_thread_exit(exception_ptr e)
{
if (future_.get()==0)
{
boost::throw_exception(promise_moved());
}
future_->set_exception_at_thread_exit(e);
}
template <typename E>
void set_exception_at_thread_exit(E ex)
{
set_exception_at_thread_exit(copy_exception(ex));
}
template<typename F>
void set_wait_callback(F f)
{
lazy_init();
future_->set_wait_callback(f,this);
}
};
template <>
class promise<void>
{
typedef boost::shared_ptr<detail::shared_state<void> > future_ptr;
future_ptr future_;
bool future_obtained;
void lazy_init()
{
#if defined BOOST_THREAD_PROVIDES_PROMISE_LAZY
if(!atomic_load(&future_))
{
future_ptr blank;
atomic_compare_exchange(&future_,&blank,future_ptr(new detail::shared_state<void>));
}
#endif
}
public:
BOOST_THREAD_MOVABLE_ONLY(promise)
#if defined BOOST_THREAD_PROVIDES_FUTURE_CTOR_ALLOCATORS
template <class Allocator>
promise(boost::allocator_arg_t, Allocator a)
{
typedef typename Allocator::template rebind<detail::shared_state<void> >::other A2;
A2 a2(a);
typedef thread_detail::allocator_destructor<A2> D;
future_ = future_ptr(::new(a2.allocate(1)) detail::shared_state<void>(), D(a2, 1) );
future_obtained = false;
}
#endif
promise():
#if defined BOOST_THREAD_PROVIDES_PROMISE_LAZY
future_(),
#else
future_(new detail::shared_state<void>),
#endif
future_obtained(false)
{}
~promise()
{
if(future_)
{
boost::unique_lock<boost::mutex> lock(future_->mutex);
if(!future_->done && !future_->is_constructed)
{
future_->mark_exceptional_finish_internal(boost::copy_exception(broken_promise()), lock);
}
}
}
// Assignment
promise(BOOST_THREAD_RV_REF(promise) rhs) BOOST_NOEXCEPT :
future_(BOOST_THREAD_RV(rhs).future_),future_obtained(BOOST_THREAD_RV(rhs).future_obtained)
{
// we need to release the future as shared_ptr doesn't implements move semantics
BOOST_THREAD_RV(rhs).future_.reset();
BOOST_THREAD_RV(rhs).future_obtained=false;
}
promise & operator=(BOOST_THREAD_RV_REF(promise) rhs) BOOST_NOEXCEPT
{
future_=BOOST_THREAD_RV(rhs).future_;
future_obtained=BOOST_THREAD_RV(rhs).future_obtained;
BOOST_THREAD_RV(rhs).future_.reset();
BOOST_THREAD_RV(rhs).future_obtained=false;
return *this;
}
void swap(promise& other)
{
future_.swap(other.future_);
std::swap(future_obtained,other.future_obtained);
}
// Result retrieval
BOOST_THREAD_FUTURE<void> get_future()
{
lazy_init();
if (future_.get()==0)
{
boost::throw_exception(promise_moved());
}
if(future_obtained)
{
boost::throw_exception(future_already_retrieved());
}
future_obtained=true;
//return BOOST_THREAD_MAKE_RV_REF(BOOST_THREAD_FUTURE<void>(future_));
return BOOST_THREAD_FUTURE<void>(future_);
}
void set_value()
{
lazy_init();
boost::unique_lock<boost::mutex> lock(future_->mutex);
if(future_->done)
{
boost::throw_exception(promise_already_satisfied());
}
future_->mark_finished_with_result_internal(lock);
}
void set_exception(boost::exception_ptr p)
{
lazy_init();
boost::unique_lock<boost::mutex> lock(future_->mutex);
if(future_->done)
{
boost::throw_exception(promise_already_satisfied());
}
future_->mark_exceptional_finish_internal(p,lock);
}
template <typename E>
void set_exception(E ex)
{
set_exception(copy_exception(ex));
}
// setting the result with deferred notification
void set_value_at_thread_exit()
{
if (future_.get()==0)
{
boost::throw_exception(promise_moved());
}
future_->set_value_at_thread_exit();
}
void set_exception_at_thread_exit(exception_ptr e)
{
if (future_.get()==0)
{
boost::throw_exception(promise_moved());
}
future_->set_exception_at_thread_exit(e);
}
template <typename E>
void set_exception_at_thread_exit(E ex)
{
set_exception_at_thread_exit(copy_exception(ex));
}
template<typename F>
void set_wait_callback(F f)
{
lazy_init();
future_->set_wait_callback(f,this);
}
};
}
#if defined BOOST_THREAD_PROVIDES_FUTURE_CTOR_ALLOCATORS
namespace boost { namespace container {
template <class R, class Alloc>
struct uses_allocator< ::boost::promise<R> , Alloc> : true_type
{
};
}}
#if ! defined BOOST_NO_CXX11_ALLOCATOR
namespace std {
template <class R, class Alloc>
struct uses_allocator< ::boost::promise<R> , Alloc> : true_type
{
};
}
#endif
#endif
namespace boost
{
BOOST_THREAD_DCL_MOVABLE_BEG(T) promise<T> BOOST_THREAD_DCL_MOVABLE_END
namespace detail
{
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
template<typename R>
struct task_base_shared_state;
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
template<typename R, typename ...ArgTypes>
struct task_base_shared_state<R(ArgTypes...)>:
#else
template<typename R>
struct task_base_shared_state<R()>:
#endif
#else
template<typename R>
struct task_base_shared_state:
#endif
detail::shared_state<R>
{
bool started;
task_base_shared_state():
started(false)
{}
void reset()
{
started=false;
}
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
virtual void do_run(BOOST_THREAD_RV_REF(ArgTypes) ... args)=0;
void run(BOOST_THREAD_RV_REF(ArgTypes) ... args)
#else
virtual void do_run()=0;
void run()
#endif
{
{
boost::lock_guard<boost::mutex> lk(this->mutex);
if(started)
{
boost::throw_exception(task_already_started());
}
started=true;
}
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
do_run(boost::forward<ArgTypes>(args)...);
#else
do_run();
#endif
}
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
virtual void do_apply(BOOST_THREAD_RV_REF(ArgTypes) ... args)=0;
void apply(BOOST_THREAD_RV_REF(ArgTypes) ... args)
#else
virtual void do_apply()=0;
void apply()
#endif
{
{
boost::lock_guard<boost::mutex> lk(this->mutex);
if(started)
{
boost::throw_exception(task_already_started());
}
started=true;
}
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
do_apply(boost::forward<ArgTypes>(args)...);
#else
do_apply();
#endif
}
void owner_destroyed()
{
boost::unique_lock<boost::mutex> lk(this->mutex);
if(!started)
{
started=true;
this->mark_exceptional_finish_internal(boost::copy_exception(boost::broken_promise()), lk);
}
}
};
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
template<typename F, typename R>
struct task_shared_state;
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
template<typename F, typename R, typename ...ArgTypes>
struct task_shared_state<F, R(ArgTypes...)>:
task_base_shared_state<R(ArgTypes...)>
#else
template<typename F, typename R>
struct task_shared_state<F, R()>:
task_base_shared_state<R()>
#endif
#else
template<typename F, typename R>
struct task_shared_state:
task_base_shared_state<R>
#endif
{
private:
task_shared_state(task_shared_state&);
public:
F f;
task_shared_state(F const& f_):
f(f_)
{}
task_shared_state(BOOST_THREAD_RV_REF(F) f_):
f(boost::move(f_))
{}
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
void do_apply(BOOST_THREAD_RV_REF(ArgTypes) ... args)
{
try
{
this->set_value_at_thread_exit(f(boost::forward<ArgTypes>(args)...));
}
#else
void do_apply()
{
try
{
this->set_value_at_thread_exit(f());
}
#endif
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
catch(thread_interrupted& )
{
this->set_interrupted_at_thread_exit();
}
#endif
catch(...)
{
this->set_exception_at_thread_exit(current_exception());
}
}
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
void do_run(BOOST_THREAD_RV_REF(ArgTypes) ... args)
{
try
{
this->mark_finished_with_result(f(boost::forward<ArgTypes>(args)...));
}
#else
void do_run()
{
try
{
#if ! defined BOOST_NO_CXX11_RVALUE_REFERENCES
R res((f()));
this->mark_finished_with_result(boost::move(res));
#else
this->mark_finished_with_result(f());
#endif
}
#endif
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
catch(thread_interrupted& )
{
this->mark_interrupted_finish();
}
#endif
catch(...)
{
this->mark_exceptional_finish();
}
}
};
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
template<typename F, typename R, typename ...ArgTypes>
struct task_shared_state<F, R&(ArgTypes...)>:
task_base_shared_state<R&(ArgTypes...)>
#else
template<typename F, typename R>
struct task_shared_state<F, R&()>:
task_base_shared_state<R&()>
#endif
#else
template<typename F, typename R>
struct task_shared_state<F,R&>:
task_base_shared_state<R&>
#endif
{
private:
task_shared_state(task_shared_state&);
public:
F f;
task_shared_state(F const& f_):
f(f_)
{}
task_shared_state(BOOST_THREAD_RV_REF(F) f_):
f(boost::move(f_))
{}
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
void do_apply(BOOST_THREAD_RV_REF(ArgTypes) ... args)
{
try
{
this->set_value_at_thread_exit(f(boost::forward<ArgTypes>(args)...));
}
#else
void do_apply()
{
try
{
this->set_value_at_thread_exit(f());
}
#endif
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
catch(thread_interrupted& )
{
this->set_interrupted_at_thread_exit();
}
#endif
catch(...)
{
this->set_exception_at_thread_exit(current_exception());
}
}
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
void do_run(BOOST_THREAD_RV_REF(ArgTypes) ... args)
{
try
{
this->mark_finished_with_result(f(boost::forward<ArgTypes>(args)...));
}
#else
void do_run()
{
try
{
R& res((f()));
this->mark_finished_with_result(res);
}
#endif
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
catch(thread_interrupted& )
{
this->mark_interrupted_finish();
}
#endif
catch(...)
{
this->mark_exceptional_finish();
}
}
};
#if defined(BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR)
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
template<typename R, typename ...ArgTypes>
struct task_shared_state<R (*)(ArgTypes...), R(ArgTypes...)>:
task_base_shared_state<R(ArgTypes...)>
#else
template<typename R>
struct task_shared_state<R (*)(), R()>:
task_base_shared_state<R()>
#endif
#else
template<typename R>
struct task_shared_state<R (*)(), R> :
task_base_shared_state<R>
#endif
{
private:
task_shared_state(task_shared_state&);
public:
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
R (*f)(BOOST_THREAD_RV_REF(ArgTypes) ... );
task_shared_state(R (*f_)(BOOST_THREAD_RV_REF(ArgTypes) ... )):
f(f_)
{}
#else
R (*f)();
task_shared_state(R (*f_)()):
f(f_)
{}
#endif
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
void do_apply(BOOST_THREAD_RV_REF(ArgTypes) ... args)
{
try
{
this->set_value_at_thread_exit(f(boost::forward<ArgTypes>(args)...));
}
#else
void do_apply()
{
try
{
R r((f()));
this->set_value_at_thread_exit(boost::move(r));
}
#endif
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
catch(thread_interrupted& )
{
this->set_interrupted_at_thread_exit();
}
#endif
catch(...)
{
this->set_exception_at_thread_exit(current_exception());
}
}
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
void do_run(BOOST_THREAD_RV_REF(ArgTypes) ... args)
{
try
{
this->mark_finished_with_result(f(boost::forward<ArgTypes>(args)...));
}
#else
void do_run()
{
try
{
R res((f()));
this->mark_finished_with_result(boost::move(res));
}
#endif
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
catch(thread_interrupted& )
{
this->mark_interrupted_finish();
}
#endif
catch(...)
{
this->mark_exceptional_finish();
}
}
};
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
template<typename R, typename ...ArgTypes>
struct task_shared_state<R& (*)(ArgTypes...), R&(ArgTypes...)>:
task_base_shared_state<R&(ArgTypes...)>
#else
template<typename R>
struct task_shared_state<R& (*)(), R&()>:
task_base_shared_state<R&()>
#endif
#else
template<typename R>
struct task_shared_state<R& (*)(), R&> :
task_base_shared_state<R&>
#endif
{
private:
task_shared_state(task_shared_state&);
public:
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
R& (*f)(BOOST_THREAD_RV_REF(ArgTypes) ... );
task_shared_state(R& (*f_)(BOOST_THREAD_RV_REF(ArgTypes) ... )):
f(f_)
{}
#else
R& (*f)();
task_shared_state(R& (*f_)()):
f(f_)
{}
#endif
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
void do_apply(BOOST_THREAD_RV_REF(ArgTypes) ... args)
{
try
{
this->set_value_at_thread_exit(f(boost::forward<ArgTypes>(args)...));
}
#else
void do_apply()
{
try
{
this->set_value_at_thread_exit(f());
}
#endif
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
catch(thread_interrupted& )
{
this->set_interrupted_at_thread_exit();
}
#endif
catch(...)
{
this->set_exception_at_thread_exit(current_exception());
}
}
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
void do_run(BOOST_THREAD_RV_REF(ArgTypes) ... args)
{
try
{
this->mark_finished_with_result(f(boost::forward<ArgTypes>(args)...));
}
#else
void do_run()
{
try
{
this->mark_finished_with_result(f());
}
#endif
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
catch(thread_interrupted& )
{
this->mark_interrupted_finish();
}
#endif
catch(...)
{
this->mark_exceptional_finish();
}
}
};
#endif
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
template<typename F, typename ...ArgTypes>
struct task_shared_state<F, void(ArgTypes...)>:
task_base_shared_state<void(ArgTypes...)>
#else
template<typename F>
struct task_shared_state<F, void()>:
task_base_shared_state<void()>
#endif
#else
template<typename F>
struct task_shared_state<F,void>:
task_base_shared_state<void>
#endif
{
private:
task_shared_state(task_shared_state&);
public:
F f;
task_shared_state(F const& f_):
f(f_)
{}
task_shared_state(BOOST_THREAD_RV_REF(F) f_):
f(boost::move(f_))
{}
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
void do_apply(BOOST_THREAD_RV_REF(ArgTypes) ... args)
{
try
{
f(boost::forward<ArgTypes>(args)...);
#else
void do_apply()
{
try
{
f();
#endif
this->set_value_at_thread_exit();
}
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
catch(thread_interrupted& )
{
this->set_interrupted_at_thread_exit();
}
#endif
catch(...)
{
this->set_exception_at_thread_exit(current_exception());
}
}
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
void do_run(BOOST_THREAD_RV_REF(ArgTypes) ... args)
{
try
{
f(boost::forward<ArgTypes>(args)...);
#else
void do_run()
{
try
{
f();
#endif
this->mark_finished_with_result();
}
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
catch(thread_interrupted& )
{
this->mark_interrupted_finish();
}
#endif
catch(...)
{
this->mark_exceptional_finish();
}
}
};
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
template<typename ...ArgTypes>
struct task_shared_state<void (*)(ArgTypes...), void(ArgTypes...)>:
task_base_shared_state<void(ArgTypes...)>
#else
template<>
struct task_shared_state<void (*)(), void()>:
task_base_shared_state<void()>
#endif
#else
template<>
struct task_shared_state<void (*)(),void>:
task_base_shared_state<void>
#endif
{
private:
task_shared_state(task_shared_state&);
public:
void (*f)();
task_shared_state(void (*f_)()):
f(f_)
{}
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
void do_apply(BOOST_THREAD_RV_REF(ArgTypes) ... args)
{
try
{
f(boost::forward<ArgTypes>(args)...);
#else
void do_apply()
{
try
{
f();
#endif
this->set_value_at_thread_exit();
}
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
catch(thread_interrupted& )
{
this->set_interrupted_at_thread_exit();
}
#endif
catch(...)
{
this->set_exception_at_thread_exit(current_exception());
}
}
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
void do_run(BOOST_THREAD_RV_REF(ArgTypes) ... args)
{
try
{
f(boost::forward<ArgTypes>(args)...);
#else
void do_run()
{
try
{
f();
#endif
this->mark_finished_with_result();
}
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
catch(thread_interrupted& )
{
this->mark_interrupted_finish();
}
#endif
catch(...)
{
this->mark_exceptional_finish();
}
}
};
}
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
template<typename R, typename ...ArgTypes>
class packaged_task<R(ArgTypes...)>
{
typedef boost::shared_ptr<detail::task_base_shared_state<R(ArgTypes...)> > task_ptr;
boost::shared_ptr<detail::task_base_shared_state<R(ArgTypes...)> > task;
#else
template<typename R>
class packaged_task<R()>
{
typedef boost::shared_ptr<detail::task_base_shared_state<R()> > task_ptr;
boost::shared_ptr<detail::task_base_shared_state<R()> > task;
#endif
#else
template<typename R>
class packaged_task
{
typedef boost::shared_ptr<detail::task_base_shared_state<R> > task_ptr;
boost::shared_ptr<detail::task_base_shared_state<R> > task;
#endif
bool future_obtained;
struct dummy;
public:
typedef R result_type;
BOOST_THREAD_MOVABLE_ONLY(packaged_task)
packaged_task():
future_obtained(false)
{}
// construction and destruction
#if defined(BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR)
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
explicit packaged_task(R(*f)(), BOOST_THREAD_FWD_REF(ArgTypes)... args)
{
typedef R(*FR)(BOOST_THREAD_FWD_REF(ArgTypes)...);
typedef detail::task_shared_state<FR,R(ArgTypes...)> task_shared_state_type;
task= task_ptr(new task_shared_state_type(f, boost::forward<ArgTypes>(args)...));
future_obtained=false;
}
#else
explicit packaged_task(R(*f)())
{
typedef R(*FR)();
typedef detail::task_shared_state<FR,R()> task_shared_state_type;
task= task_ptr(new task_shared_state_type(f));
future_obtained=false;
}
#endif
#else
explicit packaged_task(R(*f)())
{
typedef R(*FR)();
typedef detail::task_shared_state<FR,R> task_shared_state_type;
task= task_ptr(new task_shared_state_type(f));
future_obtained=false;
}
#endif
#endif
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
template <class F>
explicit packaged_task(BOOST_THREAD_FWD_REF(F) f
, typename boost::disable_if<is_same<typename decay<F>::type, packaged_task>, dummy* >::type=0
)
{
//typedef typename remove_cv<typename remove_reference<F>::type>::type FR;
typedef typename decay<F>::type FR;
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
typedef detail::task_shared_state<FR,R(ArgTypes...)> task_shared_state_type;
#else
typedef detail::task_shared_state<FR,R()> task_shared_state_type;
#endif
#else
typedef detail::task_shared_state<FR,R> task_shared_state_type;
#endif
task = task_ptr(new task_shared_state_type(boost::forward<F>(f)));
future_obtained = false;
}
#else
template <class F>
explicit packaged_task(F const& f
, typename boost::disable_if<is_same<typename decay<F>::type, packaged_task>, dummy* >::type=0
)
{
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
typedef detail::task_shared_state<F,R(ArgTypes...)> task_shared_state_type;
#else
typedef detail::task_shared_state<F,R()> task_shared_state_type;
#endif
#else
typedef detail::task_shared_state<F,R> task_shared_state_type;
#endif
task = task_ptr(new task_shared_state_type(f));
future_obtained=false;
}
template <class F>
explicit packaged_task(BOOST_THREAD_RV_REF(F) f)
{
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
typedef detail::task_shared_state<F,R(ArgTypes...)> task_shared_state_type;
task = task_ptr(new task_shared_state_type(boost::forward<F>(f)));
#else
typedef detail::task_shared_state<F,R()> task_shared_state_type;
task = task_ptr(new task_shared_state_type(boost::move(f))); // TODO forward
#endif
#else
typedef detail::task_shared_state<F,R> task_shared_state_type;
task = task_ptr(new task_shared_state_type(boost::forward<F>(f)));
#endif
future_obtained=false;
}
#endif
#if defined BOOST_THREAD_PROVIDES_FUTURE_CTOR_ALLOCATORS
#if defined(BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR)
template <class Allocator>
packaged_task(boost::allocator_arg_t, Allocator a, R(*f)())
{
typedef R(*FR)();
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
typedef detail::task_shared_state<FR,R(ArgTypes...)> task_shared_state_type;
#else
typedef detail::task_shared_state<FR,R()> task_shared_state_type;
#endif
#else
typedef detail::task_shared_state<FR,R> task_shared_state_type;
#endif
typedef typename Allocator::template rebind<task_shared_state_type>::other A2;
A2 a2(a);
typedef thread_detail::allocator_destructor<A2> D;
task = task_ptr(::new(a2.allocate(1)) task_shared_state_type(f), D(a2, 1) );
future_obtained = false;
}
#endif // BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR
#if ! defined BOOST_NO_CXX11_RVALUE_REFERENCES
template <class F, class Allocator>
packaged_task(boost::allocator_arg_t, Allocator a, BOOST_THREAD_FWD_REF(F) f)
{
//typedef typename remove_cv<typename remove_reference<F>::type>::type FR;
typedef typename decay<F>::type FR;
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
typedef detail::task_shared_state<FR,R(ArgTypes...)> task_shared_state_type;
#else
typedef detail::task_shared_state<FR,R()> task_shared_state_type;
#endif
#else
typedef detail::task_shared_state<FR,R> task_shared_state_type;
#endif
typedef typename Allocator::template rebind<task_shared_state_type>::other A2;
A2 a2(a);
typedef thread_detail::allocator_destructor<A2> D;
task = task_ptr(::new(a2.allocate(1)) task_shared_state_type(boost::forward<F>(f)), D(a2, 1) );
future_obtained = false;
}
#else // ! defined BOOST_NO_CXX11_RVALUE_REFERENCES
template <class F, class Allocator>
packaged_task(boost::allocator_arg_t, Allocator a, const F& f)
{
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
typedef detail::task_shared_state<F,R(ArgTypes...)> task_shared_state_type;
#else
typedef detail::task_shared_state<F,R()> task_shared_state_type;
#endif
#else
typedef detail::task_shared_state<F,R> task_shared_state_type;
#endif
typedef typename Allocator::template rebind<task_shared_state_type>::other A2;
A2 a2(a);
typedef thread_detail::allocator_destructor<A2> D;
task = task_ptr(::new(a2.allocate(1)) task_shared_state_type(f), D(a2, 1) );
future_obtained = false;
}
template <class F, class Allocator>
packaged_task(boost::allocator_arg_t, Allocator a, BOOST_THREAD_RV_REF(F) f)
{
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
typedef detail::task_shared_state<F,R(ArgTypes...)> task_shared_state_type;
#else
typedef detail::task_shared_state<F,R()> task_shared_state_type;
#endif
#else
typedef detail::task_shared_state<F,R> task_shared_state_type;
#endif
typedef typename Allocator::template rebind<task_shared_state_type>::other A2;
A2 a2(a);
typedef thread_detail::allocator_destructor<A2> D;
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
task = task_ptr(::new(a2.allocate(1)) task_shared_state_type(boost::forward<F>(f)), D(a2, 1) );
#else
task = task_ptr(::new(a2.allocate(1)) task_shared_state_type(boost::move(f)), D(a2, 1) ); // TODO forward
#endif
future_obtained = false;
}
#endif //BOOST_NO_CXX11_RVALUE_REFERENCES
#endif // BOOST_THREAD_PROVIDES_FUTURE_CTOR_ALLOCATORS
~packaged_task() {
if(task) {
task->owner_destroyed();
}
}
// assignment
packaged_task(BOOST_THREAD_RV_REF(packaged_task) other) BOOST_NOEXCEPT
: future_obtained(BOOST_THREAD_RV(other).future_obtained) {
task.swap(BOOST_THREAD_RV(other).task);
BOOST_THREAD_RV(other).future_obtained=false;
}
packaged_task& operator=(BOOST_THREAD_RV_REF(packaged_task) other) BOOST_NOEXCEPT {
// todo use forward
#if ! defined BOOST_NO_CXX11_RVALUE_REFERENCES
packaged_task temp(boost::move(other));
#else
packaged_task temp(static_cast<BOOST_THREAD_RV_REF(packaged_task)>(other));
#endif
swap(temp);
return *this;
}
void reset() {
if (!valid())
throw future_error(system::make_error_code(future_errc::no_state));
task->reset();
future_obtained=false;
}
void swap(packaged_task& other) BOOST_NOEXCEPT {
task.swap(other.task);
std::swap(future_obtained,other.future_obtained);
}
bool valid() const BOOST_NOEXCEPT {
return task.get()!=0;
}
// result retrieval
BOOST_THREAD_FUTURE<R> get_future() {
if(!task) {
boost::throw_exception(task_moved());
} else if(!future_obtained) {
future_obtained=true;
return BOOST_THREAD_FUTURE<R>(task);
} else {
boost::throw_exception(future_already_retrieved());
}
}
// execution
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
void operator()(BOOST_THREAD_RV_REF(ArgTypes)... args) {
if(!task) {
boost::throw_exception(task_moved());
}
task->run(boost::forward<ArgTypes>(args)...);
}
void make_ready_at_thread_exit(ArgTypes... args) {
if(!task) {
boost::throw_exception(task_moved());
}
if (task->has_value()) {
boost::throw_exception(promise_already_satisfied());
}
task->apply(boost::forward<ArgTypes>(args)...);
}
#else
void operator()() {
if(!task) {
boost::throw_exception(task_moved());
}
task->run();
}
void make_ready_at_thread_exit() {
if(!task) {
boost::throw_exception(task_moved());
}
if (task->has_value()) boost::throw_exception(promise_already_satisfied());
task->apply();
}
#endif
template<typename F>
void set_wait_callback(F f) {
task->set_wait_callback(f,this);
}
};
}
#if defined BOOST_THREAD_PROVIDES_FUTURE_CTOR_ALLOCATORS
namespace boost { namespace container {
template <class R, class Alloc>
struct uses_allocator< ::boost::packaged_task<R> , Alloc> : true_type
{};
}}
#if ! defined BOOST_NO_CXX11_ALLOCATOR
namespace std {
template <class R, class Alloc>
struct uses_allocator< ::boost::packaged_task<R> , Alloc> : true_type
{};
}
#endif
#endif
namespace boost
{
BOOST_THREAD_DCL_MOVABLE_BEG(T) packaged_task<T> BOOST_THREAD_DCL_MOVABLE_END
namespace detail
{
////////////////////////////////
// make_future_deferred_shared_state
////////////////////////////////
template <class Rp, class Fp>
BOOST_THREAD_FUTURE<Rp>
make_future_deferred_shared_state(BOOST_THREAD_FWD_REF(Fp) f) {
shared_ptr<future_deferred_shared_state<Rp, Fp> >
h(new future_deferred_shared_state<Rp, Fp>(boost::forward<Fp>(f)));
return BOOST_THREAD_FUTURE<Rp>(h);
}
////////////////////////////////
// make_future_async_shared_state
////////////////////////////////
template <class Rp, class Fp>
BOOST_THREAD_FUTURE<Rp>
make_future_async_shared_state(BOOST_THREAD_FWD_REF(Fp) f) {
shared_ptr<future_async_shared_state<Rp, Fp> >
h(new future_async_shared_state<Rp, Fp>(boost::forward<Fp>(f)));
return BOOST_THREAD_FUTURE<Rp>(h);
}
}
////////////////////////////////
// template <class F, class... ArgTypes>
// future<R> async(launch policy, F&&, ArgTypes&&...);
////////////////////////////////
#if defined BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
template <class R, class... ArgTypes>
BOOST_THREAD_FUTURE<R>
async(launch policy, R(*f)(BOOST_THREAD_FWD_REF(ArgTypes)...), BOOST_THREAD_FWD_REF(ArgTypes)... args) {
typedef R(*F)(BOOST_THREAD_FWD_REF(ArgTypes)...);
typedef detail::invoker<typename decay<F>::type, typename decay<ArgTypes>::type...> BF;
typedef typename BF::result_type Rp;
if (underlying_cast<int>(policy) & int(launch::async)) {
return BOOST_THREAD_MAKE_RV_REF(boost::detail::make_future_async_shared_state<Rp>(
BF(
thread_detail::decay_copy(boost::forward<F>(f))
, thread_detail::decay_copy(boost::forward<ArgTypes>(args))...
)
));
} else if (underlying_cast<int>(policy) & int(launch::deferred)) {
return BOOST_THREAD_MAKE_RV_REF(boost::detail::make_future_deferred_shared_state<Rp>(
BF(
thread_detail::decay_copy(boost::forward<F>(f))
, thread_detail::decay_copy(boost::forward<ArgTypes>(args))...
)
));
} else {
std::terminate();
BOOST_THREAD_FUTURE<R> ret;
return ::boost::move(ret);
}
}
#else // defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
template <class R>
BOOST_THREAD_FUTURE<R>
async(launch policy, R(*f)()) {
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
typedef packaged_task<R()> packaged_task_type;
#else
typedef packaged_task<R> packaged_task_type;
#endif
if (underlying_cast<int>(policy) & int(launch::async)) {
packaged_task_type pt( f );
BOOST_THREAD_FUTURE<R> ret = BOOST_THREAD_MAKE_RV_REF(pt.get_future());
ret.set_async();
boost::thread( boost::move(pt) ).detach();
return ::boost::move(ret);
} else if (underlying_cast<int>(policy) & int(launch::deferred)) {
std::terminate();
BOOST_THREAD_FUTURE<R> ret;
return ::boost::move(ret);
} else {
std::terminate();
BOOST_THREAD_FUTURE<R> ret;
return ::boost::move(ret);
}
}
#endif
#endif // defined(BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR)
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
template <class F, class ...ArgTypes>
BOOST_THREAD_FUTURE<typename boost::result_of<typename decay<F>::type(
typename decay<ArgTypes>::type...
)>::type>
async(launch policy, BOOST_THREAD_FWD_REF(F) f, BOOST_THREAD_FWD_REF(ArgTypes)... args) {
typedef typename boost::result_of<typename decay<F>::type(
typename decay<ArgTypes>::type...
)>::type R;
typedef detail::invoker<typename decay<F>::type, typename decay<ArgTypes>::type...> BF;
typedef typename BF::result_type Rp;
if (underlying_cast<int>(policy) & int(launch::async)) {
return BOOST_THREAD_MAKE_RV_REF(boost::detail::make_future_async_shared_state<Rp>(
BF(
thread_detail::decay_copy(boost::forward<F>(f))
, thread_detail::decay_copy(boost::forward<ArgTypes>(args))...
)
));
} else if (underlying_cast<int>(policy) & int(launch::deferred)) {
return BOOST_THREAD_MAKE_RV_REF(boost::detail::make_future_deferred_shared_state<Rp>(
BF(
thread_detail::decay_copy(boost::forward<F>(f))
, thread_detail::decay_copy(boost::forward<ArgTypes>(args))...
)
));
} else {
std::terminate();
BOOST_THREAD_FUTURE<R> ret;
return ::boost::move(ret);
}
}
#else // defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
template <class F>
BOOST_THREAD_FUTURE<typename boost::result_of<typename decay<F>::type()>::type>
async(launch policy, BOOST_THREAD_FWD_REF(F) f) {
typedef typename boost::result_of<typename decay<F>::type()>::type R;
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
typedef packaged_task<R()> packaged_task_type;
#else // defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
typedef packaged_task<R> packaged_task_type;
#endif // defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK
if (underlying_cast<int>(policy) & int(launch::async)) {
packaged_task_type pt( boost::forward<F>(f) );
BOOST_THREAD_FUTURE<R> ret = pt.get_future();
ret.set_async();
boost::thread( boost::move(pt) ).detach();
return ::boost::move(ret);
} else if (underlying_cast<int>(policy) & int(launch::deferred)) {
std::terminate();
BOOST_THREAD_FUTURE<R> ret;
return ::boost::move(ret);
// return boost::detail::make_future_deferred_shared_state<Rp>(
// BF(
// thread_detail::decay_copy(boost::forward<F>(f))
// )
// );
} else {
std::terminate();
BOOST_THREAD_FUTURE<R> ret;
return ::boost::move(ret);
}
}
#endif // defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
#ifdef BOOST_THREAD_PROVIDES_EXECUTORS
namespace detail {
/////////////////////////
/// shared_state_nullary_task
/////////////////////////
template<typename Rp, typename Fp>
struct shared_state_nullary_task
{
shared_state<Rp>* that;
Fp f_;
public:
shared_state_nullary_task(shared_state<Rp>* st, BOOST_THREAD_FWD_REF(Fp) f)
: that(st), f_(boost::forward<Fp>(f))
{};
#if ! defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
BOOST_THREAD_MOVABLE(shared_state_nullary_task)
shared_state_nullary_task(shared_state_nullary_task const& x) //BOOST_NOEXCEPT
: that(x.that), f_(x.f_)
{}
shared_state_nullary_task& operator=(BOOST_COPY_ASSIGN_REF(shared_state_nullary_task) x) //BOOST_NOEXCEPT
{
if (this != &x) {
that=x.that;
f_=x.f_;
}
return *this;
}
// move
shared_state_nullary_task(BOOST_THREAD_RV_REF(shared_state_nullary_task) x) //BOOST_NOEXCEPT
: that(x.that), f_(boost::move(x.f_))
{
x.that=0;
}
shared_state_nullary_task& operator=(BOOST_THREAD_RV_REF(shared_state_nullary_task) x) //BOOST_NOEXCEPT
{
if (this != &x) {
that=x.that;
f_=boost::move(x.f_);
x.that=0;
}
return *this;
}
#endif
void operator()() {
try {
that->mark_finished_with_result(f_());
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
} catch(thread_interrupted& ) {
that->mark_interrupted_finish();
#endif // defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
} catch(...) {
that->mark_exceptional_finish();
}
}
};
template<typename Fp>
struct shared_state_nullary_task<void, Fp>
{
shared_state<void>* that;
Fp f_;
public:
shared_state_nullary_task(shared_state<void>* st, BOOST_THREAD_FWD_REF(Fp) f)
: that(st), f_(boost::forward<Fp>(f))
{};
#if ! defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
BOOST_THREAD_MOVABLE(shared_state_nullary_task)
shared_state_nullary_task(shared_state_nullary_task const& x) //BOOST_NOEXCEPT
: that(x.that), f_(x.f_)
{}
shared_state_nullary_task& operator=(BOOST_COPY_ASSIGN_REF(shared_state_nullary_task) x) //BOOST_NOEXCEPT
{
if (this != &x) {
that=x.that;
f_=x.f_;
}
return *this;
}
// move
shared_state_nullary_task(BOOST_THREAD_RV_REF(shared_state_nullary_task) x) BOOST_NOEXCEPT
: that(x.that), f_(boost::move(x.f_))
{
x.that=0;
}
shared_state_nullary_task& operator=(BOOST_THREAD_RV_REF(shared_state_nullary_task) x) BOOST_NOEXCEPT {
if (this != &x) {
that=x.that;
f_=boost::move(x.f_);
x.that=0;
}
return *this;
}
#endif
void operator()() {
try {
f_();
that->mark_finished_with_result();
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
} catch(thread_interrupted& ) {
that->mark_interrupted_finish();
#endif // defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
} catch(...) {
that->mark_exceptional_finish();
}
}
};
template<typename Rp, typename Fp>
struct shared_state_nullary_task<Rp&, Fp>
{
shared_state<Rp&>* that;
Fp f_;
public:
shared_state_nullary_task(shared_state<Rp&>* st, BOOST_THREAD_FWD_REF(Fp) f)
: that(st), f_(boost::forward<Fp>(f))
{}
#if ! defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
BOOST_THREAD_MOVABLE(shared_state_nullary_task)
shared_state_nullary_task(shared_state_nullary_task const& x) BOOST_NOEXCEPT
: that(x.that), f_(x.f_) {}
shared_state_nullary_task& operator=(BOOST_COPY_ASSIGN_REF(shared_state_nullary_task) x) BOOST_NOEXCEPT {
if (this != &x){
that=x.that;
f_=x.f_;
}
return *this;
}
// move
shared_state_nullary_task(BOOST_THREAD_RV_REF(shared_state_nullary_task) x) BOOST_NOEXCEPT
: that(x.that), f_(boost::move(x.f_))
{
x.that=0;
}
shared_state_nullary_task& operator=(BOOST_THREAD_RV_REF(shared_state_nullary_task) x) BOOST_NOEXCEPT {
if (this != &x) {
that=x.that;
f_=boost::move(x.f_);
x.that=0;
}
return *this;
}
#endif
void operator()() {
try {
that->mark_finished_with_result(f_());
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
} catch(thread_interrupted& ) {
that->mark_interrupted_finish();
#endif // defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
} catch(...) {
that->mark_exceptional_finish();
}
}
};
/////////////////////////
/// future_executor_shared_state_base
/////////////////////////
template<typename Rp, typename Executor>
struct future_executor_shared_state: shared_state<Rp>
{
typedef shared_state<Rp> base_type;
protected:
public:
template<typename Fp>
future_executor_shared_state(Executor& ex, BOOST_THREAD_FWD_REF(Fp) f) {
this->set_executor();
shared_state_nullary_task<Rp,Fp> t(this, boost::forward<Fp>(f));
ex.submit(boost::move(t));
}
~future_executor_shared_state() {
this->wait(false);
}
};
////////////////////////////////
// make_future_executor_shared_state
////////////////////////////////
template <class Rp, class Fp, class Executor>
BOOST_THREAD_FUTURE<Rp>
make_future_executor_shared_state(Executor& ex, BOOST_THREAD_FWD_REF(Fp) f) {
shared_ptr<future_executor_shared_state<Rp, Executor> >
h(new future_executor_shared_state<Rp, Executor>(ex, boost::forward<Fp>(f)));
return BOOST_THREAD_FUTURE<Rp>(h);
}
} // detail
////////////////////////////////
// template <class Executor, class F, class... ArgTypes>
// future<R> async(Executor& ex, F&&, ArgTypes&&...);
////////////////////////////////
#if ! defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
#if defined BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR
template <class Executor, class R, class... ArgTypes>
BOOST_THREAD_FUTURE<R>
async(Executor& ex, R(*f)(BOOST_THREAD_FWD_REF(ArgTypes)...), BOOST_THREAD_FWD_REF(ArgTypes)... args) {
typedef R(*F)(BOOST_THREAD_FWD_REF(ArgTypes)...);
typedef detail::invoker<typename decay<F>::type, typename decay<ArgTypes>::type...> BF;
typedef typename BF::result_type Rp;
return BOOST_THREAD_MAKE_RV_REF(boost::detail::make_future_executor_shared_state<Rp>(ex,
BF(
thread_detail::decay_copy(boost::forward<F>(f))
, thread_detail::decay_copy(boost::forward<ArgTypes>(args))...
)
));
}
#endif // defined BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR
template <class Executor, class F, class ...ArgTypes>
BOOST_THREAD_FUTURE<typename boost::result_of<typename decay<F>::type(
typename decay<ArgTypes>::type...
)>::type>
async(Executor& ex, BOOST_THREAD_FWD_REF(F) f, BOOST_THREAD_FWD_REF(ArgTypes)... args) {
typedef detail::invoker<typename decay<F>::type, typename decay<ArgTypes>::type...> BF;
typedef typename BF::result_type Rp;
return BOOST_THREAD_MAKE_RV_REF(boost::detail::make_future_executor_shared_state<Rp>(ex,
BF(
thread_detail::decay_copy(boost::forward<F>(f))
, thread_detail::decay_copy(boost::forward<ArgTypes>(args))...
)
));
}
// template <class R, class Executor, class F, class ...ArgTypes>
// BOOST_THREAD_FUTURE<typename boost::result_of<typename decay<F>::type(
// typename decay<ArgTypes>::type...
// )>::type>
// async(Executor& ex, BOOST_THREAD_FWD_REF(F) f, BOOST_THREAD_FWD_REF(ArgTypes)... args) {
// typedef detail::invoker_ret<R, typename decay<F>::type, typename decay<ArgTypes>::type...> BF;
// typedef typename BF::result_type Rp;
//
// return BOOST_THREAD_MAKE_RV_REF(boost::detail::make_future_executor_shared_state<Rp>(ex,
// BF(
// thread_detail::decay_copy(boost::forward<F>(f))
// , thread_detail::decay_copy(boost::forward<ArgTypes>(args))...
// )
// ));
// }
#else // ! defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
#if defined BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR
template <class Executor, class R>
BOOST_THREAD_FUTURE<R>
async(Executor& ex, R(*f)()) {
typedef R(*F)();
typedef detail::invoker<F> BF;
typedef typename BF::result_type Rp;
return BOOST_THREAD_MAKE_RV_REF(boost::detail::make_future_executor_shared_state<Rp>(ex,
BF(
f
)
));
}
template <class Executor, class R, class A1>
BOOST_THREAD_FUTURE<R>
async(Executor& ex, R(*f)(BOOST_THREAD_FWD_REF(A1)), BOOST_THREAD_FWD_REF(A1) a1) {
typedef R(*F)(BOOST_THREAD_FWD_REF(A1));
typedef detail::invoker<F, typename decay<A1>::type> BF;
typedef typename BF::result_type Rp;
return BOOST_THREAD_MAKE_RV_REF(boost::detail::make_future_executor_shared_state<Rp>(ex,
BF(
f
, thread_detail::decay_copy(boost::forward<A1>(a1))
)
));
}
#endif // defined BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR
template <class Executor, class F>
BOOST_THREAD_FUTURE<typename boost::result_of<typename decay<F>::type()>::type>
async(Executor& ex, BOOST_THREAD_FWD_REF(F) f) {
typedef detail::invoker<typename decay<F>::type> BF;
typedef typename BF::result_type Rp;
return boost::detail::make_future_executor_shared_state<Rp>(ex,
BF(
thread_detail::decay_copy(boost::forward<F>(f))
)
);
}
template <class Executor, class F, class A1>
BOOST_THREAD_FUTURE<typename boost::result_of<typename decay<F>::type(
typename decay<A1>::type
)>::type>
async(Executor& ex, BOOST_THREAD_FWD_REF(F) f, BOOST_THREAD_FWD_REF(A1) a1) {
typedef detail::invoker<typename decay<F>::type, typename decay<A1>::type> BF;
typedef typename BF::result_type Rp;
return BOOST_THREAD_MAKE_RV_REF(boost::detail::make_future_executor_shared_state<Rp>(ex,
BF(
thread_detail::decay_copy(boost::forward<F>(f))
, thread_detail::decay_copy(boost::forward<A1>(a1))
)
));
}
template <class Executor, class F, class A1, class A2>
BOOST_THREAD_FUTURE<typename boost::result_of<typename decay<F>::type(
typename decay<A1>::type, typename decay<A2>::type
)>::type>
async(Executor& ex, BOOST_THREAD_FWD_REF(F) f, BOOST_THREAD_FWD_REF(A1) a1, BOOST_THREAD_FWD_REF(A2) a2) {
typedef detail::invoker<typename decay<F>::type, typename decay<A1>::type, typename decay<A2>::type> BF;
typedef typename BF::result_type Rp;
return BOOST_THREAD_MAKE_RV_REF(boost::detail::make_future_executor_shared_state<Rp>(ex,
BF(
thread_detail::decay_copy(boost::forward<F>(f))
, thread_detail::decay_copy(boost::forward<A1>(a1))
, thread_detail::decay_copy(boost::forward<A2>(a2))
)
));
}
#endif //! defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
#endif
////////////////////////////////
// template <class F, class... ArgTypes>
// future<R> async(F&&, ArgTypes&&...);
////////////////////////////////
#if defined BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
template <class R, class... ArgTypes>
BOOST_THREAD_FUTURE<R>
async(R(*f)(BOOST_THREAD_FWD_REF(ArgTypes)...), BOOST_THREAD_FWD_REF(ArgTypes)... args) {
return BOOST_THREAD_MAKE_RV_REF(async(launch(launch::any), f, boost::forward<ArgTypes>(args)...));
}
#else
template <class R>
BOOST_THREAD_FUTURE<R>
async(R(*f)()) {
return BOOST_THREAD_MAKE_RV_REF(async(launch(launch::any), f));
}
#endif
#endif
#if defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
template <class F, class ...ArgTypes>
BOOST_THREAD_FUTURE<typename boost::result_of<typename decay<F>::type(
typename decay<ArgTypes>::type...
)>::type>
async(BOOST_THREAD_FWD_REF(F) f, BOOST_THREAD_FWD_REF(ArgTypes)... args) {
return BOOST_THREAD_MAKE_RV_REF(async(launch(launch::any), boost::forward<F>(f), boost::forward<ArgTypes>(args)...));
}
#else
template <class F>
BOOST_THREAD_FUTURE<typename boost::result_of<F()>::type>
async(BOOST_THREAD_RV_REF(F) f) {
return BOOST_THREAD_MAKE_RV_REF(async(launch(launch::any), boost::forward<F>(f)));
}
#endif
////////////////////////////////
// make_future deprecated
////////////////////////////////
template <typename T>
BOOST_THREAD_FUTURE<typename decay<T>::type> make_future(BOOST_THREAD_FWD_REF(T) value) {
typedef typename decay<T>::type future_value_type;
promise<future_value_type> p;
p.set_value(boost::forward<future_value_type>(value));
return BOOST_THREAD_MAKE_RV_REF(p.get_future());
}
#if defined BOOST_THREAD_USES_MOVE
inline BOOST_THREAD_FUTURE<void> make_future() {
promise<void> p;
p.set_value();
return BOOST_THREAD_MAKE_RV_REF(p.get_future());
}
#endif
////////////////////////////////
// make_ready_future
////////////////////////////////
template <typename T>
BOOST_THREAD_FUTURE<typename decay<T>::type> make_ready_future(BOOST_THREAD_FWD_REF(T) value) {
typedef typename decay<T>::type future_value_type;
promise<future_value_type> p;
p.set_value(boost::forward<future_value_type>(value));
return BOOST_THREAD_MAKE_RV_REF(p.get_future());
}
template <typename T, typename T1>
BOOST_THREAD_FUTURE<T> make_ready_no_decay_future(T1 value) {
typedef T future_value_type;
promise<future_value_type> p;
p.set_value(value);
return BOOST_THREAD_MAKE_RV_REF(p.get_future());
}
#if defined BOOST_THREAD_USES_MOVE
inline BOOST_THREAD_FUTURE<void> make_ready_future() {
promise<void> p;
p.set_value();
return BOOST_THREAD_MAKE_RV_REF(p.get_future());
}
#endif
template <typename T>
BOOST_THREAD_FUTURE<T> make_ready_future(exception_ptr ex) {
promise<T> p;
p.set_exception(ex);
return BOOST_THREAD_MAKE_RV_REF(p.get_future());
}
// template <typename T, typename E>
// BOOST_THREAD_FUTURE<T> make_ready_future(E ex)
// {
// promise<T> p;
// p.set_exception(boost::copy_exception(ex));
// return BOOST_THREAD_MAKE_RV_REF(p.get_future());
// }
template <typename T>
BOOST_THREAD_FUTURE<T> make_exceptional_future(exception_ptr ex) {
promise<T> p;
p.set_exception(ex);
return BOOST_THREAD_MAKE_RV_REF(p.get_future());
}
template <typename T, typename E>
BOOST_THREAD_FUTURE<T> make_exceptional_future(E ex) {
promise<T> p;
p.set_exception(boost::copy_exception(ex));
return BOOST_THREAD_MAKE_RV_REF(p.get_future());
}
template <typename T>
BOOST_THREAD_FUTURE<T> make_exceptional_future() {
promise<T> p;
p.set_exception(boost::current_exception());
return BOOST_THREAD_MAKE_RV_REF(p.get_future());
}
#if 0
template<typename CLOSURE>
make_future(CLOSURE closure) -> BOOST_THREAD_FUTURE<decltype(closure())> {
typedef decltype(closure()) T;
promise<T> p;
try {
p.set_value(closure());
} catch(...) {
p.set_exception(std::current_exception());
}
return BOOST_THREAD_MAKE_RV_REF(p.get_future());
}
#endif
////////////////////////////////
// make_shared_future deprecated
////////////////////////////////
template <typename T>
shared_future<typename decay<T>::type> make_shared_future(BOOST_THREAD_FWD_REF(T) value) {
typedef typename decay<T>::type future_type;
promise<future_type> p;
p.set_value(boost::forward<T>(value));
return BOOST_THREAD_MAKE_RV_REF(p.get_future().share());
}
inline shared_future<void> make_shared_future() {
promise<void> p;
return BOOST_THREAD_MAKE_RV_REF(p.get_future().share());
}
// ////////////////////////////////
// // make_ready_shared_future
// ////////////////////////////////
// template <typename T>
// shared_future<typename decay<T>::type> make_ready_shared_future(BOOST_THREAD_FWD_REF(T) value)
// {
// typedef typename decay<T>::type future_type;
// promise<future_type> p;
// p.set_value(boost::forward<T>(value));
// return p.get_future().share();
// }
//
//
// inline shared_future<void> make_ready_shared_future()
// {
// promise<void> p;
// return BOOST_THREAD_MAKE_RV_REF(p.get_future().share());
//
// }
//
// ////////////////////////////////
// // make_exceptional_shared_future
// ////////////////////////////////
// template <typename T>
// shared_future<T> make_exceptional_shared_future(exception_ptr ex)
// {
// promise<T> p;
// p.set_exception(ex);
// return p.get_future().share();
// }
////////////////////////////////
// detail::future_async_continuation_shared_state
////////////////////////////////
#if defined BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION
namespace detail
{
/////////////////////////
/// future_async_continuation_shared_state
/////////////////////////
template<typename F, typename Rp, typename Fp>
struct future_async_continuation_shared_state: future_async_shared_state_base<Rp>
{
F parent;
Fp continuation;
public:
future_async_continuation_shared_state(BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c)
: parent(boost::move(f)),
continuation(boost::move(c)) {
}
void launch_continuation(boost::unique_lock<boost::mutex>& ) {
//lock.unlock();
this->thr_ = thread(&future_async_continuation_shared_state::run, this);
}
static void run(future_async_continuation_shared_state* that) {
try {
that->mark_finished_with_result(that->continuation(boost::move(that->parent)));
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
} catch(thread_interrupted& ) {
that->mark_interrupted_finish();
#endif
} catch(...) {
that->mark_exceptional_finish();
}
}
~future_async_continuation_shared_state() {
this->join();
}
};
template<typename F, typename Fp>
struct future_async_continuation_shared_state<F, void, Fp>: public future_async_shared_state_base<void>
{
F parent;
Fp continuation;
public:
future_async_continuation_shared_state(BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c)
: parent(boost::move(f)),
continuation(boost::move(c)) {
}
void launch_continuation(boost::unique_lock<boost::mutex>& ) {
//lk.unlock();
this->thr_ = thread(&future_async_continuation_shared_state::run, this);
}
static void run(future_async_continuation_shared_state* that) {
try {
that->continuation(boost::move(that->parent));
that->mark_finished_with_result();
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
} catch(thread_interrupted& ) {
that->mark_interrupted_finish();
#endif
} catch(...) {
that->mark_exceptional_finish();
}
}
~future_async_continuation_shared_state() {
this->join();
}
};
//////////////////////////
/// future_deferred_continuation_shared_state
//////////////////////////
template<typename F, typename Rp, typename Fp>
struct future_deferred_continuation_shared_state: shared_state<Rp>
{
F parent;
Fp continuation;
public:
future_deferred_continuation_shared_state(BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c)
: parent(boost::move(f)),
continuation(boost::move(c)) {
this->set_deferred();
}
virtual void launch_continuation(boost::unique_lock<boost::mutex>& ) {
//execute(lk);
}
virtual void execute(boost::unique_lock<boost::mutex>& lck) {
try {
Fp local_fuct=boost::move(continuation);
F ftmp = boost::move(parent);
relocker relock(lck);
Rp res = local_fuct(boost::move(ftmp));
relock.lock();
this->mark_finished_with_result_internal(boost::move(res), lck);
} catch (...) {
this->mark_exceptional_finish_internal(current_exception(), lck);
}
}
};
template<typename F, typename Fp>
struct future_deferred_continuation_shared_state<F,void,Fp>: shared_state<void>
{
F parent;
Fp continuation;
public:
future_deferred_continuation_shared_state(BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c)
: parent(boost::move(f)),
continuation(boost::move(c)) {
this->set_deferred();
}
virtual void launch_continuation(boost::unique_lock<boost::mutex>& ) {
//execute(lk);
}
virtual void execute(boost::unique_lock<boost::mutex>& lck) {
try {
Fp local_fuct=boost::move(continuation);
F ftmp = boost::move(parent);
relocker relock(lck);
local_fuct(boost::move(ftmp));
relock.lock();
this->mark_finished_with_result_internal(lck);
} catch (...) {
this->mark_exceptional_finish_internal(current_exception(), lck);
}
}
};
////////////////////////////////
// make_future_deferred_continuation_shared_state
////////////////////////////////
template<typename F, typename Rp, typename Fp>
BOOST_THREAD_FUTURE<Rp>
make_future_deferred_continuation_shared_state(
boost::unique_lock<boost::mutex> &lock,
BOOST_THREAD_RV_REF(F) f, BOOST_THREAD_FWD_REF(Fp) c) {
shared_ptr<future_deferred_continuation_shared_state<F, Rp, Fp> >
h(new future_deferred_continuation_shared_state<F, Rp, Fp>(boost::move(f), boost::forward<Fp>(c)));
h->parent.future_->set_continuation_ptr(h, lock);
return BOOST_THREAD_FUTURE<Rp>(h);
}
////////////////////////////////
// make_future_async_continuation_shared_state
////////////////////////////////
template<typename F, typename Rp, typename Fp>
BOOST_THREAD_FUTURE<Rp>
make_future_async_continuation_shared_state(
boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f,
BOOST_THREAD_FWD_REF(Fp) c) {
shared_ptr<future_async_continuation_shared_state<F,Rp, Fp> >
h(new future_async_continuation_shared_state<F,Rp, Fp>(boost::move(f), boost::forward<Fp>(c)));
h->parent.future_->set_continuation_ptr(h, lock);
return BOOST_THREAD_FUTURE<Rp>(h);
}
}
////////////////////////////////
// template<typename F>
// auto future<R>::then(F&& func) -> BOOST_THREAD_FUTURE<decltype(func(*this))>;
////////////////////////////////
template <typename R>
template <typename F>
inline BOOST_THREAD_FUTURE<typename boost::result_of<F(BOOST_THREAD_FUTURE<R>)>::type>
BOOST_THREAD_FUTURE<R>::then(launch policy, BOOST_THREAD_FWD_REF(F) func) {
typedef typename boost::result_of<F(BOOST_THREAD_FUTURE<R>)>::type future_type;
BOOST_THREAD_ASSERT_PRECONDITION(this->future_!=0, future_uninitialized());
boost::unique_lock<boost::mutex> lock(this->future_->mutex);
if (underlying_cast<int>(policy) & int(launch::async)) {
return BOOST_THREAD_MAKE_RV_REF((boost::detail::make_future_async_continuation_shared_state<BOOST_THREAD_FUTURE<R>, future_type, F>(
lock, boost::move(*this), boost::forward<F>(func)
)));
} else if (underlying_cast<int>(policy) & int(launch::deferred)) {
return BOOST_THREAD_MAKE_RV_REF((boost::detail::make_future_deferred_continuation_shared_state<BOOST_THREAD_FUTURE<R>, future_type, F>(
lock, boost::move(*this), boost::forward<F>(func)
)));
} else {
return BOOST_THREAD_MAKE_RV_REF((boost::detail::make_future_async_continuation_shared_state<BOOST_THREAD_FUTURE<R>, future_type, F>(
lock, boost::move(*this), boost::forward<F>(func)
)));
}
}
template <typename R>
template <typename F>
inline BOOST_THREAD_FUTURE<typename boost::result_of<F(BOOST_THREAD_FUTURE<R>)>::type>
BOOST_THREAD_FUTURE<R>::then(BOOST_THREAD_FWD_REF(F) func) {
typedef typename boost::result_of<F(BOOST_THREAD_FUTURE<R>)>::type future_type;
BOOST_THREAD_ASSERT_PRECONDITION(this->future_!=0, future_uninitialized());
boost::unique_lock<boost::mutex> lock(this->future_->mutex);
if (underlying_cast<int>(this->launch_policy(lock)) & int(launch::async)) {
return boost::detail::make_future_async_continuation_shared_state<BOOST_THREAD_FUTURE<R>, future_type, F>(
lock, boost::move(*this), boost::forward<F>(func)
);
} else if (underlying_cast<int>(this->launch_policy(lock)) & int(launch::deferred)) {
this->future_->wait_internal(lock);
return boost::detail::make_future_deferred_continuation_shared_state<BOOST_THREAD_FUTURE<R>, future_type, F>(
lock, boost::move(*this), boost::forward<F>(func)
);
} else {
return boost::detail::make_future_async_continuation_shared_state<BOOST_THREAD_FUTURE<R>, future_type, F>(
lock, boost::move(*this), boost::forward<F>(func)
);
}
}
//#if 0 && defined(BOOST_THREAD_RVALUE_REFERENCES_DONT_MATCH_FUNTION_PTR)
// template <typename R>
// template<typename RF>
// BOOST_THREAD_FUTURE<RF>
// BOOST_THREAD_FUTURE<R>::then(RF(*func)(BOOST_THREAD_FUTURE<R>&))
// {
//
// typedef RF future_type;
//
// if (this->future_)
// {
// boost::unique_lock<boost::mutex> lock(this->future_->mutex);
// detail::future_continuation<BOOST_THREAD_FUTURE<R>, future_type, RF(*)(BOOST_THREAD_FUTURE&) > *ptr =
// new detail::future_continuation<BOOST_THREAD_FUTURE<R>, future_type, RF(*)(BOOST_THREAD_FUTURE&)>(*this, func);
// if (ptr==0)
// {
// return BOOST_THREAD_MAKE_RV_REF(BOOST_THREAD_FUTURE<future_type>());
// }
// this->future_->set_continuation_ptr(ptr, lock);
// return ptr->get_future();
// } else {
// // fixme what to do when the future has no associated state?
// return BOOST_THREAD_MAKE_RV_REF(BOOST_THREAD_FUTURE<future_type>());
// }
//
// }
// template <typename R>
// template<typename RF>
// BOOST_THREAD_FUTURE<RF>
// BOOST_THREAD_FUTURE<R>::then(launch policy, RF(*func)(BOOST_THREAD_FUTURE<R>&))
// {
//
// typedef RF future_type;
//
// if (this->future_)
// {
// boost::unique_lock<boost::mutex> lock(this->future_->mutex);
// detail::future_continuation<BOOST_THREAD_FUTURE<R>, future_type, RF(*)(BOOST_THREAD_FUTURE&) > *ptr =
// new detail::future_continuation<BOOST_THREAD_FUTURE<R>, future_type, RF(*)(BOOST_THREAD_FUTURE&)>(*this, func, policy);
// if (ptr==0)
// {
// return BOOST_THREAD_MAKE_RV_REF(BOOST_THREAD_FUTURE<future_type>());
// }
// this->future_->set_continuation_ptr(ptr, lock);
// return ptr->get_future();
// } else {
// // fixme what to do when the future has no associated state?
// return BOOST_THREAD_MAKE_RV_REF(BOOST_THREAD_FUTURE<future_type>());
// }
//
// }
//#endif
template <typename R>
template <typename F>
inline BOOST_THREAD_FUTURE<typename boost::result_of<F(shared_future<R>)>::type>
shared_future<R>::then(launch policy, BOOST_THREAD_FWD_REF(F) func)
{
typedef typename boost::result_of<F(shared_future<R>)>::type future_type;
BOOST_THREAD_ASSERT_PRECONDITION(this->future_!=0, future_uninitialized());
boost::unique_lock<boost::mutex> lock(this->future_->mutex);
if (underlying_cast<int>(policy) & int(launch::async)) {
return BOOST_THREAD_MAKE_RV_REF((boost::detail::make_future_async_continuation_shared_state<shared_future<R>, future_type, F>(
lock, boost::move(*this), boost::forward<F>(func)
)));
} else if (underlying_cast<int>(policy) & int(launch::deferred)) {
return BOOST_THREAD_MAKE_RV_REF((boost::detail::make_future_deferred_continuation_shared_state<shared_future<R>, future_type, F>(
lock, boost::move(*this), boost::forward<F>(func)
)));
} else {
return BOOST_THREAD_MAKE_RV_REF((boost::detail::make_future_async_continuation_shared_state<shared_future<R>, future_type, F>(
lock, boost::move(*this), boost::forward<F>(func)
)));
}
}
template <typename R>
template <typename F>
inline BOOST_THREAD_FUTURE<typename boost::result_of<F(shared_future<R>)>::type>
shared_future<R>::then(BOOST_THREAD_FWD_REF(F) func) {
typedef typename boost::result_of<F(shared_future<R>)>::type future_type;
BOOST_THREAD_ASSERT_PRECONDITION(this->future_!=0, future_uninitialized());
boost::unique_lock<boost::mutex> lock(this->future_->mutex);
if (underlying_cast<int>(this->launch_policy(lock)) & int(launch::async)) {
return boost::detail::make_future_async_continuation_shared_state<shared_future<R>, future_type, F>(
lock, boost::move(*this), boost::forward<F>(func));
} else if (underlying_cast<int>(this->launch_policy(lock)) & int(launch::deferred)) {
this->future_->wait_internal(lock);
return boost::detail::make_future_deferred_continuation_shared_state<shared_future<R>, future_type, F>(
lock, boost::move(*this), boost::forward<F>(func));
} else {
return boost::detail::make_future_async_continuation_shared_state<shared_future<R>, future_type, F>(
lock, boost::move(*this), boost::forward<F>(func));
}
}
namespace detail
{
template <typename T>
struct mfallbacker_to
{
T value_;
typedef T result_type;
mfallbacker_to(BOOST_THREAD_RV_REF(T) v)
: value_(boost::move(v))
{}
T operator()(BOOST_THREAD_FUTURE<T> fut) {
return fut.get_or(boost::move(value_));
}
};
template <typename T>
struct cfallbacker_to
{
T value_;
typedef T result_type;
cfallbacker_to(T const& v)
: value_(v)
{}
T operator()(BOOST_THREAD_FUTURE<T> fut) {
return fut.get_or(value_);
}
};
}
////////////////////////////////
// future<R> future<R>::fallback_to(R&& v);
////////////////////////////////
template <typename R>
template <typename R2>
inline typename boost::disable_if< is_void<R2>, BOOST_THREAD_FUTURE<R> >::type
BOOST_THREAD_FUTURE<R>::fallback_to(BOOST_THREAD_RV_REF(R2) v) {
return then(detail::mfallbacker_to<R>(boost::move(v)));
}
template <typename R>
template <typename R2>
inline typename boost::disable_if< is_void<R2>, BOOST_THREAD_FUTURE<R> >::type
BOOST_THREAD_FUTURE<R>::fallback_to(R2 const& v) {
return then(detail::cfallbacker_to<R>(v));
}
#endif
#if defined BOOST_THREAD_PROVIDES_FUTURE_UNWRAP
namespace detail
{
/////////////////////////
/// future_unwrap_shared_state
/////////////////////////
template<typename F, typename Rp>
struct future_unwrap_shared_state: shared_state<Rp>
{
F parent;
public:
explicit future_unwrap_shared_state(BOOST_THREAD_RV_REF(F) f)
: parent(boost::move(f)) {}
virtual void wait(bool ) { // todo see if rethrow must be used
boost::unique_lock<boost::mutex> lock(mutex);
parent.get().wait();
}
virtual Rp get() {
boost::unique_lock<boost::mutex> lock(mutex);
return parent.get().get();
}
};
template <class F, class Rp>
BOOST_THREAD_FUTURE<Rp>
make_future_unwrap_shared_state(boost::unique_lock<boost::mutex> &lock, BOOST_THREAD_RV_REF(F) f) {
shared_ptr<future_unwrap_shared_state<F, Rp> >
h(new future_unwrap_shared_state<F, Rp>(boost::move(f)));
h->parent.future_->set_continuation_ptr(h, lock);
return BOOST_THREAD_FUTURE<Rp>(h);
}
}
template <typename R>
inline BOOST_THREAD_FUTURE<R>::BOOST_THREAD_FUTURE(BOOST_THREAD_RV_REF(BOOST_THREAD_FUTURE<BOOST_THREAD_FUTURE<R> >) other)
: base_type(other.unwrap()) {}
template <typename R2>
BOOST_THREAD_FUTURE<R2>
BOOST_THREAD_FUTURE<BOOST_THREAD_FUTURE<R2> >::unwrap()
{
BOOST_THREAD_ASSERT_PRECONDITION(this->future_!=0, future_uninitialized());
boost::unique_lock<boost::mutex> lock(this->future_->mutex);
return boost::detail::make_future_unwrap_shared_state<BOOST_THREAD_FUTURE<BOOST_THREAD_FUTURE<R2> >, R2>(lock, boost::move(*this));
}
#endif
#if defined BOOST_THREAD_PROVIDES_FUTURE_WHEN_ALL_WHEN_ANY
namespace detail
{
struct input_iterator_tag {};
struct vector_tag {};
struct values_tag {};
template <typename T>
struct alias_t { typedef T type; };
BOOST_CONSTEXPR_OR_CONST input_iterator_tag input_iterator_tag_value = {};
BOOST_CONSTEXPR_OR_CONST vector_tag vector_tag_value = {};
BOOST_CONSTEXPR_OR_CONST values_tag values_tag_value = {};
////////////////////////////////
// detail::future_async_when_all_shared_state
////////////////////////////////
template<typename F>
struct future_when_all_vector_shared_state: future_async_shared_state_base<csbl::vector<F> >
{
typedef csbl::vector<F> vector_type;
typedef typename F::value_type value_type;
csbl::vector<F> vec_;
static void run(future_when_all_vector_shared_state* that) {
try {
boost::wait_for_all(that->vec_.begin(), that->vec_.end());
that->mark_finished_with_result(boost::move(that->vec_));
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
} catch(thread_interrupted& ) {
that->mark_interrupted_finish();
#endif
} catch(...) {
that->mark_exceptional_finish();
}
}
void init() {
this->thr_ = thread(&future_when_all_vector_shared_state::run, this);
}
public:
template< typename InputIterator>
future_when_all_vector_shared_state(input_iterator_tag, InputIterator first, InputIterator last)
: vec_(std::make_move_iterator(first), std::make_move_iterator(last))
{
init();
}
future_when_all_vector_shared_state(vector_tag, BOOST_THREAD_RV_REF(csbl::vector<F>) v)
: vec_(boost::move(v))
{
init();
}
#if ! defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
template< typename T0, typename ...T>
future_when_all_vector_shared_state(values_tag, BOOST_THREAD_RV_REF(T0) f, BOOST_THREAD_RV_REF(T) ... futures) {
vec_.push_back(boost::forward<T0>(f));
typename alias_t<char[]>::type{
( //first part of magic unpacker
vec_.push_back(boost::forward<T>(futures)),'0'
)..., '0'
}; //second part of magic unpacker
init();
}
#else
#endif
~future_when_all_vector_shared_state() {
this->join();
}
};
////////////////////////////////
// detail::future_async_when_any_shared_state
////////////////////////////////
template<typename F>
struct future_when_any_vector_shared_state: future_async_shared_state_base<csbl::vector<F> >
{
typedef csbl::vector<F> vector_type;
typedef typename F::value_type value_type;
csbl::vector<F> vec_;
static void run(future_when_any_vector_shared_state* that)
{
try {
boost::wait_for_any(that->vec_.begin(), that->vec_.end());
that->mark_finished_with_result(boost::move(that->vec_));
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
} catch(thread_interrupted& ) {
that->mark_interrupted_finish();
#endif
} catch(...) {
that->mark_exceptional_finish();
}
}
void init() {
this->thr_ = thread(&future_when_any_vector_shared_state::run, this);
}
public:
template< typename InputIterator>
future_when_any_vector_shared_state(input_iterator_tag, InputIterator first, InputIterator last)
: vec_(std::make_move_iterator(first), std::make_move_iterator(last))
{
init();
}
future_when_any_vector_shared_state(vector_tag, BOOST_THREAD_RV_REF(csbl::vector<F>) v)
: vec_(boost::move(v))
{
init();
}
#if ! defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
template< typename T0, typename ...T>
future_when_any_vector_shared_state(values_tag,
BOOST_THREAD_RV_REF(T0) f, BOOST_THREAD_RV_REF(T) ... futures
) {
vec_.push_back(boost::forward<T0>(f));
typename alias_t<char[]>::type{
( //first part of magic unpacker
vec_.push_back(boost::forward<T>(futures))
,'0'
)...,
'0'
}; //second part of magic unpacker
init();
}
#endif
~future_when_any_vector_shared_state() {
this->join();
}
};
#if ! defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
//#if ! defined(BOOST_NO_CXX11_HDR_TUPLE)
template< typename T0, typename ...T>
struct future_when_all_tuple_shared_state: future_async_shared_state_base<
csbl::tuple<BOOST_THREAD_FUTURE<typename T0::value_type>, BOOST_THREAD_FUTURE<typename T::value_type>... >
>
{
};
template< typename T0, typename ...T>
struct future_when_any_tuple_shared_state: future_async_shared_state_base<
csbl::tuple<BOOST_THREAD_FUTURE<typename T0::value_type>, BOOST_THREAD_FUTURE<typename T::value_type>... >
>
{
};
//#endif
#endif
#if ! defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
template< typename ...T>
struct are_same : true_type {};
template< typename T0 >
struct are_same<T0> : true_type {};
template< typename T0, typename T1, typename ...T>
struct are_same<T0, T1, T...> : integral_constant<bool, is_same<T0,T1>::value && are_same<T1, T...>::value> {};
template< bool AreSame, typename T0, typename ...T>
struct when_type_impl;
template< typename T0, typename ...T>
struct when_type_impl<true, T0, T...>
{
typedef csbl::vector<typename decay<T0>::type> container_type;
typedef typename container_type::value_type value_type;
typedef detail::future_when_all_vector_shared_state<value_type> factory_all_type;
typedef detail::future_when_any_vector_shared_state<value_type> factory_any_type;
};
//#if ! defined(BOOST_NO_CXX11_HDR_TUPLE)
template< typename T0, typename ...T>
struct when_type_impl<false, T0, T...>
{
typedef csbl::tuple<BOOST_THREAD_FUTURE<typename T0::value_type>, BOOST_THREAD_FUTURE<typename T::value_type>... > container_type;
typedef detail::future_when_all_tuple_shared_state<T0, T...> factory_all_type;
typedef detail::future_when_any_tuple_shared_state<T0, T...> factory_any_type;
};
//#endif
template< typename T0, typename ...T>
struct when_type : when_type_impl<are_same<T0, T...>::value, T0, T...> {};
#endif
}
template< typename InputIterator>
typename boost::disable_if<is_future_type<InputIterator>,
BOOST_THREAD_FUTURE<csbl::vector<typename InputIterator::value_type> >
>::type
when_all(InputIterator first, InputIterator last) {
typedef typename InputIterator::value_type value_type;
typedef csbl::vector<value_type> container_type;
typedef detail::future_when_all_vector_shared_state<value_type> factory_type;
if (first==last) return make_ready_future(container_type());
shared_ptr<factory_type >
h(new factory_type>(detail::input_iterator_tag_value, first,last));
return BOOST_THREAD_FUTURE<container_type>(h);
}
//#if ! defined(BOOST_NO_CXX11_HDR_TUPLE)
inline BOOST_THREAD_FUTURE<csbl::tuple<> > when_all() {
return make_ready_future(csbl::tuple<>());
}
//#endif
#if ! defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
template< typename T0, typename ...T>
BOOST_THREAD_FUTURE<typename detail::when_type<T0, T...>::container_type>
when_all(BOOST_THREAD_RV_REF(T0) f, BOOST_THREAD_RV_REF(T) ... futures) {
typedef typename detail::when_type<T0, T...>::container_type container_type;
typedef typename detail::when_type<T0, T...>::factory_all_type factory_type;
shared_ptr<factory_type>
h(new factory_type(detail::values_tag_value, boost::forward<T0>(f), boost::forward<T>(futures)...));
return BOOST_THREAD_FUTURE<container_type>(h);
}
#endif
template< typename InputIterator>
typename boost::disable_if<is_future_type<InputIterator>,
BOOST_THREAD_FUTURE<csbl::vector<typename InputIterator::value_type> >
>::type
when_any(InputIterator first, InputIterator last) {
typedef typename InputIterator::value_type value_type;
typedef csbl::vector<value_type> container_type;
typedef detail::future_when_any_vector_shared_state<value_type> factory_type;
if (first==last) return make_ready_future(container_type());
shared_ptr<factory_type >
h(new factory_type>(detail::input_iterator_tag_value, first,last));
return BOOST_THREAD_FUTURE<container_type>(h);
}
//#if ! defined(BOOST_NO_CXX11_HDR_TUPLE)
inline BOOST_THREAD_FUTURE<csbl::tuple<> > when_any() {
return make_ready_future(csbl::tuple<>());
}
//#endif
#if ! defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
template< typename T0, typename ...T>
BOOST_THREAD_FUTURE<typename detail::when_type<T0, T...>::container_type>
when_any(BOOST_THREAD_RV_REF(T0) f, BOOST_THREAD_RV_REF(T) ... futures) {
typedef typename detail::when_type<T0, T...>::container_type container_type;
typedef typename detail::when_type<T0, T...>::factory_any_type factory_type;
shared_ptr<factory_type>
h(new factory_type(detail::values_tag_value, boost::forward<T0>(f), boost::forward<T>(futures)...));
return BOOST_THREAD_FUTURE<container_type>(h);
}
#endif
#endif // BOOST_THREAD_PROVIDES_FUTURE_WHEN_ALL_WHEN_ANY
}
#endif // BOOST_NO_EXCEPTION
#endif // header
| {
"content_hash": "20ca55339b2811ec2ec542847e72d2e4",
"timestamp": "",
"source": "github",
"line_count": 4831,
"max_line_length": 170,
"avg_line_length": 33.97743738356448,
"alnum_prop": 0.5416491516646867,
"repo_name": "xissburg/XDefrac",
"id": "44f30d724553e733cd21eb3ca48d859d0007c037",
"size": "164409",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "boost/thread/future.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "9408801"
},
{
"name": "C++",
"bytes": "112947287"
},
{
"name": "Cuda",
"bytes": "97077"
},
{
"name": "Erlang",
"bytes": "286"
},
{
"name": "FLUX",
"bytes": "8351"
},
{
"name": "Objective-C",
"bytes": "171241"
},
{
"name": "Objective-C++",
"bytes": "8498"
},
{
"name": "PHP",
"bytes": "86"
},
{
"name": "Perl",
"bytes": "197851"
},
{
"name": "Python",
"bytes": "5345"
},
{
"name": "R",
"bytes": "4052"
},
{
"name": "Ruby",
"bytes": "12845"
},
{
"name": "Shell",
"bytes": "37402"
}
],
"symlink_target": ""
} |
typedef unsigned int uint32;
typedef struct {
uint32 moves,
reuses,
inplace,
additions,
deletions,
stringLen;
} EditStat;
void initEditStat(EditStat *est);
inline EditStat *allocEditStat(void);
EditStat *allocAndInitEditStat(void);
void printStat(const EditStat *);
int getRank(const char *query, const char *from);
EditStat *getEditStats(const char *subject, const char *base);
#endif
| {
"content_hash": "c63d6254da6dade32f528fbdd9d81de6",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 64,
"avg_line_length": 21.45,
"alnum_prop": 0.7062937062937062,
"repo_name": "odeke-em/rodats",
"id": "de0610d4bd8dcf820f5850a4bd74fe92978994e6",
"size": "530",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "hashtable/wordTransition.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "89274"
},
{
"name": "C++",
"bytes": "2012"
},
{
"name": "Makefile",
"bytes": "1420"
}
],
"symlink_target": ""
} |
package wint.sessionx.provider.cookie;
import wint.lang.utils.CollectionUtil;
import wint.lang.utils.MapUtil;
import wint.sessionx.constants.SpecSessionKeys;
import wint.sessionx.cookie.WintCookie;
import wint.sessionx.provider.BaseConfig;
import wint.sessionx.provider.batch.BatchGetReceiver;
import wint.sessionx.provider.batch.BatchSetter;
import wint.sessionx.provider.batch.CookieSessionAttributeReader;
import wint.sessionx.provider.batch.CookieSessionAttributeWriter;
import wint.sessionx.provider.sessionid.SessionIdGenerator;
import wint.sessionx.store.AbstractSessionStore;
import wint.sessionx.store.SessionData;
import java.util.Map;
import java.util.Set;
/**
* Created by pister on 14-2-26.
*/
public class CookieSessionStore extends AbstractSessionStore {
private CookieSessionConfig config;
private SessionIdGenerator sessionIdGenerator;
private Map<String, SessionData> orgData = MapUtil.newHashMap();
private Set<String> toBeDeleteNames = CollectionUtil.newHashSet();
private Map<String, SessionData> updatedData = MapUtil.newHashMap();
private CookieCodec cookieCodec;
public CookieSessionStore(CookieCodec cookieCodec, CookieSessionConfig config, SessionIdGenerator sessionIdGenerator) {
this.cookieCodec = cookieCodec;
this.config = config;
this.sessionIdGenerator = sessionIdGenerator;
}
@Override
public String getSessionId() {
return getString(SpecSessionKeys.SESSION_ID);
}
public void set(String name, SessionData data) {
updatedData.put(name, data);
toBeDeleteNames.remove(name);
}
public SessionData get(String name) {
if (toBeDeleteNames.contains(name)) {
return null;
}
SessionData ret = updatedData.get(name);
if (ret != null) {
return ret;
}
return orgData.get(name);
}
@Override
public void batchGet(BatchGetReceiver batchGetReceiver) {
batchGetReceiver.onReceive(new CookieSessionAttributeReader(this));
}
@Override
public void batchSet(BatchSetter batchSetter) {
batchSetter.onSet(new CookieSessionAttributeWriter(this));
}
public void remove(String name) {
updatedData.remove(name);
toBeDeleteNames.add(name);
}
public Set<String> getNames() {
Set<String> ret = CollectionUtil.newHashSet();
ret.addAll(orgData.keySet());
ret.addAll(updatedData.keySet());
ret.removeAll(toBeDeleteNames);
return ret;
}
public void clearAll() {
orgData.clear();
toBeDeleteNames.clear();
updatedData.clear();
}
public WintCookie commitForCookie() {
return commitForCookie(0);
}
@Override
public WintCookie commitForCookie(int expire) {
return cookieCodec.buildCookie(this);
}
public Map<String, SessionData> getOrgData() {
return orgData;
}
public void initData(Map<String, SessionData> data) {
this.orgData.putAll(data);
}
public Set<String> getToBeDeleteNames() {
return toBeDeleteNames;
}
public Map<String, SessionData> getUpdatedData() {
return updatedData;
}
@Override
protected BaseConfig getConfig() {
return config;
}
@Override
protected SessionIdGenerator getSessionIdGenerator() {
return sessionIdGenerator;
}
}
| {
"content_hash": "dead34bc7a532c61ba2282e02a4c26d0",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 123,
"avg_line_length": 29.305785123966942,
"alnum_prop": 0.6714608009024252,
"repo_name": "pister/wint",
"id": "cd8fbfd8f65154e27e5d0012c35799a9bf24b3d1",
"size": "3546",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "wint-framework/src/main/java/wint/sessionx/provider/cookie/CookieSessionStore.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FreeMarker",
"bytes": "33"
},
{
"name": "Java",
"bytes": "1365563"
}
],
"symlink_target": ""
} |
tryDemo
ladjladfjdjasdfadfa
adfadfaf
adsfasfasfa
adsfasfasf
| {
"content_hash": "03e74ae80a30866a84fae4c41ab7a455",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 19,
"avg_line_length": 12,
"alnum_prop": 0.9166666666666666,
"repo_name": "myOrganizationName/tryDemo",
"id": "b6af4938aa011702b6b0481ba29e53c2161588f6",
"size": "70",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!doctype html>
<html>
<head>
<title>Fable · Mandelbrot with Fable</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Mandelbrot Fractal</h1>
<!-- [body] -->
<canvas align="center" id="canvas" width="1000" height="800"></canvas>
<!-- [/body] -->
<script src="bundle.js"></script>
</body>
</html> | {
"content_hash": "2c0bc41cf1dfc4cefa52fff3f0a75fb1",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 72,
"avg_line_length": 26.5,
"alnum_prop": 0.6415094339622641,
"repo_name": "fable-compiler/samples",
"id": "d10ffb9cb4063329523fef5dd03537c761d18766",
"size": "425",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/mandelbrot/index.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "87"
},
{
"name": "CSS",
"bytes": "32526"
},
{
"name": "F#",
"bytes": "532730"
},
{
"name": "HTML",
"bytes": "16468"
},
{
"name": "JavaScript",
"bytes": "76943"
},
{
"name": "Shell",
"bytes": "837"
}
],
"symlink_target": ""
} |
layout: default
title: LiftExists
---
`LiftExists` is a more general `exists` with the ability to auto-deduce where a given predicate should be applied based upon the argument type of the predicate and the applicability of the type structure to which it is applied. That is, `liftExists` can lift a predicate into the first suitable context for which it can be applied. Hence, given a predicate of the form `A => Boolean` it can be applied to `F[A]`, `F1[F2[A]]` and all the way to `F1[F2[...Fn[A]...]]` for any `n`.
Underneath the hood, `LiftExists` operates by calling successive `map` operations until it finds the first type for which `A => Boolean` may act. If the argument type, `A`, is a general type such as `Any`, it will be applied to the first correct type such `F[B]` that `A >: B`. There is currently no forcing mechanism to coerce the application point lower in the type structure.
Contains: *Scalaz*, *Cats*
## Syntax Extension
The syntax extension adds the method `liftExists` (`liftAny` in the case of Scalaz) to any object of whose type can be expressed in the form `F[A]` where `A` may in fact be some higher-kinded type. To demonstrate, given the following code:
```tut
val optList = Option(List(2, 4, 6, 8))
val out = optList.map{
_.exists(_ % 3 == 0)
}
```
the same can be had with
```tut
import scalaz._
import Scalaz._
import autolift.Scalaz._
val optList = Option(List(2, 4, 6, 8))
val out = optList.liftAny{ x: Int => x % 3 == 0 }
```
## Context
The context allows the function to work on any object of the form `F[A]` where `A` may in fact be some higher-kinded type.
```tut
import scalaz._
import Scalaz._
import autolift.Scalaz._
val lifted = liftAny{ x: Int => x.toString.size < 2 }
val single = lifted(List(1, 10, 100))
val doubly = lifted(NonEmptyList(List(1, 10, 100)))
``` | {
"content_hash": "62897af7759e43b042cfa655ef130388",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 478,
"avg_line_length": 40.51111111111111,
"alnum_prop": 0.7098189797037849,
"repo_name": "wheaties/AutoLifts",
"id": "313762150b5369e1f750f3959dbeac8cdeb0e9c0",
"size": "1827",
"binary": false,
"copies": "1",
"ref": "refs/heads/0.7",
"path": "docs/src/main/tut/LiftExists.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Scala",
"bytes": "195280"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
in Peck, Ann. Rep. N. Y. St. Mus. nat. Hist. 30: 53 (1878)
#### Original name
Puccinia orbicula Peck & Clinton, 1878
### Remarks
null | {
"content_hash": "ef8ab95495dea1ce7a38934e33704592",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 58,
"avg_line_length": 17.076923076923077,
"alnum_prop": 0.6756756756756757,
"repo_name": "mdoering/backbone",
"id": "428d53e11ea6bc9f052d42163070b86409a475d4",
"size": "284",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Basidiomycota/Pucciniomycetes/Pucciniales/Pucciniaceae/Puccinia/Puccinia orbicula/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
layout: post
title: "subprocessについて"
date: 2021-02-14
excerpt: "subprocessについて"
computer_science: true
hide_from_post: true
tag: ["subprocess"]
comments: false
sort_key: "2021-02-14"
update_dates: ["2021-02-14"]
---
# subprocessについて
## 概要
- 標準出力に入出力するインターフェース
- linuxでは`fd(file descriptor)`を用いてやり取りする
## pythonでの例
```python
from subprocess import PIPE
from subprocess import Popen
with Popen(["cat"], stdin=PIPE, stdout=PIPE) as proc:
proc.stdin.write(b"something input\n")
proc.stdin.close()
print(proc.stdout.read())
```
*output*
```console
b'something input\n'
```
- pythonでは高機能なsubprocessのラッパーである`Popen`が用意されている
- `cat`を起動して、`something input`のバイナリ列を書き込む
- `cat`から出力された内容を読み込む
- 他の機能は[公式を参照](https://docs.python.org/3/library/subprocess.html#subprocess.Popen)
| {
"content_hash": "8c8b24d095015c6c08cfcb7289d6a026",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 83,
"avg_line_length": 20.763157894736842,
"alnum_prop": 0.7287705956907478,
"repo_name": "GINK03/gink03.github.io",
"id": "239565d6719d1504a0bca3b982c467f06462c86b",
"size": "1013",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/computer-science/2021-02-14-subprocess.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "43896"
},
{
"name": "JavaScript",
"bytes": "1777"
},
{
"name": "Ruby",
"bytes": "187"
},
{
"name": "SCSS",
"bytes": "29974"
}
],
"symlink_target": ""
} |
namespace Snittlistan.Web.HtmlHelpers;
public enum ScriptType
{
/// <summary>
/// Main jQuery library.
/// </summary>
JQuery,
/// <summary>
/// Validation library of jQuery.
/// </summary>
JQueryValidate,
/// <summary>
/// Localization of jQuery validation.
/// </summary>
JQueryValidateLocalized,
/// <summary>
/// ASP.NET jQuery Validate Unobtrusive.
/// </summary>
JQueryValidateUnobtrusive,
/// <summary>
/// User interface library.
/// </summary>
JQueryUI,
/// <summary>
/// User interface localization files.
/// </summary>
JQueryUII18N,
/// <summary>
/// Modernizer library.
/// </summary>
Modernizr
}
| {
"content_hash": "5479339be5caaf4dd382da822fa24790",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 44,
"avg_line_length": 19.692307692307693,
"alnum_prop": 0.5455729166666666,
"repo_name": "dlidstrom/Snittlistan",
"id": "4af8183c2209d0499dd30d5ce6e91fc4917d171a",
"size": "770",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Snittlistan.Web/HtmlHelpers/ScriptType.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "107"
},
{
"name": "Batchfile",
"bytes": "79"
},
{
"name": "C#",
"bytes": "1550365"
},
{
"name": "CSS",
"bytes": "58717"
},
{
"name": "F#",
"bytes": "1316"
},
{
"name": "HTML",
"bytes": "2380877"
},
{
"name": "JavaScript",
"bytes": "19222"
},
{
"name": "Less",
"bytes": "8308"
},
{
"name": "PowerShell",
"bytes": "9727"
},
{
"name": "XSLT",
"bytes": "9784"
}
],
"symlink_target": ""
} |
' JustMock Lite
' Copyright © 2010-2014,2022 Telerik EAD
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Imports Telerik.JustMock
Namespace JustMock.NonElevatedExamples.BasicUsage.Mock_Raises
''' <summary>
''' The Raises method is used to fire an event once a method is called.
''' See http://www.telerik.com/help/justmock/basic-usage-mock-raises.html for full documentation of the feature.
''' </summary>
<TestClass> _
Public Class Mock_Raises_Tests
<TestMethod> _
Public Sub ShouldRaiseCustomEventOnMethodCall()
Dim expected = "ping"
Dim actual As String = String.Empty
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: When foo.RaiseMethod() is called, it should raise foo.CustomEvent with expected args.
Mock.Arrange(Sub() foo.RaiseMethod()).Raises(Sub() AddHandler foo.CustomEvent, Nothing, expected)
AddHandler foo.CustomEvent, Sub(s)
actual = s
End Sub
' ACT
foo.RaiseMethod()
' ASSERT
Assert.AreEqual(expected, actual)
End Sub
<TestMethod> _
Public Sub ShouldRaiseCustomEventForFuncCalls()
Dim isRaised As Boolean = False
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: When foo.Echo() is called with expected arguments, it should raise foo.EchoEvent with arg: true.
Mock.Arrange(Function() foo.Echo("string")).Raises(Sub() AddHandler foo.EchoEvent, Nothing, True)
AddHandler foo.EchoEvent, Sub(c)
isRaised = c
End Sub
' ACT
Dim actual = foo.Echo("string")
' ASSERT
Assert.IsTrue(isRaised)
End Sub
<TestMethod> _
Public Sub ShouldAssertMultipleEventSubscription()
Dim isRaisedForFirstSubscr As Boolean = False
Dim isRaisedForSecondSubscr As Boolean = False
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: When foo.Execute() is called, it should raise foo.EchoEvent with arg: true.
Mock.Arrange(Sub() foo.Execute()).Raises(Sub() AddHandler foo.EchoEvent, Nothing, True)
' Subscribing for the event
AddHandler foo.EchoEvent, Sub(c)
isRaisedForFirstSubscr = c
End Sub
AddHandler foo.EchoEvent, Sub(c)
isRaisedForSecondSubscr = c
End Sub
' ACT
foo.Execute()
' ASSERT
Assert.IsTrue(isRaisedForFirstSubscr)
Assert.IsTrue(isRaisedForSecondSubscr)
End Sub
End Class
#Region "SUT"
Public Delegate Sub CustomEvent(value As String)
Public Delegate Sub EchoEvent(echoed As Boolean)
Public Interface IFoo
Event CustomEvent As CustomEvent
Event EchoEvent As EchoEvent
Sub RaiseMethod()
Function Echo(arg As String) As String
Sub Execute()
End Interface
#End Region
End Namespace
| {
"content_hash": "69fcaf5e6b2a37aace86de64832fced6",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 121,
"avg_line_length": 35.5,
"alnum_prop": 0.5925206410879067,
"repo_name": "telerik/JustMockLite",
"id": "bfdea72a6ea1b3f3b93840af3d60e2c4cb03c3e8",
"size": "4119",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Examples/VBExamples/JustMock.NonElevatedExamples.VS2022/BasicUsage/Mock.Raises.vb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "3250617"
}
],
"symlink_target": ""
} |
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for iteratee shorthands.
*
* @param array The _array to inspect.
* @param predicate The function invoked per iteration.
* @param fromIndex The index to search from.
* @param fromRight Specify iterating from right to left.
*/
export function baseFindIndex(array: any[], predicate: Function, fromIndex: number, fromRight?: boolean): number {
const length = array.length;
let index: number = fromIndex + (fromRight ? 1 : -1);
while (fromRight ? index-- : ++index < length) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
| {
"content_hash": "99216e7b553798478c9e33936b7ce1e9",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 114,
"avg_line_length": 33.4,
"alnum_prop": 0.6841317365269461,
"repo_name": "UIUXEngineering/ix-material",
"id": "0ee04e2c7b31e53b6af83520fa67e1fa465ddbb6",
"size": "668",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "libs/fn/src/lib/_common/_baseFindIndex.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "176288"
},
{
"name": "HTML",
"bytes": "93553"
},
{
"name": "JavaScript",
"bytes": "11976"
},
{
"name": "Shell",
"bytes": "4844"
},
{
"name": "TypeScript",
"bytes": "879276"
}
],
"symlink_target": ""
} |
.b-menu_layout_horiz .b-menu__list
{
display: inline-table;
vertical-align: middle;
}
.b-menu_layout_horiz .b-menu__item,
.b-menu_layout_horiz .b-menu__gap
{
display: table-cell;
vertical-align: middle;
}
| {
"content_hash": "35fe8b3c8c94a8875bb6ae51fcee3cfe",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 35,
"avg_line_length": 18.5,
"alnum_prop": 0.6576576576576577,
"repo_name": "vladrudych/realvnz",
"id": "edf97fc272d98d3d34b35e8ac32b967cfd699769",
"size": "222",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/bem-node/node_modules/bem-bl/blocks-touch/b-menu/_layout/b-menu_layout_horiz.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "53648"
},
{
"name": "JavaScript",
"bytes": "109069"
},
{
"name": "Ruby",
"bytes": "1149"
},
{
"name": "Shell",
"bytes": "57"
}
],
"symlink_target": ""
} |
/* motif.h,v 1.1.1.2 1992/07/10 02:40:57 davew Exp */
#ifndef Already_Included_Motif
#define Already_Included_Motif
#if ! defined BATCH_ONLY_PETIT
#if defined(_Omega_String_h) && defined(String)
#include <basic/leave_String.h>
#endif
#include <X11/Intrinsic.h>
#undef True
#undef False
#define Motif_True 1
#define Motif_False 0
#include <petit/tree.h>
namespace omega {
typedef void (*refresher)( int );
typedef int (*Handler)( int dummy );
typedef struct Menu_struc{
char *menu_name;
void* (*menu_builder)( void );
Handler menu_prolog;
Handler menu_epilog;
int menu_parameter;
}Menu_struc;
typedef struct mm
{
struct mm *parent;
Handler refresh;
int num;
Widget menu_box;
Menu_struc root[20];
struct mm *child[20];
} menu;
extern menu *GLOBAL_MENU;
extern Widget top, form, text, message;
extern XtAppContext app;
menu *Build_Menu(Menu_struc MM[], Handler MMF, unsigned int def);
void motif_init(int argc, char *argv[]);
void motif_fini();
void motif_loop(menu *m);
void motif_menu(menu *m);
void motif_message(char *msg);
void motif_display(char *buffer);
void motif_lowlight(node *n);
void motif_highlight(node *n);
void motif_getword(char *prompt, void (*action_routine)(char *));
void motif_getfile(char *prompt, void (*action_routine)(char *), char *pattern);
void motif_list(char *Message_Buffer, unsigned int Message_Buffer_Size,
unsigned int Message_Width);
void set_mouse_buttons();
}
#endif
#endif
| {
"content_hash": "40b75226bf8a2da6f21d8e0334bf423f",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 80,
"avg_line_length": 18.25925925925926,
"alnum_prop": 0.6997971602434077,
"repo_name": "gcampax/omega-calc",
"id": "d86254acdfb41286a2d087c3e682cbc5b7c5f29f",
"size": "1479",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "petit/include/petit/motif.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Awk",
"bytes": "109"
},
{
"name": "Bison",
"bytes": "81074"
},
{
"name": "C",
"bytes": "2092842"
},
{
"name": "C++",
"bytes": "290054"
},
{
"name": "Clean",
"bytes": "8102"
},
{
"name": "Groff",
"bytes": "484"
},
{
"name": "Io",
"bytes": "3294"
},
{
"name": "JavaScript",
"bytes": "41"
},
{
"name": "Makefile",
"bytes": "21680"
},
{
"name": "Perl",
"bytes": "4435"
},
{
"name": "Perl6",
"bytes": "4511"
},
{
"name": "Shell",
"bytes": "7600"
},
{
"name": "TeX",
"bytes": "280873"
}
],
"symlink_target": ""
} |
def WordCount(str)
return str.split(' ').count
end
| {
"content_hash": "86c1bce5dd3ad69e0acdbf1997d9ce68",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 31,
"avg_line_length": 18.333333333333332,
"alnum_prop": 0.6727272727272727,
"repo_name": "Gyubin/TIL",
"id": "b6688ec6211b860bfa48ff4351deed775bd71558",
"size": "55",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Ruby_on_Rails/Coderbyte/easy/word_count.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "46483"
},
{
"name": "HTML",
"bytes": "2382"
},
{
"name": "JavaScript",
"bytes": "88987"
},
{
"name": "Jupyter Notebook",
"bytes": "17627"
},
{
"name": "Python",
"bytes": "9071"
},
{
"name": "Ruby",
"bytes": "7094"
}
],
"symlink_target": ""
} |
package io.github.m0pt0pmatt.survivalgames.command.executor.print;
import io.github.m0pt0pmatt.survivalgames.command.element.SurvivalGameCommandElement;
import org.spongepowered.api.text.Text;
import java.util.Optional;
import java.util.stream.Collectors;
class PrintEventIntervalsCommand extends AbstractPrintCommand {
private static final PrintEventIntervalsCommand INSTANCE = new PrintEventIntervalsCommand();
private PrintEventIntervalsCommand() {
super(
"event-intervals",
SurvivalGameCommandElement.getInstance(),
survivalGame ->
Optional.of(
Text.joinWith(
Text.of('\n'),
survivalGame
.getConfig()
.getEventIntervals()
.entrySet()
.stream()
.map(e -> Text.of(e.getKey(), " -> ", e.getValue()))
.collect(Collectors.toList()))));
}
static PrintEventIntervalsCommand getInstance() {
return INSTANCE;
}
}
| {
"content_hash": "2d348c02b0eccf543ffc01c26e8f7a30",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 100,
"avg_line_length": 37.82857142857143,
"alnum_prop": 0.48867069486404835,
"repo_name": "m0pt0pmatt/SpongeSurvivalGames",
"id": "4ac6fe182336030d0d6a0beb6339d2228e2147c4",
"size": "2576",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/io/github/m0pt0pmatt/survivalgames/command/executor/print/PrintEventIntervalsCommand.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "370364"
},
{
"name": "Shell",
"bytes": "2196"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
Ravenelia papillosa Speg., 1899
### Remarks
null | {
"content_hash": "3c02fdc038bb09f32c085430cd71fc4f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 12.384615384615385,
"alnum_prop": 0.7142857142857143,
"repo_name": "mdoering/backbone",
"id": "ae76c22ed5e42e565fe9ce0928e27f4e8a2a08de",
"size": "216",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Basidiomycota/Pucciniomycetes/Pucciniales/Raveneliaceae/Ravenelia/Ravenelia papillosa/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>W29021_text</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div style="margin-left: auto; margin-right: auto; width: 800px; overflow: hidden;">
<div style="float: left;">
<a href="page65.html">«</a>
</div>
<div style="float: right;">
</div>
</div>
<hr/>
<div style="position: absolute; margin-left: 1593px; margin-top: 2422px;">
<p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">17 </p>
</div>
<div style="position: absolute; margin-left: 0px; margin-top: 2528px;">
<p class="styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 63px; margin-top: 85px;">
<p class="styleSans409.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Company: Whiting Oil and Gas Corp. Job Number: Calculation Method Minimum Curvature <br/>Einlrl- onh:n|‘ FLU-I -r <br/>I now. \Jal "all Magnetic :4qu I Proposed Azimuth 102.48 Cty/Blk/Par: Mountrail Co. Grid Corr.: 0.00 Depth Reference 1,965' Well Name: Dishman #13-19-2H Total Survey Corr.: 7.77 Tie lnto Surface <br/>' Patterson 336 Target Info: 13' into Middle Bakken @ 10,251' TVD <br/>Rig. a Tool Survey Incl Course VS Coordinates Bld Rate Type Depth (ft) (°) (°) Lth (ft (ft) (ft) N/S (ft) E/W(ft) (°/100’) (°/100‘) (°/100') Remarks <br/> <br/> <br/> <br/> <br/> <br/> <br/>-E_ —-m_ 141.76 unis-am— — mwo 0.1 mm 11mm— 15811-2155— Mwo 0.37 amm— amam— IE— m— m— Mwo 8407 0.56 67.66 33.56 -3.o — .213 8597.38 mm— mm— Em 8884.36 0.20 -02 — mwo— lama-ma— mwo .214— <br/> </p>
</div>
<div style="position: absolute; margin-left: 3129px; margin-top: 106px;">
<p class="styleSans16.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">l—|.——.—| </p>
</div>
<div style="position: absolute; margin-left: 3293px; margin-top: 850px;">
<p class="styleSans55.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
</body>
</html>
| {
"content_hash": "a0edbd3420221b7915feb888a2223cc6",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 975,
"avg_line_length": 63,
"alnum_prop": 0.6202686202686203,
"repo_name": "datamade/elpc_bakken",
"id": "0c1be4ecf72e3f423a41b356df9e6fc3e20d086e",
"size": "2511",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ocr_extracted/W29021_text/page66.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "17512999"
},
{
"name": "HTML",
"bytes": "421900941"
},
{
"name": "Makefile",
"bytes": "991"
},
{
"name": "Python",
"bytes": "7186"
}
],
"symlink_target": ""
} |
X Steps Recorder
This program is a clone of [PSR for Windows](https://blogs.msdn.microsoft.com/patricka/2010/01/04/using-the-secret-windows-7-problem-steps-recorder-to-create-step-by-step-screenshot-documents/), a program that allows users to make a recording of all of the steps they took. (It's like a screen recorder except it doesn't record a video.)
The main differences are that this only runs on Linux, that it records your keystrokes too (!), and that it saves the output as standard html (base64-uri-encoded images) rather than mhtml. This allows for easy editing of the resultant file, such as to remove passwords you typed (which is why psr doesn't record keystrokes in the first place).
# Installation
See the [Releases Page](https://github.com/nonnymoose/xsr/releases).
Make sure you have `scrot` installed; I recommend that you have `imagemagick` and `xdotool` installed as well (to add pointer to screenshots).
# Usage
```
Usage: xsr [options] [outfile]
Options:
-o|--out outfile Output file name (also can be first argument)
-e|--edit-images-before-save Edit images before saving file
-d|--image-deps Do not convert images to base64; instead, output the dependent file and it's resources directory
-c|--image-extension=ext Extension of image output (png or jpg)
-u|--capture-focused Captured the focused window only
-q|--quiet Supress output to STDOUT
--mouse-icon|--cursor=file Specify cursor image (default: the one installed to /usr/share/xsr/Cursor.png)
--no-mouse Do not add mouse to screenshots
--countdown[=seconds] Display countdown (default 5)
--no-countdown Don't display countdown
-h|--help Print this message
```
To quit, press `Break` (usually `Shift`+`Pause`). `Ctrl`+`C` works most of time fine too, although xsr will record that keypress.
# Notes for this file
__Please don't edit this file (`README.md`) directly!__
Please edit rather `README.md.m4`, and run `make README.md` after.
You can commit the generated changes in `README.md` along with the manual changes in `README.md.m4`.
| {
"content_hash": "c5b7c2dd69600efdf66a3a50b538f818",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 343,
"avg_line_length": 57.19444444444444,
"alnum_prop": 0.7484215638659544,
"repo_name": "nonnymoose/xsr",
"id": "8f94d2df790b12f31fba72832b629e6cc84838b6",
"size": "2065",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1255"
},
{
"name": "M4",
"bytes": "69"
},
{
"name": "Makefile",
"bytes": "320"
},
{
"name": "Perl",
"bytes": "16293"
}
],
"symlink_target": ""
} |
package com.eharmony.aloha.semantics.compiled.plugin.proto.codegen
import com.eharmony.aloha.semantics.compiled.plugin.proto.accessor._
import MapType._
private[proto] object CodeGenerators {
/** Camel-case a protocol buffer field name (so we can generate code for the getters / setters). This is a
* slightly atypical version of camel-case. The original version was just:
*
* {{{
* private[this] def toCamelCase(s: String) = s.split("_+").map(_.capitalize) mkString ""
* }}}
*
* But this disagrees with Google's protocol buffer implementation of camel-case that capitalizes
* letters appearing directly after a number. So, the following protocol buffer specification:
*
* {{{
* optional bool comm_7d_c = 7;
* }}}
*
* creates getter:
*
* {{{
* public boolean getComm7DC(){ // ...
* }}}
*
* Therefore, we have to do the slight craziness to match.
* @param s input String to be camel-cased.
* @return a camel-cased String
*/
private[this] def toCamelCase(s: String) = {
if (s.isEmpty) s
else {
val v = s.toVector
v.drop(1).foldLeft(Vector(s.toString.capitalize.head)) { case(s, x) =>
val l = s.last
s :+ (if (l == '_' || (0x30 <= l && l <= 0x39)) x.toString.capitalize.head else x)
}.filter(_ != '_').mkString
}
}
implicit object RequiredCodeGenerator extends RequiredAccessorCodeGenerator[Required] {
override def generateGet(r: Required) = "get" + toCamelCase(r.field.getName)
}
implicit object DerefReqCodeGenerator extends RequiredAccessorCodeGenerator[DerefReq] {
override def generateGet(d: DerefReq) = "get" + toCamelCase(d.field.getName) + "(" + d.index + ")"
}
implicit object RepeatedCodeGenerator extends RequiredAccessorCodeGenerator[Repeated] {
override def generateGet(r: Repeated) = "get" + toCamelCase(r.field.getName) + "List"
}
implicit object OptionalCodeGenerator extends OptionalAccessorCodeGenerator[Optional] {
override def generateGet(o: Optional) = "get" + toCamelCase(o.field.getName)
override def generateHas(o: Optional) = "has" + toCamelCase(o.field.getName)
}
implicit object DerefOptCodeGenerator extends OptionalAccessorCodeGenerator[DerefOpt] {
override def generateGet(d: DerefOpt) = "get" + toCamelCase(d.field.getName) + "(" + d.index + ")"
override def generateHas(d: DerefOpt) = "get" + toCamelCase(d.field.getName) + "Count > " + d.index
}
implicit object ReqCodeGenerator extends RequiredAccessorCodeGenerator[Req] {
override def generateGet(r: Req) = r match {
case r: Repeated => RepeatedCodeGenerator.generateGet(r)
case r: Required => RequiredCodeGenerator.generateGet(r)
case r: DerefReq => DerefReqCodeGenerator.generateGet(r)
}
}
implicit object OptCodeGenerator extends OptionalAccessorCodeGenerator[Opt] {
override def generateGet(o: Opt) = o match {
case o: Repeated => RepeatedCodeGenerator.generateGet(o)
case o: Required => RequiredCodeGenerator.generateGet(o)
case o: DerefReq => DerefReqCodeGenerator.generateGet(o)
case o: Optional => OptionalCodeGenerator.generateGet(o)
case o: DerefOpt => DerefOptCodeGenerator.generateGet(o)
}
override def generateHas(o: Opt) = o match {
case o: Optional => OptionalCodeGenerator.generateHas(o)
case o: DerefOpt => DerefOptCodeGenerator.generateHas(o)
}
}
trait UnitCodeGen[A] {
def unit(req: Seq[Req], i: Int, fa: A): String
def indent(i: Int) = Seq.fill(i * 2)(" ").mkString("")
def arg(i: Int) = "_" + i
def reqPrefix(i: Int, req: Seq[Req]) =
if (req.isEmpty) arg(i - 1) else req.map(generateGet(_)).mkString(arg(i - 1) + ".", ".", "")
}
object NoSuffixCodeGen extends UnitCodeGen[Any] {
def unit(req: Seq[Req], i: Int, fa: Any = None): String = indent(i) + reqPrefix(i, req)
}
trait ContainerCodeGen[A <: FieldAccessor] { self: UnitCodeGen[A] =>
def mapOp(unitCode: String, i: Int, mapType: MapType): String = {
val mapOp = if (mapType != NONE) ("." + mapType.toString +"(" + arg(i) + " => ") else ""
unitCode + mapOp
}
}
implicit object OptionalCodeGen extends ContainerCodeGen[Opt] with UnitCodeGen[Opt] {
def unit(req: Seq[Req], i: Int, fa: Opt): String = {
val prefix = reqPrefix(i, req) + "."
indent(i) + "(if (" + prefix + generateHas(fa) + ") Option(" + prefix + generateGet(fa) + ") else None)"
}
}
implicit object RepeatedCodeGen extends ContainerCodeGen[Repeated] with UnitCodeGen[Repeated] {
def unit(req: Seq[Req], i: Int, fa: Repeated): String =
indent(i) + reqPrefix(i, req) + "." + generateGet(fa) + ".toSeq"
}
def containerCodeGen[A <: FieldAccessor](req: Seq[Req], fa: A, i: Int, mapType: MapType)(implicit ccg: ContainerCodeGen[A], ucg: UnitCodeGen[A]) =
ccg.mapOp(ucg.unit(req, i, fa), i, mapType)
def generateGet[A <: FieldAccessor](a: A)(implicit g: RequiredAccessorCodeGenerator[A]) = g.generateGet(a)
def generateHas[A <: FieldAccessor](a: A)(implicit g: OptionalAccessorCodeGenerator[A]) = g.generateHas(a)
}
| {
"content_hash": "8a437a382fae1d1fe689409668a62445",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 150,
"avg_line_length": 43.53968253968254,
"alnum_prop": 0.6239518775063799,
"repo_name": "eHarmony/aloha",
"id": "9cb7133d22a3212c9aa09a31bfd913739c2ac7c9",
"size": "5486",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aloha-io-proto/src/main/scala/com/eharmony/aloha/semantics/compiled/plugin/proto/codegen/CodeGenerators.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1977"
},
{
"name": "Java",
"bytes": "229868"
},
{
"name": "JavaScript",
"bytes": "5763"
},
{
"name": "PureBasic",
"bytes": "32"
},
{
"name": "Scala",
"bytes": "1710367"
},
{
"name": "Shell",
"bytes": "8671"
}
],
"symlink_target": ""
} |
var should= require('chai').should(),
assert= require('chai').assert,
AWS = require('aws-sdk'),
_= require('lodash'),
fs= require('fs'),
dyngo= require('../index.js');
const _noerr= function (done)
{
return function (err)
{
if (err) console.log(err,err.stack);
should.not.exist(err);
done();
};
},
accept= function (code,done)
{
return function (err)
{
if (err.code==code)
done();
else
done(err);
};
},
profiles= function ()
{
return JSON.parse(fs.readFileSync('test/sample.small.json','utf8'));
};
describe('text',function ()
{
var db;
before(function (done)
{
dyngo({ dynamo: { endpoint: new AWS.Endpoint('http://localhost:8000') }, hints: false },
function (err,_db)
{
db= _db;
db.test.remove().success(function ()
{
var ensure= function ()
{
return db.test.ensureIndex
({
name: 'S',
$text: function (item)
{
return _.pick(item,['name','company','about']);
}
})
};
ensure().success(function ()
{
db.test.indexes[0].drop().success(function ()
{
ensure().success(function ()
{
var p= profiles();
db.test.save(p)
.success(done)
.error(done);
}).error(done);
}).error(done);
}).error(_noerr(done));
})
.error(_noerr(done));
});
});
it('Can do bloodhound like full text searches', function (done)
{
db.test.findOne({ $text: 'interdum adi' }) // inspired by bloodhound search with whitespace tokenizer
.result(function (obj)
{
obj.name.should.equal('Duncan Wall');
done();
})
.error(_noerr(done));
});
it('Can chain full text searches with normal fields', function (done)
{
db.test.findOne({ name: 'Duncan Wall', $text: 'interdum adi' })
.result(function (obj)
{
obj.name.should.equal('Duncan Wall');
db.test.findOne({ name: 'Hedley Booth', $text: 'interdum adi' })
.result(function (obj)
{
should.not.exist(obj);
done();
})
.error(accept('notfound',done));
})
.error(_noerr(done));
});
it('Should not find any result', function (done)
{
db.test.findOne({ $text: 'Xinterdum adi' }) // inspired by bloodhound search with whitespace tokenizer
.result(function (obj)
{
should.not.exist(obj);
done();
})
.error(accept('notfound',done));
});
});
| {
"content_hash": "9953c3f2658dec11f801b8826ffab9a9",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 115,
"avg_line_length": 31.99145299145299,
"alnum_prop": 0.36174191824739516,
"repo_name": "rospogeo/dynodb-client",
"id": "11b1af51982cdf544e18a7ff6fedd380c3ba15ad",
"size": "3743",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/text.test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "283787"
}
],
"symlink_target": ""
} |
package org.fastquery.analysis;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import org.fastquery.core.Modifying;
import org.fastquery.core.Query;
import org.fastquery.core.QueryBuilder;
import org.fastquery.core.QueryByNamed;
import org.fastquery.util.TypeUtil;
/**
* 在QueryRepository中 {@link Modifying} 依赖检测 <br>
* Modifying 要么跟 Query 组合, 要么跟QueryByNamed组合 不能独存
*
* @author xixifeng (fastquery@126.com)
*/
class ModifyingDependencyFilter implements MethodFilter
{
@Override
public void doFilter(Method method)
{
Modifying m = method.getAnnotation(Modifying.class);
int queryLen = method.getAnnotationsByType(Query.class).length;
QueryByNamed queryByNamed = method.getAnnotation(QueryByNamed.class);
Parameter[] parameters = method.getParameters();
boolean hasQueryBuilder = TypeUtil.hasType(QueryBuilder.class, parameters);
if (m != null && queryLen == 0 && queryByNamed == null && !hasQueryBuilder)
{
this.abortWith(method, "@Modifying 要么跟 @Query 组合, 要么跟@QueryByNamed组合, 要么跟QueryBuilder参数组合!");
}
}
}
| {
"content_hash": "9bd09dcf32d109f3fa6903018eca5cfd",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 105,
"avg_line_length": 30.594594594594593,
"alnum_prop": 0.7190812720848057,
"repo_name": "xixifeng/fastquery",
"id": "34ae65ba602d3b0d53ddd1e777706540b977c838",
"size": "2166",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/fastquery/analysis/ModifyingDependencyFilter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "925562"
}
],
"symlink_target": ""
} |
/// <reference path="../../../node.d.ts" />
export = ResourcePathNotFoundException;
import HttpNotFoundException = require('../../errors/HttpNotFoundException');
'use strict';
/**
* 対象が見つかりません。パスに誤りがあります。
*/
class ResourcePathNotFoundException extends HttpNotFoundException {
/**
* @constructor
* @public
* @param {number} status
* @param {string} code=null
* @param {string} message=""
*/
constructor(status:number, code:string=null, message:string="") {
super(status, code, message == null || message == "" ? "対象が見つかりません。パスに誤りがあります。" : message);
}
}
| {
"content_hash": "0a40227ec0a3d4e103e9a825ecf3b2db",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 93,
"avg_line_length": 22.307692307692307,
"alnum_prop": 0.6689655172413793,
"repo_name": "sakura-internet/saklient.node",
"id": "ed2810cfd87b06a22bd0665c7457d236b6b845d2",
"size": "668",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/saklient/cloud/errors/ResourcePathNotFoundException.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "836514"
},
{
"name": "Shell",
"bytes": "1425"
},
{
"name": "TypeScript",
"bytes": "614649"
}
],
"symlink_target": ""
} |
package org.jtwig.parser.parboiled.expression;
import org.jtwig.model.expression.ConstantExpression;
import org.jtwig.model.expression.Expression;
import org.jtwig.parser.parboiled.AbstractParserTest;
import org.jtwig.parser.parboiled.ParserContext;
import org.junit.Test;
import org.parboiled.support.ParsingResult;
import static junit.framework.TestCase.assertEquals;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
public class ConstantExpressionParserTest extends AbstractParserTest {
private ParserContext context = ParserContext.instance();
private ConstantExpressionParser underTest = context.parser(ConstantExpressionParser.class);
@Test
public void numberExpression() throws Exception {
ParsingResult<Expression> result = parse(underTest.ExpressionRule(), "123");
assertThat(result.matched, is(true));
Expression expression = result.valueStack.pop();
assertThat(expression, is(instanceOf(ConstantExpression.class)));
ConstantExpression variableExpression = (ConstantExpression) expression;
assertThat(variableExpression.getConstantValue().toString(), equalTo("123"));
assertThat(variableExpression.getPosition().getLine(), is(1));
assertThat(variableExpression.getPosition().getColumn(), is(1));
}
@Test
public void stringExpression() throws Exception {
ParsingResult<Expression> result = parse(underTest.ExpressionRule(), "'test'");
assertThat(result.matched, is(true));
Expression expression = result.valueStack.pop();
assertThat(expression, is(instanceOf(ConstantExpression.class)));
ConstantExpression variableExpression = (ConstantExpression) expression;
assertThat(variableExpression.getConstantValue().toString(), equalTo("test"));
assertThat(variableExpression.getPosition().getLine(), is(1));
assertThat(variableExpression.getPosition().getColumn(), is(1));
}
@Test
public void trueExpression() throws Exception {
ParsingResult<Expression> result = parse(underTest.ExpressionRule(), "true");
assertThat(result.matched, is(true));
Expression expression = result.valueStack.pop();
assertThat(expression, is(instanceOf(ConstantExpression.class)));
ConstantExpression variableExpression = (ConstantExpression) expression;
assertEquals(variableExpression.getConstantValue(), true);
assertThat(variableExpression.getPosition().getLine(), is(1));
assertThat(variableExpression.getPosition().getColumn(), is(1));
}
@Test
public void falseExpression() throws Exception {
ParsingResult<Expression> result = parse(underTest.ExpressionRule(), "false");
assertThat(result.matched, is(true));
Expression expression = result.valueStack.pop();
assertThat(expression, is(instanceOf(ConstantExpression.class)));
ConstantExpression variableExpression = (ConstantExpression) expression;
assertEquals(variableExpression.getConstantValue(), false);
assertThat(variableExpression.getPosition().getLine(), is(1));
assertThat(variableExpression.getPosition().getColumn(), is(1));
}
} | {
"content_hash": "6ebc2246293e07d09c6ff18d19b8abb1",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 96,
"avg_line_length": 47.16901408450704,
"alnum_prop": 0.7384293819050463,
"repo_name": "lyncodev/jtwig-draft",
"id": "320d68e0a26db87568f22359f0cce173fbf97c33",
"size": "3349",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jtwig-core/src/test/java/org/jtwig/parser/parboiled/expression/ConstantExpressionParserTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "505767"
},
{
"name": "PHP",
"bytes": "215"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
Acacia subternata F.Muell.
### Remarks
null | {
"content_hash": "46432378802fd7d013f2395902e2d2b4",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 11.384615384615385,
"alnum_prop": 0.722972972972973,
"repo_name": "mdoering/backbone",
"id": "5eff3ddb9f10a7a783ade22f9a8bfb78c1c67793",
"size": "212",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Racosperma/Racosperma subternatum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
'use strict';
angular.module('app').component('graphControl', graphControl());
function graphControl() {
return {
templateUrl: 'app/graph/graph-control/graph-control.html',
controller: GraphControlController,
controllerAs: 'ctrl',
bindings: {
'quickHop': '&',
'redraw': '&',
'reset': '&',
'remove': '&',
'filter': '&'
}
}
}
/**
* The graph controls component comprises of a search bar and a series of buttons
* which allow a user to interact with the graph.
*
* @param {*} graph The graph service
* @param {*} navigation The navigation service
*/
function GraphControlController(graph, navigation) {
var vm = this;
vm.searchTerm;
/**
* Sets the initial search term
*/
vm.$onInit = function() {
vm.searchTerm = graph.getSearchTerm();
}
/**
* Use the injected filter function
*/
vm.search = function() {
vm.filter({searchTerm: vm.searchTerm})
}
/**
* Updates the service value on destruction
*/
vm.$onDestroy = function() {
graph.setSearchTerm(vm.searchTerm)
}
/**
* navigate to the query page.
*/
vm.goToQuery = function() {
navigation.goToQuery()
}
}
| {
"content_hash": "40efe2ef60e0eb66a9ebf9a64817fc4b",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 82,
"avg_line_length": 21.8,
"alnum_prop": 0.5611620795107034,
"repo_name": "gchq/gaffer-tools",
"id": "8897f76fed50e710d531f0242f8a34089d0f6ec4",
"size": "1911",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "ui/src/main/webapp/app/graph/graph-control/graph-control-component.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "26002"
},
{
"name": "HTML",
"bytes": "142354"
},
{
"name": "Java",
"bytes": "336179"
},
{
"name": "JavaScript",
"bytes": "1193042"
},
{
"name": "Jupyter Notebook",
"bytes": "14365"
},
{
"name": "Python",
"bytes": "584562"
},
{
"name": "SCSS",
"bytes": "2775"
},
{
"name": "Scala",
"bytes": "3160"
},
{
"name": "Shell",
"bytes": "118599"
},
{
"name": "TypeScript",
"bytes": "174552"
}
],
"symlink_target": ""
} |
require "spec_helper"
describe Sapience::Formatters::Default do
include_context "logs"
before { travel_to Time.new(2015, 9, 10, 20, 13, 45) }
after { travel_back }
let(:formatter) { described_class.new }
describe "#call" do
subject(:formatted) { formatter.call(log, nil) }
let(:payload) { "HEY HO" }
specify do
is_expected.to start_with(
"2015-09-10 20:13:45.000000 I [#{$PROCESS_ID}:#{thread_name} sapience.rb:10]" \
" [tag_one] [tag_two] (9.999s) Alex -- Sapience is really cool" \
" -- \"HEY HO\" -- Exception: RuntimeError: Error 2",
)
end
end
end
| {
"content_hash": "1a97eecc2894ff521cb07a060591651b",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 87,
"avg_line_length": 29.476190476190474,
"alnum_prop": 0.6074313408723748,
"repo_name": "reevoo/sapience-rb",
"id": "b2bb9dafa23367e5ae13c8b7bc22885e2b295f42",
"size": "649",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/lib/sapience/formatters/default_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4345"
},
{
"name": "HTML",
"bytes": "20526"
},
{
"name": "JavaScript",
"bytes": "1752"
},
{
"name": "Ruby",
"bytes": "332149"
},
{
"name": "Shell",
"bytes": "2677"
}
],
"symlink_target": ""
} |
import Login from './pages/Login';
import Dashboard from './pages/Dashboard';
import Setting from './pages/Setting';
// User
import User from './pages/users/User';
import UserList from './pages/users/UserList';
import UserNew from './pages/users/UserNew';
export default {
'/login': {
component: Login,
},
'/': {
component: Dashboard,
},
'/user': {
component: User,
subRoutes: {
'/list': {
component: UserList,
},
'/new': {
component: UserNew,
},
},
},
'/settings': {
component: Setting,
},
};
| {
"content_hash": "1df5091402f1f04f87d1d91100a4014a",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 46,
"avg_line_length": 18.580645161290324,
"alnum_prop": 0.5711805555555556,
"repo_name": "rorikurniadi/vuejs-AdminLTE",
"id": "2d477f89272ee54d4b30d9b55c2d753abf00b9ff",
"size": "576",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/routes.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "502102"
},
{
"name": "HTML",
"bytes": "1699593"
},
{
"name": "JavaScript",
"bytes": "2887218"
},
{
"name": "PHP",
"bytes": "1684"
},
{
"name": "Vue",
"bytes": "19947"
}
],
"symlink_target": ""
} |
inherit STD_WEAPON;
inherit STD_LORE;
void create_object(void);
void init(void);
mixed weapon_hit(void);
int wielding_func(object ob);
int do_kill(string str);
int do_runes(string str);
void create_object(void)
{
set_name("staff");
add_id("staff of dragon bone");
set_short("a staff of dragon bone");
set_long("This staff is made of the blackened bone of a dragon. It is " +
"extremely hard and slender, and a black jewel is fitted at " +
"the tip of the staff. Strange, evil runes run up and down " +
"the length of the staff. This staff radiates a powerful " +
"evil.\n");
set_value(175);
set_weight(3);
set_type("staff");
set_class(30);
set_material("bone");
set_hit_func(TO);
set_wield_func(TO);
set_property("magic");
add_lore("A staff made of dragon bone?? A weapon of this kind must " +
"be very rare indeed...\n",1,30);
add_lore("You have heard tales of a staff made of the bone of a dragon, " +
"but never did you believe you would ever set eyes on it. To " +
"wield a weapon of this kind, one would have to be dark souled " +
"indeed.\n",31,50);
add_lore("This must be the legendary staff made from the bone of the " +
"great wyrmkin wizard Aldarak, who was slain in his dragon " +
"form by Diedor Wyrmslayer, Knight of Kordar. The legend says " +
"Aldarak's spirit is still present in the staff, and that only " +
"the most black-souled can wield it.\n",51);
set_property("exceptional");
}
void init(void)
{
add_action("do_kill","kill");
add_multi_action("do_runes","l|look|examine|read");
::init();
}
// This just provides special effects
mixed weapon_hit(void)
{
switch(random(5))
{
case 0: W("You flap your huge wings in ecstasy as the power of the " +
"dragon flows through your soul!!\n");
S("The huge shadow flaps its wings in ecstasy as " + TP->QN +
" crushes " + TP->query_attack()->QN + " with the black " +
"staff!!\n");
break;
case 1: W("The dragon spirit whispers powerful spells in your " +
"head...\n");
S("Smoke spews out of " + TP->QN + "'s nostril as the huge " +
"shadow looms over you!!\n");
break;
}
return 0;
}
int wielding_func(object ob)
{
if(TP->query_alignment() > (-299))
{
W("You feel the spirit of the dragon trying to possess your " +
"body, but dissatisfied with the purity of your soul it leaves, " +
"howling with rage. The staff suddenly burns you, and you " +
"can't hold on to it.\n");
S("As " + TP->QN + " tries to wield the black staff, a dark spirit " +
"appears and begins to circle " + TP->QO + ". Suddenly it " +
"leaves, howling with rage.\n");
TP->command("drop staff");
return 0;
}
else
{
W("The spirit of the dragon enters your body howling with rage. " +
"you can hear it whisper evil spells and feel its power flow " +
"through your soul.\n");
S("As " + TP->QN + " wields the staff, a dark spirit appears and " +
"begins to circle " + TP->QO + " slowly. Howling with rage it " +
"enters " + TP->QN + "'s body, and for a moment you thought you " +
"saw a black dragon in "+TP->QN+"'s place.\n");
set_wielding_extra(TP->QN +"'s shadow is that of a dragon.\n");
return 1;
}
}
int do_kill(string str)
{
if(str && wielded_by && present(str,ENV(TP)))
{
W("The spirit of the black dragon seizes control! Spreading huge, " +
"black wings and howling with rage you charge your enemy.\n");
S("Suddenly " + TP->QN + "'s shadow grows into that of a huge " +
"dragon!! The shadow spreads its wings as " + TP->QN +
" approaches " + TP->QPO + " enemy!!\n");
}
return 0;
}
int do_runes(string str)
{
if(str == "runes" || str == "at runes")
{
if(TP->query_skill("runes") + TP->query_int() > 60)
{
if(TP->query_skill("magic") + TP->query_int() > 60)
{
W("The runes of the staff are runes of powerful magic of " +
"the kind used to bind spirits to artifacts. You wonder " +
"what powerful spirit would need so many seals and " +
"pentagrams to be contained.\n");
S(TP->QN + " studies the runes on the black staff and seems " +
"awed.\n");
return 1;
}
W("The runes on the staff are runes of powerful magic.\n");
S(TP->QN + " studies the runes on the black staff.\n");
return 1;
}
W("You can't make anything out of these runes.\n");
S(TP->QN + " seems baffled by the runes on the staff.\n");
return 1;
}
}
| {
"content_hash": "b6537b118003132d198a04f9605fce85",
"timestamp": "",
"source": "github",
"line_count": 137,
"max_line_length": 79,
"avg_line_length": 36.934306569343065,
"alnum_prop": 0.5511857707509882,
"repo_name": "yodakingdoms/kingdoms",
"id": "d07e96c1bb1d1dae813eba8a6635e36072e37832",
"size": "5101",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Areas/Bird/Oakdale/o/Castle/Weapon/dragonstaff.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1479706"
},
{
"name": "PHP",
"bytes": "13216"
}
],
"symlink_target": ""
} |
// JavaScript Document | {
"content_hash": "70263cb849bcdb9602b5efda8687d044",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 23,
"avg_line_length": 23,
"alnum_prop": 0.782608695652174,
"repo_name": "ldjking/sharegrid",
"id": "4d7560db8a4bbebd36fcd140b019b81a3a9a348f",
"size": "25",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web/design/testForm/formdesgin/form.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3189478"
},
{
"name": "HTML",
"bytes": "5772493"
},
{
"name": "Java",
"bytes": "26303"
},
{
"name": "JavaScript",
"bytes": "4048407"
},
{
"name": "Shell",
"bytes": "9474"
},
{
"name": "Smarty",
"bytes": "7724"
},
{
"name": "Stata",
"bytes": "756441"
}
],
"symlink_target": ""
} |
require 'rails_helper'
describe EoyDonationEmail do
let(:ak_raw_id) { "#{Settings.action_kit.akid_secret}.2678.323423423999" }
let(:ak_hash) { Base64.urlsafe_encode64(Digest::SHA256.digest(ak_raw_id))[0..5] }
let(:akid) { "2678.323423423999.#{ak_hash}" }
describe '.opt_out' do
context 'nil value' do
subject { EoyDonationEmail.new(nil) }
it 'should return error' do
subject.opt_out
errors = subject.errors.full_messages
expect(errors).to match_array(["Akid can't be blank", "Actionkit user can't be blank"])
end
end
context 'member without local actionkit id' do
let(:member) { create :member, actionkit_user_id: nil }
subject { EoyDonationEmail.new(akid) }
it 'should return true when opt_out' do
stub_request(:any, /#{Settings.ak_api_url}/).to_return(status: [204, 'No Content'])
expect(subject.opt_out).to eql true
expect(subject.member).to eql nil
end
end
context 'member with local actionkit id' do
before do
create :member, actionkit_user_id: '323423423999'
stub_request(:any, /#{Settings.ak_api_url}/).to_return(status: [204, 'No Content'])
end
subject { EoyDonationEmail.new(akid) }
it 'should return true' do
expect(subject.opt_out).to eql true
expect(subject.member.opt_out_eoy_donation).to eql 1
end
end
context 'actionkit update failed' do
before do
create :member, actionkit_user_id: '323423423999'
stub_request(:any, /#{Settings.ak_api_url}/).to_return(status: [404, 'Not Found'])
end
subject { EoyDonationEmail.new(akid) }
it 'should return false' do
expect(subject.opt_out).to eql false
expect(subject.errors.full_messages).to include('Error updating actionkit')
expect(subject.member.opt_out_eoy_donation).to eql 0
end
end
end
describe '.opt_in' do
context 'nil value' do
subject { EoyDonationEmail.new(nil) }
it 'should return error' do
subject.opt_in
errors = subject.errors.full_messages
expect(errors).to match_array(["Akid can't be blank", "Actionkit user can't be blank"])
end
end
context 'member without local actionkit id' do
let(:member) { create :member, actionkit_user_id: nil }
subject { EoyDonationEmail.new(akid) }
it 'should return true when opt_out' do
stub_request(:any, /#{Settings.ak_api_url}/).to_return(status: [204, 'No Content'])
expect(subject.opt_in).to eql true
expect(subject.member).to eql nil
end
end
context 'member with local actionkit id' do
before do
create :member, actionkit_user_id: '323423423999', opt_out_eoy_donation: 1
stub_request(:any, /#{Settings.ak_api_url}/).to_return(status: [204, 'No Content'])
end
subject { EoyDonationEmail.new(akid) }
it 'should return true' do
expect(subject.opt_in).to eql true
expect(subject.member.opt_out_eoy_donation).to eql 0
end
end
context 'actionkit update failed' do
before do
create :member, actionkit_user_id: '323423423999', opt_out_eoy_donation: 1
stub_request(:any, /#{Settings.ak_api_url}/).to_return(status: [404, 'Not Found'])
end
subject { EoyDonationEmail.new(akid) }
it 'should return false' do
expect(subject.opt_in).to eql false
expect(subject.errors.full_messages).to include('Error updating actionkit')
expect(subject.member.opt_out_eoy_donation).to eql 1
end
end
end
end
| {
"content_hash": "c97e2f4fa32039b67fdcdc7d5720c5bc",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 95,
"avg_line_length": 32.67567567567568,
"alnum_prop": 0.6360628618693135,
"repo_name": "SumOfUs/Champaign",
"id": "f076fd672f66a16ea697ae812c3cf5a47bb9a333",
"size": "3658",
"binary": false,
"copies": "1",
"ref": "refs/heads/development",
"path": "spec/services/eoy_donation_email_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9404"
},
{
"name": "Dockerfile",
"bytes": "254"
},
{
"name": "HTML",
"bytes": "584586"
},
{
"name": "JavaScript",
"bytes": "467169"
},
{
"name": "Liquid",
"bytes": "42808"
},
{
"name": "Procfile",
"bytes": "87"
},
{
"name": "Ruby",
"bytes": "1656000"
},
{
"name": "SCSS",
"bytes": "87041"
},
{
"name": "Shell",
"bytes": "5335"
},
{
"name": "Slim",
"bytes": "141763"
},
{
"name": "TypeScript",
"bytes": "68833"
}
],
"symlink_target": ""
} |
<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org> //
// available at http://getid3.sourceforge.net //
// or http://www.getid3.org //
/////////////////////////////////////////////////////////////////
// See readme.txt for more details //
/////////////////////////////////////////////////////////////////
// //
// module.audio.shorten.php //
// module for analyzing Shorten Audio files //
// dependencies: NONE //
// ///
/////////////////////////////////////////////////////////////////
class getid3_shorten
{
function getid3_shorten(&$fd, &$ThisFileInfo) {
fseek($fd, $ThisFileInfo['avdataoffset'], SEEK_SET);
$ShortenHeader = fread($fd, 8);
if (substr($ShortenHeader, 0, 4) != 'ajkg') {
$ThisFileInfo['error'][] = 'Expecting "ajkg" at offset '.$ThisFileInfo['avdataoffset'].', found "'.substr($ShortenHeader, 0, 4).'"';
return false;
}
$ThisFileInfo['fileformat'] = 'shn';
$ThisFileInfo['audio']['dataformat'] = 'shn';
$ThisFileInfo['audio']['lossless'] = true;
$ThisFileInfo['audio']['bitrate_mode'] = 'vbr';
$ThisFileInfo['shn']['version'] = getid3_lib::LittleEndian2Int(substr($ShortenHeader, 4, 1));
fseek($fd, $ThisFileInfo['avdataend'] - 12, SEEK_SET);
$SeekTableSignatureTest = fread($fd, 12);
$ThisFileInfo['shn']['seektable']['present'] = (bool) (substr($SeekTableSignatureTest, 4, 8) == 'SHNAMPSK');
if ($ThisFileInfo['shn']['seektable']['present']) {
$ThisFileInfo['shn']['seektable']['length'] = getid3_lib::LittleEndian2Int(substr($SeekTableSignatureTest, 0, 4));
$ThisFileInfo['shn']['seektable']['offset'] = $ThisFileInfo['avdataend'] - $ThisFileInfo['shn']['seektable']['length'];
fseek($fd, $ThisFileInfo['shn']['seektable']['offset'], SEEK_SET);
$SeekTableMagic = fread($fd, 4);
if ($SeekTableMagic != 'SEEK') {
$ThisFileInfo['error'][] = 'Expecting "SEEK" at offset '.$ThisFileInfo['shn']['seektable']['offset'].', found "'.$SeekTableMagic.'"';
return false;
} else {
// typedef struct tag_TSeekEntry
// {
// unsigned long SampleNumber;
// unsigned long SHNFileByteOffset;
// unsigned long SHNLastBufferReadPosition;
// unsigned short SHNByteGet;
// unsigned short SHNBufferOffset;
// unsigned short SHNFileBitOffset;
// unsigned long SHNGBuffer;
// unsigned short SHNBitShift;
// long CBuf0[3];
// long CBuf1[3];
// long Offset0[4];
// long Offset1[4];
// }TSeekEntry;
$SeekTableData = fread($fd, $ThisFileInfo['shn']['seektable']['length'] - 16);
$ThisFileInfo['shn']['seektable']['entry_count'] = floor(strlen($SeekTableData) / 80);
//$ThisFileInfo['shn']['seektable']['entries'] = array();
//$SeekTableOffset = 0;
//for ($i = 0; $i < $ThisFileInfo['shn']['seektable']['entry_count']; $i++) {
// $SeekTableEntry['sample_number'] = getid3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 4));
// $SeekTableOffset += 4;
// $SeekTableEntry['shn_file_byte_offset'] = getid3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 4));
// $SeekTableOffset += 4;
// $SeekTableEntry['shn_last_buffer_read_position'] = getid3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 4));
// $SeekTableOffset += 4;
// $SeekTableEntry['shn_byte_get'] = getid3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 2));
// $SeekTableOffset += 2;
// $SeekTableEntry['shn_buffer_offset'] = getid3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 2));
// $SeekTableOffset += 2;
// $SeekTableEntry['shn_file_bit_offset'] = getid3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 2));
// $SeekTableOffset += 2;
// $SeekTableEntry['shn_gbuffer'] = getid3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 4));
// $SeekTableOffset += 4;
// $SeekTableEntry['shn_bit_shift'] = getid3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 2));
// $SeekTableOffset += 2;
// for ($j = 0; $j < 3; $j++) {
// $SeekTableEntry['cbuf0'][$j] = getid3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 4));
// $SeekTableOffset += 4;
// }
// for ($j = 0; $j < 3; $j++) {
// $SeekTableEntry['cbuf1'][$j] = getid3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 4));
// $SeekTableOffset += 4;
// }
// for ($j = 0; $j < 4; $j++) {
// $SeekTableEntry['offset0'][$j] = getid3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 4));
// $SeekTableOffset += 4;
// }
// for ($j = 0; $j < 4; $j++) {
// $SeekTableEntry['offset1'][$j] = getid3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 4));
// $SeekTableOffset += 4;
// }
//
// $ThisFileInfo['shn']['seektable']['entries'][] = $SeekTableEntry;
//}
}
}
if (preg_match('#(1|ON)#i', ini_get('safe_mode'))) {
$ThisFileInfo['error'][] = 'PHP running in Safe Mode - backtick operator not available, cannot run shntool to analyze Shorten files';
return false;
}
if (GETID3_OS_ISWINDOWS) {
$RequiredFiles = array('shorten.exe', 'cygwin1.dll', 'head.exe');
foreach ($RequiredFiles as $required_file) {
if (!is_readable(GETID3_HELPERAPPSDIR.$required_file)) {
$ThisFileInfo['error'][] = GETID3_HELPERAPPSDIR.$required_file.' does not exist';
return false;
}
}
$commandline = GETID3_HELPERAPPSDIR.'shorten.exe -x "'.$ThisFileInfo['filenamepath'].'" - | '.GETID3_HELPERAPPSDIR.'head.exe -c 64';
$commandline = str_replace('/', '\\', $commandline);
} else {
static $shorten_present;
if (!isset($shorten_present)) {
$shorten_present = file_exists('/usr/local/bin/shorten') || `which shorten`;
}
if (!$shorten_present) {
$ThisFileInfo['error'][] = 'shorten binary was not found in path or /usr/local/bin';
return false;
}
$commandline = (file_exists('/usr/local/bin/shorten') ? '/usr/local/bin/' : '' ) . 'shorten -x '.escapeshellarg($ThisFileInfo['filenamepath']).' - | head -c 64';
}
$output = `$commandline`;
if (!empty($output) && (substr($output, 12, 4) == 'fmt ')) {
getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio-video.riff.php', __FILE__, true);
$fmt_size = getid3_lib::LittleEndian2Int(substr($output, 16, 4));
$DecodedWAVFORMATEX = getid3_riff::RIFFparseWAVEFORMATex(substr($output, 20, $fmt_size));
$ThisFileInfo['audio']['channels'] = $DecodedWAVFORMATEX['channels'];
$ThisFileInfo['audio']['bits_per_sample'] = $DecodedWAVFORMATEX['bits_per_sample'];
$ThisFileInfo['audio']['sample_rate'] = $DecodedWAVFORMATEX['sample_rate'];
if (substr($output, 20 + $fmt_size, 4) == 'data') {
$ThisFileInfo['playtime_seconds'] = getid3_lib::LittleEndian2Int(substr($output, 20 + 4 + $fmt_size, 4)) / $DecodedWAVFORMATEX['raw']['nAvgBytesPerSec'];
} else {
$ThisFileInfo['error'][] = 'shorten failed to decode DATA chunk to expected location, cannot determine playtime';
return false;
}
$ThisFileInfo['audio']['bitrate'] = (($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset']) / $ThisFileInfo['playtime_seconds']) * 8;
} else {
$ThisFileInfo['error'][] = 'shorten failed to decode file to WAV for parsing';
return false;
}
return true;
}
}
?> | {
"content_hash": "a6148243b8e188ee1733977e6d9ba484",
"timestamp": "",
"source": "github",
"line_count": 180,
"max_line_length": 173,
"avg_line_length": 43.43333333333333,
"alnum_prop": 0.5800716295727808,
"repo_name": "jiminald/PHP-Multimedia-Sorter",
"id": "07461847c5de8cabdc935269dac981746c003979",
"size": "7818",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "lib/getID3/module.audio.shorten.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "476410"
}
],
"symlink_target": ""
} |
package com.intellij.vcs.log.ui.actions;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.vcs.log.VcsLogDataKeys;
import com.intellij.vcs.log.VcsLogUi;
import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector;
import com.intellij.vcs.log.ui.VcsLogUiImpl;
import com.intellij.vcs.log.ui.frame.MainFrame;
import org.jetbrains.annotations.NotNull;
public class FocusTextFilterAction extends DumbAwareAction {
public FocusTextFilterAction() {
super("Focus Text Filter", "Focus text filter or move focus back to the commits list", null);
}
@Override
public void update(@NotNull AnActionEvent e) {
Project project = e.getProject();
VcsLogUi ui = e.getData(VcsLogDataKeys.VCS_LOG_UI);
e.getPresentation().setEnabledAndVisible(project != null && ui instanceof VcsLogUiImpl);
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
VcsLogUsageTriggerCollector.triggerUsage(e, this);
Project project = e.getRequiredData(CommonDataKeys.PROJECT);
MainFrame mainFrame = ((VcsLogUiImpl)e.getRequiredData(VcsLogDataKeys.VCS_LOG_UI)).getMainFrame();
if (IdeFocusManager.getInstance(project).getFocusedDescendantFor(mainFrame.getToolbar()) != null) {
IdeFocusManager.getInstance(project).requestFocus(mainFrame.getGraphTable(), true);
}
else {
IdeFocusManager.getInstance(project).requestFocus(mainFrame.getTextFilter(), true);
}
}
}
| {
"content_hash": "5af00d2949983abfd6af99365c9d12a4",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 103,
"avg_line_length": 40.170731707317074,
"alnum_prop": 0.7802064359441409,
"repo_name": "paplorinc/intellij-community",
"id": "83c87027d43d6dea1336cad638b0a4e846d6a0ae",
"size": "2247",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/FocusTextFilterAction.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
Bull. Soc. linn. Lyon, Num. Spéc. 10: 10 (1943)
#### Original name
Clitopilus giovanellae var. giovanellae (Bres.) Joss.
### Remarks
null | {
"content_hash": "145fa41f01e74a950265de8c0062eee3",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 53,
"avg_line_length": 15.461538461538462,
"alnum_prop": 0.6915422885572139,
"repo_name": "mdoering/backbone",
"id": "1161733fb013d9fc29ff7f6de5a5658f70894924",
"size": "279",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Entolomataceae/Clitopilus/Clitopilus giovanellae/Clitopilus giovanellae giovanellae/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
class Grupos_model extends CI_Model {
public function __construct(){
$this->load->database();
}
public function crearGrupo($datos){
$this->db->insert('grupo', $datos);
}
public function getMaterias(){
$result = $this->db->get('materia');
return $result->result_array();
}
public function buscarGrupo($clave){
$this->db->where('clave', $clave);
$result = $this->db->get('grupo');
return $result->row_array();
}
public function getGrupos(){
$sql = "SELECT g.clave, g.horario, g.capacidad, m.nombre as materia, m.clave as clavemateria, dp.nombre ,dp.paterno, dp.materno FROM grupo AS g INNER JOIN materia AS m ON m.clave=g.cve_materia INNER JOIN profesor AS p ON p.clave = g.cve_profesor INNER JOIN datos_personales AS dp ON dp.RFC=p.clave;";
$result = $this->db->query($sql);
return $result->result_array();
}
public function modificarGrupo($clave, $datos){
$this->db->where('clave', $clave);
$this->db->update('grupo', $datos);
}
public function eliminarGrupo($clave){
$this->db->delete('grupo', array('clave' => $clave));
}
public function getGruposProfe($cve_profe){
$query = "SELECT g.clave, m.nombre, g.cve_profesor, g.capacidad, g.horario FROM grupo as g INNER JOIN materia as m ON m.clave=g.cve_materia WHERE cve_profesor='".$cve_profe."'";
$result = $this->db->query($query);
return $result->result_array();
}
public function getGrupo($cve_grupo){
$query = "SELECT a.clave as cuenta, dp.nombre, dp.paterno, dp.materno, c.* from datos_personales as dp inner join alumno as a on a.cve_datos = dp.clave inner join alumnos_x_grupo as axg on axg.cve_alumno=a.clave inner join calificacion as c on c.clave = axg.cve_calificacion where axg.cve_grupo=".$cve_grupo;
$result = $this->db->query($query);
return $result->result_array();
}
} | {
"content_hash": "b2959b1920056995a85b6ea0477420d2",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 313,
"avg_line_length": 35.45283018867924,
"alnum_prop": 0.6583288983501863,
"repo_name": "lalolb/sicde",
"id": "d98646be2b458e7c59d3f094e5304ea44cf332b2",
"size": "1879",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/models/Grupos_model.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "240"
},
{
"name": "CSS",
"bytes": "688335"
},
{
"name": "HTML",
"bytes": "2149327"
},
{
"name": "JavaScript",
"bytes": "3311921"
},
{
"name": "PHP",
"bytes": "2001938"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Support.V4.View;
using Com.Viewpagerindicator;
namespace Xamarin.Android.ViewPagerIndicator.Sample
{
[Activity (Label = "Titles/Default")]
[IntentFilter (new[]{Intent.ActionMain}, Categories = new[]{ "mono.viewpagerindicator.sample" })]
public class SampleTitlesDefault : BaseSampleActivity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.simple_titles);
mAdapter = new TestTitleFragmentAdapter (SupportFragmentManager);
mPager = FindViewById<ViewPager> (Resource.Id.pager);
mPager.Adapter = mAdapter;
mIndicator = FindViewById<TitlePageIndicator> (Resource.Id.indicator);
mIndicator.SetViewPager (mPager);
}
}
}
| {
"content_hash": "6b030c8b76b4478ced8a9128e59bed12",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 98,
"avg_line_length": 25.513513513513512,
"alnum_prop": 0.7648305084745762,
"repo_name": "wada811/Xamarin.Android.ViewPagerIndicator",
"id": "f7fa72ffe732df919452aad8fc437518556fe77d",
"size": "944",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Xamarin.Android.ViewPagerIndicator/Xamarin.Android.ViewPagerIndicator.Sample/Titles/SampleTitlesDefault.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "34667"
}
],
"symlink_target": ""
} |
var MongoClient = require('mongodb').MongoClient;
var mongoVersion = require('mongo-version');
var compareVersion = require('compare-version');
var _ = require('underscore');
module.exports = function aggregateOut(collection, array, options, cb) {
// No options or No out arg: passthrough
if (!cb || !options.out) return collection.aggregate(array, options, cb);
isLegacy(collection.db, function (err, isLegacy) {
if (err) return cb(err);
if (!isLegacy)
return collection.aggregate(array, options, cb);
collection.db.collection(options.out, function (err, out) {
if (err) return cb(err);
delete options.out;
overrideCollection(out, function (err, out) {
if (err) return cb(err);
var cur = collection.aggregate(array, _.extend({}, options, {cursor:{batchSize:100}}));
cur.on('data', function (d) {
out.insert(d, function(err){
if (err) cur.emit('error', err);
});
}).on('error', function (err) {
cb(err);
})
.on('end', function () {
cb(null,[]);
})
})
})
})
}
function overrideCollection(collection, cb) {
var db = collection.db;
var collectionName = collection.collectionName;
collection.drop( function (err) {
db.collection(collectionName, cb);
})
}
function isLegacy(db, cb) {
mongoVersion(db, function (err, ver) {
if (err) return cb(err);
cb(null,compareVersion('2.6.0', ver)>0);
})
} | {
"content_hash": "23b8517facd2536a6bb1a33191656f04",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 95,
"avg_line_length": 28.71153846153846,
"alnum_prop": 0.6068318821165438,
"repo_name": "tounano/mongo-aggregate-out",
"id": "bfceb7a0194133b7b1f522841911aabaae24dd51",
"size": "1493",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aggregate.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1533"
}
],
"symlink_target": ""
} |
<?php
namespace rg4;
class Ingredient {
private $name;
private $cost;
public function __construct($name, $cost) {
$this->name = $name;
$this->cost = $cost;
print "Class (rg4)Ingredient initialized with Name $name and Cost $cost.\n";
}
public function setName($name) {
print $this->getID().": Name changed from [".$this->name;
$this->name = $name;
print "] to [".$this->name."]\n";
}
public function getName() {
return $this->name;
}
public function setCost($cost) {
print $this->getID().": Cost changed from [".$this->cost;
$this->cost = $cost;
print "] to [".$this->cost."]\n";
}
public function getCost() {
return $this->cost;
}
public function getID() {
return "(rg4)Ingredient ".$this->name." [".$this->cost."]";
}
}
?>
| {
"content_hash": "e70e78e729507cba646d1bfcde6e0dd1",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 79,
"avg_line_length": 20.487179487179485,
"alnum_prop": 0.5869837296620776,
"repo_name": "jmd7/LearningPHP",
"id": "51af87ed95e2bb380afcffb7f91d52f45eda844a",
"size": "799",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ch06/ch06_e04n.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "93620"
}
],
"symlink_target": ""
} |
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
protect_from_forgery # See ActionController::RequestForgeryProtection for details
# Scrub sensitive parameters from your log
# filter_parameter_logging :password
before_filter :init_time_zone
#sets the time zone for this request if a session time zone exists if it doesn't the default is UTC
def init_time_zone
if session[:time_zone_name]
@time_zone = ActiveSupport::TimeZone[session[:time_zone_name]]
Time.zone = @time_zone.name if @time_zone
end
true
end
protected :init_time_zone
end
| {
"content_hash": "eea74eb02470ad25707c2035cf3655cc",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 101,
"avg_line_length": 33.526315789473685,
"alnum_prop": 0.7346938775510204,
"repo_name": "flogic/larry",
"id": "96b6515952e9676a9d3fe834f0f0c29c1a0b8c56",
"size": "791",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/controllers/application_controller.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "33122"
},
{
"name": "Ruby",
"bytes": "345807"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en-gb" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Comment - UIkit tests</title>
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script src="js/test.js"></script>
</head>
<body>
<div class="uk-container">
<h3>Comment</h3>
<div class="uk-width-2-3@m">
<ul class="uk-comment-list">
<li>
<article class="uk-comment">
<header class="uk-comment-header uk-grid-medium uk-flex-middle" uk-grid>
<div class="uk-width-auto">
<img class="uk-comment-avatar" src="images/avatar.jpg" width="50" alt="">
</div>
<div class="uk-width-expand">
<h4 class="uk-comment-title uk-margin-remove"><a class="uk-link-reset" href="#">Author</a></h4>
<ul class="uk-comment-meta uk-subnav uk-subnav-divider uk-margin-remove-top">
<li><a href="#">12 days ago</a></li>
<li><a href="#">Reply</a></li>
</ul>
</div>
</header>
<div class="uk-comment-body">
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
</div>
</article>
</li>
<li>
<article class="uk-comment uk-visible-toggle">
<header class="uk-comment-header uk-position-relative">
<div class="uk-grid-medium uk-flex-middle" uk-grid>
<div class="uk-width-auto">
<img class="uk-comment-avatar" src="images/avatar.jpg" width="50" alt="">
</div>
<div class="uk-width-expand">
<h4 class="uk-comment-title uk-margin-remove"><a class="uk-link-reset" href="#">Author</a></h4>
<p class="uk-comment-meta uk-margin-remove-top"><a class="uk-link-reset" href="#">12 days ago</a></p>
</div>
</div>
<div class="uk-position-top-right uk-position-small uk-hidden-hover"><a class="uk-link-muted" href="#">Reply</a></div>
</header>
<div class="uk-comment-body">
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
</div>
</article>
<ul>
<li>
<article class="uk-comment uk-visible-toggle">
<header class="uk-comment-header uk-position-relative">
<div class="uk-grid-medium uk-flex-middle" uk-grid>
<div class="uk-width-auto">
<img class="uk-comment-avatar" src="images/avatar.jpg" width="50" alt="">
</div>
<div class="uk-width-expand">
<h4 class="uk-comment-title uk-margin-remove"><a class="uk-link-reset" href="#">Author</a></h4>
<p class="uk-comment-meta uk-margin-remove-top"><a class="uk-link-reset" href="#">12 days ago</a></p>
</div>
</div>
<div class="uk-position-top-right uk-position-small uk-hidden-hover"><a class="uk-link-muted" href="#">Reply</a></div>
</header>
<div class="uk-comment-body">
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
</div>
</article>
<ul>
<li>
<article class="uk-comment uk-comment-primary uk-visible-toggle">
<header class="uk-comment-header uk-position-relative">
<div class="uk-grid-medium uk-flex-middle" uk-grid>
<div class="uk-width-auto">
<img class="uk-comment-avatar" src="images/avatar.jpg" width="50" alt="">
</div>
<div class="uk-width-expand">
<h4 class="uk-comment-title uk-margin-remove"><a class="uk-link-reset" href="#">Author</a></h4>
<p class="uk-comment-meta uk-margin-remove-top"><a class="uk-link-reset" href="#">12 days ago</a></p>
</div>
</div>
<div class="uk-position-top-right uk-position-small uk-hidden-hover"><a class="uk-link-muted" href="#">Reply</a></div>
</header>
<div class="uk-comment-body">
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
</div>
</article>
<ul>
<li>
<article class="uk-comment uk-visible-toggle">
<header class="uk-comment-header uk-position-relative">
<div class="uk-grid-medium uk-flex-middle" uk-grid>
<div class="uk-width-auto">
<img class="uk-comment-avatar" src="images/avatar.jpg" width="50" alt="">
</div>
<div class="uk-width-expand">
<h4 class="uk-comment-title uk-margin-remove"><a class="uk-link-reset" href="#">Author</a></h4>
<p class="uk-comment-meta uk-margin-remove-top"><a class="uk-link-reset" href="#">12 days ago</a></p>
</div>
</div>
<div class="uk-position-top-right uk-position-small uk-hidden-hover"><a class="uk-link-muted" href="#">Reply</a></div>
</header>
<div class="uk-comment-body">
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
</div>
</article>
</li>
</ul>
</li>
</ul>
</li>
<li>
<article class="uk-comment uk-visible-toggle">
<header class="uk-comment-header uk-position-relative">
<div class="uk-grid-medium uk-flex-middle" uk-grid>
<div class="uk-width-auto">
<img class="uk-comment-avatar" src="images/avatar.jpg" width="50" alt="">
</div>
<div class="uk-width-expand">
<h4 class="uk-comment-title uk-margin-remove"><a class="uk-link-reset" href="#">Author</a></h4>
<p class="uk-comment-meta uk-margin-remove-top"><a class="uk-link-reset" href="#">12 days ago</a></p>
</div>
</div>
<div class="uk-position-top-right uk-position-small uk-hidden-hover"><a class="uk-link-muted" href="#">Reply</a></div>
</header>
<div class="uk-comment-body">
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
</div>
</article>
</li>
</ul>
</li>
<li>
<article class="uk-comment uk-visible-toggle">
<header class="uk-comment-header uk-position-relative">
<div class="uk-grid-medium uk-flex-middle" uk-grid>
<div class="uk-width-auto">
<img class="uk-comment-avatar" src="images/avatar.jpg" width="50" alt="">
</div>
<div class="uk-width-expand">
<h4 class="uk-comment-title uk-margin-remove"><a class="uk-link-reset" href="#">Author</a></h4>
<p class="uk-comment-meta uk-margin-remove-top"><a class="uk-link-reset" href="#">12 days ago</a></p>
</div>
</div>
<div class="uk-position-top-right uk-position-small uk-hidden-hover"><a class="uk-link-muted" href="#">Reply</a></div>
</header>
<div class="uk-comment-body">
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
</div>
</article>
</li>
<li>
<article class="uk-comment uk-comment-primary uk-visible-toggle">
<header class="uk-comment-header uk-position-relative">
<div class="uk-grid-medium uk-flex-middle" uk-grid>
<div class="uk-width-auto">
<img class="uk-comment-avatar" src="images/avatar.jpg" width="50" alt="">
</div>
<div class="uk-width-expand">
<h4 class="uk-comment-title uk-margin-remove"><a class="uk-link-reset" href="#">Author</a></h4>
<p class="uk-comment-meta uk-margin-remove-top"><a class="uk-link-reset" href="#">12 days ago</a></p>
</div>
</div>
<div class="uk-position-top-right uk-position-small uk-hidden-hover"><a class="uk-link-muted" href="#">Reply</a></div>
</header>
<div class="uk-comment-body">
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
</div>
</article>
<ul>
<li>
<article class="uk-comment uk-visible-toggle">
<header class="uk-comment-header uk-position-relative">
<div class="uk-grid-medium uk-flex-middle" uk-grid>
<div class="uk-width-auto">
<img class="uk-comment-avatar" src="images/avatar.jpg" width="50" alt="">
</div>
<div class="uk-width-expand">
<h4 class="uk-comment-title uk-margin-remove"><a class="uk-link-reset" href="#">Author</a></h4>
<p class="uk-comment-meta uk-margin-remove-top"><a class="uk-link-reset" href="#">12 days ago</a></p>
</div>
</div>
<div class="uk-position-top-right uk-position-small uk-hidden-hover"><a class="uk-link-muted" href="#">Reply</a></div>
</header>
<div class="uk-comment-body">
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
</div>
</article>
</li>
</ul>
</li>
</ul>
</div>
</div>
</body>
</html>
| {
"content_hash": "44119a3b9e5ca1ed0240153704db37a5",
"timestamp": "",
"source": "github",
"line_count": 208,
"max_line_length": 358,
"avg_line_length": 78.28846153846153,
"alnum_prop": 0.4106484893146647,
"repo_name": "decaf-emu/huehuetenango",
"id": "c0a0e68acb9fc0f40c3d33fd86f2b37e750d0c94",
"size": "16284",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "static/node_modules/uikit/tests/comment.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "262"
},
{
"name": "Dockerfile",
"bytes": "1801"
},
{
"name": "Go",
"bytes": "80767"
},
{
"name": "HTML",
"bytes": "86"
},
{
"name": "JavaScript",
"bytes": "18200"
},
{
"name": "Makefile",
"bytes": "318"
},
{
"name": "Vue",
"bytes": "22364"
}
],
"symlink_target": ""
} |
//@ts-check
'use strict';
const bootstrapWindow = require('../../../../bootstrap-window');
bootstrapWindow.load(['vs/code/electron-browser/issue/issueReporterMain'], function (issueReporter, configuration) {
issueReporter.startup(configuration);
}, { forceEnableDeveloperKeybindings: true }); | {
"content_hash": "3ed3e0b706b8703b12de9bc6c9de6276",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 116,
"avg_line_length": 30.6,
"alnum_prop": 0.7254901960784313,
"repo_name": "KTXSoftware/KodeStudio-win32",
"id": "2af77c6c61b6dcb76e82cb14e33dcb44bd8cc557",
"size": "660",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "resources/app/out/vs/code/electron-browser/issue/issueReporter.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "5914"
},
{
"name": "C",
"bytes": "16536150"
},
{
"name": "C#",
"bytes": "6892"
},
{
"name": "C++",
"bytes": "2853489"
},
{
"name": "CMake",
"bytes": "215"
},
{
"name": "CSS",
"bytes": "580404"
},
{
"name": "GLSL",
"bytes": "4560"
},
{
"name": "HTML",
"bytes": "10983"
},
{
"name": "Haxe",
"bytes": "6650959"
},
{
"name": "Java",
"bytes": "5737"
},
{
"name": "JavaScript",
"bytes": "15087995"
},
{
"name": "Lua",
"bytes": "3242"
},
{
"name": "Objective-C",
"bytes": "25344"
},
{
"name": "Objective-C++",
"bytes": "72165"
},
{
"name": "PAWN",
"bytes": "4478"
},
{
"name": "Shell",
"bytes": "3252"
},
{
"name": "Smarty",
"bytes": "13338"
},
{
"name": "TypeScript",
"bytes": "306451"
}
],
"symlink_target": ""
} |
package org.rabix.bindings.draft2;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.rabix.bindings.BindingException;
import org.rabix.bindings.ProtocolProcessor;
import org.rabix.bindings.draft2.bean.Draft2CommandLineTool;
import org.rabix.bindings.draft2.bean.Draft2ExpressionTool;
import org.rabix.bindings.draft2.bean.Draft2Job;
import org.rabix.bindings.draft2.bean.Draft2JobApp;
import org.rabix.bindings.draft2.bean.Draft2OutputPort;
import org.rabix.bindings.draft2.expression.Draft2ExpressionException;
import org.rabix.bindings.draft2.expression.helper.Draft2ExpressionBeanHelper;
import org.rabix.bindings.draft2.helper.Draft2BindingHelper;
import org.rabix.bindings.draft2.helper.Draft2FileValueHelper;
import org.rabix.bindings.draft2.helper.Draft2JobHelper;
import org.rabix.bindings.draft2.helper.Draft2SchemaHelper;
import org.rabix.bindings.draft2.processor.Draft2PortProcessor;
import org.rabix.bindings.draft2.processor.Draft2PortProcessorException;
import org.rabix.bindings.draft2.processor.callback.Draft2FilePathMapProcessorCallback;
import org.rabix.bindings.draft2.processor.callback.Draft2PortProcessorHelper;
import org.rabix.bindings.draft2.service.Draft2GlobException;
import org.rabix.bindings.draft2.service.Draft2GlobService;
import org.rabix.bindings.draft2.service.Draft2MetadataService;
import org.rabix.bindings.draft2.service.impl.Draft2GlobServiceImpl;
import org.rabix.bindings.draft2.service.impl.Draft2MetadataServiceImpl;
import org.rabix.bindings.mapper.FilePathMapper;
import org.rabix.bindings.model.Job;
import org.rabix.common.helper.ChecksumHelper;
import org.rabix.common.helper.ChecksumHelper.HashAlgorithm;
import org.rabix.common.helper.JSONHelper;
import org.rabix.common.json.BeanSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Draft2Processor implements ProtocolProcessor {
public final static int DEFAULT_SUCCESS_CODE = 0;
public final static String JOB_FILE = "job.json";
public final static String RESULT_FILENAME = "cwl.output.json";
private final static Logger logger = LoggerFactory.getLogger(Draft2Processor.class);
private final Draft2GlobService globService;
private final Draft2MetadataService metadataService;
public Draft2Processor() {
this.globService = new Draft2GlobServiceImpl();
this.metadataService = new Draft2MetadataServiceImpl();
}
@Override
public Job preprocess(final Job job, final File workingDir, FilePathMapper logFilesPathMapper) throws BindingException {
Draft2Job draft2Job = Draft2JobHelper.getDraft2Job(job);
Draft2PortProcessorHelper portProcessorHelper = new Draft2PortProcessorHelper(draft2Job);
try {
Map<String, Object> inputs = draft2Job.getInputs();
inputs = portProcessorHelper.setFileSize(inputs);
inputs = portProcessorHelper.loadInputContents(inputs);
inputs = portProcessorHelper.stageInputFiles(inputs, workingDir);
Map<String, Object> mappedInputs = inputs;
if (logFilesPathMapper != null) {
Map<String, Object> config = job.getConfig();
Draft2PortProcessor draft2PortProcessor = new Draft2PortProcessor(draft2Job);
mappedInputs = draft2PortProcessor.processInputs(inputs, new Draft2FilePathMapProcessorCallback(logFilesPathMapper, config));
}
File jobFile = new File(workingDir, Draft2Processor.JOB_FILE);
String serializedJob = BeanSerializer.serializePartial(new Draft2Job(draft2Job.getId(), draft2Job.getApp(), mappedInputs, draft2Job.getOutputs()));
try {
FileUtils.writeStringToFile(jobFile, serializedJob);
} catch (IOException e) {
throw new BindingException(e);
}
@SuppressWarnings("unchecked")
Map<String, Object> commonInputs = (Map<String, Object>) Draft2ValueTranslator.translateToCommon(inputs);
return Job.cloneWithInputs(job, commonInputs);
} catch (Draft2PortProcessorException e) {
throw new BindingException(e);
}
}
@Override
public boolean isSuccessful(Job job, int statusCode) throws BindingException {
Draft2Job draft2Job = Draft2JobHelper.getDraft2Job(job);
List<Integer> successCodes = draft2Job.getApp().getSuccessCodes();
if (successCodes == null) {
successCodes = new ArrayList<>();
}
if (successCodes.isEmpty()) {
successCodes.add(DEFAULT_SUCCESS_CODE);
}
for (Integer successCode : successCodes) {
if (successCode.intValue() == statusCode) {
return true;
}
}
return false;
}
@Override
public Job postprocess(Job job, File workingDir, HashAlgorithm hashAlgorithm, FilePathMapper logFilePathMapper) throws BindingException {
Draft2Job draft2Job = Draft2JobHelper.getDraft2Job(job);
try {
Map<String, Object> outputs = null;
if (draft2Job.getApp().isExpressionTool()) {
Draft2ExpressionTool expressionTool = (Draft2ExpressionTool) draft2Job.getApp();
try {
outputs = Draft2ExpressionBeanHelper.evaluate(draft2Job, expressionTool.getScript());
} catch (Draft2ExpressionException e) {
throw new BindingException("Failed to populate outputs", e);
}
} else {
outputs = collectOutputs(draft2Job, workingDir, hashAlgorithm);
}
outputs = new Draft2PortProcessorHelper(draft2Job).fixOutputMetadata(draft2Job.getInputs(), outputs);
if (logFilePathMapper != null) {
try {
Map<String, Object> mappedResult = new Draft2PortProcessor(draft2Job).processOutputs(outputs, new Draft2FilePathMapProcessorCallback(logFilePathMapper, job.getConfig()));
BeanSerializer.serializePartial(new File(workingDir, RESULT_FILENAME), mappedResult);
} catch (Draft2PortProcessorException e) {
logger.error("Failed to map outputs", e);
throw new BindingException(e);
}
} else {
BeanSerializer.serializePartial(new File(workingDir, RESULT_FILENAME), outputs);
}
@SuppressWarnings("unchecked")
Map<String, Object> commonOutputs = (Map<String, Object>) Draft2ValueTranslator.translateToCommon(outputs);
return Job.cloneWithOutputs(job, commonOutputs);
} catch (Draft2GlobException | Draft2ExpressionException | IOException | Draft2PortProcessorException e) {
throw new BindingException(e);
}
}
private Map<String, Object> collectOutputs(Draft2Job job, File workingDir, HashAlgorithm hashAlgorithm) throws Draft2GlobException, Draft2ExpressionException, IOException, BindingException {
File resultFile = new File(workingDir, RESULT_FILENAME);
if (resultFile.exists()) {
String resultStr = FileUtils.readFileToString(resultFile);
Map<String, Object> outputs = JSONHelper.readMap(resultStr);
postprocessToolCreatedResults(outputs, hashAlgorithm);
return JSONHelper.readMap(resultStr);
}
Map<String, Object> result = new HashMap<>();
Draft2CommandLineTool commandLineTool = (Draft2CommandLineTool) job.getApp();
for (Draft2OutputPort outputPort : commandLineTool.getOutputs()) {
Object singleResult = collectOutput(job, workingDir, hashAlgorithm, outputPort.getSchema(), outputPort.getOutputBinding(), outputPort);
if (singleResult != null) {
result.put(Draft2SchemaHelper.normalizeId(outputPort.getId()), singleResult);
}
}
return result;
}
private void postprocessToolCreatedResults(Object value, HashAlgorithm hashAlgorithm) {
if (value == null) {
return;
}
if ((Draft2SchemaHelper.isFileFromValue(value))) {
File file = new File(Draft2FileValueHelper.getPath(value));
if (!file.exists()) {
return;
}
Draft2FileValueHelper.setSize(file.length(), value);
if(hashAlgorithm != null) {
String checksum = ChecksumHelper.checksum(file, hashAlgorithm);
if (checksum != null) {
Draft2FileValueHelper.setChecksum(checksum, value);
}
}
List<Map<String, Object>> secondaryFiles = Draft2FileValueHelper.getSecondaryFiles(value);
if (secondaryFiles != null) {
for (Object secondaryFile : secondaryFiles) {
postprocessToolCreatedResults(secondaryFile, hashAlgorithm);
}
}
} else if (value instanceof List<?>) {
for (Object subvalue : (List<?>) value) {
postprocessToolCreatedResults(subvalue, hashAlgorithm);
}
} else if (value instanceof Map<?, ?>) {
for (Object subvalue : ((Map<?, ?>) value).values()) {
postprocessToolCreatedResults(subvalue, hashAlgorithm);
}
}
}
@SuppressWarnings("unchecked")
private Object collectOutput(Draft2Job job, File workingDir, HashAlgorithm hashAlgorithm, Object schema, Object binding, Draft2OutputPort outputPort) throws Draft2GlobException, Draft2ExpressionException, BindingException {
if (binding == null) {
binding = Draft2SchemaHelper.getOutputBinding(schema);
}
logger.debug("Collecting outputs for {}.", job.getId());
if (schema == null) {
schema = Draft2SchemaHelper.TYPE_JOB_FILE;
}
Object result = null;
if (Draft2SchemaHelper.isArrayFromSchema(schema)) {
Draft2JobApp app = job.getApp();
Object itemSchema = Draft2SchemaHelper.getSchemaForArrayItem(null, app.getSchemaDefs(), schema);
if (itemSchema == null) {
return null;
}
if (itemSchema.equals(Draft2SchemaHelper.TYPE_JOB_FILE) || Draft2SchemaHelper.isFileFromSchema(itemSchema)) {
Object itemBinding = Draft2SchemaHelper.getOutputBinding(itemSchema);
if (itemBinding != null) {
binding = itemBinding;
}
result = globFiles(job, workingDir, hashAlgorithm, outputPort, binding);
} else {
return collectOutput(job, workingDir, hashAlgorithm, itemSchema, binding, outputPort);
}
} else if (Draft2SchemaHelper.isRecordFromSchema(schema)) {
Map<String, Object> record = new HashMap<>();
Object fields = Draft2SchemaHelper.getFields(schema);
if (fields instanceof List<?>) {
List<Object> fieldList = (List<Object>) fields;
for (Object field : fieldList) {
Map<String, Object> fieldMap = (Map<String, Object>) field;
String id = (String) fieldMap.get(Draft2SchemaHelper.KEY_SCHEMA_NAME);
Object fieldSchema = fieldMap.get(Draft2SchemaHelper.KEY_SCHEMA_TYPE);
Object fieldBinding = Draft2SchemaHelper.getOutputBinding(fieldMap);
if (fieldBinding != null) {
binding = fieldBinding;
}
Object singleResult = collectOutput(job, workingDir, hashAlgorithm, fieldSchema, binding, outputPort);
if (singleResult != null) {
record.put(id, singleResult);
}
}
}
result = record;
} else {
result = globFiles(job, workingDir, hashAlgorithm, outputPort, binding);
}
Object outputEval = Draft2BindingHelper.getOutputEval(binding);
if (outputEval != null) {
result = Draft2BindingHelper.evaluateOutputEval(job, result, binding);
logger.info("OutputEval transformed result into {}.", result);
}
if (result instanceof List<?>) {
if (Draft2SchemaHelper.isFileFromSchema(schema)) {
switch (((List<?>) result).size()) {
case 0:
result = null;
break;
case 1:
result = ((List<?>) result).get(0);
break;
default:
throw new BindingException("Invalid file format " + result);
}
}
}
return result;
}
/**
* Extracts files from a directory based on GLOB expression
*/
private List<Map<String, Object>> globFiles(final Draft2Job job, final File workingDir, HashAlgorithm hashAlgorithm, final Draft2OutputPort outputPort, Object outputBinding) throws Draft2GlobException {
if (outputPort.getOutputBinding() != null) {
outputBinding = outputPort.getOutputBinding(); // override
}
if (outputBinding == null) {
logger.debug("Output binding is empty. Skip output extraction.");
return null;
}
Object glob = Draft2BindingHelper.getGlob(outputBinding);
if (glob == null) {
logger.debug("GLOB does not exist. Skip output extraction.");
return null;
}
Set<File> paths = globService.glob(job, workingDir, glob);
if (paths == null) {
logger.info("Glob service didn't find any files.");
return null;
}
logger.debug("Glob service returned result {}", paths);
final List<Map<String, Object>> result = new ArrayList<>();
for (File path : paths) {
try {
logger.info("Processing {}.", path);
File file = path;
Map<String, Object> fileData = new HashMap<>();
Draft2FileValueHelper.setFileType(fileData);
if (hashAlgorithm != null) {
Draft2FileValueHelper.setChecksum(file, fileData, hashAlgorithm);
}
Draft2FileValueHelper.setSize(file.length(), fileData);
Draft2FileValueHelper.setName(file.getName(), fileData);
Draft2FileValueHelper.setPath(file.getAbsolutePath(), fileData);
List<?> secondaryFiles = getSecondaryFiles(job, hashAlgorithm, fileData, file.getAbsolutePath(), outputBinding);
if (secondaryFiles != null) {
Draft2FileValueHelper.setSecondaryFiles(secondaryFiles, fileData);
}
Object metadata = Draft2BindingHelper.getMetadata(outputBinding);
metadata = metadataService.evaluateMetadataExpressions(job, fileData, metadata);
logger.info("Metadata expressions evaluated. Metadata is {}.", metadata);
if (metadata != null) {
Draft2FileValueHelper.setMetadata(metadata, fileData);
}
metadata = metadataService.processMetadata(job, fileData, outputPort, outputBinding);
if (metadata != null) {
logger.info("Metadata for {} resolved. Metadata is {}", outputPort.getId(), metadata);
Draft2FileValueHelper.setMetadata(metadata, fileData);
} else {
logger.info("Metadata for {} output is empty.", outputPort.getId());
}
result.add(fileData);
boolean loadContents = Draft2BindingHelper.loadContents(outputBinding);
if (loadContents) {
Draft2FileValueHelper.setContents(fileData);
}
} catch (Exception e) {
logger.error("Failed to extract outputs", e);
throw new Draft2GlobException("Failed to extract outputs.", e);
}
}
return result;
}
/**
* Gets secondary files (absolute paths)
*/
private List<Map<String, Object>> getSecondaryFiles(Draft2Job job, HashAlgorithm hashAlgorithm, Map<String, Object> fileValue, String fileName, Object binding) throws Draft2ExpressionException {
List<String> secondaryFileSufixes = Draft2BindingHelper.getSecondaryFiles(binding);
if (secondaryFileSufixes == null) {
return null;
}
List<Map<String, Object>> secondaryFileMaps = new ArrayList<>();
for (String suffix : secondaryFileSufixes) {
String secondaryFilePath = fileName.toString();
if (Draft2ExpressionBeanHelper.isExpression(suffix)) {
secondaryFilePath = Draft2ExpressionBeanHelper.evaluate(job, fileValue, suffix);
} else {
while (suffix.startsWith("^")) {
int extensionIndex = secondaryFilePath.lastIndexOf(".");
if (extensionIndex != -1) {
secondaryFilePath = secondaryFilePath.substring(0, extensionIndex);
suffix = suffix.substring(1);
} else {
break;
}
}
secondaryFilePath += suffix.startsWith(".") ? suffix : "." + suffix;
}
File secondaryFile = new File(secondaryFilePath);
if (secondaryFile.exists()) {
Map<String, Object> secondaryFileMap = new HashMap<>();
Draft2FileValueHelper.setFileType(secondaryFileMap);
Draft2FileValueHelper.setPath(secondaryFile.getAbsolutePath(), secondaryFileMap);
Draft2FileValueHelper.setSize(secondaryFile.length(), secondaryFileMap);
Draft2FileValueHelper.setName(secondaryFile.getName(), secondaryFileMap);
if (hashAlgorithm != null) {
Draft2FileValueHelper.setChecksum(secondaryFile, secondaryFileMap, hashAlgorithm);
}
secondaryFileMaps.add(secondaryFileMap);
}
}
return secondaryFileMaps;
}
@Override
public Object transformInputs(Object value, Job job, Object transform) throws BindingException {
return value;
}
}
| {
"content_hash": "a3ea7828c9836d82af0761ea2a3ba216",
"timestamp": "",
"source": "github",
"line_count": 400,
"max_line_length": 225,
"avg_line_length": 41.8,
"alnum_prop": 0.6994019138755981,
"repo_name": "markosbg/debug",
"id": "db71e38730bda3cfd437193295ffe0ce5db17c82",
"size": "16720",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rabix-bindings-draft2/src/main/java/org/rabix/bindings/draft2/Draft2Processor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "297"
},
{
"name": "HTML",
"bytes": "2451"
},
{
"name": "Java",
"bytes": "1689311"
},
{
"name": "JavaScript",
"bytes": "4011"
},
{
"name": "Shell",
"bytes": "4900"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<title>Array Extension Reference</title>
<link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
<link rel="stylesheet" type="text/css" href="../css/highlight.css" />
<meta charset="utf-8">
<script src="../js/jquery.min.js" defer></script>
<script src="../js/jazzy.js" defer></script>
<script src="../js/lunr.min.js" defer></script>
<script src="../js/typeahead.jquery.js" defer></script>
<script src="../js/jazzy.search.js" defer></script>
</head>
<body>
<a name="//apple_ref/swift/Extension/Array" class="dashAnchor"></a>
<a title="Array Extension Reference"></a>
<header class="header">
<p class="header-col header-col--primary">
<a class="header-link" href="../index.html">
Alamofire 5.4.3 Docs
</a>
(97% documented)
</p>
<p class="header-col--secondary">
<form role="search" action="../search.json">
<input type="text" placeholder="Search documentation" data-typeahead>
</form>
</p>
<p class="header-col header-col--secondary">
<a class="header-link" href="https://github.com/Alamofire/Alamofire">
<img class="header-icon" src="../img/gh.png"/>
View on GitHub
</a>
</p>
<p class="header-col header-col--secondary">
<a class="header-link" href="dash-feed://https%3A%2F%2Falamofire.github.io%2FAlamofire%2Fdocsets%2FAlamofire.xml">
<img class="header-icon" src="../img/dash.png"/>
Install in Dash
</a>
</p>
</header>
<p class="breadcrumbs">
<a class="breadcrumb" href="../index.html">Alamofire Reference</a>
<img class="carat" src="../img/carat.png" />
Array Extension Reference
</p>
<div class="content-wrapper">
<nav class="navigation">
<ul class="nav-groups">
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Classes.html">Classes</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/Adapter.html">Adapter</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/AlamofireNotifications.html">AlamofireNotifications</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/AuthenticationInterceptor.html">AuthenticationInterceptor</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/AuthenticationInterceptor/RefreshWindow.html">– RefreshWindow</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/ClosureEventMonitor.html">ClosureEventMonitor</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/CompositeEventMonitor.html">CompositeEventMonitor</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/CompositeTrustEvaluator.html">CompositeTrustEvaluator</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/ConnectionLostRetryPolicy.html">ConnectionLostRetryPolicy</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/DataRequest.html">DataRequest</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/DataResponseSerializer.html">DataResponseSerializer</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/DataStreamRequest.html">DataStreamRequest</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/DataStreamRequest/Stream.html">– Stream</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/DataStreamRequest/Event.html">– Event</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/DataStreamRequest/Completion.html">– Completion</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/DataStreamRequest/CancellationToken.html">– CancellationToken</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/DecodableResponseSerializer.html">DecodableResponseSerializer</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/DefaultTrustEvaluator.html">DefaultTrustEvaluator</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/DisabledTrustEvaluator.html">DisabledTrustEvaluator</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/DownloadRequest.html">DownloadRequest</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/DownloadRequest/Options.html">– Options</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/DownloadRequest/Downloadable.html">– Downloadable</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/Interceptor.html">Interceptor</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/JSONParameterEncoder.html">JSONParameterEncoder</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/JSONResponseSerializer.html">JSONResponseSerializer</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/MultipartFormData.html">MultipartFormData</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/NetworkReachabilityManager.html">NetworkReachabilityManager</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/NetworkReachabilityManager/NetworkReachabilityStatus.html">– NetworkReachabilityStatus</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/PinnedCertificatesTrustEvaluator.html">PinnedCertificatesTrustEvaluator</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/PublicKeysTrustEvaluator.html">PublicKeysTrustEvaluator</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/Request.html">Request</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/Request/State.html">– State</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/Retrier.html">Retrier</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/RetryPolicy.html">RetryPolicy</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/RevocationTrustEvaluator.html">RevocationTrustEvaluator</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/RevocationTrustEvaluator/Options.html">– Options</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/ServerTrustManager.html">ServerTrustManager</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/Session.html">Session</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/SessionDelegate.html">SessionDelegate</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/StringResponseSerializer.html">StringResponseSerializer</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/URLEncodedFormEncoder.html">URLEncodedFormEncoder</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/URLEncodedFormEncoder/ArrayEncoding.html">– ArrayEncoding</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/URLEncodedFormEncoder/BoolEncoding.html">– BoolEncoding</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/URLEncodedFormEncoder/DataEncoding.html">– DataEncoding</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/URLEncodedFormEncoder/DateEncoding.html">– DateEncoding</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/URLEncodedFormEncoder/KeyEncoding.html">– KeyEncoding</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/URLEncodedFormEncoder/SpaceEncoding.html">– SpaceEncoding</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/URLEncodedFormEncoder/Error.html">– Error</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/URLEncodedFormParameterEncoder.html">URLEncodedFormParameterEncoder</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/URLEncodedFormParameterEncoder/Destination.html">– Destination</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/UploadRequest.html">UploadRequest</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Classes/UploadRequest/Uploadable.html">– Uploadable</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Global%20Variables.html">Global Variables</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Global%20Variables.html#/s:9Alamofire2AFAA7SessionCvp">AF</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Enums.html">Enumerations</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Enums/AFError.html">AFError</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Enums/AFError/MultipartEncodingFailureReason.html">– MultipartEncodingFailureReason</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Enums/AFError/UnexpectedInputStreamLength.html">– UnexpectedInputStreamLength</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Enums/AFError/ParameterEncodingFailureReason.html">– ParameterEncodingFailureReason</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Enums/AFError/ParameterEncoderFailureReason.html">– ParameterEncoderFailureReason</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Enums/AFError/ResponseValidationFailureReason.html">– ResponseValidationFailureReason</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Enums/AFError/ResponseSerializationFailureReason.html">– ResponseSerializationFailureReason</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Enums/AFError/ServerTrustFailureReason.html">– ServerTrustFailureReason</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Enums/AFError/URLRequestValidationFailureReason.html">– URLRequestValidationFailureReason</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Enums/AuthenticationError.html">AuthenticationError</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Enums/RetryResult.html">RetryResult</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Extensions.html">Extensions</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions/Array.html">Array</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions.html#/c:objc(cs)NSBundle">Bundle</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions/CharacterSet.html">CharacterSet</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions/Error.html">Error</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions/HTTPURLResponse.html">HTTPURLResponse</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions.html#/s:10Foundation11JSONDecoderC">JSONDecoder</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions/Notification.html">Notification</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions.html#/c:@T@OSStatus">OSStatus</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions.html#/s:10Foundation19PropertyListDecoderC">PropertyListDecoder</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions.html#/c:@T@SecCertificateRef">SecCertificate</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions.html#/c:@T@SecPolicyRef">SecPolicy</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions.html#/c:@T@SecTrustRef">SecTrust</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions.html#/c:@E@SecTrustResultType">SecTrustResultType</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions/String.html">String</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions/URL.html">URL</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions/URLComponents.html">URLComponents</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions/URLRequest.html">URLRequest</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions/URLSessionConfiguration.html">URLSessionConfiguration</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Protocols.html">Protocols</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/AlamofireExtended.html">AlamofireExtended</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/AuthenticationCredential.html">AuthenticationCredential</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/Authenticator.html">Authenticator</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/CachedResponseHandler.html">CachedResponseHandler</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/DataDecoder.html">DataDecoder</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/DataPreprocessor.html">DataPreprocessor</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/DataResponseSerializerProtocol.html">DataResponseSerializerProtocol</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/DataStreamSerializer.html">DataStreamSerializer</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/DownloadResponseSerializerProtocol.html">DownloadResponseSerializerProtocol</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/EmptyResponse.html">EmptyResponse</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/EventMonitor.html">EventMonitor</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/ParameterEncoder.html">ParameterEncoder</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/ParameterEncoding.html">ParameterEncoding</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/RedirectHandler.html">RedirectHandler</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/RequestAdapter.html">RequestAdapter</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/RequestDelegate.html">RequestDelegate</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/RequestInterceptor.html">RequestInterceptor</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/RequestRetrier.html">RequestRetrier</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/ResponseSerializer.html">ResponseSerializer</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/ServerTrustEvaluating.html">ServerTrustEvaluating</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/URLConvertible.html">URLConvertible</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/URLRequestConvertible.html">URLRequestConvertible</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols.html#/s:9Alamofire17UploadConvertibleP">UploadConvertible</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/UploadableConvertible.html">UploadableConvertible</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Structs.html">Structures</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/AlamofireExtension.html">AlamofireExtension</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/DataResponse.html">DataResponse</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/DataResponsePublisher.html">DataResponsePublisher</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/DataStreamPublisher.html">DataStreamPublisher</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/DecodableStreamSerializer.html">DecodableStreamSerializer</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/DownloadResponse.html">DownloadResponse</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/DownloadResponsePublisher.html">DownloadResponsePublisher</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/Empty.html">Empty</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/GoogleXSSIPreprocessor.html">GoogleXSSIPreprocessor</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/HTTPHeader.html">HTTPHeader</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/HTTPHeaders.html">HTTPHeaders</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/HTTPMethod.html">HTTPMethod</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/JSONEncoding.html">JSONEncoding</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/PassthroughPreprocessor.html">PassthroughPreprocessor</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/PassthroughStreamSerializer.html">PassthroughStreamSerializer</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/Redirector.html">Redirector</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/Redirector/Behavior.html">– Behavior</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/ResponseCacher.html">ResponseCacher</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/ResponseCacher/Behavior.html">– Behavior</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/StringStreamSerializer.html">StringStreamSerializer</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/URLEncoding.html">URLEncoding</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/URLEncoding/Destination.html">– Destination</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/URLEncoding/ArrayEncoding.html">– ArrayEncoding</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/URLEncoding/BoolEncoding.html">– BoolEncoding</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/URLResponseSerializer.html">URLResponseSerializer</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Typealiases.html">Type Aliases</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Typealiases.html#/s:9Alamofire14AFDataResponsea">AFDataResponse</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Typealiases.html#/s:9Alamofire18AFDownloadResponsea">AFDownloadResponse</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Typealiases.html#/s:9Alamofire8AFResulta">AFResult</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Typealiases.html#/s:9Alamofire12AdaptHandlera">AdaptHandler</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Typealiases.html#/s:9Alamofire17DisabledEvaluatora">DisabledEvaluator</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Typealiases.html#/s:9Alamofire10Parametersa">Parameters</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Typealiases.html#/s:9Alamofire12RetryHandlera">RetryHandler</a>
</li>
</ul>
</li>
</ul>
</nav>
<article class="main-content">
<section class="section">
<div class="section-content top-matter">
<h1>Array</h1>
<div class="declaration">
<div class="language">
<pre class="highlight swift"><code><span class="kd">extension</span> <span class="kt">Array</span><span class="p">:</span> <span class="kt"><a href="../Protocols/AlamofireExtended.html">AlamofireExtended</a></span></code></pre>
<pre class="highlight swift"><code><span class="kd">extension</span> <span class="kt">Array</span> <span class="k">where</span> <span class="kt">Element</span> <span class="o">==</span> <span class="kt"><a href="../Protocols/ServerTrustEvaluating.html">ServerTrustEvaluating</a></span></code></pre>
</div>
</div>
</div>
</section>
<section class="section">
<div class="section-content">
<div class="task-group">
<div class="task-name-container">
<a name="/Available%20where%20%60Element%60%20%3D%3D%20%60ServerTrustEvaluating%60"></a>
<a name="//apple_ref/swift/Section/Available where `Element` == `ServerTrustEvaluating`" class="dashAnchor"></a>
<div class="section-name-container">
<a class="section-name-link" href="#/Available%20where%20%60Element%60%20%3D%3D%20%60ServerTrustEvaluating%60"></a>
<h3 class="section-name"><p>Available where <code>Element</code> == <code><a href="../Protocols/ServerTrustEvaluating.html">ServerTrustEvaluating</a></code></p>
</h3>
</div>
</div>
<ul class="item-container">
<li class="item">
<div>
<code>
<a name="/s:Sa9AlamofireAA21ServerTrustEvaluating_pRszlE8evaluate_7forHostySo03SecC3Refa_SStKF"></a>
<a name="//apple_ref/swift/Method/evaluate(_:forHost:)" class="dashAnchor"></a>
<a class="token" href="#/s:Sa9AlamofireAA21ServerTrustEvaluating_pRszlE8evaluate_7forHostySo03SecC3Refa_SStKF">evaluate(_:<wbr>forHost:<wbr>)</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Evaluates the given <code>SecTrust</code> value for the given <code>host</code>.</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">func</span> <span class="nf">evaluate</span><span class="p">(</span><span class="n">_</span> <span class="nv">trust</span><span class="p">:</span> <span class="kt">SecTrust</span><span class="p">,</span> <span class="n">forHost</span> <span class="nv">host</span><span class="p">:</span> <span class="kt">String</span><span class="p">)</span> <span class="k">throws</span></code></pre>
</div>
</div>
<div>
<h4>Parameters</h4>
<table class="graybox">
<tbody>
<tr>
<td>
<code>
<em>trust</em>
</code>
</td>
<td>
<div>
<p>The <code>SecTrust</code> value to evaluate.</p>
</div>
</td>
</tr>
<tr>
<td>
<code>
<em>host</em>
</code>
</td>
<td>
<div>
<p>The host for which to evaluate the <code>SecTrust</code> value.</p>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div>
<h4>Return Value</h4>
<p>Whether or not the evaluator considers the <code>SecTrust</code> value valid for <code>host</code>.</p>
</div>
</section>
</div>
</li>
</ul>
</div>
</div>
</section>
</article>
</div>
<section class="footer">
<p>© 2021 <a class="link" href="http://alamofire.org/" target="_blank" rel="external">Alamofire Software Foundation</a>. All rights reserved. (Last updated: 2021-04-21)</p>
<p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.13.6</a>, a <a class="link" href="https://realm.io" target="_blank" rel="external">Realm</a> project.</p>
</section>
</body>
</div>
</html>
| {
"content_hash": "c502b55de31552e49009c14cd28a44e5",
"timestamp": "",
"source": "github",
"line_count": 612,
"max_line_length": 494,
"avg_line_length": 54.18464052287582,
"alnum_prop": 0.5286028768734357,
"repo_name": "easyui/Alamofire",
"id": "53b896d29cc66a725cd9590190289f21ba6ff0cf",
"size": "33229",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/Extensions/Array.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "1325"
},
{
"name": "Ruby",
"bytes": "619"
},
{
"name": "Swift",
"bytes": "514345"
}
],
"symlink_target": ""
} |
#datepicker-dropdown {
font-size: 12px;
}
/* Style the calendar custom widget */
.date-range {
position:relative;
}
.date-range-field {
/*height: 22px;*/
overflow: hidden;
position: relative;
cursor:pointer;
border: 1px solid #CCCCCC;
border-radius: 5px 5px 5px 5px;
background-color: white;
}
.date-range-field a {
color:#D2D2D2;
/*background-color:#F7F7F7;*/
text-align:center;
display: block;
position: absolute;
width: 26px;
/*height: 23px;*/
top: 0;
right: 0;
text-decoration: none;
padding-top:2px;
border-radius: 0 5px 5px 0;
}
.date-range-field span {
font-size: 12px;
font-weight: bold;
color: #404040;
position: relative;
top: 0;
/*height: 26px;
line-height: 26px;
*/
left: 5px;
text-align: center;
}
#datepicker-dropdown {
position: absolute;
top: 23px;
left: 0;
overflow: hidden;
width: 750px;
/*height:300px;*/
background-color: #F7F7F7;
border: 1px solid #CCCCCC;
display:none;
padding:10px 0 0 10px;
z-index: 99;
}
/* Remove default border from the custom widget since we're adding our own. TBD: rework the dropdown calendar to use the default borders */
#datepicker-dropdown div.datepicker {
background-color: transparent;
border: none;
border-radius: 0;
padding: 0;
}
#datepicker-dropdown select {
width: auto;
height: 20px;
font-size: 90%;
vertical-align: top;
padding: 0;
}
#datepicker-dropdown input {
width: auto;
height: 10px;
font-size: 90%;
vertical-align: top;
}
.datepicker-calendar {
float: left;
}
.datepicker-compare-calendar {
clear: both;
float: left;
}
/*.date-range-field span.comparison-divider, */
.date-range-field span.comparison {
text-align: left;
display: block;
color: gray;
font-weight: normal;
font-size: 60%;
}
#datepicker-dropdown .right {
float:left;
}
#datepicker-dropdown input[type=text] {
width: 7em;
}
.datepicker, .date-ranges-form {
float: left;
}
.date-ranges-form {
margin-left: 10px;
float: right;
}
.dr1.active {
border-color: #07C
}
.dr2.active {
border-color: #86BE2B
}
#datepicker-dropdown input.daterange-preset-parameter1 {
width: 40px;
height: 18px;
font-size: 90%;
vertical-align: top;
padding: 0;
}
span.aggregation {
background: #eee;
border: #ccc 1px solid;
border-radius: 4px;
margin-right: 5px;
margin-top: 4px;
padding: 2px 3px 0 3px;
float: left;
height: 20px;
} | {
"content_hash": "6f343ae57521eabff91deddafc496949",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 140,
"avg_line_length": 16.604166666666668,
"alnum_prop": 0.6741948975324132,
"repo_name": "sideeffects/stats_core",
"id": "ce9390e92f7e497ea8393256cc76e7c771c1decb",
"size": "2391",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "stats_main/static/DatePicker-master/css/DateRangesWidget/base.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "78874"
},
{
"name": "HTML",
"bytes": "78512"
},
{
"name": "JavaScript",
"bytes": "244314"
},
{
"name": "Makefile",
"bytes": "4023"
},
{
"name": "Python",
"bytes": "178579"
}
],
"symlink_target": ""
} |
package net.ssehub.kernel_haven.variability_model;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Properties;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import net.ssehub.kernel_haven.AllTests;
import net.ssehub.kernel_haven.SetUpException;
import net.ssehub.kernel_haven.config.DefaultSettings;
import net.ssehub.kernel_haven.test_utils.TestConfiguration;
import net.ssehub.kernel_haven.util.ExtractorException;
import net.ssehub.kernel_haven.util.null_checks.NonNull;
/**
* Tests the {@link DIMACSVariabilityModelExtractor}.
* @author El-Sharkawy
*
*/
public class DIMACSVariabilityModelExtractorTest {
private static final File TESTDATA = new File(AllTests.TESTDATA, "vmDimacs");
/**
* Tests correct error message if no input DIMACS file was specified.
*/
@Test
public void testNoFileSpecified() {
DIMACSVariabilityModelExtractor extractor = new DIMACSVariabilityModelExtractor();
try {
extractor.init(new TestConfiguration(new Properties()));
Assert.fail("No error produced if no input file is specified.");
} catch (SetUpException e) {
Assert.assertEquals(DefaultSettings.VARIABILITY_INPUT_FILE.getKey() + " was not specified, it must "
+ "point to input DIMACS file.", e.getMessage());
}
}
/**
* Tests parsing of a DIMACS file.
* With the following specification:
* <ul>
* <li><b>Variables:</b>1 Variable, with no data type</li>
* <li><b>Constraints:</b> 1 Constraint</li>
* </ul>
*/
@Test
public void testOneVar() {
VariabilityModel varModel = parseDimacsFile(new File(TESTDATA, "oneVar.dimacs"));
// Assert model
Set<VariabilityVariable> variables = varModel.getVariables();
Assert.assertEquals(1, variables.size());
// Assert variable
VariabilityVariable var = variables.iterator().next();
Assert.assertEquals("Variable", var.getName());
Assert.assertEquals(1, var.getDimacsNumber());
Assert.assertEquals(DIMACSVariabilityModelExtractor.UNKNOWN_VARIABE_TYPE, var.getType());
}
/**
* Tests parsing of a DIMACS file.
* With the following specification:
* <ul>
* <li><b>Variables:</b>1 Variable, data type specification</li>
* <li><b>Constraints:</b> 1 Constraint</li>
* </ul>
*/
@Test
public void testOneVarWithDataType() {
VariabilityModel varModel = parseDimacsFile(new File(TESTDATA, "oneVarWithDataType.dimacs"));
// Assert model
Set<VariabilityVariable> variables = varModel.getVariables();
Assert.assertEquals(1, variables.size());
// Assert variable
VariabilityVariable var = variables.iterator().next();
Assert.assertEquals("Variable", var.getName());
Assert.assertEquals(1, var.getDimacsNumber());
Assert.assertEquals("SomethingSpecial", var.getType());
}
/**
* Tests parsing of a DIMACS file.
* With the following specification:
* <ul>
* <li><b>Variables:</b>1 Variable, data type specification</li>
* <li><b>Constraints:</b> 1 Constraint</li>
* </ul>
*/
@Test
public void testTwoVarsWithMixedDataType() {
VariabilityModel varModel = parseDimacsFile(new File(TESTDATA, "twoVarsWithMixedDataType.dimacs"));
// Assert model
Set<VariabilityVariable> variables = varModel.getVariables();
Assert.assertEquals(2, variables.size());
// Assert 1st variable
VariabilityVariable var = varModel.getVariableMap().get("VAR1");
Assert.assertNotNull("VAR1 was not translated.", var);
Assert.assertEquals("VAR1", var.getName());
Assert.assertEquals(1, var.getDimacsNumber());
Assert.assertEquals(DIMACSVariabilityModelExtractor.UNKNOWN_VARIABE_TYPE, var.getType());
// Assert 2nd variable
var = varModel.getVariableMap().get("VAR2");
Assert.assertNotNull("VAR2 was not translated.", var);
Assert.assertEquals("VAR2", var.getName());
Assert.assertEquals(2, var.getDimacsNumber());
Assert.assertEquals("SomethingSpecial", var.getType());
}
/**
* Tests a DIMACS file with "random" (i.e. normal text) comments.
*/
@Test
public void testRandomComments() {
VariabilityModel varModel = parseDimacsFile(new File(TESTDATA, "randomComments.dimacs"));
// Assert model
Set<VariabilityVariable> variables = varModel.getVariables();
Assert.assertEquals(0, variables.size());
}
/**
* Tests a DIMACS file with variables mixed with normal text comments.
*/
@Test
public void testMixedCommentsAndVariables() {
VariabilityModel varModel = parseDimacsFile(new File(TESTDATA, "mixedCommentsAndVariables.dimacs"));
// Assert model
Set<VariabilityVariable> variables = varModel.getVariables();
Assert.assertEquals(2, variables.size());
// Assert 1st variable
VariabilityVariable var = varModel.getVariableMap().get("VAR1");
Assert.assertNotNull("VAR1 was not translated.", var);
Assert.assertEquals("VAR1", var.getName());
Assert.assertEquals(1, var.getDimacsNumber());
Assert.assertEquals(DIMACSVariabilityModelExtractor.UNKNOWN_VARIABE_TYPE, var.getType());
// Assert 2nd variable
var = varModel.getVariableMap().get("VAR2");
Assert.assertNotNull("VAR2 was not translated.", var);
Assert.assertEquals("VAR2", var.getName());
Assert.assertEquals(2, var.getDimacsNumber());
Assert.assertEquals("SomethingSpecial", var.getType());
}
/**
* Helper function to parse a DIMACS file to a {@link VariabilityModel} and to facilitate testing in a test method.
* @param dimcasFile The file (absolute path) to test.
* @return The converted variability model, won't be <tt>null</tt>.
*/
@SuppressWarnings("null")
private @NonNull VariabilityModel parseDimacsFile(File dimcasFile) {
DIMACSVariabilityModelExtractor extractor = new DIMACSVariabilityModelExtractor();
Properties prop = new Properties();
prop.setProperty(DefaultSettings.VARIABILITY_INPUT_FILE.getKey(), dimcasFile.getAbsolutePath());
try {
extractor.init(new TestConfiguration(prop));
} catch (SetUpException e) {
e.printStackTrace();
Assert.fail("Could not initialize " + DIMACSVariabilityModelExtractor.class.getSimpleName() + " due to "
+ e.getMessage());
}
VariabilityModel varModel = null;
try {
varModel = extractor.runOnFile(null);
} catch (ExtractorException e) {
e.printStackTrace();
Assert.fail("Could not parse " + dimcasFile.getAbsolutePath() + " due to "
+ e.getMessage());
}
Assert.assertNotNull(dimcasFile.getAbsolutePath() + " was parsed to null", varModel);
Assert.assertEquals(readFile(dimcasFile), readFile(varModel.getConstraintModel()));
return varModel;
}
/**
* Helper method to compare DIMACS files. Reads the specified file to a String.
* @param txtFile A text file to be read.
* @return The content of the specified file.
*/
private static String readFile(File txtFile) {
Assert.assertNotNull(txtFile);
Assert.assertTrue(txtFile.getAbsolutePath() + " does not exist", txtFile.exists());
StringBuilder result = new StringBuilder();
try {
Files.lines(txtFile.toPath()).forEachOrdered(l -> result.append(l));
} catch (IOException e) {
e.printStackTrace();
Assert.fail("Could not read " + txtFile.getAbsolutePath() + " due to " + e.getMessage());
}
return result.toString();
}
}
| {
"content_hash": "47a7a7bf171afee808efe031dd3cdf86",
"timestamp": "",
"source": "github",
"line_count": 212,
"max_line_length": 119,
"avg_line_length": 38.31132075471698,
"alnum_prop": 0.6415907411967495,
"repo_name": "KernelHaven/KernelHaven",
"id": "032f4753238c1fe6b53c33d6fbebd45f6983f656",
"size": "8765",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/net/ssehub/kernel_haven/variability_model/DIMACSVariabilityModelExtractorTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1363917"
},
{
"name": "JavaScript",
"bytes": "868"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LionFire.MultiTyping;
using LionFire.Ontology;
using LionFire.Referencing;
using LionFire.Serialization;
using LionFire.Structures;
namespace LionFire.ObjectBus.Redis
{
[LionSerializable(SerializeMethod.ByValue)]
public class RedisReference : LocalReferenceBase<RedisReference>, IHas<IOBase>, IHas<IOBus>
{
IOBus IHas<IOBus>.Object => ManualSingleton<RedisOBus>.GuaranteedInstance;
IOBase IHas<IOBase>.Object => RedisOBase;
RedisOBase RedisOBase => RedisOBase.DefaultInstance; // TODO: different hosts
#region Construction and Implicit Construction
public RedisReference() { }
/// <summary>
/// (Does not support URIs (TODO))
/// </summary>
/// <param name="path"></param>
public RedisReference(string path)
{
this.Path = path;
}
//public RedisReference(IReference reference)
//{
// ValidateCanConvertFrom(reference);
// CopyFrom(reference);
//}
public static implicit operator RedisReference(string path)
{
return new RedisReference(path);
}
#endregion
#region Conversion and Implicit operators
//public static implicit operator Handle(RedisReference redisRef)
//{
// return redisRef.ToHandle();
//}
#endregion
#region Conversion
public static void ValidateCanConvertFrom(IReference reference)
{
if (reference.Scheme != UriScheme)
{
throw new OBusReferenceException("UriScheme not supported");
}
}
public static RedisReference ConvertFrom(IReference parent)
{
RedisReference fileRef = parent as RedisReference;
if (fileRef == null && parent.Scheme == UriScheme)
{
fileRef = new RedisReference(parent.Path);
}
return fileRef;
}
#endregion
#region Scheme
public const string UriScheme = "redis";
public const string UriPrefixDefault = "redis:";
public static readonly IEnumerable<string> UriSchemes = new string[] { UriScheme };
public override IEnumerable<string> AllowedSchemes => UriSchemes;
public override string Scheme => UriScheme;
#endregion
public override string Path
{
get { return path; }
set
{
//#if MONO
value = value.Replace('\\', '/');
//#else
// value = value.Replace('/', '\\');
//#endif
//if (value != null)
//{
// if (value.Length >= 1)
// {
// if (value[0] == ':') throw new ArgumentException();
// }
// var colon = value.LastIndexOf(':');
// if (colon != -1 && colon != 1)
// {
// throw new ArgumentException();
// }
//}
path = value;
}
}
private string path;
//public override IOBaseProvider DefaultObjectStoreProvider
//{
// get
// {
// return RedisOBaseProvider.Instance;
// }
//}
public override string ToString() => String.Concat(UriPrefixDefault, Path);
public override string Key { get => this.ToString(); protected set => throw new NotImplementedException(); }
}
public static class RedisReferenceExtensions
{
public static RedisReference AsRedisReference(this string path)
{
return new RedisReference(path);
}
}
}
| {
"content_hash": "01ab95760a0d0f08507239afca62bfc4",
"timestamp": "",
"source": "github",
"line_count": 141,
"max_line_length": 116,
"avg_line_length": 28.49645390070922,
"alnum_prop": 0.5266301642608263,
"repo_name": "jaredthirsk/Core",
"id": "022978a1b2fb467308f9bd7b638c5e2bfca58f01",
"size": "4020",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/LionFire.ObjectBus.Redis/Redis/Referencing/RedisReference.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1436332"
},
{
"name": "Smalltalk",
"bytes": "3"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
J. Mycol. 1(8): 100 (1885)
#### Original name
Septoria pyrolae Ellis & G. Martin
### Remarks
null | {
"content_hash": "58e5b7a0eb20a7723c9f8303895797cc",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 34,
"avg_line_length": 12.384615384615385,
"alnum_prop": 0.6708074534161491,
"repo_name": "mdoering/backbone",
"id": "a9a2095d09439fca11c0375d846aacf474ba3a90",
"size": "219",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Mycosphaerellaceae/Septoria/Septoria pyrolae/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
namespace Google.Cloud.Compute.V1.Snippets
{
// [START compute_v1_generated_RegionNetworkFirewallPolicies_GetEffectiveFirewalls_sync]
using Google.Cloud.Compute.V1;
public sealed partial class GeneratedRegionNetworkFirewallPoliciesClientSnippets
{
/// <summary>Snippet for GetEffectiveFirewalls</summary>
/// <remarks>
/// This snippet has been automatically generated and should be regarded as a code template only.
/// It will require modifications to work:
/// - It may require correct/in-range values for request initialization.
/// - It may require specifying regional endpoints when creating the service client as shown in
/// https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
/// </remarks>
public void GetEffectiveFirewallsRequestObject()
{
// Create client
RegionNetworkFirewallPoliciesClient regionNetworkFirewallPoliciesClient = RegionNetworkFirewallPoliciesClient.Create();
// Initialize request argument(s)
GetEffectiveFirewallsRegionNetworkFirewallPolicyRequest request = new GetEffectiveFirewallsRegionNetworkFirewallPolicyRequest
{
Region = "",
Project = "",
Network = "",
};
// Make the request
RegionNetworkFirewallPoliciesGetEffectiveFirewallsResponse response = regionNetworkFirewallPoliciesClient.GetEffectiveFirewalls(request);
}
}
// [END compute_v1_generated_RegionNetworkFirewallPolicies_GetEffectiveFirewalls_sync]
}
| {
"content_hash": "657d145510f855e1227acbcefb06994c",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 149,
"avg_line_length": 51.09375,
"alnum_prop": 0.6948012232415902,
"repo_name": "googleapis/google-cloud-dotnet",
"id": "9a3a232fc55660bb1537a48d1e8e3a06ba200e5c",
"size": "2257",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "apis/Google.Cloud.Compute.V1/Google.Cloud.Compute.V1.GeneratedSnippets/RegionNetworkFirewallPoliciesClient.GetEffectiveFirewallsRequestObjectSnippet.g.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "767"
},
{
"name": "C#",
"bytes": "319820004"
},
{
"name": "Dockerfile",
"bytes": "3415"
},
{
"name": "PowerShell",
"bytes": "3303"
},
{
"name": "Python",
"bytes": "2744"
},
{
"name": "Shell",
"bytes": "65881"
}
],
"symlink_target": ""
} |
package com.navercorp.pinpoint.plugin.redis.redisson;
import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig;
/**
* @author jaehong.kim
*/
public class RedissonPluginConfig {
private boolean enable;
private boolean keyTrace;
public RedissonPluginConfig(ProfilerConfig src) {
this.enable = src.readBoolean("profiler.redis.redisson.enable", true);
this.keyTrace = src.readBoolean("profiler.redis.redisson.keytrace", false);
}
public boolean isEnable() {
return enable;
}
public boolean isKeyTrace() {
return keyTrace;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("RedissonPluginConfig{");
sb.append("enable=").append(enable);
sb.append(", keyTrace=").append(keyTrace);
sb.append('}');
return sb.toString();
}
}
| {
"content_hash": "f8ab0871a4009e5c1090b7de749267c4",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 83,
"avg_line_length": 24.444444444444443,
"alnum_prop": 0.6613636363636364,
"repo_name": "Xylus/pinpoint",
"id": "18e5dfba9f582d19eb6501948b116849b316f210",
"size": "1475",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "plugins/redis-redisson/src/main/java/com/navercorp/pinpoint/plugin/redis/redisson/RedissonPluginConfig.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "23110"
},
{
"name": "CSS",
"bytes": "534643"
},
{
"name": "CoffeeScript",
"bytes": "10124"
},
{
"name": "Groovy",
"bytes": "1423"
},
{
"name": "HTML",
"bytes": "783457"
},
{
"name": "Java",
"bytes": "16266462"
},
{
"name": "JavaScript",
"bytes": "4821525"
},
{
"name": "Makefile",
"bytes": "5246"
},
{
"name": "PLSQL",
"bytes": "4156"
},
{
"name": "Python",
"bytes": "3523"
},
{
"name": "Ruby",
"bytes": "943"
},
{
"name": "Shell",
"bytes": "31351"
},
{
"name": "TSQL",
"bytes": "4316"
},
{
"name": "Thrift",
"bytes": "15284"
},
{
"name": "TypeScript",
"bytes": "1385542"
}
],
"symlink_target": ""
} |
"""NOEtools: For predicting NOE coordinates from assignment data.
The input and output are modelled on nmrview peaklists.
This modules is suitable for directly generating an nmrview
peaklist with predicted crosspeaks directly from the
input assignment peaklist.
"""
from . import xpktools
__docformat__ = "restructuredtext en"
def predictNOE(peaklist, originNuc, detectedNuc, originResNum, toResNum):
"""Predict the i->j NOE position based on self peak (diagonal) assignments
Parameters
----------
peaklist : xprtools.Peaklist
List of peaks from which to derive predictions
originNuc : str
Name of originating nucleus.
originResNum : int
Index of originating residue.
detectedNuc : str
Name of detected nucleus.
toResNum : int
Index of detected residue.
Returns
-------
returnLine : str
The .xpk file entry for the predicted crosspeak.
Examples
--------
Using predictNOE(peaklist,"N15","H1",10,12)
where peaklist is of the type xpktools.peaklist
would generate a .xpk file entry for a crosspeak
that originated on N15 of residue 10 and ended up
as magnetization detected on the H1 nucleus of
residue 12
Notes
=====
The initial peaklist is assumed to be diagonal (self peaks only)
and currently there is no checking done to insure that this
assumption holds true. Check your peaklist for errors and
off diagonal peaks before attempting to use predictNOE.
"""
returnLine = "" # The modified line to be returned to the caller
datamap = _data_map(peaklist.datalabels)
# Construct labels for keying into dictionary
originAssCol = datamap[originNuc + ".L"] + 1
originPPMCol = datamap[originNuc + ".P"] + 1
detectedPPMCol = datamap[detectedNuc + ".P"] + 1
# Make a list of the data lines involving the detected
if str(toResNum) in peaklist.residue_dict(detectedNuc) \
and str(originResNum) in peaklist.residue_dict(detectedNuc):
detectedList = peaklist.residue_dict(detectedNuc)[str(toResNum)]
originList = peaklist.residue_dict(detectedNuc)[str(originResNum)]
returnLine = detectedList[0]
for line in detectedList:
aveDetectedPPM = _col_ave(detectedList, detectedPPMCol)
aveOriginPPM = _col_ave(originList, originPPMCol)
originAss = originList[0].split()[originAssCol]
returnLine = xpktools.replace_entry(returnLine, originAssCol + 1, originAss)
returnLine = xpktools.replace_entry(returnLine, originPPMCol + 1, aveOriginPPM)
return returnLine
def _data_map(labelline):
# Generate a map between datalabels and column number
# based on a labelline
i = 0 # A counter
datamap = {} # The data map dictionary
labelList = labelline.split() # Get the label line
# Get the column number for each label
for i in range(len(labelList)):
datamap[labelList[i]] = i
return datamap
def _col_ave(list, col):
# Compute average values from a particular column in a string list
total = 0.0
n = 0
for element in list:
total += float(element.split()[col])
n += 1
return total / n
| {
"content_hash": "7eccec02f47ddbdcb0a7e4bcf97f4327",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 87,
"avg_line_length": 31.725490196078432,
"alnum_prop": 0.6820148331273177,
"repo_name": "poojavade/Genomics_Docker",
"id": "bab5b1e45c9e31ea67eed37f5d3d219b5bee749d",
"size": "3459",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/Bio/NMR/NOEtools.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AGS Script",
"bytes": "457842"
},
{
"name": "Assembly",
"bytes": "10509"
},
{
"name": "C",
"bytes": "1265138"
},
{
"name": "C++",
"bytes": "4734960"
},
{
"name": "CSS",
"bytes": "17332"
},
{
"name": "FORTRAN",
"bytes": "10375"
},
{
"name": "GLSL",
"bytes": "493"
},
{
"name": "Groff",
"bytes": "77173"
},
{
"name": "HTML",
"bytes": "395483"
},
{
"name": "Java",
"bytes": "9223"
},
{
"name": "JavaScript",
"bytes": "783663"
},
{
"name": "Jupyter Notebook",
"bytes": "189877"
},
{
"name": "Lua",
"bytes": "28217"
},
{
"name": "Makefile",
"bytes": "77825"
},
{
"name": "Matlab",
"bytes": "4346"
},
{
"name": "Objective-C",
"bytes": "567"
},
{
"name": "Perl",
"bytes": "244796"
},
{
"name": "Python",
"bytes": "54562861"
},
{
"name": "R",
"bytes": "2568"
},
{
"name": "Shell",
"bytes": "40620"
},
{
"name": "Smarty",
"bytes": "21035"
},
{
"name": "TeX",
"bytes": "55310"
}
],
"symlink_target": ""
} |
Patterns used to bind names must be irrefutable. That is, they must guarantee
that a name will be extracted in all cases. Instead of pattern matching the
loop variable, consider using a `match` or `if let` inside the loop body. For
instance:
```compile_fail,E0005
let xs : Vec<Option<i32>> = vec![Some(1), None];
// This fails because `None` is not covered.
for Some(x) in xs {
// ...
}
```
Match inside the loop instead:
```
let xs : Vec<Option<i32>> = vec![Some(1), None];
for item in xs {
match item {
Some(x) => {},
None => {},
}
}
```
Or use `if let`:
```
let xs : Vec<Option<i32>> = vec![Some(1), None];
for item in xs {
if let Some(x) = item {
// ...
}
}
```
| {
"content_hash": "1dd9e2bc128d53e31f5c86418f5180a7",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 77,
"avg_line_length": 18.894736842105264,
"alnum_prop": 0.5933147632311978,
"repo_name": "aidancully/rust",
"id": "66c31376d8b2851d234446221daeb2504ec183d1",
"size": "784",
"binary": false,
"copies": "20",
"ref": "refs/heads/master",
"path": "compiler/rustc_error_codes/src/error_codes/E0297.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "26968"
},
{
"name": "Assembly",
"bytes": "20050"
},
{
"name": "Awk",
"bytes": "159"
},
{
"name": "C",
"bytes": "726643"
},
{
"name": "C++",
"bytes": "54397"
},
{
"name": "CSS",
"bytes": "22328"
},
{
"name": "JavaScript",
"bytes": "38337"
},
{
"name": "LLVM",
"bytes": "5040"
},
{
"name": "Lex",
"bytes": "9238"
},
{
"name": "Makefile",
"bytes": "238787"
},
{
"name": "Pascal",
"bytes": "13073"
},
{
"name": "Puppet",
"bytes": "3193"
},
{
"name": "Python",
"bytes": "149063"
},
{
"name": "RenderScript",
"bytes": "26426"
},
{
"name": "Rust",
"bytes": "18504256"
},
{
"name": "Shell",
"bytes": "270708"
},
{
"name": "TeX",
"bytes": "57"
},
{
"name": "Yacc",
"bytes": "80496"
}
],
"symlink_target": ""
} |
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>PHPXRef 0.7.1 : Unnamed Project : Variable Reference: $children</title>
<link rel="stylesheet" href="../sample.css" type="text/css">
<link rel="stylesheet" href="../sample-print.css" type="text/css" media="print">
<style id="hilight" type="text/css"></style>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
</head>
<body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff">
<table class="pagetitle" width="100%">
<tr>
<td valign="top" class="pagetitle">
[ <a href="../index.html">Index</a> ]
</td>
<td align="right" class="pagetitle">
<h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2>
</td>
</tr>
</table>
<!-- Generated by PHPXref 0.7.1 at Thu Oct 23 18:57:41 2014 -->
<!-- PHPXref (c) 2000-2010 Gareth Watts - gareth@omnipotent.net -->
<!-- http://phpxref.sourceforge.net/ -->
<script src="../phpxref.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
ext='.html';
relbase='../';
subdir='_variables';
filename='index.html';
cookiekey='phpxref';
handleNavFrame(relbase, subdir, filename);
logVariable('children');
// -->
</script>
<script language="JavaScript" type="text/javascript">
if (gwGetCookie('xrefnav')=='off')
document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>');
else
document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>');
</script>
<noscript>
<p class="navlinks">
[ <a href="../nav.html" target="_top">Show Explorer</a> ]
[ <a href="index.html" target="_top">Hide Navbar</a> ]
</p>
</noscript>
[<a href="../index.html">Top level directory</a>]<br>
<script language="JavaScript" type="text/javascript">
<!--
document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>');
document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">');
document.writeln('<tr><td class="searchbox-title">');
document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>');
document.writeln('<\/td><\/tr>');
document.writeln('<tr><td class="searchbox-body" id="searchbox-body">');
document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>');
document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="classname"><br>');
document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="funcname"><br>');
document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="varname"><br>');
document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="constname"><br>');
document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="tablename"><br>');
document.writeln('<input type="submit" class="searchbox-button" value="Search">');
document.writeln('<\/form>');
document.writeln('<\/td><\/tr><\/table>');
document.writeln('<\/td><\/tr><\/table>');
// -->
</script>
<div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div>
<h3>Variable Cross Reference</h3>
<h2><a href="index.html#children">$children</a></h2>
<b>Defined at:</b><ul>
<li><a href="../application/libraries/Lex/Parser.php.html">/application/libraries/Lex/Parser.php</A> -> <a href="../application/libraries/Lex/Parser.php.source.html#l356"> line 356</A></li>
<li><a href="../application/libraries/Lex/Parser.php.html">/application/libraries/Lex/Parser.php</A> -> <a href="../application/libraries/Lex/Parser.php.source.html#l362"> line 362</A></li>
</ul>
<br><b>Referenced 6 times:</b><ul>
<li><a href="../application/libraries/Lex/Parser.php.html">/application/libraries/Lex/Parser.php</a> -> <a href="../application/libraries/Lex/Parser.php.source.html#l356"> line 356</a></li>
<li><a href="../application/libraries/Lex/Parser.php.html">/application/libraries/Lex/Parser.php</a> -> <a href="../application/libraries/Lex/Parser.php.source.html#l357"> line 357</a></li>
<li><a href="../application/libraries/Lex/Parser.php.html">/application/libraries/Lex/Parser.php</a> -> <a href="../application/libraries/Lex/Parser.php.source.html#l361"> line 361</a></li>
<li><a href="../application/libraries/Lex/Parser.php.html">/application/libraries/Lex/Parser.php</a> -> <a href="../application/libraries/Lex/Parser.php.source.html#l362"> line 362</a></li>
<li><a href="../application/libraries/Lex/Parser.php.html">/application/libraries/Lex/Parser.php</a> -> <a href="../application/libraries/Lex/Parser.php.source.html#l362"> line 362</a></li>
<li><a href="../application/libraries/Lex/Parser.php.html">/application/libraries/Lex/Parser.php</a> -> <a href="../application/libraries/Lex/Parser.php.source.html#l366"> line 366</a></li>
</ul>
<!-- A link to the phpxref site in your customized footer file is appreciated ;-) -->
<br><hr>
<table width="100%">
<tr><td>Generated: Thu Oct 23 18:57:41 2014</td>
<td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td>
</tr>
</table>
</body></html>
| {
"content_hash": "6254cf5fa353a2b0478ffa897422bb7e",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 253,
"avg_line_length": 58.009803921568626,
"alnum_prop": 0.6780463072502958,
"repo_name": "inputx/code-ref-doc",
"id": "6c744dac96ab75dfb381c0632d006b33168fe2ba",
"size": "5917",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bonfire/_variables/children.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "17952"
},
{
"name": "JavaScript",
"bytes": "255489"
}
],
"symlink_target": ""
} |
REM*******************************************************************
REM File : ACCOUNTROLL.sql
REM Short Description : Create Data Table SQL Scripts
REM Author : DBCode Generator
REM Created Date : 13.06.2013
REM Tech.Support : LiuWeiZhao. email:welljoe@hotmail.com
REM*******************************************************************
REM DROP TABLE ...
Drop Table ACCOUNTROLL;
REM CREATE TABLE ...
Create Table ACCOUNTROLL(
tdate VARCHAR2(32) ,
crewno VARCHAR2(8) ,
shiftno NUMBER(5) CONSTRAINT cACCOUNTROLL_2 CHECK (shiftno BETWEEN -32768 AND +32767),
standno NUMBER(5) NOT NULL CONSTRAINT cACCOUNTROLL_3 CHECK (standno BETWEEN -32768 AND +32767),
recid NUMBER(10) CONSTRAINT cACCOUNTROLL_4 CHECK (recid BETWEEN -2147483648 AND +2147483647),
rollidup VARCHAR2(32) NOT NULL ,
rolliddw VARCHAR2(32) NOT NULL ,
rollweightup NUMBER(10) CONSTRAINT cACCOUNTROLL_7 CHECK (rollweightup BETWEEN -2147483648 AND +2147483647),
rollweightdw NUMBER(10) CONSTRAINT cACCOUNTROLL_8 CHECK (rollweightdw BETWEEN -2147483648 AND +2147483647),
rollchgreason NUMBER(5) CONSTRAINT cACCOUNTROLL_9 CHECK (rollchgreason BETWEEN -32768 AND +32767),
rollcheck NUMBER(5) CONSTRAINT cACCOUNTROLL_10 CHECK (rollcheck BETWEEN -32768 AND +32767),
recman VARCHAR2(32) ,
toc DATE ,
tom DATE ,
mop VARCHAR2(120) ,
CONSTRAINT pk_ACCOUNTROLL PRIMARY KEY (standno,rollidup,rolliddw)
USING INDEX TABLESPACE INDTBS STORAGE ( FREELIST GROUPS 2 )
)
TABLESPACE DATATBS
PCTFREE 20
STORAGE ( INITIAL 500K
NEXT 500K
MINEXTENTS 1
MAXEXTENTS UNLIMITED
PCTINCREASE 0
FREELIST GROUPS 2 );
COMMENT ON Table ACCOUNTROLL IS ' ACCOUNT ROLL TABLE ';
COMMENT ON COLUMN ACCOUNTROLL.tdate IS ' Unit[-]:ÈÕÆÚ.Limit:[-,-] ';
COMMENT ON COLUMN ACCOUNTROLL.crewno IS ' Unit[-]:°à×é.Limit:[-,-] ';
COMMENT ON COLUMN ACCOUNTROLL.shiftno IS ' Unit[-]:°à´Î.Limit:[-,-] ';
COMMENT ON COLUMN ACCOUNTROLL.standno IS ' Unit[-]:»ú¼ÜºÅ.Limit:[-,-] ';
COMMENT ON COLUMN ACCOUNTROLL.recid IS ' Unit[-]:¼Ç¼ºÅ.Limit:[-,-] ';
COMMENT ON COLUMN ACCOUNTROLL.rollidup IS ' Unit[-]:ÉϹ¤×÷¹õID.Limit:[-,-] ';
COMMENT ON COLUMN ACCOUNTROLL.rolliddw IS ' Unit[-]:Ϲ¤×÷¹õID.Limit:[-,-] ';
COMMENT ON COLUMN ACCOUNTROLL.rollweightup IS ' Unit[-]:ÉϹ¤×÷¹õÔþÖÆÖØÁ¿.Limit:[-,-] ';
COMMENT ON COLUMN ACCOUNTROLL.rollweightdw IS ' Unit[-]:ÉϹ¤×÷¹õÔþÖÆÖØÁ¿.Limit:[-,-] ';
COMMENT ON COLUMN ACCOUNTROLL.rollchgreason IS ' Unit[-]:»»¹õÔÒò.Limit:[-,-] ';
COMMENT ON COLUMN ACCOUNTROLL.rollcheck IS ' Unit[-]:¹õÃæ¼ì²é½á¹û.Limit:[-,-] ';
COMMENT ON COLUMN ACCOUNTROLL.recman IS ' Unit[-]:¼Ç¼ÈË.Limit:[-,-] ';
COMMENT ON COLUMN ACCOUNTROLL.toc IS ' Unit[-]:´´½¨Ê±¼ä.Limit:[-,-] ';
COMMENT ON COLUMN ACCOUNTROLL.tom IS ' Unit[-]:×îºóÐÞ¸Äʱ¼ä.Limit:[-,-] ';
COMMENT ON COLUMN ACCOUNTROLL.mop IS ' Unit[-]:´´½¨»òÕßÐÞ¸ÄÕß.Limit:[-,-] ';
/
REM*************************************
REM INSERT TRIGGER FOR TABLE
REM ACCOUNTROLL
REM*************************************
DROP TRIGGER ins_b_ACCOUNTROLL;
CREATE OR REPLACE TRIGGER ins_b_ACCOUNTROLL
BEFORE INSERT ON ACCOUNTROLL FOR EACH ROW
DECLARE
programm VARCHAR(120);
user VARCHAR(30);
session_id NUMBER;
BEGIN
SELECT userenv('SESSIONID') INTO session_id FROM dual;
BEGIN
SELECT program,username INTO programm,user FROM V$SESSION
WHERE audsid = session_id;
EXCEPTION
WHEN NO_DATA_FOUND THEN
programm := 'UNKNOWN';
user := 'UNKNOWN';
WHEN OTHERS THEN
IF (session_id = 0) THEN
programm := 'JOB';
ELSE
programm := 'UNKNOWN';
END IF;
END;
:new.toc := sysdate;
:new.tom := sysdate;
:new.mop := substr( programm ,1 ,60);
END;
/
REM*************************************
REM UPDATE TRIGGER FOR TABLE
REM ACCOUNTROLL
REM*************************************
DROP TRIGGER upd_b_ACCOUNTROLL;
CREATE OR REPLACE TRIGGER upd_b_ACCOUNTROLL
BEFORE UPDATE ON ACCOUNTROLL FOR EACH ROW
DECLARE
programm VARCHAR(120);
user VARCHAR(30);
session_id NUMBER;
BEGIN
SELECT userenv('SESSIONID') INTO session_id FROM dual;
BEGIN
SELECT program,username INTO programm,user FROM V$SESSION
WHERE audsid = session_id;
EXCEPTION
WHEN NO_DATA_FOUND THEN
programm := 'UNKNOWN';
user := 'UNKNOWN';
WHEN OTHERS THEN
IF (session_id = 0) THEN
programm := 'JOB';
ELSE
programm := 'UNKNOWN';
END IF;
END;
:new.tom := sysdate;
:new.mop := substr( programm ,1 ,60);
END;
/
REM*******************************************************************
REM End of Scripts
REM Copyright (c) SGAI AI 2009. All Rights Reserved
REM*******************************************************************
| {
"content_hash": "165ce0455920910d5bf1ba53b597930b",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 124,
"avg_line_length": 38.32575757575758,
"alnum_prop": 0.5852935362719905,
"repo_name": "welljoe/code-sidelights",
"id": "2a7767f17c579fc3bd82c6effdea3c98a63ef5bc",
"size": "5059",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DBCodeGenerator/dump/sql/ACCOUNTROLL.sql",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "696901"
},
{
"name": "CSS",
"bytes": "3141"
},
{
"name": "Visual Basic",
"bytes": "677731"
},
{
"name": "XSLT",
"bytes": "12273"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html version="-//W3C//DTD XHTML 1.1//EN"
xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3.org/1999/xhtml
http://www.w3.org/MarkUp/SCHEMA/xhtml11.xsd">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<meta name=viewport content="width=device-width, initial-scale=0.3333334">
<meta name="google-site-verification" content="_bMOCDpkx9ZAzBwb2kF3PRHbfUUdFj2uO8Jd1AXArz4"/>
<title>ImageMagick: MagickCore, C API for ImageMagick: Segment an Image with Thresholding Fuzzy c-Means</title>
<meta http-equiv="content-language" content="en-US"/>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="reply-to" content="magick-users@imagemagick.org"/>
<meta name="application-name" content="ImageMagick"/>
<meta name="description" content="ImageMagick® is a software suite to create, edit, compose, or convert bitmap images. It can read and write images in a variety of formats (over 200) including PNG, JPEG, JPEG-2000, GIF, WebP, Postscript, PDF, and SVG. Use ImageMagick to resize, flip, mirror, rotate, distort, shear and transform images, adjust image colors, apply various special effects, or draw text, lines, polygons, ellipses and Bézier curves."/>
<meta name="application-url" content="http://www.imagemagick.org"/>
<meta name="generator" content="PHP"/>
<meta name="keywords" content="magickcore, c, api, for, imagemagick:, segment, an, image, with, thresholding, fuzzy, c-means, ImageMagick, PerlMagick, image processing, image, photo, software, Magick++, OpenMP, convert"/>
<meta name="rating" content="GENERAL"/>
<meta name="robots" content="INDEX, FOLLOW"/>
<meta name="generator" content="ImageMagick Studio LLC"/>
<meta name="author" content="ImageMagick Studio LLC"/>
<meta name="revisit-after" content="2 DAYS"/>
<meta name="resource-type" content="document"/>
<meta name="copyright" content="Copyright (c) 1999-2012 ImageMagick Studio LLC"/>
<meta name="distribution" content="Global"/>
<meta name="magick-serial" content="P131-S030410-R485315270133-P82224-A6668-G1245-1"/>
<link rel="icon" href="../../images/wand.png"/>
<link rel="shortcut icon" href="../../images/wand.ico" type="images/x-icon"/>
<link rel="canonical" href="../../index.html" />
<link rel="meta" type="application/rdf+xml" title="ICI" href="http://imagemagick.org/ici.rdf"/>
<!-- Add jQuery library -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<!-- Add mousewheel plugin (this is optional) -->
<script type="text/javascript" src="http://www.imagemagick.org/fancybox/lib/jquery.mousewheel-3.0.6.pack.js"></script>
<!-- Add fancyBox -->
<link rel="stylesheet" href="http://www.imagemagick.org/fancybox/source/jquery.fancybox.css?v=2.1.5" type="text/css" media="screen" />
<script type="text/javascript" src="http://www.imagemagick.org/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
<!-- Optionally add helpers - button, thumbnail and/or media -->
<link rel="stylesheet" href="http://www.imagemagick.org/fancybox/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" type="text/css" media="screen" />
<script type="text/javascript" src="http://www.imagemagick.org/fancybox/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script>
<script type="text/javascript" src="http://www.imagemagick.org/fancybox/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script>
<link rel="stylesheet" href="http://www.imagemagick.org/fancybox/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" type="text/css" media="screen" />
<script type="text/javascript" src="http://www.imagemagick.org/fancybox/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".fancybox").fancybox();
});
</script>
<!-- ImageMagick style -->
<style type="text/css" media="all">
@import url("../../www/magick.css");
</style>
</head>
<body id="www-imagemagick-org">
<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,'offline-script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-40133312-1', 'imagemagick.org');
ga('send', 'pageview');
</script>
<div class="titlebar">
<div style="margin: 17px auto; float: left;">
<script type="text/javascript">
<!--
google_ad_client = "pub-3129977114552745";
google_ad_slot = "5439289906";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
<a href="../../discourse-server">
<img src="../../images/logo.jpg"
alt="ImageMagick Logo" width="123" height="118"
style="width: 123px; height: 118px; border: 0px; float: right;" /></a>
<a href="../../index.html">
<img src="../../images/sprite.jpg"
alt="ImageMagick Sprite" width="114" height="118"
style="width: 114px; height: 118px; border: 0px; float: right;" /></a>
</div>
<div class="westbar">
<div class="menu">
<a title="About ImageMagick" href="../../index.html">About ImageMagick</a>
</div>
<div class="menu">
<a title="Binary Releases" href="../../www/binary-releases.html">Binary Releases</a>
</div>
<div class="sub">
<a title="Binary Release: Unix" href="../../www/binary-releases.html#unix">Unix</a>
</div>
<div class="sub">
<a title="Binary Release: MacOS X" href="../../www/binary-releases.html#macosx">Mac OS X</a>
</div>
<div class="sub">
<a title="Binary Release: iOS" href="../../www/binary-releases.html#iOS">iOS</a>
</div>
<div class="sub">
<a title="Binary Release: Windows" href="../../www/binary-releases.html#windows">Windows</a>
</div>
<div class="sep"></div>
<div class="menu">
<a title="Command-line Tools" href="../../www/command-line-tools.html">Command-line Tools</a>
</div>
<div class="sub">
<a title="Command-line Tools: Processing" href="../../www/command-line-processing.html">Processing</a>
</div>
<div class="sub">
<a title="Command-line Tools: Options" href="../../www/command-line-options.html">Options</a>
</div>
<div class="sub">
<a title="Command-line Tools: Usage" href="http://www.imagemagick.org/Usage/">Usage</a>
</div>
<div class="menu">
<a title="Program Interfaces" href="../../www/api.html">Program Interfaces</a>
</div>
<div class="sub">
<a title="Program Interface: MagickWand" href="../../www/magick-wand.html">MagickWand</a>
</div>
<div class="sub">
<a title="Program Interface: MagickCore" href="../../www/magick-core.html">MagickCore</a>
</div>
<div class="sub">
<a title="Program Interface: PerlMagick" href="../../www/perl-magick.html">PerlMagick</a>
</div>
<div class="sub">
<a title="Program Interface: Magick++" href="../../www/magick++.html">Magick++</a>
</div>
<div class="sep"></div>
<div class="menu">
<a title="Install from Source" href="../../www/install-source.html">Install from Source</a>
</div>
<div class="sub">
<a title="Install from Source: Unix" href="../../www/install-source.html#unix">Unix</a>
</div>
<div class="sub">
<a title="Install from Source: Windows" href="../../www/install-source.html#windows">Windows</a>
</div>
<div class="menu">
<a title="Resources" href="../../www/resources.html">Resources</a>
</div>
<div class="menu">
<a title="Architecture" href="../../www/architecture.html">Architecture</a>
</div>
<div class="menu">
<a title="Download" href="../../www/download.html">Download</a>
</div>
<div class="sep"></div>
<div class="menu">
<a title="Search" href="http://www.imagemagick.org/script/search.php">Search</a>
</div>
<div class="sep"></div>
<div class="menu">
<a title="Site Map" href="../../www/sitemap.html">Site Map</a>
</div>
<div class="sub">
<a title="Site Map: Links" href="../../www/links.html">Links</a>
</div>
<div class="sep"></div>
<div class="menu">
<a title="Support ImageMagick Development" href="../../www/support.html">Support ImageMagick Development</a>
</div>
</div>
<div class="eastbar">
<script type="text/javascript">
/* <![CDATA[ */
(function() {
var po = document.createElement('offline-script'), t = document.getElementsByTagName('offline-script')[0];
po.type = 'text/javascript';
po.async = true;
po.src = 'http://api.flattr.com/js/0.6/load.js?mode=auto';
var script = document.getElementsByTagName('offline-script')[0];
script.parentNode.insertBefore(po, script);
})();
/* ]]> */
</script>
<a class="FlattrButton" style="display:none;" rev="flattr;button:compact;" href="../../index.html"></a>
<noscript>
<a href="http://flattr.com/thing/947300/Convert-Edit-And-Compose-Images" target="_blank">
<img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" width="93" height="20" border="0" /></a>
</noscript>
</div>
<div class="main">
<h1>Module segment Methods</h1>
<p class="navigation-index">[<a href="segment.html#SegmentImage">SegmentImage</a>]</p>
<h2><a href="http://www.imagemagick.org/api/MagickCore/segment_8c.html" id="SegmentImage">SegmentImage</a></h2>
<div class="doc-section">
<p>SegmentImage() segment an image by analyzing the histograms of the color components and identifying units that are homogeneous with the fuzzy C-means technique.</p>
<p>The format of the SegmentImage method is:</p>
<pre class="code">
MagickBooleanType SegmentImage(Image *image,
const ColorspaceType colorspace,const MagickBooleanType verbose,
const double cluster_threshold,const double smooth_threshold)
</pre>
<p>A description of each parameter follows.</p>
<h5>image</h5>
<p>the image.</p>
<h5>colorspace</h5>
<p>Indicate the colorspace.</p>
<h5>verbose</h5>
<p>Set to MagickTrue to print detailed information about the identified classes.</p>
<h5>cluster_threshold</h5>
<p>This represents the minimum number of pixels contained in a hexahedra before it can be considered valid (expressed as a percentage).</p>
<h5>smooth_threshold</h5>
<p>the smoothing threshold eliminates noise in the second derivative of the histogram. As the value is increased, you can expect a smoother second derivative.</p>
</div>
</div>
<div id="linkbar">
<span id="linkbar-west"> </span>
<span id="linkbar-center">
<a href="../../discourse-server">Discourse Server</a> •
<a href="http://pgp.mit.edu:11371/pks/lookup?op=get&search=0x89AB63D48277377A">Public Key</a> •
<a href="http://www.imagemagick.org/MagickStudio/scripts/MagickStudio.cgi">Studio</a> •
<a href="http://jqmagick.imagemagick.org/">JqMagick</a>
</span>
<span id="linkbar-east"> </span>
</div>
<div class="footer">
<span id="footer-west">© 1999-2015 ImageMagick Studio LLC</span>
<span id="footer-east"> <a href="../../www/contact.html">Contact the Wizards</a></span>
</div>
<div style="clear: both; margin: 0; width: 100%; "></div>
</body>
</html>
| {
"content_hash": "5b3155b895ba565c003c46cd79c31f17",
"timestamp": "",
"source": "github",
"line_count": 265,
"max_line_length": 453,
"avg_line_length": 43.09811320754717,
"alnum_prop": 0.6757726994133614,
"repo_name": "hxfxjun/ImageMagick-6.9.1",
"id": "2ff4a596ab36e713edf4cb4d1330675e1a5271d1",
"size": "11430",
"binary": false,
"copies": "1",
"ref": "refs/heads/redhat",
"path": "www/api/segment.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ada",
"bytes": "85363"
},
{
"name": "Assembly",
"bytes": "1773894"
},
{
"name": "Awk",
"bytes": "49176"
},
{
"name": "C",
"bytes": "89301783"
},
{
"name": "C#",
"bytes": "105510"
},
{
"name": "C++",
"bytes": "13070408"
},
{
"name": "CLIPS",
"bytes": "5291"
},
{
"name": "CMake",
"bytes": "174368"
},
{
"name": "CSS",
"bytes": "137622"
},
{
"name": "Clean",
"bytes": "6801"
},
{
"name": "DTrace",
"bytes": "964"
},
{
"name": "Emacs Lisp",
"bytes": "41"
},
{
"name": "Go",
"bytes": "1235"
},
{
"name": "Groff",
"bytes": "2676870"
},
{
"name": "HTML",
"bytes": "16887087"
},
{
"name": "Inno Setup",
"bytes": "12736"
},
{
"name": "Java",
"bytes": "257845"
},
{
"name": "JavaScript",
"bytes": "51322"
},
{
"name": "Makefile",
"bytes": "1321970"
},
{
"name": "Matlab",
"bytes": "259"
},
{
"name": "Objective-C",
"bytes": "103246"
},
{
"name": "Pascal",
"bytes": "166295"
},
{
"name": "Perl",
"bytes": "384845"
},
{
"name": "Prolog",
"bytes": "510"
},
{
"name": "Python",
"bytes": "773025"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "Shell",
"bytes": "5896255"
},
{
"name": "Smalltalk",
"bytes": "408856"
},
{
"name": "Tcl",
"bytes": "49365"
},
{
"name": "TeX",
"bytes": "326716"
},
{
"name": "Vala",
"bytes": "1452"
},
{
"name": "Visual Basic",
"bytes": "26467"
},
{
"name": "XS",
"bytes": "936412"
},
{
"name": "XSLT",
"bytes": "43784"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_20) on Wed May 05 11:17:09 PDT 2010 -->
<TITLE>
org.apache.pig.backend.hadoop.hbase (Pig 0.7.0 API)
</TITLE>
<META NAME="date" CONTENT="2010-05-05">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<FONT size="+1" CLASS="FrameTitleFont">
<A HREF="../../../../../../org/apache/pig/backend/hadoop/hbase/package-summary.html" target="classFrame">org.apache.pig.backend.hadoop.hbase</A></FONT>
<TABLE BORDER="0" WIDTH="100%" SUMMARY="">
<TR>
<TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont">
Classes</FONT>
<FONT CLASS="FrameItemFont">
<BR>
<A HREF="HBaseStorage.html" title="class in org.apache.pig.backend.hadoop.hbase" target="classFrame">HBaseStorage</A></FONT></TD>
</TR>
</TABLE>
</BODY>
</HTML>
| {
"content_hash": "2f1cf6a42acf4f407097c64a7fdcc0e8",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 151,
"avg_line_length": 30.0625,
"alnum_prop": 0.6642411642411642,
"repo_name": "hirohanin/pig7hadoop21",
"id": "d384c1adf9226e0b72f754c5f481aa5e758990a4",
"size": "962",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/api/org/apache/pig/backend/hadoop/hbase/package-frame.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using System;
namespace Grauenwolf.TravellerTools.Characters
{
public static class SimpleCharacterEngine
{
public static void AddCharacteristics(Person person, Dice random)
{
Func<int> Bump = () => ((random.NextDouble() <= 0.054) ? 1 : 0);
person.Strength = random.D(2, 6);
person.Dexterity = random.D(2, 6);
person.Endurance = random.D(2, 6);
person.Intellect = random.D(2, 6);
person.Education = random.D(2, 6);
person.Social = random.D(2, 6);
var termsServed = (int)Math.Floor((person.ApparentAge - 18) / 4.0);
for (var i = 0; i < termsServed; i++)
{
person.Strength += Bump();
person.Dexterity += Bump();
person.Endurance += Bump();
person.Intellect += Bump();
person.Education += Bump();
person.Social += Bump();
if (i >= 4)
ApplyAgePenalty(person, random, i);
}
}
static public void AddTrait(Person person, Dice dice)
{
int roll1 = dice.D66();
switch (roll1)
{
case 11: person.Trait = "Loyal"; return;
case 12: person.Trait = "Distracted by other worries"; return;
case 13: person.Trait = "In debt to criminals"; return;
case 14: person.Trait = "Makes very bad jokes"; return;
case 15: person.Trait = "Will betray characters"; return;
case 16: person.Trait = "Aggressive"; return;
case 21: person.Trait = "Has secret allies"; return;
case 22: person.Trait = "Secret anagathic user"; return;
case 23: person.Trait = "Looking for something"; return;
case 24: person.Trait = "Helpful"; return;
case 25: person.Trait = "Forgetful"; return;
case 26:
person.IsPatron = true;
person.Trait = "Wants to hire the characters";
person.PatronMission = PatronBuilder.PickMission(dice);
return;
case 31: person.Trait = "Has useful contacts"; return;
case 32: person.Trait = "Artistic"; return;
case 33: person.Trait = "Easily confused"; return;
case 34: person.Trait = "Unusually ugly"; return;
case 35: person.Trait = "Worried about current situation"; return;
case 36: person.Trait = "Shows pictures of children"; return;
case 41: person.Trait = "Rumor-monger"; return;
case 42: person.Trait = "Unusually provincial"; return;
case 43: person.Trait = "Drunkard or drug addict"; return;
case 44: person.Trait = "Government informant"; return;
case 45: person.Trait = "Mistakes a PC for someone else"; return;
case 46: person.Trait = "Possess unusually advanced technology"; return;
case 51: person.Trait = "Unusually handsome or beautiful"; return;
case 52: person.Trait = "Spying on the characters"; return;
case 53: person.Trait = "Possesses a TAS membership"; return;
case 54: person.Trait = "Is secretly hostile to characters"; return;
case 55: person.Trait = "Wants to borrow money"; return;
case 56: person.Trait = "Is convinced the PCs are dangerous"; return;
case 61: person.Trait = "Involved in political intrigue"; return;
case 62: person.Trait = "Has a dangerous secret"; return;
case 63: person.Trait = "Wants to get off-planet as soon as possible"; return;
case 64: person.Trait = "Attracted to a player character"; return;
case 65: person.Trait = "From offworld"; return;
case 66: person.Trait = "Possesses telepathy or other usual ability"; return;
}
}
public static void ApplyAgePenalty(Person person, Dice random, int termsComplete)
{
var roll = random.D(2, 6) - termsComplete;
if (roll == -6)
{
person.Strength -= 2;
person.Dexterity -= 2;
person.Endurance -= 2;
AlterRandomMental(person, random, -1);
}
else if (roll == -5)
{
person.Strength -= 2;
person.Dexterity -= 2;
person.Endurance -= 2;
}
else if (roll == -4)
{
person.Strength -= 2;
person.Dexterity -= 2;
person.Endurance -= 2;
AlterRandomPhysical(person, random, 1);//undo one reduction
}
else if (roll == -3)
{
person.Strength -= 1;
person.Dexterity -= 1;
person.Endurance -= 1;
AlterRandomPhysical(person, random, -1);
}
else if (roll == -2)
{
person.Strength -= 1;
person.Dexterity -= 1;
person.Endurance -= 1;
}
else if (roll == -1)
{
person.Strength -= 1;
person.Dexterity -= 1;
person.Endurance -= 1;
AlterRandomPhysical(person, random, 1); //undo one reduction
}
else if (roll == 0)
{
AlterRandomPhysical(person, random, -1);
}
//Upper limits
if (person.Strength.Value > 15) { person.Strength = 15; }
if (person.Dexterity.Value > 15) { person.Dexterity = 15; }
if (person.Endurance.Value > 15) { person.Endurance = 15; }
if (person.Intellect.Value > 15) { person.Intellect = 15; }
if (person.Education.Value > 15) { person.Education = 15; }
if (person.Social.Value > 15) { person.Social = 15; }
////Aging crisis
//if (person.Strength.Value <= 0) { person.Strength = 1; person.AgingCrisis = true; }
//if (person.Dexterity.Value <= 0) { person.Dexterity = 1; person.AgingCrisis = true; }
//if (person.Endurance.Value <= 0) { person.Endurance = 1; person.AgingCrisis = true; }
//if (person.Intellect.Value <= 0) { person.Intellect = 1; person.AgingCrisis = true; }
//if (person.Education.Value <= 0) { person.Education = 1; person.AgingCrisis = true; }
//if (person.Social.Value <= 0) { person.Social = 1; person.AgingCrisis = true; }
}
static void AlterRandomMental(Person person, Dice random, int amount)
{
switch (random.D(3))
{
case 1: person.Intellect += amount; return;
case 2: person.Education += amount; return;
case 3: person.Social += amount; return;
}
}
static void AlterRandomPhysical(Person person, Dice random, int amount)
{
switch (random.D(3))
{
case 1: person.Strength += amount; return;
case 2: person.Dexterity += amount; return;
case 3: person.Endurance += amount; return;
}
}
}
} | {
"content_hash": "8e5a5ca671a2f48b557be93197279698",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 99,
"avg_line_length": 44.375,
"alnum_prop": 0.5103957075788061,
"repo_name": "Grauenwolf/TravellerTools",
"id": "0a007844c804943b283e303928f5223288aaccee",
"size": "7457",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "TravellerTools/Grauenwolf.TravellerTools.Services/Characters/SimpleCharacterEngine.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "112"
},
{
"name": "C#",
"bytes": "849902"
},
{
"name": "CSS",
"bytes": "3381"
},
{
"name": "HTML",
"bytes": "95035"
},
{
"name": "JavaScript",
"bytes": "237498"
},
{
"name": "TypeScript",
"bytes": "8421"
}
],
"symlink_target": ""
} |
wlux_web_service
================
The new version of the "back end" code, starting with Winter 2014
| {
"content_hash": "e95ee0b7d54f0efb533d29d3566e270d",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 65,
"avg_line_length": 25.25,
"alnum_prop": 0.6435643564356436,
"repo_name": "rbwatson/wlux_web_service",
"id": "906fa9f182ede7c89b1f392b7b5cff4b08229ab6",
"size": "101",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1513"
},
{
"name": "JavaScript",
"bytes": "13821"
},
{
"name": "PHP",
"bytes": "146230"
},
{
"name": "Shell",
"bytes": "10800"
}
],
"symlink_target": ""
} |
package org.apache.hadoop.examples;
import java.util.Random;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.mapred.lib.*;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
/* Extracts matching regexs from input files and counts them. */
public class Grep extends Configured implements Tool {
private Grep() {
} // singleton
public int run(String[] args) throws Exception {
if (args.length < 3) {
System.out.println("Grep <inDir> <outDir> <regex> [<group>]");
ToolRunner.printGenericCommandUsage(System.out);
return -1;
}
Path tempDir = new Path("grep-temp-" + Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
JobConf grepJob = new JobConf(getConf(), Grep.class);
try {
grepJob.setJobName("grep-search");
FileInputFormat.setInputPaths(grepJob, args[0]);
grepJob.setMapperClass(RegexMapper.class);
grepJob.set("mapred.mapper.regex", args[2]);
if (args.length == 4)
grepJob.set("mapred.mapper.regex.group", args[3]);
grepJob.setCombinerClass(LongSumReducer.class);
grepJob.setReducerClass(LongSumReducer.class);
FileOutputFormat.setOutputPath(grepJob, tempDir);
grepJob.setOutputFormat(SequenceFileOutputFormat.class);
grepJob.setOutputKeyClass(Text.class);
grepJob.setOutputValueClass(LongWritable.class);
JobClient.runJob(grepJob);
JobConf sortJob = new JobConf(Grep.class);
sortJob.setJobName("grep-sort");
FileInputFormat.setInputPaths(sortJob, tempDir);
sortJob.setInputFormat(SequenceFileInputFormat.class);
sortJob.setMapperClass(InverseMapper.class);
sortJob.setNumReduceTasks(1); // write a single file
FileOutputFormat.setOutputPath(sortJob, new Path(args[1]));
sortJob.setOutputKeyComparatorClass // sort by decreasing freq
(LongWritable.DecreasingComparator.class);
JobClient.runJob(sortJob);
} finally {
FileSystem.get(grepJob).delete(tempDir, true);
}
return 0;
}
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(), new Grep(), args);
System.exit(res);
}
}
| {
"content_hash": "b8c7dcc50f5eb97f29f6174155dc2431",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 106,
"avg_line_length": 33.69620253164557,
"alnum_prop": 0.654770848985725,
"repo_name": "dongpf/hadoop-0.19.1",
"id": "1a3fa1b6bcce9d2a07621f50b1352387fa60280b",
"size": "3468",
"binary": false,
"copies": "1",
"ref": "refs/heads/rsc",
"path": "src/examples/org/apache/hadoop/examples/Grep.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "631"
},
{
"name": "C",
"bytes": "368366"
},
{
"name": "C++",
"bytes": "506373"
},
{
"name": "Java",
"bytes": "11404415"
},
{
"name": "JavaScript",
"bytes": "60544"
},
{
"name": "Objective-C",
"bytes": "118487"
},
{
"name": "PHP",
"bytes": "884765"
},
{
"name": "Perl",
"bytes": "150452"
},
{
"name": "Python",
"bytes": "1619112"
},
{
"name": "Ruby",
"bytes": "28485"
},
{
"name": "Shell",
"bytes": "878487"
},
{
"name": "Smalltalk",
"bytes": "56562"
},
{
"name": "XML",
"bytes": "243803"
}
],
"symlink_target": ""
} |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="70sp"
android:text="Gravity ve Weight"
android:id="@+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button"
android:layout_weight="0.5"
android:layout_gravity="right"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button2"
android:layout_weight="0.4"
android:layout_gravity="center_horizontal"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button3"
android:layout_weight="0.1"
android:layout_gravity="left"/>
</LinearLayout>
| {
"content_hash": "2b5c2b90d67b4c33b222de97bbccb495",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 72,
"avg_line_length": 32.65217391304348,
"alnum_prop": 0.6504660452729694,
"repo_name": "Osman93/Android",
"id": "4bbc76b486b842ddaace746a84ea942d5459b2f3",
"size": "1502",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "GravityAndWeightKavramları/app/src/main/res/layout/activity_main.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1"
},
{
"name": "C++",
"bytes": "1"
},
{
"name": "Java",
"bytes": "123751"
}
],
"symlink_target": ""
} |
namespace CGAL {
namespace internal {
template<typename Polynomial_2, typename Bound>
struct Interval_evaluate_2 : public std::binary_function
<Polynomial_2,CGAL::cpp11::array<Bound,4>,
std::pair<typename CGAL::Coercion_traits<typename CGAL::Polynomial_traits_d<Polynomial_2>::Innermost_coefficient_type,Bound>::Type,
typename CGAL::Coercion_traits<typename CGAL::Polynomial_traits_d<Polynomial_2>::Innermost_coefficient_type,Bound>::Type> > {
public:
typedef CGAL::Polynomial_traits_d< Polynomial_2 > PT_2;
typedef typename PT_2::Innermost_coefficient_type Innermost_coefficient_type;
typedef CGAL::Coercion_traits< Innermost_coefficient_type, Bound > CT;
typedef typename CT::Type Coercion_type;
typedef std::pair< Coercion_type, Coercion_type > result_type;
result_type operator()(const Polynomial_2& p,
const CGAL::cpp11::array< Bound, 4 >& b) const {
typename CT::Cast cast;
typedef ::boost::numeric::interval< Coercion_type > Coercion_interval;
typedef typename PT_2::Coefficient_const_iterator
Coefficient_const_iterator;
typedef typename PT_2::Coefficient_const_iterator_range
Coefficient_const_iterator_range;
typedef typename PT_2::Coefficient_type Polynomial_1;
CGAL::internal::Interval_evaluate_1< Polynomial_1,Bound >
interval_evaluate_1;
typedef typename CGAL::internal::Interval_evaluate_1< Polynomial_1,Bound >::
result_type Interval_result_type;
std::pair< Bound, Bound > x_pair = std::make_pair(b[0],b[1]);
Coercion_interval iy(cast(b[2]),cast(b[3]));
// CGAL::Polynomial does not provide Coercion_traits for number
// types => therefore evaluate manually
Coefficient_const_iterator_range range =
typename PT_2::Construct_coefficient_const_iterator_range()(p);
Coefficient_const_iterator it = CGAL::cpp11::prev(range.second);
Interval_result_type initial_pair = interval_evaluate_1(*it,x_pair);
Coercion_interval res(initial_pair.first,initial_pair.second);
Coefficient_const_iterator p_begin = range.first;
while((it) != p_begin) {
it--;
Interval_result_type curr_iv = interval_evaluate_1(*it,x_pair);
res = res * iy + Coercion_interval(curr_iv.first,curr_iv.second);
}
return std::make_pair(res.lower(),res.upper());
}
};
} // namespace internal
} // namespace CGAL
#endif // CGAL_INTERVAL_EVALUATE_2
| {
"content_hash": "2437280535b9f74678a2a5c41e718416",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 141,
"avg_line_length": 33.333333333333336,
"alnum_prop": 0.6816,
"repo_name": "alexandrustaetu/natural_editor",
"id": "43e342239410297ab689706295a11445a176b4ba",
"size": "3681",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "external/CGAL-4.4-beta1/include/CGAL/Algebraic_kernel_d/Interval_evaluate_2.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "85830"
},
{
"name": "C++",
"bytes": "341100"
},
{
"name": "Shell",
"bytes": "2362"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 330572 $ -->
<reference xml:id="ref.opcache" xmlns="http://docbook.org/ns/docbook">
<title>OPcache &Functions;</title>
&reference.opcache.entities.functions;
</reference>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
| {
"content_hash": "389e62267a6dfb4aeb377724657c527d",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 70,
"avg_line_length": 22.096774193548388,
"alnum_prop": 0.7372262773722628,
"repo_name": "mziyut/.vim",
"id": "7e8dddb338e74ef102a7e5d4a79b6675517fde0e",
"size": "685",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "dict/.neocomplete-php/phpdoc/en/reference/opcache/reference.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2223"
},
{
"name": "Ruby",
"bytes": "939"
},
{
"name": "Shell",
"bytes": "582"
},
{
"name": "Vim script",
"bytes": "22415"
}
],
"symlink_target": ""
} |
package com.github.bohnman.squiggly.examples.springboot.exception;
public class NotFoundException extends RuntimeException {
public NotFoundException() {
}
public NotFoundException(String message) {
super(message);
}
public NotFoundException(String message, Throwable cause) {
super(message, cause);
}
public NotFoundException(Throwable cause) {
super(cause);
}
public NotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| {
"content_hash": "33502bd3a644734098db7f016ef81f18",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 118,
"avg_line_length": 28.181818181818183,
"alnum_prop": 0.717741935483871,
"repo_name": "bohnman/squiggly-filter-jackson",
"id": "3b6882df1faa5a9002a2d148a3629dd76520caf9",
"size": "620",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/spring-boot/src/main/java/com/github/bohnman/squiggly/examples/springboot/exception/NotFoundException.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ANTLR",
"bytes": "1983"
},
{
"name": "Java",
"bytes": "94973"
},
{
"name": "Shell",
"bytes": "2393"
}
],
"symlink_target": ""
} |
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h"
#include "util.h"
#include "sync.h"
#include "ui_interface.h"
#include "base58.h"
#include "bitcoinrpc.h"
#include "db.h"
#undef printf
#include <boost/asio.hpp>
#include <boost/asio/ip/v6_only.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/shared_ptr.hpp>
#include <list>
#define printf OutputDebugStringF
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
void ThreadRPCServer2(void* parg);
static std::string strRPCUserColonPass;
const Object emptyobj;
void ThreadRPCServer3(void* parg);
static inline unsigned short GetDefaultRPCPort()
{
return GetBoolArg("-testnet", false) ? 20802 : 20802;
}
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
void RPCTypeCheck(const Array& params,
const list<Value_type>& typesExpected,
bool fAllowNull)
{
unsigned int i = 0;
BOOST_FOREACH(Value_type t, typesExpected)
{
if (params.size() <= i)
break;
const Value& v = params[i];
if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s, got %s",
Value_type_name[t], Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
i++;
}
}
void RPCTypeCheck(const Object& o,
const map<string, Value_type>& typesExpected,
bool fAllowNull)
{
BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
{
const Value& v = find_value(o, t.first);
if (!fAllowNull && v.type() == null_type)
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s for %s, got %s",
Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
}
}
int64 AmountFromValue(const Value& value)
{
double dAmount = value.get_real();
if (dAmount <= 0.0 || dAmount > MAX_MONEY)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
int64 nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount))
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
return nAmount;
}
Value ValueFromAmount(int64 amount)
{
return (double)amount / (double)COIN;
}
std::string HexBits(unsigned int nBits)
{
union {
int32_t nBits;
char cBits[4];
} uBits;
uBits.nBits = htonl((int32_t)nBits);
return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
}
///
/// Note: This interface may still be subject to change.
///
string CRPCTable::help(string strCommand) const
{
string strRet;
set<rpcfn_type> setDone;
for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
{
const CRPCCommand *pcmd = mi->second;
string strMethod = mi->first;
// We already filter duplicates, but these deprecated screw up the sort order
if (strMethod.find("label") != string::npos)
continue;
if (strCommand != "" && strMethod != strCommand)
continue;
try
{
Array params;
rpcfn_type pfn = pcmd->actor;
if (setDone.insert(pfn).second)
(*pfn)(params, true);
}
catch (std::exception& e)
{
// Help text is returned in an exception
string strHelp = string(e.what());
if (strCommand == "")
if (strHelp.find('\n') != string::npos)
strHelp = strHelp.substr(0, strHelp.find('\n'));
strRet += strHelp + "\n";
}
}
if (strRet == "")
strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
Value help(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"help [command]\n"
"List commands, or get help for a command.");
string strCommand;
if (params.size() > 0)
strCommand = params[0].get_str();
return tableRPC.help(strCommand);
}
Value stop(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"stop <detach>\n"
"<detach> is true or false to detach the database or not for this stop only\n"
"Stop chakracoin server (and possibly override the detachdb config value).");
// Shutdown will take long enough that the response should get back
if (params.size() > 0)
bitdb.SetDetach(params[0].get_bool());
StartShutdown();
return "chakracoin server stopping";
}
//
// Call Table
//
static const CRPCCommand vRPCCommands[] =
{ // name function safemd unlocked
// ------------------------ ----------------------- ------ --------
{ "help", &help, true, true },
{ "stop", &stop, true, true },
{ "getblockcount", &getblockcount, true, false },
{ "getconnectioncount", &getconnectioncount, true, false },
{ "getpeerinfo", &getpeerinfo, true, false },
{ "getdifficulty", &getdifficulty, true, false },
{ "getgenerate", &getgenerate, true, false },
{ "setgenerate", &setgenerate, true, false },
{ "gethashespersec", &gethashespersec, true, false },
{ "getinfo", &getinfo, true, false },
{ "getmininginfo", &getmininginfo, true, false },
{ "getnewaddress", &getnewaddress, true, false },
{ "getnewpubkey", &getnewpubkey, true, false },
{ "getaccountaddress", &getaccountaddress, true, false },
{ "setaccount", &setaccount, true, false },
{ "getaccount", &getaccount, false, false },
{ "getaddressesbyaccount", &getaddressesbyaccount, true, false },
{ "sendtoaddress", &sendtoaddress, false, false },
{ "getreceivedbyaddress", &getreceivedbyaddress, false, false },
{ "getreceivedbyaccount", &getreceivedbyaccount, false, false },
{ "listreceivedbyaddress", &listreceivedbyaddress, false, false },
{ "listreceivedbyaccount", &listreceivedbyaccount, false, false },
{ "backupwallet", &backupwallet, true, false },
{ "keypoolrefill", &keypoolrefill, true, false },
{ "walletpassphrase", &walletpassphrase, true, false },
{ "walletpassphrasechange", &walletpassphrasechange, false, false },
{ "walletlock", &walletlock, true, false },
{ "encryptwallet", &encryptwallet, false, false },
{ "validateaddress", &validateaddress, true, false },
{ "validatepubkey", &validatepubkey, true, false },
{ "getbalance", &getbalance, false, false },
{ "move", &movecmd, false, false },
{ "sendfrom", &sendfrom, false, false },
{ "sendmany", &sendmany, false, false },
{ "addmultisigaddress", &addmultisigaddress, false, false },
{ "getrawmempool", &getrawmempool, true, false },
{ "getblock", &getblock, false, false },
{ "getblockbynumber", &getblockbynumber, false, false },
{ "getblockhash", &getblockhash, false, false },
{ "gettransaction", &gettransaction, false, false },
{ "listtransactions", &listtransactions, false, false },
{ "listaddressgroupings", &listaddressgroupings, false, false },
{ "signmessage", &signmessage, false, false },
{ "verifymessage", &verifymessage, false, false },
{ "getwork", &getwork, true, false },
{ "getworkex", &getworkex, true, false },
{ "listaccounts", &listaccounts, false, false },
{ "settxfee", &settxfee, false, false },
{ "getblocktemplate", &getblocktemplate, true, false },
{ "submitblock", &submitblock, false, false },
{ "listsinceblock", &listsinceblock, false, false },
{ "dumpprivkey", &dumpprivkey, false, false },
{ "importprivkey", &importprivkey, false, false },
{ "listunspent", &listunspent, false, false },
{ "getrawtransaction", &getrawtransaction, false, false },
{ "createrawtransaction", &createrawtransaction, false, false },
{ "decoderawtransaction", &decoderawtransaction, false, false },
{ "signrawtransaction", &signrawtransaction, false, false },
{ "sendrawtransaction", &sendrawtransaction, false, false },
{ "getcheckpoint", &getcheckpoint, true, false },
{ "reservebalance", &reservebalance, false, true},
{ "checkwallet", &checkwallet, false, true},
{ "repairwallet", &repairwallet, false, true},
{ "resendtx", &resendtx, false, true},
{ "makekeypair", &makekeypair, false, true},
{ "sendalert", &sendalert, false, false},
};
CRPCTable::CRPCTable()
{
unsigned int vcidx;
for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
{
const CRPCCommand *pcmd;
pcmd = &vRPCCommands[vcidx];
mapCommands[pcmd->name] = pcmd;
}
}
const CRPCCommand *CRPCTable::operator[](string name) const
{
map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end())
return NULL;
return (*it).second;
}
//
// HTTP protocol
//
// This ain't Apache. We're just using HTTP header for the length field
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: chakracoin-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
string rfc1123Time()
{
char buffer[64];
time_t now;
time(&now);
struct tm* now_gmt = gmtime(&now);
string locale(setlocale(LC_TIME, NULL));
setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
setlocale(LC_TIME, locale.c_str());
return string(buffer);
}
static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
{
if (nStatus == HTTP_UNAUTHORIZED)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: chakracoin-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
const char *cStatus;
if (nStatus == HTTP_OK) cStatus = "OK";
else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
else cStatus = "";
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %"PRIszu"\r\n"
"Content-Type: application/json\r\n"
"Server: chakracoin-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
cStatus,
rfc1123Time().c_str(),
keepalive ? "keep-alive" : "close",
strMsg.size(),
FormatFullVersion().c_str(),
strMsg.c_str());
}
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return HTTP_INTERNAL_SERVER_ERROR;
proto = 0;
const char *ver = strstr(str.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return atoi(vWords[1].c_str());
}
int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
loop
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read status
int nProto = 0;
int nStatus = ReadHTTPStatus(stream, nProto);
// Read header
int nLen = ReadHTTPHeader(stream, mapHeadersRet);
if (nLen < 0 || nLen > (int)MAX_SIZE)
return HTTP_INTERNAL_SERVER_ERROR;
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
{
if (nProto >= 1)
mapHeadersRet["connection"] = "keep-alive";
else
mapHeadersRet["connection"] = "close";
}
return nStatus;
}
bool HTTPAuthorized(map<string, string>& mapHeaders)
{
string strAuth = mapHeaders["authorization"];
if (strAuth.substr(0,6) != "Basic ")
return false;
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
string strUserPass = DecodeBase64(strUserPass64);
return strUserPass == strRPCUserColonPass;
}
//
// JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
// unspecified (HTTP errors and contents of 'error').
//
// 1.0 spec: http://json-rpc.org/wiki/specification
// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
{
// Send error reply from json-rpc error object
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
int code = find_value(objError, "code").get_int();
if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
string strReply = JSONRPCReply(Value::null, objError, id);
stream << HTTPReply(nStatus, strReply, false) << std::flush;
}
bool ClientAllowed(const boost::asio::ip::address& address)
{
// Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
if (address.is_v6()
&& (address.to_v6().is_v4_compatible()
|| address.to_v6().is_v4_mapped()))
return ClientAllowed(address.to_v6().to_v4());
std::string ipv4addr = address.to_string();
if (address == asio::ip::address_v4::loopback()
|| address == asio::ip::address_v6::loopback()
|| (address.is_v4()
// Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
&& (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
return true;
const string strAddress = address.to_string();
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow))
return true;
return false;
}
//
// IOStream device that speaks SSL but can also speak non-SSL
//
template <typename Protocol>
class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
public:
SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
{
fUseSSL = fUseSSLIn;
fNeedHandshake = fUseSSLIn;
}
void handshake(ssl::stream_base::handshake_type role)
{
if (!fNeedHandshake) return;
fNeedHandshake = false;
stream.handshake(role);
}
std::streamsize read(char* s, std::streamsize n)
{
handshake(ssl::stream_base::server); // HTTPS servers read first
if (fUseSSL) return stream.read_some(asio::buffer(s, n));
return stream.next_layer().read_some(asio::buffer(s, n));
}
std::streamsize write(const char* s, std::streamsize n)
{
handshake(ssl::stream_base::client); // HTTPS clients write first
if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
return asio::write(stream.next_layer(), asio::buffer(s, n));
}
bool connect(const std::string& server, const std::string& port)
{
ip::tcp::resolver resolver(stream.get_io_service());
ip::tcp::resolver::query query(server.c_str(), port.c_str());
ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
ip::tcp::resolver::iterator end;
boost::system::error_code error = asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
stream.lowest_layer().close();
stream.lowest_layer().connect(*endpoint_iterator++, error);
}
if (error)
return false;
return true;
}
private:
bool fNeedHandshake;
bool fUseSSL;
asio::ssl::stream<typename Protocol::socket>& stream;
};
class AcceptedConnection
{
public:
virtual ~AcceptedConnection() {}
virtual std::iostream& stream() = 0;
virtual std::string peer_address_to_string() const = 0;
virtual void close() = 0;
};
template <typename Protocol>
class AcceptedConnectionImpl : public AcceptedConnection
{
public:
AcceptedConnectionImpl(
asio::io_service& io_service,
ssl::context &context,
bool fUseSSL) :
sslStream(io_service, context),
_d(sslStream, fUseSSL),
_stream(_d)
{
}
virtual std::iostream& stream()
{
return _stream;
}
virtual std::string peer_address_to_string() const
{
return peer.address().to_string();
}
virtual void close()
{
_stream.close();
}
typename Protocol::endpoint peer;
asio::ssl::stream<typename Protocol::socket> sslStream;
private:
SSLIOStreamDevice<Protocol> _d;
iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
};
void ThreadRPCServer(void* parg)
{
// Make this thread recognisable as the RPC listener
RenameThread("bitcoin-rpclist");
try
{
vnThreadsRunning[THREAD_RPCLISTENER]++;
ThreadRPCServer2(parg);
vnThreadsRunning[THREAD_RPCLISTENER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_RPCLISTENER]--;
PrintException(&e, "ThreadRPCServer()");
} catch (...) {
vnThreadsRunning[THREAD_RPCLISTENER]--;
PrintException(NULL, "ThreadRPCServer()");
}
printf("ThreadRPCServer exited\n");
}
// Forward declaration required for RPCListen
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error);
/**
* Sets up I/O resources to accept and handle a new connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL)
{
// Accept connection
AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
acceptor->async_accept(
conn->sslStream.lowest_layer(),
conn->peer,
boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
acceptor,
boost::ref(context),
fUseSSL,
conn,
boost::asio::placeholders::error));
}
/**
* Accept and handle incoming connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error)
{
vnThreadsRunning[THREAD_RPCLISTENER]++;
// Immediately start accepting new connections, except when we're cancelled or our socket is closed.
if (error != asio::error::operation_aborted
&& acceptor->is_open())
RPCListen(acceptor, context, fUseSSL);
AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
// TODO: Actually handle errors
if (error)
{
delete conn;
}
// Restrict callers by IP. It is important to
// do this before starting client thread, to filter out
// certain DoS and misbehaving clients.
else if (tcp_conn
&& !ClientAllowed(tcp_conn->peer.address()))
{
// Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
if (!fUseSSL)
conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
delete conn;
}
// start HTTP client thread
else if (!NewThread(ThreadRPCServer3, conn)) {
printf("Failed to create RPC server client thread\n");
delete conn;
}
vnThreadsRunning[THREAD_RPCLISTENER]--;
}
void ThreadRPCServer2(void* parg)
{
printf("ThreadRPCServer started\n");
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
if (mapArgs["-rpcpassword"] == "")
{
unsigned char rand_pwd[32];
RAND_bytes(rand_pwd, 32);
string strWhatAmI = "To use chakracoind";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
uiInterface.ThreadSafeMessageBox(strprintf(
_("%s, you must set a rpcpassword in the configuration file:\n %s\n"
"It is recommended you use the following random password:\n"
"rpcuser=bitcoinrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"If the file does not exist, create it with owner-readable-only file permissions.\n"),
strWhatAmI.c_str(),
GetConfigFile().string().c_str(),
EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
_("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
StartShutdown();
return;
}
const bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
if (fUseSSL)
{
context.set_options(ssl::context::no_sslv2);
filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
if (filesystem::exists(pathCertFile)) context.use_certificate_chain_file(pathCertFile.string());
else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
if (filesystem::exists(pathPKFile)) context.use_private_key_file(pathPKFile.string(), ssl::context::pem);
else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(context.impl(), strCiphers.c_str());
}
// Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
const bool loopback = !mapArgs.count("-rpcallowip");
asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort()));
boost::system::error_code v6_only_error;
boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(io_service));
boost::signals2::signal<void ()> StopRequests;
bool fListening = false;
std::string strerr;
try
{
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
// Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, context, fUseSSL);
// Cancel outstanding listen-requests for this acceptor when shutting down
StopRequests.connect(signals2::slot<void ()>(
static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
.track(acceptor));
fListening = true;
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what());
}
try {
// If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
if (!fListening || loopback || v6_only_error)
{
bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
endpoint.address(bindAddress);
acceptor.reset(new ip::tcp::acceptor(io_service));
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, context, fUseSSL);
// Cancel outstanding listen-requests for this acceptor when shutting down
StopRequests.connect(signals2::slot<void ()>(
static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
.track(acceptor));
fListening = true;
}
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
}
if (!fListening) {
uiInterface.ThreadSafeMessageBox(strerr, _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
StartShutdown();
return;
}
vnThreadsRunning[THREAD_RPCLISTENER]--;
while (!fShutdown)
io_service.run_one();
vnThreadsRunning[THREAD_RPCLISTENER]++;
StopRequests();
}
class JSONRequest
{
public:
Value id;
string strMethod;
Array params;
JSONRequest() { id = Value::null; }
void parse(const Value& valRequest);
};
void JSONRequest::parse(const Value& valRequest)
{
// Parse request
if (valRequest.type() != obj_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
const Object& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
Value valMethod = find_value(request, "method");
if (valMethod.type() == null_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
if (valMethod.type() != str_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
if (strMethod != "getwork" && strMethod != "getblocktemplate")
printf("ThreadRPCServer method=%s\n", strMethod.c_str());
// Parse params
Value valParams = find_value(request, "params");
if (valParams.type() == array_type)
params = valParams.get_array();
else if (valParams.type() == null_type)
params = Array();
else
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
}
static Object JSONRPCExecOne(const Value& req)
{
Object rpc_result;
JSONRequest jreq;
try {
jreq.parse(req);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
}
catch (Object& objError)
{
rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
}
catch (std::exception& e)
{
rpc_result = JSONRPCReplyObj(Value::null,
JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
}
return rpc_result;
}
static string JSONRPCExecBatch(const Array& vReq)
{
Array ret;
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
return write_string(Value(ret), false) + "\n";
}
static CCriticalSection cs_THREAD_RPCHANDLER;
void ThreadRPCServer3(void* parg)
{
// Make this thread recognisable as the RPC handler
RenameThread("bitcoin-rpchand");
{
LOCK(cs_THREAD_RPCHANDLER);
vnThreadsRunning[THREAD_RPCHANDLER]++;
}
AcceptedConnection *conn = (AcceptedConnection *) parg;
bool fRun = true;
loop {
if (fShutdown || !fRun)
{
conn->close();
delete conn;
{
LOCK(cs_THREAD_RPCHANDLER);
--vnThreadsRunning[THREAD_RPCHANDLER];
}
return;
}
map<string, string> mapHeaders;
string strRequest;
ReadHTTP(conn->stream(), mapHeaders, strRequest);
// Check authorization
if (mapHeaders.count("authorization") == 0)
{
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (!HTTPAuthorized(mapHeaders))
{
printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
/* Deter brute-forcing short passwords.
If this results in a DOS the user really
shouldn't have their RPC port exposed.*/
if (mapArgs["-rpcpassword"].size() < 20)
Sleep(250);
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (mapHeaders["connection"] == "close")
fRun = false;
JSONRequest jreq;
try
{
// Parse request
Value valRequest;
if (!read_string(strRequest, valRequest))
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
string strReply;
// singleton request
if (valRequest.type() == obj_type) {
jreq.parse(valRequest);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
// Send reply
strReply = JSONRPCReply(result, Value::null, jreq.id);
// array of requests
} else if (valRequest.type() == array_type)
strReply = JSONRPCExecBatch(valRequest.get_array());
else
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
}
catch (Object& objError)
{
ErrorReply(conn->stream(), objError, jreq.id);
break;
}
catch (std::exception& e)
{
ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
break;
}
}
delete conn;
{
LOCK(cs_THREAD_RPCHANDLER);
vnThreadsRunning[THREAD_RPCHANDLER]--;
}
}
json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
{
// Find method
const CRPCCommand *pcmd = tableRPC[strMethod];
if (!pcmd)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
// Observe safe mode
string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
!pcmd->okSafeMode)
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
try
{
// Execute
Value result;
{
if (pcmd->unlocked)
result = pcmd->actor(params, false);
else {
LOCK2(cs_main, pwalletMain->cs_wallet);
result = pcmd->actor(params, false);
}
}
return result;
}
catch (std::exception& e)
{
throw JSONRPCError(RPC_MISC_ERROR, e.what());
}
}
Object CallRPC(const string& strMethod, const Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().string().c_str()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort()))))
throw runtime_error("couldn't connect to server");
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive reply
map<string, string> mapHeaders;
string strReply;
int nStatus = ReadHTTP(stream, mapHeaders, strReply);
if (nStatus == HTTP_UNAUTHORIZED)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
// Parse reply
Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
template<typename T>
void ConvertTo(Value& value, bool fAllowNull=false)
{
if (fAllowNull && value.type() == null_type)
return;
if (value.type() == str_type)
{
// reinterpret string as unquoted json value
Value value2;
string strJSON = value.get_str();
if (!read_string(strJSON, value2))
throw runtime_error(string("Error parsing JSON:")+strJSON);
ConvertTo<T>(value2, fAllowNull);
value = value2;
}
else
{
value = value.get_value<T>();
}
}
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
BOOST_FOREACH(const std::string ¶m, strParams)
params.push_back(param);
int n = params.size();
//
// Special case non-string parameter types
//
if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getblockbynumber" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "getblockbynumber" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "walletpassphrase" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "reservebalance" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "reservebalance" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
return params;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try
{
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0]))
{
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
std::vector<std::string> strParams(&argv[2], &argv[argc]);
Array params = RPCConvertValues(strMethod, strParams);
// Execute
Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
if (error.type() != null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
int code = find_value(error.get_obj(), "code").get_int();
nRet = abs(code);
}
else
{
// Result
if (result.type() == null_type)
strPrint = "";
else if (result.type() == str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
}
}
catch (std::exception& e)
{
strPrint = string("error: ") + e.what();
nRet = 87;
}
catch (...)
{
PrintException(NULL, "CommandLineRPC()");
}
if (strPrint != "")
{
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
#ifdef TEST
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
try
{
if (argc >= 2 && string(argv[1]) == "-server")
{
printf("server ready\n");
ThreadRPCServer(NULL);
}
else
{
return CommandLineRPC(argc, argv);
}
}
catch (std::exception& e) {
PrintException(&e, "main()");
} catch (...) {
PrintException(NULL, "main()");
}
return 0;
}
#endif
const CRPCTable tableRPC;
| {
"content_hash": "ce48de12d97de6d1a5de9653a20bd963",
"timestamp": "",
"source": "github",
"line_count": 1292,
"max_line_length": 159,
"avg_line_length": 35.8328173374613,
"alnum_prop": 0.5847589424572317,
"repo_name": "chakracoin/chakracoin-master",
"id": "61bcdceae7023b7e216a187b0312acc415a90a9e",
"size": "46296",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/bitcoinrpc.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "61562"
},
{
"name": "C",
"bytes": "65871"
},
{
"name": "C++",
"bytes": "1574576"
},
{
"name": "IDL",
"bytes": "11435"
},
{
"name": "Objective-C++",
"bytes": "2451"
},
{
"name": "Python",
"bytes": "11646"
},
{
"name": "Shell",
"bytes": "1026"
},
{
"name": "TypeScript",
"bytes": "232274"
}
],
"symlink_target": ""
} |
This gem provides a simple way to download report data from salesforce.com.
It works well with any ruby applications, include such as Ruby on Rails.
You can access salesfore.com using only your salesforce login id (=email) and password.
A security token is no need.
Data will be saved in CSV format.
[![Gem Version](https://badge.fury.io/rb/salesforce_http_client.svg)](http://badge.fury.io/rb/salesforce_http_client)
[![Build Status](https://travis-ci.org/apuruni/salesforce_http_client.svg?branch=master)](https://travis-ci.org/apuruni/salesforce_http_client)
[![Coverage Status](https://coveralls.io/repos/apuruni/salesforce_http_client/badge.svg?branch=master)](https://coveralls.io/r/apuruni/salesforce_http_client?branch=master)
## Installation
Add this line to your application's Gemfile:
gem 'salesforce_http_client'
And then execute:
$ bundle
Or install it yourself as:
$ gem install salesforce_http_client
## Configuring SalesforceHttpClient
Add configurations to set your salesforce.com login_id/password.
You must check your salesforce.com instance to get the right domain for your account.
For example: https://na12.salesforce.com/000000000000ABC, where 'http://na12.salesforce.com/' is the salesforce.com instance domain.
```ruby
require 'fileutils'
require 'httpclient'
SalesforceHttpClient.configure do |config|
config.salesforce_login_id = 'my_login_id_or_email'
config.salesforce_password = 'my_password'
# this parameter must be set if you are not using the default (ap.salesforce.com) instance domain of this gem.
config.salesforce_instance_domain = 'https://na12.salesforce.com'
end
```
If you're using Rails, create an initializer for this:
config/initializers/salesforce_http_client.rb
## Downloading report from salesforce.com
First, you need find the salesforce ID for your report.
For example: http://na1.salesforce.com/000000000000ABC, where '000000000000ABC' is the salesforce ID.
Then, pass the salesforce ID and a file path to SalesforceHttpClient::Client#download_report(salesforce_id, report_save_path) method.
```ruby
salesforce_id = '000000000000ABC'
report_save_path = "tmp/#{salesforce_id}.csv"
sf_client = SalesforceHttpClient::Client.new
sf_client.download_report(salesforce_id, report_save_path)
```
After a few seconds, you will find your report data(csv format) at report_save_path.
## Contributing
1. Fork it ( https://github.com/[my-github-username]/salesforce_http_client/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request
| {
"content_hash": "5da6bb5d1247189e139f241c23c96d1a",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 172,
"avg_line_length": 37.31944444444444,
"alnum_prop": 0.7662820989951619,
"repo_name": "apuruni/salesforce_http_client",
"id": "6d5baa5c70f9ff65e3b6449cff69c36d65b11a16",
"size": "2711",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "11679"
}
],
"symlink_target": ""
} |
module.exports = function ({ $lookup }) {
return {
object: function () {
return function (object, $buffer, $start) {
let $_, $i = []
$buffer[$start++] = object.nudge & 0xff
$_ = 0
object.array.copy($buffer, $start)
$start += object.array.length
$_ += object.array.length
$buffer[$start++] = object.sentry & 0xff
return { start: $start, serialize: null }
}
} ()
}
}
| {
"content_hash": "79e077911fb3a6021e6bf2e57dc47352",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 57,
"avg_line_length": 27.25,
"alnum_prop": 0.42201834862385323,
"repo_name": "bigeasy/packet",
"id": "6c39270cefc03057ff4675594c0957dc87ca6f4f",
"size": "545",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/generated/fixed/static/concat/unpadded.serializer.all.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "8829"
},
{
"name": "JavaScript",
"bytes": "209972"
},
{
"name": "Makefile",
"bytes": "42"
}
],
"symlink_target": ""
} |
package com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.DebuggerContainer;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import com.google.common.base.Preconditions;
import com.google.security.zynamics.binnavi.CMain;
import com.google.security.zynamics.binnavi.Database.Interfaces.IDatabase;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CAbstractLazyComponent;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CAbstractNodeComponent;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CProjectTreeNode;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.Debugger.CDebuggerNode;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.DebuggerContainer.Component.CDebuggerContainerNodeComponent;
import com.google.security.zynamics.binnavi.debug.debugger.DebuggerTemplate;
import com.google.security.zynamics.binnavi.debug.debugger.DebuggerTemplateManager;
import com.google.security.zynamics.binnavi.debug.debugger.interfaces.IDebuggerTemplateManagerListener;
/**
* Project tree node that represents a debugger container.
*/
public final class CDebuggerContainerNode extends CProjectTreeNode<Object> {
/**
* Used for serialization.
*/
private static final long serialVersionUID = 7942293319476781440L;
/**
* Icon used for this tree node.
*/
private static final ImageIcon ICON_DEBUGGER_CONTAINER = new ImageIcon(
CMain.class.getResource("data/projecttreeicons/debugger_container2.png"));
/**
* Database the debuggers belong to.
*/
private final IDatabase m_database;
/**
* Updates the node on relevant changes in the debugger template manager.
*/
private final InternalDebuggerTemplateManagerListener m_debuggerManagerListener =
new InternalDebuggerTemplateManagerListener();
/**
* Creates a new node object.
*
* @param projectTree The project tree of the main window.
* @param database Database the debuggers belong to.
*/
public CDebuggerContainerNode(final JTree projectTree, final IDatabase database) {
super(projectTree, new CAbstractLazyComponent() {
@Override
protected CAbstractNodeComponent createComponent() {
return new CDebuggerContainerNodeComponent(projectTree, database);
}
}, new CDebuggerContainerNodeMenuBuilder(projectTree, database));
m_database = Preconditions.checkNotNull(database, "IE01968: Database can't be null");
m_database.getContent().getDebuggerTemplateManager().addListener(m_debuggerManagerListener);
createChildren();
}
@Override
protected void createChildren() {
if (m_database.isLoaded()) {
for (final DebuggerTemplate debugger : m_database.getContent().getDebuggerTemplateManager()) {
add(new CDebuggerNode(getProjectTree(), this, m_database, debugger));
}
}
}
@Override
public void dispose() {
super.dispose();
final DebuggerTemplateManager debuggerManager =
m_database.getContent().getDebuggerTemplateManager();
debuggerManager.removeListener(m_debuggerManagerListener);
deleteChildren();
}
@Override
public void doubleClicked() {
// Do nothing
}
@Override
public Icon getIcon() {
return ICON_DEBUGGER_CONTAINER;
}
@Override
public String toString() {
return "Debuggers" + " ("
+ m_database.getContent().getDebuggerTemplateManager().debuggerCount() + ")";
}
/**
* Updates the node on relevant changes in the debugger template manager.
*/
private class InternalDebuggerTemplateManagerListener implements IDebuggerTemplateManagerListener {
@Override
public void addedDebugger(final DebuggerTemplateManager manager,
final DebuggerTemplate debugger) {
add(new CDebuggerNode(getProjectTree(), CDebuggerContainerNode.this, m_database, debugger));
getTreeModel().nodeStructureChanged(CDebuggerContainerNode.this);
}
@Override
public void removedDebugger(final DebuggerTemplateManager manager,
final DebuggerTemplate debugger) {
for (int i = 0; i < getChildCount(); i++) {
final CDebuggerNode node = (CDebuggerNode) getChildAt(i);
if (node.getObject() == debugger) {
node.dispose();
remove(node);
break;
}
}
getTreeModel().nodeStructureChanged(CDebuggerContainerNode.this);
}
}
}
| {
"content_hash": "3ae0e97f528fa658e5408f4bb44d652f",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 137,
"avg_line_length": 33.00735294117647,
"alnum_prop": 0.7456003564268211,
"repo_name": "AmesianX/binnavi",
"id": "831ae7fc9646b383778cf73367137d2d46dc9dd9",
"size": "5072",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/main/java/com/google/security/zynamics/binnavi/Gui/MainWindow/ProjectTree/Nodes/DebuggerContainer/CDebuggerContainerNode.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1479"
},
{
"name": "C++",
"bytes": "1876"
},
{
"name": "CSS",
"bytes": "12843"
},
{
"name": "GAP",
"bytes": "3637"
},
{
"name": "HTML",
"bytes": "437420"
},
{
"name": "Java",
"bytes": "21671316"
},
{
"name": "PLSQL",
"bytes": "1866504"
},
{
"name": "PLpgSQL",
"bytes": "638893"
},
{
"name": "Python",
"bytes": "23981"
},
{
"name": "SQLPL",
"bytes": "330046"
},
{
"name": "Shell",
"bytes": "708"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using RemotePlusClient.Utils;
using RemotePlusLibrary.SubSystem.Command;
namespace RemotePlusClient.ViewModels
{
public class ConsoleViewModel : BaseViewModel
{
RichTextBox _box = null;
Label _progressText = null;
Label _progressLabel = null;
ProgressBar _progressBar = null;
SplitContainer _splitPanel = null;
Color _originalForegroundColor;
Color _originalBackgroundColor;
public ConsoleViewModel(string fn, RichTextBox r, Label pt, Label pl, ProgressBar pb, SplitContainer sp) : base(fn)
{
_box = r;
_progressText = pt;
_progressLabel = pl;
_progressBar = pb;
_splitPanel = sp;
_originalBackgroundColor = _box.BackColor;
_originalForegroundColor = _box.ForeColor;
}
public void Append(string text)
{
if(_box.InvokeRequired)
{
_box.Invoke(new Action(() => _box.AppendText(text)));
}
else
{
_box.AppendText(text);
}
}
public void Append(ConsoleText text)
{
if(_box.InvokeRequired)
{
_box.Invoke(new Action(() => _box.AppendWithColor(text.Text, text.TextColor)));
}
else
{
_box.AppendWithColor(text.Text, text.TextColor);
}
}
public void AppendLine(string text)
{
Append(text + Environment.NewLine);
}
public void AppendLine(ConsoleText text)
{
Append(text);
Append(Environment.NewLine);
}
public void SetBackgroundColor(Color bgColor)
{
_box.BackColor = bgColor;
}
public void SetForegroundColor(Color fgColor)
{
_box.ForeColor = fgColor;
}
public void ResetColors()
{
_box.BackColor = _originalBackgroundColor;
_box.ForeColor = _originalForegroundColor;
}
public void ResetText()
{
_box.ResetText();
}
public void LongOperationStarted(string description, int max)
{
_splitPanel.InvokeEx(() => _splitPanel.Panel1Collapsed = false);
_progressText.InvokeEx(() => _progressText.Text = description);
_progressBar.InvokeEx(() => _progressBar.Maximum = max);
_splitPanel.InvokeEx(() => _splitPanel.Panel1.Refresh());
}
public void UpdateLongOperation(int value, string progress)
{
_progressBar.InvokeEx(() => _progressBar.Value = value);
_progressLabel.InvokeEx(() => _progressLabel.Text = progress.ToString());
}
public void FinishedLongOperation()
{
_splitPanel.InvokeEx(() => _splitPanel.Panel1Collapsed = true);
_progressBar.InvokeEx(() => _progressBar.Value = 0);
_progressLabel.InvokeEx(() => _progressLabel.Text = "Status");
}
}
} | {
"content_hash": "5c4f85fd646b3a1c4f701c40def3757a",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 123,
"avg_line_length": 32.84848484848485,
"alnum_prop": 0.5581180811808119,
"repo_name": "brianb12321/RemotePlus",
"id": "48b75559b6a79585976ca38c6377ae83d211b914",
"size": "3254",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/RemotePlusClient/ViewModels/ConsoleViewModel.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "989564"
}
],
"symlink_target": ""
} |
package com.sparetimelabs.serial;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* The type Comm port.
*/
public abstract class CommPort {
/**
* The Name.
*/
protected String name;
/**
* Closes the communications port.
*/
public void close() {
CommPortIdentifier.close(this);
}
/**
* Disables receive framing.
*/
public abstract void disableReceiveFraming();
/**
* Disables receive threshold.
*/
public abstract void disableReceiveThreshold();
/**
* Disables receive timeout.
*/
public abstract void disableReceiveTimeout();
/**
* Enables receive framing.
*
* @param framingByte the framing byte
* @throws UnsupportedCommOperationException the unsupported comm operation exception
*/
public abstract void enableReceiveFraming(int framingByte) throws UnsupportedCommOperationException;
/**
* Enables receive threshold.
*
* @param threshold the threshold
* @throws UnsupportedCommOperationException the unsupported comm operation exception
*/
public abstract void enableReceiveThreshold(int threshold) throws UnsupportedCommOperationException;
/**
* Enables receive timeout.
*
* @param rcvTimeout Timeout value in milliseconds
* @throws UnsupportedCommOperationException the unsupported comm operation exception
*/
public abstract void enableReceiveTimeout(int rcvTimeout) throws UnsupportedCommOperationException;
/**
* Returns the input buffer size in bytes.
*
* @return The input buffer size in bytes.
*/
public abstract int getInputBufferSize();
/**
* Returns an input stream.
*
* @return An input stream, or <code>null</code> if the port is unidirectional and doesn't support receiving data.
* @throws IOException the io exception
*/
public abstract InputStream getInputStream() throws IOException;
/**
* Returns the port name.
*
* @return The port name.
*/
public String getName() {
return name;
}
/**
* Returns the output buffer size in bytes.
*
* @return The output buffer size in bytes.
*/
public abstract int getOutputBufferSize();
/**
* Returns an output stream.
*
* @return An output stream, or <code>null</code> if the port is unidirectional and doesn't support sending data.
* @throws IOException the io exception
*/
public abstract OutputStream getOutputStream() throws IOException;
/**
* Returns the current byte used for receive framing.
*
* @return The current byte used for receive framing.
*/
public abstract int getReceiveFramingByte();
/**
* Returns the integer value of the receive threshold.
*
* @return The integer value of the receive threshold.
*/
public abstract int getReceiveThreshold();
/**
* Returns the integer value of the receive timeout. If the receive timeout
* is disabled, then the value returned is meaningless.
*
* @return The integer value of the receive timeout.
*/
public abstract int getReceiveTimeout();
/**
* Returns <code>true</code> if receive framing is enabled.
*
* @return <code>true</code> if receive framing is enabled.
*/
public abstract boolean isReceiveFramingEnabled();
/**
* Returns <code>true</code> if receive threshold is enabled.
*
* @return <code>true</code> if receive threshold is enabled.
*/
public abstract boolean isReceiveThresholdEnabled();
/**
* Returns <code>true</code> if receive timeout is enabled.
*
* @return <code>true</code> if receive timeout is enabled.
*/
public abstract boolean isReceiveTimeoutEnabled();
/**
* Reads data into the <code>buffer</code> byte array if any bytes are
* available and returns the number of bytes read.
*
* @param buffer
* @param offset
* @param length
* @return The number of bytes read.
* @throws IOException
*/
/**
* Sets the input buffer size.
*
* @param size the size
*/
public abstract void setInputBufferSize(int size);
/**
* Sets the output buffer size.
*
* @param size the size
*/
public abstract void setOutputBufferSize(int size);
}
| {
"content_hash": "f0147e19cf0a6fc4f36ce6f25a14ca7f",
"timestamp": "",
"source": "github",
"line_count": 169,
"max_line_length": 118,
"avg_line_length": 26.402366863905325,
"alnum_prop": 0.6463469296279695,
"repo_name": "bluebiz/modbus-javacomm",
"id": "83cadba635a2c06d88a2ac941823b37b80b6faa2",
"size": "6066",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/sparetimelabs/serial/CommPort.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "42872"
},
{
"name": "HTML",
"bytes": "2920"
},
{
"name": "Java",
"bytes": "923580"
}
],
"symlink_target": ""
} |
function ShowHideContent() {
var self = this;
self.escapeElementName = function(str) {
result = str.replace('[', '\\[').replace(']', '\\]');
return(result);
};
self.showHideRadioToggledContent = function () {
$("input.govuk-radios__input[type=radio]").each(function () {
var $radio = $(this);
var $radioGroupName = $radio.attr('name');
var $radioLabel = $radio.parent('label');
//var dataTarget = $radioLabel.attr('data-target');
var dataTarget = $radio.attr('data-target');
// Add ARIA attributes
// If the data-target attribute is defined
if (dataTarget) {
// Set aria-controls
$radio.attr('aria-controls', dataTarget);
$radio.on('click', function () {
// Select radio buttons in the same group
$radio.closest('form').find("input.govuk-radios__input[name=" + self.escapeElementName($radioGroupName) + "]").each(function () {
var $this = $(this);
var groupDataTarget = $this.parent('input').attr('data-target');
var $groupDataTarget = $('#' + groupDataTarget);
// Hide toggled content
$groupDataTarget.hide();
// Set aria-expanded and aria-hidden for hidden content
$this.attr('aria-expanded', 'false');
$groupDataTarget.attr('aria-hidden', 'true');
});
var $dataTarget = $('#' + dataTarget);
$dataTarget.show();
// Set aria-expanded and aria-hidden for clicked radio
$radio.attr('aria-expanded', 'true');
$dataTarget.attr('aria-hidden', 'false');
// added to handle /postage-return-options screen radio buttons with the new govuk-frontend buttons
if(dataTarget === "business-info-hide") {
$("#business-info").hide();
}
});
} else {
// If the data-target attribute is undefined for a radio button,
// hide visible data-target content for radio buttons in the same group
$radio.on('click', function () {
// Select radio buttons in the same group
$("input.govuk-radios__input[name=" + self.escapeElementName($radioGroupName) + "]").each(function () {
var groupDataTarget = $(this).parent('input').attr('data-target');
var $groupDataTarget = $('#' + groupDataTarget);
// Hide toggled content
$groupDataTarget.hide();
// Set aria-expanded and aria-hidden for hidden content
$(this).attr('aria-expanded', 'false');
$groupDataTarget.attr('aria-hidden', 'true');
});
});
}
});
};
self.showHideCheckboxToggledContent = function () {
$(".block-label input[type='checkbox']").each(function() {
var $checkbox = $(this);
var $checkboxLabel = $(this).parent();
var $dataTarget = $checkboxLabel.attr('data-target');
// Add ARIA attributes
// If the data-target attribute is defined
if (typeof $dataTarget !== 'undefined' && $dataTarget !== false) {
// Set aria-controls
$checkbox.attr('aria-controls', $dataTarget);
// Set aria-expanded and aria-hidden
$checkbox.attr('aria-expanded', 'false');
$('#'+$dataTarget).attr('aria-hidden', 'true');
// For checkboxes revealing hidden content
$checkbox.on('click', function() {
var state = $(this).attr('aria-expanded') === 'false' ? true : false;
// Toggle hidden content
$('#'+$dataTarget).toggle();
// Update aria-expanded and aria-hidden attributes
$(this).attr('aria-expanded', state);
$('#'+$dataTarget).attr('aria-hidden', !state);
});
}
});
};
}
$(document).ready(function() {
// Turn off jQuery animation
jQuery.fx.off = true;
// Use GOV.UK selection-buttons.js to set selected
// and focused states for block labels
if(window.location.pathname !== '/cookies')
{
var $blockLabels = $(".block-label input[type='radio'], .block-label input[type='checkbox']");
new GOVUK.SelectionButtons($blockLabels);
}
// Details/summary polyfill
// See /javascripts/vendor/details.polyfill.js
// Where .block-label uses the data-target attribute
// to toggle hidden content
var toggleContent = new ShowHideContent();
toggleContent.showHideRadioToggledContent();
toggleContent.showHideCheckboxToggledContent();
});
// Stageprompt 2.0.1
//
// See: https://github.com/alphagov/stageprompt
//
// Stageprompt allows user journeys to be described and instrumented
// using data attributes.
//
// Setup (run this on document ready):
//
// GOVUK.performance.stageprompt.setupForGoogleAnalytics();
//
// Usage:
//
// Sending events on page load:
//
// <div id="wrapper" class="service" data-journey="pay-register-birth-abroad:start">
// [...]
// </div>
//
// Sending events on click:
//
// <a class="help-button" href="#" data-journey-click="stage:help:info">See more info...</a>
var GOVUK = GOVUK || {};
GOVUK.performance = GOVUK.performance || {};
GOVUK.performance.stageprompt = (function () {
var setup, setupForGoogleAnalytics, splitAction;
splitAction = function (action) {
var parts = action.split(':');
if (parts.length <= 3) return parts;
return [parts.shift(), parts.shift(), parts.join(':')];
};
setup = function (analyticsCallback) {
var journeyStage = $('[data-journey]').attr('data-journey'),
journeyHelpers = $('[data-journey-click]');
if (journeyStage) {
analyticsCallback.apply(null, splitAction(journeyStage));
}
journeyHelpers.on('click', function (event) {
analyticsCallback.apply(null, splitAction($(this).data('journey-click')));
});
};
setupForGoogleAnalytics = function () {
setup(GOVUK.performance.sendGoogleAnalyticsEvent);
};
return {
setup: setup,
setupForGoogleAnalytics: setupForGoogleAnalytics
};
}());
GOVUK.performance.sendGoogleAnalyticsEvent = function (category, event, label) {
_gaq.push(['_trackEvent', category, event, label, undefined, true]);
};
(function () {
"use strict";
var root = this,
$ = root.jQuery;
if (typeof GOVUK === 'undefined') { root.GOVUK = {}; }
var SelectionButtons = function (elmsOrSelector, opts) {
var $elms;
this.selectedClass = 'selected';
this.focusedClass = 'focused';
if (opts !== undefined) {
$.each(opts, function (optionName, optionObj) {
this[optionName] = optionObj;
}.bind(this));
}
if (typeof elmsOrSelector === 'string') {
$elms = $(elmsOrSelector);
this.selector = elmsOrSelector;
this.setInitialState($(this.selector));
} else {
this.$elms = elmsOrSelector;
this.setInitialState(this.$elms);
}
this.addEvents();
};
SelectionButtons.prototype.addEvents = function () {
if (typeof this.$elms !== 'undefined') {
this.addElementLevelEvents();
} else {
this.addDocumentLevelEvents();
}
};
SelectionButtons.prototype.setInitialState = function ($elms) {
$elms.each(function (idx, elm) {
var $elm = $(elm);
if ($elm.is(':checked')) {
this.markSelected($elm);
}
}.bind(this));
};
SelectionButtons.prototype.markFocused = function ($elm, state) {
if (state === 'focused') {
$elm.parent('label').addClass(this.focusedClass);
} else {
$elm.parent('label').removeClass(this.focusedClass);
}
};
SelectionButtons.prototype.markSelected = function ($elm) {
var radioName;
if ($elm.attr('type') === 'radio') {
radioName = $elm.attr('name');
$($elm[0].form).find('input[name="' + radioName + '"]')
.parent('label')
.removeClass(this.selectedClass);
$elm.parent('label').addClass(this.selectedClass);
} else { // checkbox
if ($elm.is(':checked')) {
$elm.parent('label').addClass(this.selectedClass);
} else {
$elm.parent('label').removeClass(this.selectedClass);
}
}
};
SelectionButtons.prototype.addElementLevelEvents = function () {
this.clickHandler = this.getClickHandler();
this.focusHandler = this.getFocusHandler({ 'level' : 'element' });
this.$elms
.on('click', this.clickHandler)
.on('focus blur', this.focusHandler);
};
SelectionButtons.prototype.addDocumentLevelEvents = function () {
this.clickHandler = this.getClickHandler();
this.focusHandler = this.getFocusHandler({ 'level' : 'document' });
$(document)
.on('click', this.selector, this.clickHandler)
.on('focus blur', this.selector, this.focusHandler);
};
SelectionButtons.prototype.getClickHandler = function () {
return function (e) {
this.markSelected($(e.target));
}.bind(this);
};
SelectionButtons.prototype.getFocusHandler = function (opts) {
var focusEvent = (opts.level === 'document') ? 'focusin' : 'focus';
return function (e) {
var state = (e.type === focusEvent) ? 'focused' : 'blurred';
this.markFocused($(e.target), state);
}.bind(this);
};
SelectionButtons.prototype.destroy = function () {
if (typeof this.selector !== 'undefined') {
$(document)
.off('click', this.selector, this.clickHandler)
.off('focus blur', this.selector, this.focusHandler);
} else {
this.$elms
.off('click', this.clickHandler)
.off('focus blur', this.focusHandler);
}
};
root.GOVUK.SelectionButtons = SelectionButtons;
}).call(this);
| {
"content_hash": "e7cf302dbdd443c2f6b45ff9aaa2ae0d",
"timestamp": "",
"source": "github",
"line_count": 319,
"max_line_length": 149,
"avg_line_length": 33.86833855799373,
"alnum_prop": 0.5393372824879674,
"repo_name": "UKForeignOffice/loi-user-service",
"id": "34f50a98e4d4380fedb4c3d2a16319f12fd638c8",
"size": "10805",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "js/gov_uk_scripts.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "274588"
},
{
"name": "Dockerfile",
"bytes": "233"
},
{
"name": "EJS",
"bytes": "164205"
},
{
"name": "HTML",
"bytes": "8334"
},
{
"name": "JavaScript",
"bytes": "368509"
},
{
"name": "SCSS",
"bytes": "33136"
}
],
"symlink_target": ""
} |
namespace Microsoft.AspNetCore.Routing;
/// <summary>
/// Interface for implementing a router.
/// </summary>
public interface IRouter
{
/// <summary>
/// Asynchronously routes based on the current <paramref name="context"/>.
/// </summary>
/// <param name="context">A <see cref="RouteContext"/> instance.</param>
Task RouteAsync(RouteContext context);
/// <summary>
/// Returns the URL that is associated with the route details provided in <paramref name="context"/>
/// </summary>
/// <param name="context">A <see cref="VirtualPathContext"/> instance.</param>
/// <returns>A <see cref="VirtualPathData"/> object. Can be null.</returns>
VirtualPathData? GetVirtualPath(VirtualPathContext context);
}
| {
"content_hash": "aeb42adfa8e52f5dd6ddfcd13285edf7",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 104,
"avg_line_length": 37.35,
"alnum_prop": 0.677376171352075,
"repo_name": "aspnet/AspNetCore",
"id": "ac79858f2d636d9349b513a5107d18ffd90600c5",
"size": "885",
"binary": false,
"copies": "1",
"ref": "refs/heads/darc-main-3ce916a7-9d9b-4849-8f14-6703adcb3cb2",
"path": "src/Http/Routing.Abstractions/src/IRouter.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "109"
},
{
"name": "Batchfile",
"bytes": "19526"
},
{
"name": "C",
"bytes": "213916"
},
{
"name": "C#",
"bytes": "47455169"
},
{
"name": "C++",
"bytes": "1900454"
},
{
"name": "CMake",
"bytes": "7955"
},
{
"name": "CSS",
"bytes": "62326"
},
{
"name": "Dockerfile",
"bytes": "3584"
},
{
"name": "F#",
"bytes": "7982"
},
{
"name": "Groovy",
"bytes": "1529"
},
{
"name": "HTML",
"bytes": "1130653"
},
{
"name": "Java",
"bytes": "297552"
},
{
"name": "JavaScript",
"bytes": "2726829"
},
{
"name": "Lua",
"bytes": "4904"
},
{
"name": "Makefile",
"bytes": "220"
},
{
"name": "Objective-C",
"bytes": "222"
},
{
"name": "PowerShell",
"bytes": "241706"
},
{
"name": "Python",
"bytes": "19476"
},
{
"name": "Roff",
"bytes": "6044"
},
{
"name": "Shell",
"bytes": "142293"
},
{
"name": "Smalltalk",
"bytes": "3"
},
{
"name": "TypeScript",
"bytes": "797435"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_14) on Sun Nov 04 20:19:11 CET 2012 -->
<TITLE>
Uses of Class org.lwjgl.opengl.ARBBufferObject (LWJGL API)
</TITLE>
<META NAME="date" CONTENT="2012-11-04">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.lwjgl.opengl.ARBBufferObject (LWJGL API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../org/lwjgl/opengl/ARBBufferObject.html" title="class in org.lwjgl.opengl"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/lwjgl/opengl/\class-useARBBufferObject.html" target="_top"><B>FRAMES</B></A>
<A HREF="ARBBufferObject.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.lwjgl.opengl.ARBBufferObject</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../org/lwjgl/opengl/ARBBufferObject.html" title="class in org.lwjgl.opengl">ARBBufferObject</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.lwjgl.opengl"><B>org.lwjgl.opengl</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="org.lwjgl.opengl"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../org/lwjgl/opengl/ARBBufferObject.html" title="class in org.lwjgl.opengl">ARBBufferObject</A> in <A HREF="../../../../org/lwjgl/opengl/package-summary.html">org.lwjgl.opengl</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../org/lwjgl/opengl/ARBBufferObject.html" title="class in org.lwjgl.opengl">ARBBufferObject</A> in <A HREF="../../../../org/lwjgl/opengl/package-summary.html">org.lwjgl.opengl</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/lwjgl/opengl/ARBPixelBufferObject.html" title="class in org.lwjgl.opengl">ARBPixelBufferObject</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/lwjgl/opengl/ARBVertexBufferObject.html" title="class in org.lwjgl.opengl">ARBVertexBufferObject</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/lwjgl/opengl/EXTPixelBufferObject.html" title="class in org.lwjgl.opengl">EXTPixelBufferObject</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../org/lwjgl/opengl/ARBBufferObject.html" title="class in org.lwjgl.opengl"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/lwjgl/opengl/\class-useARBBufferObject.html" target="_top"><B>FRAMES</B></A>
<A HREF="ARBBufferObject.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright © 2002-2009 lwjgl.org. All Rights Reserved.</i>
</BODY>
</HTML>
| {
"content_hash": "ae030679a7d9ae17ef63b980d84b47dc",
"timestamp": "",
"source": "github",
"line_count": 196,
"max_line_length": 252,
"avg_line_length": 43.37755102040816,
"alnum_prop": 0.6136203246294989,
"repo_name": "jmcomets/tropical-escape",
"id": "bb58aec756ef7d06cc31c7dc910a8efdcc8da24e",
"size": "8502",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/lwjgl/javadoc/org/lwjgl/opengl/class-use/ARBBufferObject.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "3410"
},
{
"name": "CSS",
"bytes": "2622"
},
{
"name": "Java",
"bytes": "5240056"
}
],
"symlink_target": ""
} |
var exec = require('cordova/exec');
var ListPicker = function() {}
ListPicker.prototype.showPicker = function(options, callback, error_callback) {
options || (options = {});
var scope = options.scope || null;
var config = {
title: options.title || ' ',
selectedValue: options.selectedValue || [],
items: options.items || {},
style: options.style || 'default',
doneButtonLabel: options.doneButtonLabel || 'Done',
cancelButtonLabel: options.cancelButtonLabel || 'Cancel'
};
var _callback = function() {
if(typeof callback == 'function') {
callback.apply(scope, arguments);
}
};
var _error_callback = function() {
if(typeof error_callback == 'function') {
error_callback.apply(scope, arguments);
}
};
cordova.exec(_callback, _error_callback, 'ListPicker', 'showPicker', [config]);
}
module.exports = new ListPicker();
| {
"content_hash": "cafeea8cccaceeb6a625d8fba3b1b815",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 83,
"avg_line_length": 30.838709677419356,
"alnum_prop": 0.602510460251046,
"repo_name": "Steven-Chan/PhoneGap-Plugin-ListPicker",
"id": "e069d92bb9c94a16db1a96ebb45ea2ad257a8479",
"size": "1105",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "www/ListPicker.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "8040"
},
{
"name": "JavaScript",
"bytes": "1105"
},
{
"name": "Objective-C",
"bytes": "16958"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.hive</groupId>
<artifactId>hive</artifactId>
<version>2.1.1</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>hive-jdbc</artifactId>
<packaging>jar</packaging>
<name>Hive JDBC</name>
<properties>
<hive.path.to.root>..</hive.path.to.root>
<packaging.minimizeJar>false</packaging.minimizeJar>
</properties>
<dependencies>
<!-- dependencies are always listed in sorted order by groupId, artifectId -->
<!-- intra-project -->
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-common</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-service</artifactId>
<version>${project.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.hive</groupId>
<artifactId>hive-exec</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-serde</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-metastore</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-shims</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-service-rpc</artifactId>
<version>${project.version}</version>
</dependency>
<!-- inter-project -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpcomponents.client.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>${httpcomponents.core.version}</version>
</dependency>
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>${libthrift.version}</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>${zookeeper.version}</version>
<exclusions>
<exclusion>
<groupId>org.jboss.netty</groupId>
<artifactId>netty</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>${curator.version}</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>${hadoop.version}</version>
<optional>true</optional>
</dependency>
<!-- test inter-project -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>dist</id>
<properties>
<packaging.minimizeJar>true</packaging.minimizeJar>
</properties>
</profile>
</profiles>
<build>
<sourceDirectory>${basedir}/src/java</sourceDirectory>
<testSourceDirectory>${basedir}/src/test</testSourceDirectory>
<resources>
<resource>
<directory>${basedir}/src/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<minimizeJar>${packaging.minimizeJar}</minimizeJar>
<shadedArtifactAttached>true</shadedArtifactAttached>
<shadedClassifierName>${hive.jdbc.driver.classifier}</shadedClassifierName>
<filters>
<filter>
<artifact>org.apache.hive.shims:hive-shims-common</artifact>
<includes>
<include>**</include>
</includes>
</filter>
<filter>
<artifact>org.apache.hive.shims:hive-shims-0.23</artifact>
<includes>
<include>**</include>
</includes>
</filter>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
<artifactSet>
<excludes>
<exclude>org.apache.commons:commons-compress</exclude>
<exclude>commons-configuration:commons-configuration</exclude>
<exclude>org.apache.hadoop:*</exclude>
<exclude>org.apache.hive:hive-ant</exclude>
<exclude>org.apache.ant:*</exclude>
<exclude>junit:*</exclude>
<exclude>org.hamcrest:*</exclude>
<exclude>org.ow2.asm:*</exclude>
<exclude>javax.jms:*</exclude>
<exclude>com.sun.jersey:*</exclude>
<exclude>com.sun.jersey.contribs:*</exclude>
<exclude>org.eclipse.jetty.aggregate:*</exclude>
<exclude>org.tukaani:*</exclude>
<exclude>org.iq80.snappy:*</exclude>
<exclude>org.apache.velocity:*</exclude>
<exclude>net.sf.jpam:*</exclude>
<exclude>org.apache.avro:*</exclude>
<exclude>net.sf.opencsv:*</exclude>
<exclude>org.antlr:*</exclude>
<exclude>org.slf4j:slf4j-log4j12</exclude>
<exclude>log4j:*</exclude>
<exclude>antlr:*</exclude>
<exclude>aopalliance:*</exclude>
<exclude>asm:*</exclude>
<exclude>com.google.code.gson:*</exclude>
<exclude>com.google.inject:*</exclude>
<exclude>com.google.inject.extensions:*</exclude>
<exclude>com.jamesmurty.utils:*</exclude>
<exclude>com.jcraft:*</exclude>
<exclude>com.jolbox:*</exclude>
<exclude>commons-beanutils:*</exclude>
<exclude>commons-cli:*</exclude>
<exclude>commons-dbcp:*</exclude>
<exclude>commons-digester:*</exclude>
<exclude>commons-el:*</exclude>
<exclude>commons-httpclient:*</exclude>
<exclude>commons-io:*</exclude>
<exclude>commons-net:*</exclude>
<exclude>commons-pool:*</exclude>
<exclude>com.google.code.findbugs:*</exclude>
<exclude>com.google.protobuf:*</exclude>
<exclude>com.sun.xml.bind:*</exclude>
<exclude>com.thoughtworks.paranamer:*</exclude>
<exclude>com.twitter:*</exclude>
<exclude>io.netty:*</exclude>
<exclude>javax.activation:*</exclude>
<exclude>javax.inject:*</exclude>
<exclude>javax.jdo:*</exclude>
<exclude>javax.mail:*</exclude>
<exclude>javax.servlet:*</exclude>
<exclude>javax.servlet.jsp:*</exclude>
<exclude>javax.transaction:*</exclude>
<exclude>javax.xml.bind:*</exclude>
<exclude>javax.xml.stream:*</exclude>
<exclude>jline:*</exclude>
<exclude>joda-time:*</exclude>
<exclude>net.java.dev.jets3t:*</exclude>
<exclude>org.apache.commons:commons-math3</exclude>
<exclude>org.apache.curator:*</exclude>
<exclude>org.apache.derby:*</exclude>
<exclude>org.apache.directory.api:*</exclude>
<exclude>org.apache.directory.server:*</exclude>
<exclude>org.apache.geronimo.specs:*</exclude>
<exclude>org.apache.zookeeper:*</exclude>
<exclude>org.codehaus.jackson:*</exclude>
<exclude>org.codehaus.jettison:*</exclude>
<exclude>org.datanucleus:*</exclude>
<exclude>org.fusesource.leveldbjni:*</exclude>
<exclude>org.htrace:*</exclude>
<exclude>org.mortbay.jetty:*</exclude>
<exclude>org.xerial.snappy:*</exclude>
<exclude>tomcat:*</exclude>
<exclude>xmlenc:*</exclude>
</excludes>
</artifactSet>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "0f02c24f9026318f804a61e7c3073c25",
"timestamp": "",
"source": "github",
"line_count": 257,
"max_line_length": 108,
"avg_line_length": 39.37354085603113,
"alnum_prop": 0.5621108805217907,
"repo_name": "BUPTAnderson/apache-hive-2.1.1-src",
"id": "e2212a7b2dc728b8b75b1434129d5876f93d682f",
"size": "10119",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jdbc/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "54136"
},
{
"name": "Batchfile",
"bytes": "51776"
},
{
"name": "C",
"bytes": "28218"
},
{
"name": "C++",
"bytes": "74801"
},
{
"name": "CSS",
"bytes": "5220"
},
{
"name": "GAP",
"bytes": "144179"
},
{
"name": "HTML",
"bytes": "51404"
},
{
"name": "HiveQL",
"bytes": "4634130"
},
{
"name": "Java",
"bytes": "34882419"
},
{
"name": "JavaScript",
"bytes": "25872"
},
{
"name": "M",
"bytes": "2176"
},
{
"name": "M4",
"bytes": "2276"
},
{
"name": "PHP",
"bytes": "148097"
},
{
"name": "PLSQL",
"bytes": "3008"
},
{
"name": "PLpgSQL",
"bytes": "223546"
},
{
"name": "Perl",
"bytes": "316401"
},
{
"name": "PigLatin",
"bytes": "12333"
},
{
"name": "Python",
"bytes": "292716"
},
{
"name": "Roff",
"bytes": "5379"
},
{
"name": "SQLPL",
"bytes": "409"
},
{
"name": "Shell",
"bytes": "206363"
},
{
"name": "TSQL",
"bytes": "1219634"
},
{
"name": "Thrift",
"bytes": "104851"
},
{
"name": "XSLT",
"bytes": "7619"
},
{
"name": "q",
"bytes": "318829"
}
],
"symlink_target": ""
} |
/* Primitive Types */
var intNum = 10;
var floatNum = 0.1;
var singleQuoteStr = 'single quote string';
var doubleQuoteStr = "double quote string";
var singleChar = 'a';
var boolVar = true;
// undefined type
var emptyVar;
// null type
var nullVar = null;
console.log(
typeof intNum, // number
typeof floatNum, // number
typeof singleQuoteStr, // string
typeof doubleQuoteStr, // string
typeof boolVar, // boolean
typeof nullVar, // object
typeof emptyVar // undefined
);
/* Number */
var num = 5 / 2;
console.log(num); // 2.5
console.log(Math.floor(num)); // 2
/* String */
var str = 'test';
console.log(str[0], str[1], str[2], str[3]); // t e s t
str[0] = 'T';
console.log(str); // test
/* null */
nullVar = null;
console.log(typeof nullVar === null); // false
console.log(nullVar === null); // true | {
"content_hash": "844ce6942626c0e04432e49f89c55e5f",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 55,
"avg_line_length": 19.46511627906977,
"alnum_prop": 0.6379928315412187,
"repo_name": "seungin/javascript",
"id": "4f92b71b4aa71f9b581b441b2b81194d97cd19d6",
"size": "837",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "3_1_primitiveType.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1993"
},
{
"name": "JavaScript",
"bytes": "23066"
}
],
"symlink_target": ""
} |
unicorn Cookbook
================
TODO: Enter the cookbook description here.
e.g.
This cookbook makes your favorite breakfast sandwhich.
Requirements
------------
TODO: List your cookbook requirements. Be sure to include any requirements this cookbook has on platforms, libraries, other cookbooks, packages, operating systems, etc.
e.g.
#### packages
- `toaster` - unicorn needs toaster to brown your bagel.
Attributes
----------
TODO: List you cookbook attributes here.
e.g.
#### unicorn::default
<table>
<tr>
<th>Key</th>
<th>Type</th>
<th>Description</th>
<th>Default</th>
</tr>
<tr>
<td><tt>['unicorn']['bacon']</tt></td>
<td>Boolean</td>
<td>whether to include bacon</td>
<td><tt>true</tt></td>
</tr>
</table>
Usage
-----
#### unicorn::default
TODO: Write usage instructions for each cookbook.
e.g.
Just include `unicorn` in your node's `run_list`:
```json
{
"name":"my_node",
"run_list": [
"recipe[unicorn]"
],
"unicorn" : {
"apps" :[{
"name" : "publify",
"root" : "/var/www/mukaer.com/publify",
"env" : "production"
},{
"name" : "sinatra",
"root" : "/var/www/mukaer.com/sinatra",
"start_command" : "unicorn",
"env" : "development",
"pid" : "/var/www/mukaer.com/sinatra/unicon.pid",
"config" : "/var/www/mukaer.com/sinatra/unicon.rb"
}
]
}
}
```
Contributing
------------
TODO: (optional) If this is a public cookbook, detail the process for contributing. If this is a private cookbook, remove this section.
e.g.
1. Fork the repository on Github
2. Create a named feature branch (like `add_component_x`)
3. Write you change
4. Write tests for your change (if applicable)
5. Run the tests, ensuring they all pass
6. Submit a Pull Request using Github
License and Authors
-------------------
Authors: TODO: List authors
| {
"content_hash": "b9c9a2a9a31a635064a0400510302ee6",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 168,
"avg_line_length": 23.142857142857142,
"alnum_prop": 0.5972222222222222,
"repo_name": "mukaer/chef-solo",
"id": "feace01199bd535d3fe37e1226faed684b8f364f",
"size": "1944",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cookbooks/unicorn/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ruby",
"bytes": "24678"
}
],
"symlink_target": ""
} |
angular.module("characterSheet.character", [])
.factory("CharacterFactory", function() {
var character = {
experience: 200000000,
abilities: {},
classes: {},
favoredClasses: 1,
favoredBonuses: {
"Skill": {
name: "Skill Point",
points: 0
},
"HP": {
name: "Hit Point",
points: 0
}
},
skills: {},
traits: {},
level: function(track) {
var advancement = {
"Slow": [0,
3000,
7500,
14000,
23000,
35000,
53000,
77000,
115000,
160000,
235000,
330000,
475000,
665000,
955000,
1350000,
1900000,
2700000,
3850000,
5350000
],
"Medium": [0,
2000,
5000,
9000,
15000,
23000,
35000,
51000,
75000,
105000,
155000,
220000,
315000,
445000,
635000,
890000,
1300000,
1800000,
2550000,
3600000
],
"Fast": [0,
1300,
3300,
6000,
10000,
15000,
23000,
34000,
50000,
71000,
105000,
145000,
210000,
295000,
425000,
600000,
850000,
1200000,
1700000,
2400000
]
};
track = track ? track : "Medium";
for (var i = advancement[track].length - 1; i > 0; i--) {
if (character.experience >= advancement[track][i]) {
return i + 1;
}
}
return 1;
},
setRace: function(race) {
for (var key in character.favoredBonuses) {
if (character.favoredBonuses[key].race) {
if (character.favoredBonuses[key].race == character.race.name) {
delete character.favoredBonuses[key];
}
}
}
delete character.race;
character.race = {};
// remove all Racial Traits
for (var key in character.traits) {
if (character.traits[key].type.indexOf("Racial Trait") > -1) {
delete character.traits[character.traits[key].name];
}
};
// Add Race Elements
for (var key in race) {
var element = race[key];
if (element.type) {
if (element.type != "Alternate Racial Trait") {
character.traits[key] = element;
}
} else character.race[key] = element;
};
for (var key in race.favoredOptions) {
character.favoredBonuses[key] = race.favoredOptions[key];
character.favoredBonuses[key].race = race.name;
character.favoredBonuses[key].points = 0;
}
},
addClass: function(aClass, archetype) {
if (character.classes[aClass.name]) {
character.classes[aClass.name].level++;
} else {
character.classes[aClass.name] = {};
for (var key in aClass) {
var element = aClass[key];
if (element.type !== "Archetype") {
character.classes[aClass.name][key] = element;
} else {
if (archetype && element.name == archetype.name) {
character.classes[aClass.name][key] = element;
}
}
};
character.classes[aClass.name].level = 1;
character.addFavoredClass(aClass);
};
},
addFavoredClass: function(aClass) {
var favoredClassCount = 0;
if (character.classes[aClass.name]) {
for (var key in character.classes) {
if (character.classes[key].favoredClass) {
favoredClassCount++;
}
}
var maxFavoredClasses = character.favoredClasses;
for (var key in character.traits) {
if (character.traits[key].favoredClass) {
maxFavoredClasses += parseInt(character.traits[key].favoredClass);
}
}
if (favoredClassCount < maxFavoredClasses) {
character.classes[aClass.name].favoredClass = true;
return true;
}
}
return false;
},
getFavoredClassLevels: function() {
var total = 0;
for (var key in character.classes) {
if (character.classes[key].favoredClass) {
total += character.classes[key].level;
}
}
return total;
},
removeFavoredClass: function(aClass) {
if (character.classes[aClass.name].favoredClass) {
delete character.classes[aClass.name].favoredClass;
return true;
}
return false;
},
removeClass: function(aClassName) {
if (character.classes[aClassName].level == 1) {
delete character.classes[aClassName];
} else {
character.classes[aClassName].level--;
};
},
// TODO: Maybe move to Class.js as this is only required there.
getClassLevels: function() {
var totalLevels = 0;
for (var key in character.classes) {
totalLevels += character.classes[key].level;
}
return totalLevels;
},
getAgingEffect: function() {
var ageGroup = "Adulthood";
if (character.race) {
if (character.age >= parseInt(character.race.agingEffects["Middle Age"])) {
ageGroup = "Middle Age";
if (character.age >= parseInt(character.race.agingEffects["Old"])) {
ageGroup = "Old";
if (character.age >= parseInt(character.race.agingEffects["Venerable"])) {
ageGroup = "Venerable";
}
}
}
}
return ageGroup;
}
};
return character;
})
.controller('CharacterController', function($scope, CharacterFactory) {
$scope.character = CharacterFactory;
});
| {
"content_hash": "4ca763938388f91f2ad5e03e17f259ad",
"timestamp": "",
"source": "github",
"line_count": 229,
"max_line_length": 102,
"avg_line_length": 36.6768558951965,
"alnum_prop": 0.35873318252172876,
"repo_name": "RedXian/CharacterSheet",
"id": "16dd4654202693afc56b6a37a59b9aabfe4e3e5a",
"size": "8399",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/js/Character.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6626"
},
{
"name": "HTML",
"bytes": "40477"
},
{
"name": "JavaScript",
"bytes": "66411"
}
],
"symlink_target": ""
} |
package org.apache.calcite.materialize;
import org.apache.calcite.util.Util;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.pentaho.aggdes.algorithm.Algorithm;
import org.pentaho.aggdes.algorithm.Progress;
import org.pentaho.aggdes.algorithm.Result;
import org.pentaho.aggdes.algorithm.impl.MonteCarloAlgorithm;
import org.pentaho.aggdes.algorithm.util.ArgumentUtils;
import org.pentaho.aggdes.model.Aggregate;
import org.pentaho.aggdes.model.Attribute;
import org.pentaho.aggdes.model.Dialect;
import org.pentaho.aggdes.model.Dimension;
import org.pentaho.aggdes.model.Measure;
import org.pentaho.aggdes.model.Parameter;
import org.pentaho.aggdes.model.Schema;
import org.pentaho.aggdes.model.StatisticsProvider;
import org.pentaho.aggdes.model.Table;
import java.io.PrintWriter;
import java.util.List;
/**
* Algorithm that suggests a set of initial tiles (materialized aggregate views)
* for a given lattice.
*/
public class TileSuggester {
private static final Function<Attribute, Lattice.Column> TO_COLUMN =
new Function<Attribute, Lattice.Column>() {
public Lattice.Column apply(Attribute input) {
return ((AttributeImpl) input).column;
}
};
private final Lattice lattice;
public TileSuggester(Lattice lattice) {
this.lattice = lattice;
}
public Iterable<? extends Lattice.Tile> tiles() {
final Algorithm algorithm = new MonteCarloAlgorithm();
final PrintWriter pw = Util.printWriter(System.out);
final Progress progress = new ArgumentUtils.TextProgress(pw);
final StatisticsProvider statisticsProvider =
new StatisticsProviderImpl(lattice);
final double f = statisticsProvider.getFactRowCount();
final ImmutableMap.Builder<Parameter, Object> map = ImmutableMap.builder();
if (lattice.algorithmMaxMillis >= 0) {
map.put(Algorithm.ParameterEnum.timeLimitSeconds,
Math.max(1, (int) (lattice.algorithmMaxMillis / 1000L)));
}
map.put(Algorithm.ParameterEnum.aggregateLimit, 3);
map.put(Algorithm.ParameterEnum.costLimit, f * 5d);
final SchemaImpl schema = new SchemaImpl(lattice, statisticsProvider);
final Result result = algorithm.run(schema, map.build(), progress);
final ImmutableList.Builder<Lattice.Tile> tiles = ImmutableList.builder();
for (Aggregate aggregate : result.getAggregates()) {
tiles.add(toTile(aggregate));
}
return tiles.build();
}
private Lattice.Tile toTile(Aggregate aggregate) {
final Lattice.TileBuilder tileBuilder = new Lattice.TileBuilder();
for (Lattice.Measure measure : lattice.defaultMeasures) {
tileBuilder.addMeasure(measure);
}
for (Attribute attribute : aggregate.getAttributes()) {
tileBuilder.addDimension(((AttributeImpl) attribute).column);
}
return tileBuilder.build();
}
/** Implementation of {@link Schema} based on a {@link Lattice}. */
private static class SchemaImpl implements Schema {
private final StatisticsProvider statisticsProvider;
private final TableImpl table;
private final ImmutableList<AttributeImpl> attributes;
SchemaImpl(Lattice lattice, StatisticsProvider statisticsProvider) {
this.statisticsProvider = statisticsProvider;
this.table = new TableImpl();
final ImmutableList.Builder<AttributeImpl> attributeBuilder =
ImmutableList.builder();
for (Lattice.Column column : lattice.columns) {
attributeBuilder.add(new AttributeImpl(column, table));
}
this.attributes = attributeBuilder.build();
}
public List<? extends Table> getTables() {
return ImmutableList.of(table);
}
public List<Measure> getMeasures() {
throw new UnsupportedOperationException();
}
public List<? extends Dimension> getDimensions() {
throw new UnsupportedOperationException();
}
public List<? extends Attribute> getAttributes() {
return attributes;
}
public StatisticsProvider getStatisticsProvider() {
return statisticsProvider;
}
public Dialect getDialect() {
throw new UnsupportedOperationException();
}
public String generateAggregateSql(Aggregate aggregate,
List<String> columnNameList) {
throw new UnsupportedOperationException();
}
}
/** Implementation of {@link Table} based on a {@link Lattice}.
* There is only one table (in this sense of table) in a lattice.
* The algorithm does not really care about tables. */
private static class TableImpl implements Table {
public String getLabel() {
return "TABLE";
}
public Table getParent() {
return null;
}
}
/** Implementation of {@link Attribute} based on a {@link Lattice.Column}. */
private static class AttributeImpl implements Attribute {
private final Lattice.Column column;
private final TableImpl table;
private AttributeImpl(Lattice.Column column, TableImpl table) {
this.column = column;
this.table = table;
}
@Override public String toString() {
return getLabel();
}
public String getLabel() {
return column.alias;
}
public Table getTable() {
return table;
}
public double estimateSpace() {
return 0;
}
public String getCandidateColumnName() {
return null;
}
public String getDatatype(Dialect dialect) {
return null;
}
public List<Attribute> getAncestorAttributes() {
return ImmutableList.of();
}
}
/** Implementation of {@link org.pentaho.aggdes.model.StatisticsProvider}
* that asks the lattice. */
private static class StatisticsProviderImpl implements StatisticsProvider {
private final Lattice lattice;
StatisticsProviderImpl(Lattice lattice) {
this.lattice = lattice;
}
public double getFactRowCount() {
return lattice.getFactRowCount();
}
public double getRowCount(List<Attribute> attributes) {
return lattice.getRowCount(Lists.transform(attributes, TO_COLUMN));
}
public double getSpace(List<Attribute> attributes) {
return attributes.size();
}
public double getLoadTime(List<Attribute> attributes) {
return getSpace(attributes) * getRowCount(attributes);
}
}
}
// End TileSuggester.java
| {
"content_hash": "2a7c90103e2cb84a563f6aa199405f74",
"timestamp": "",
"source": "github",
"line_count": 207,
"max_line_length": 80,
"avg_line_length": 30.93719806763285,
"alnum_prop": 0.712211118051218,
"repo_name": "minji-kim/calcite",
"id": "bc98d944c185927cfffb9426b1d23a4e9f385b44",
"size": "7201",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "core/src/main/java/org/apache/calcite/materialize/TileSuggester.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2942"
},
{
"name": "CSS",
"bytes": "36560"
},
{
"name": "FreeMarker",
"bytes": "4728"
},
{
"name": "HTML",
"bytes": "28423"
},
{
"name": "Java",
"bytes": "13573652"
},
{
"name": "Python",
"bytes": "1610"
},
{
"name": "Ruby",
"bytes": "1802"
},
{
"name": "Shell",
"bytes": "5211"
}
],
"symlink_target": ""
} |
import pygame
import os
import sys
from pygame.locals import *
pygame.init()
def parse_message(message,typeMessage=""):
messageList = []
count = 0
part = ''
for char in message:
if count != 0:
if count > len(typeMessage)-1:
if char == "_" or char == "|":
messageList.append(part)
part = ''
else:
part += char
if count == len(message) - 1:
messageList.append(part)
part = ''
count += 1
return messageList
def load_image(name, colorkey=None):
fullname = os.path.join('data', name)
try:
image = pygame.image.load(fullname)
except pygame.error as message:
print('Cannot load image: ' + str(name))
raise SystemExit,message
image = image.convert_alpha()
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, RLEACCEL)
return image, image.get_rect()
def load_sound(name):
class NoneSound:
def play(self): pass
if not pygame.mixer:
return NoneSound()
fullname = os.path.join('data', name)
try:
sound = pygame.mixer.Sound(fullname)
except pygame.error as message:
print('Cannot load sound: ' + str(wav))
raise SystemExit, message
return sound
| {
"content_hash": "4637096e2ae2eb3f0f677c84bb009589",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 49,
"avg_line_length": 27.865384615384617,
"alnum_prop": 0.5410628019323671,
"repo_name": "mstubinis/Tic-Tac-Pi",
"id": "0987e9a8bdeeeb6e026a2ed492cf25b0fc8eed8a",
"size": "1449",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Tic-Tac-Pi/resourceManager.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "37401"
}
],
"symlink_target": ""
} |
namespace starboard {
namespace shared {
namespace starboard {
namespace player {
namespace filter {
class VideoRenderAlgorithmImpl : public VideoRenderAlgorithm {
public:
typedef std::function<double()> GetRefreshRateFn;
explicit VideoRenderAlgorithmImpl(
const GetRefreshRateFn& get_refresh_rate_fn = GetRefreshRateFn());
void Render(MediaTimeProvider* media_time_provider,
std::list<scoped_refptr<VideoFrame>>* frames,
VideoRendererSink::DrawFrameCB draw_frame_cb) override;
void Seek(SbTime seek_to_time) override;
int GetDroppedFrames() override { return dropped_frames_; }
private:
void RenderWithCadence(MediaTimeProvider* media_time_provider,
std::list<scoped_refptr<VideoFrame>>* frames,
VideoRendererSink::DrawFrameCB draw_frame_cb);
const GetRefreshRateFn get_refresh_rate_fn_;
VideoFrameCadencePatternGenerator cadence_pattern_generator_;
VideoFrameRateEstimator frame_rate_estimate_;
#if SB_PLAYER_FILTER_ENABLE_STATE_CHECK
static constexpr int kMaxLogPerPlaybackSession = 32;
int times_logged_ = 0;
SbTime media_time_of_last_render_call_;
SbTime system_time_of_last_render_call_;
#endif // SB_PLAYER_FILTER_ENABLE_STATE_CHECK
SbTime last_frame_timestamp_ = -1;
int current_frame_rendered_times_ = -1;
int dropped_frames_ = 0;
};
} // namespace filter
} // namespace player
} // namespace starboard
} // namespace shared
} // namespace starboard
#endif // STARBOARD_SHARED_STARBOARD_PLAYER_FILTER_VIDEO_RENDER_ALGORITHM_IMPL_H_
| {
"content_hash": "7b9427911d28715baf91f597de2da33c",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 82,
"avg_line_length": 32.183673469387756,
"alnum_prop": 0.7279644895370958,
"repo_name": "youtube/cobalt_sandbox",
"id": "ff8d47400252c19cc3c7094d456748f218f7198c",
"size": "3073",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "starboard/shared/starboard/player/filter/video_render_algorithm_impl.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
using CTPPV5.Infrastructure.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using CTPPV5.Infrastructure.Extension;
namespace CTPPV5.Security.Impl
{
public class IdentifierProvider : IIdentifierProvider
{
static string identifier = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("ctppv5_command_server")).ToHex();
public string GetIdentifier()
{
return identifier;
}
}
}
| {
"content_hash": "53dda0fd5e665f6ebbf962e860099f99",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 117,
"avg_line_length": 27.15,
"alnum_prop": 0.7274401473296501,
"repo_name": "zesus19/c5.v1",
"id": "7343e503d4d0aa0768bcf3ef056e50362225b9e2",
"size": "545",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Sources/CTPPV5.Security.Impl.Server/IdentifierProvider.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "206"
},
{
"name": "Batchfile",
"bytes": "3260"
},
{
"name": "C#",
"bytes": "3091504"
},
{
"name": "CSS",
"bytes": "447741"
},
{
"name": "HTML",
"bytes": "773938"
},
{
"name": "JavaScript",
"bytes": "1635572"
},
{
"name": "Python",
"bytes": "672"
},
{
"name": "Shell",
"bytes": "55"
},
{
"name": "XSLT",
"bytes": "1348"
}
],
"symlink_target": ""
} |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.addthis.hydra.data.filter.lambda;
import java.io.IOException;
import com.addthis.codec.config.Configs;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestStringWithValueFilter {
private static class TestClass {
@JsonProperty
StringWithValueFilter startDate;
}
@Test
public void deserialize() throws IOException {
TestClass instance = Configs.decodeObject(TestClass.class, "{startDate: hello}");
assertEquals("hello", instance.startDate.get());
instance = Configs.decodeObject(TestClass.class, "{startDate: {input: hello, filter.case.upper:true}}");
assertEquals("HELLO", instance.startDate.get());
}
}
| {
"content_hash": "5bd74b87ed2756b93e475921aca3a61c",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 112,
"avg_line_length": 32.609756097560975,
"alnum_prop": 0.7314884068810771,
"repo_name": "mythguided/hydra",
"id": "d9809b1fe150f09a129aab5a5ed5264f518e166e",
"size": "1337",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "hydra-filters/src/test/java/com/addthis/hydra/data/filter/lambda/TestStringWithValueFilter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "37939"
},
{
"name": "HTML",
"bytes": "103283"
},
{
"name": "Java",
"bytes": "4732762"
},
{
"name": "JavaScript",
"bytes": "582863"
},
{
"name": "Shell",
"bytes": "13923"
}
],
"symlink_target": ""
} |
---
title: Event Processing (CEP)
weight: 1
type: docs
aliases:
- /dev/libs/cep.html
- /apis/streaming/libs/cep.html
---
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# FlinkCEP - Complex event processing for Flink
FlinkCEP is the Complex Event Processing (CEP) library implemented on top of Flink.
It allows you to detect event patterns in an endless stream of events, giving you the opportunity to get hold of what's important in your
data.
This page describes the API calls available in Flink CEP. We start by presenting the [Pattern API](#the-pattern-api),
which allows you to specify the patterns that you want to detect in your stream, before presenting how you can
[detect and act upon matching event sequences](#detecting-patterns). We then present the assumptions the CEP
library makes when [dealing with lateness](#handling-lateness-in-event-time) in event time and how you can
[migrate your job](#migrating-from-an-older-flink-versionpre-13) from an older Flink version to Flink-1.3.
## Getting Started
If you want to jump right in, [set up a Flink program]({{< ref "docs/dev/datastream/project-configuration" >}}) and
add the FlinkCEP dependency to the `pom.xml` of your project.
{{< tabs "3b3e4675-dd86-4b2d-8487-9c8711f234b3" >}}
{{< tab "Java" >}}
{{< artifact flink-cep withScalaVersion >}}
{{< /tab >}}
{{< tab "Scala" >}}
{{< artifact flink-cep-scala withScalaVersion >}}
{{< /tab >}}
{{< /tabs >}}
FlinkCEP is not part of the binary distribution. See how to link with it for cluster execution [here]({{< ref "docs/dev/datastream/project-configuration" >}}).
Now you can start writing your first CEP program using the Pattern API.
{{< hint warning >}}
The events in the `DataStream` to which
you want to apply pattern matching must implement proper `equals()` and `hashCode()` methods
because FlinkCEP uses them for comparing and matching events.
{{< /hint >}}
{{< tabs "8951ef0a-cdd4-40d1-bda8-dec1299aaf41" >}}
{{< tab "Java" >}}
```java
DataStream<Event> input = ...
Pattern<Event, ?> pattern = Pattern.<Event>begin("start").where(
new SimpleCondition<Event>() {
@Override
public boolean filter(Event event) {
return event.getId() == 42;
}
}
).next("middle").subtype(SubEvent.class).where(
new SimpleCondition<SubEvent>() {
@Override
public boolean filter(SubEvent subEvent) {
return subEvent.getVolume() >= 10.0;
}
}
).followedBy("end").where(
new SimpleCondition<Event>() {
@Override
public boolean filter(Event event) {
return event.getName().equals("end");
}
}
);
PatternStream<Event> patternStream = CEP.pattern(input, pattern);
DataStream<Alert> result = patternStream.process(
new PatternProcessFunction<Event, Alert>() {
@Override
public void processMatch(
Map<String, List<Event>> pattern,
Context ctx,
Collector<Alert> out) throws Exception {
out.collect(createAlertFrom(pattern));
}
});
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
val input: DataStream[Event] = ...
val pattern = Pattern.begin[Event]("start").where(_.getId == 42)
.next("middle").subtype(classOf[SubEvent]).where(_.getVolume >= 10.0)
.followedBy("end").where(_.getName == "end")
val patternStream = CEP.pattern(input, pattern)
val result: DataStream[Alert] = patternStream.process(
new PatternProcessFunction[Event, Alert]() {
override def processMatch(
`match`: util.Map[String, util.List[Event]],
ctx: PatternProcessFunction.Context,
out: Collector[Alert]): Unit = {
out.collect(createAlertFrom(pattern))
}
})
```
{{< /tab >}}
{{< /tabs >}}
## The Pattern API
The pattern API allows you to define complex pattern sequences that you want to extract from your input stream.
Each complex pattern sequence consists of multiple simple patterns, i.e. patterns looking for individual events with the same properties. From now on, we will call these simple patterns **patterns**, and the final complex pattern sequence we are searching for in the stream, the **pattern sequence**. You can see a pattern sequence as a graph of such patterns, where transitions from one pattern to the next occur based on user-specified
*conditions*, e.g. `event.getName().equals("end")`. A **match** is a sequence of input events which visits all
patterns of the complex pattern graph, through a sequence of valid pattern transitions.
{{< hint info >}}
Each pattern must have a unique name, which you use later to identify the matched events.
{{< /hint >}}
{{< hint danger >}}
Pattern names **CANNOT** contain the character `":"`.
{{< /hint >}}
In the rest of this section we will first describe how to define [Individual Patterns](#individual-patterns), and then how you can combine individual patterns into [Complex Patterns](#combining-patterns).
### Individual Patterns
A **Pattern** can be either a *singleton* or a *looping* pattern. Singleton patterns accept a single
event, while looping patterns can accept more than one. In pattern matching symbols, the pattern `"a b+ c? d"` (or `"a"`, followed by *one or more* `"b"`'s, optionally followed by a `"c"`, followed by a `"d"`), `a`, `c?`, and `d` are
singleton patterns, while `b+` is a looping one. By default, a pattern is a singleton pattern and you can transform
it to a looping one by using [Quantifiers](#quantifiers). Each pattern can have one or more
[Conditions](#conditions) based on which it accepts events.
#### Quantifiers
In FlinkCEP, you can specify looping patterns using these methods: `pattern.oneOrMore()`, for patterns that expect one or more occurrences of a given event (e.g. the `b+` mentioned before); and `pattern.times(#ofTimes)`, for patterns that
expect a specific number of occurrences of a given type of event, e.g. 4 `a`'s; and `pattern.times(#fromTimes, #toTimes)`, for patterns that expect a specific minimum number of occurrences and a maximum number of occurrences of a given type of event, e.g. 2-4 `a`s.
You can make looping patterns greedy using the `pattern.greedy()` method, but you cannot yet make group patterns greedy. You can make all patterns, looping or not, optional using the `pattern.optional()` method.
For a pattern named `start`, the following are valid quantifiers:
{{< tabs "83522c42-0d20-4068-ac8c-3ab942de8fb0" >}}
{{< tab "Java" >}}
```java
// expecting 4 occurrences
start.times(4);
// expecting 0 or 4 occurrences
start.times(4).optional();
// expecting 2, 3 or 4 occurrences
start.times(2, 4);
// expecting 2, 3 or 4 occurrences and repeating as many as possible
start.times(2, 4).greedy();
// expecting 0, 2, 3 or 4 occurrences
start.times(2, 4).optional();
// expecting 0, 2, 3 or 4 occurrences and repeating as many as possible
start.times(2, 4).optional().greedy();
// expecting 1 or more occurrences
start.oneOrMore();
// expecting 1 or more occurrences and repeating as many as possible
start.oneOrMore().greedy();
// expecting 0 or more occurrences
start.oneOrMore().optional();
// expecting 0 or more occurrences and repeating as many as possible
start.oneOrMore().optional().greedy();
// expecting 2 or more occurrences
start.timesOrMore(2);
// expecting 2 or more occurrences and repeating as many as possible
start.timesOrMore(2).greedy();
// expecting 0, 2 or more occurrences
start.timesOrMore(2).optional()
// expecting 0, 2 or more occurrences and repeating as many as possible
start.timesOrMore(2).optional().greedy();
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
// expecting 4 occurrences
start.times(4)
// expecting 0 or 4 occurrences
start.times(4).optional()
// expecting 2, 3 or 4 occurrences
start.times(2, 4)
// expecting 2, 3 or 4 occurrences and repeating as many as possible
start.times(2, 4).greedy()
// expecting 0, 2, 3 or 4 occurrences
start.times(2, 4).optional()
// expecting 0, 2, 3 or 4 occurrences and repeating as many as possible
start.times(2, 4).optional().greedy()
// expecting 1 or more occurrences
start.oneOrMore()
// expecting 1 or more occurrences and repeating as many as possible
start.oneOrMore().greedy()
// expecting 0 or more occurrences
start.oneOrMore().optional()
// expecting 0 or more occurrences and repeating as many as possible
start.oneOrMore().optional().greedy()
// expecting 2 or more occurrences
start.timesOrMore(2)
// expecting 2 or more occurrences and repeating as many as possible
start.timesOrMore(2).greedy()
// expecting 0, 2 or more occurrences
start.timesOrMore(2).optional()
// expecting 0, 2 or more occurrences and repeating as many as possible
start.timesOrMore(2).optional().greedy()
```
{{< /tab >}}
{{< /tabs >}}
#### Conditions
For every pattern you can specify a condition that an incoming event has to meet in order to be "accepted" into the pattern e.g. its value should be larger than 5,
or larger than the average value of the previously accepted events.
You can specify conditions on the event properties via the `pattern.where()`, `pattern.or()` or `pattern.until()` methods.
These can be either `IterativeCondition`s or `SimpleCondition`s.
**Iterative Conditions:** This is the most general type of condition. This is how you can specify a condition that
accepts subsequent events based on properties of the previously accepted events or a statistic over a subset of them.
Below is the code for an iterative condition that accepts the next event for a pattern named "middle" if its name starts
with "foo", and if the sum of the prices of the previously accepted events for that pattern plus the price of the current event do not exceed the value of 5.0. Iterative conditions can be powerful, especially in combination with looping patterns, e.g. `oneOrMore()`.
{{< tabs "f60c47c8-7629-4a3a-bb42-d2eddff17082" >}}
{{< tab "Java" >}}
```java
middle.oneOrMore()
.subtype(SubEvent.class)
.where(new IterativeCondition<SubEvent>() {
@Override
public boolean filter(SubEvent value, Context<SubEvent> ctx) throws Exception {
if (!value.getName().startsWith("foo")) {
return false;
}
double sum = value.getPrice();
for (Event event : ctx.getEventsForPattern("middle")) {
sum += event.getPrice();
}
return Double.compare(sum, 5.0) < 0;
}
});
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
middle.oneOrMore()
.subtype(classOf[SubEvent])
.where(
(value, ctx) => {
lazy val sum = ctx.getEventsForPattern("middle").map(_.getPrice).sum
value.getName.startsWith("foo") && sum + value.getPrice < 5.0
}
)
```
{{< /tab >}}
{{< /tabs >}}
{{< hint info >}}
The call to `ctx.getEventsForPattern(...)` finds all the
previously accepted events for a given potential match. The cost of this operation can vary, so when implementing
your condition, try to minimize its use.
{{< /hint >}}
Described context gives one access to event time characteristics as well. For more info see [Time context](#time-context).
**Simple Conditions:** This type of condition extends the aforementioned `IterativeCondition` class and decides
whether to accept an event or not, based *only* on properties of the event itself.
{{< tabs "3a34bfc1-691f-41e7-88ee-c76ca6430e4c" >}}
{{< tab "Java" >}}
```java
start.where(new SimpleCondition<Event>() {
@Override
public boolean filter(Event value) {
return value.getName().startsWith("foo");
}
});
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
start.where(event => event.getName.startsWith("foo"))
```
{{< /tab >}}
{{< /tabs >}}
Finally, you can also restrict the type of the accepted event to a subtype of the initial event type (here `Event`)
via the `pattern.subtype(subClass)` method.
{{< tabs "be703e92-5424-4a03-a358-abc84f0f2e65" >}}
{{< tab "Java" >}}
```java
start.subtype(SubEvent.class).where(new SimpleCondition<SubEvent>() {
@Override
public boolean filter(SubEvent value) {
return ... // some condition
}
});
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
start.subtype(classOf[SubEvent]).where(subEvent => ... /* some condition */)
```
{{< /tab >}}
{{< /tabs >}}
**Combining Conditions:** As shown above, you can combine the `subtype` condition with additional conditions. This holds for every condition. You can arbitrarily combine conditions by sequentially calling `where()`. The final result will be the logical **AND** of the results of the individual conditions. To combine conditions using **OR**, you can use the `or()` method, as shown below.
{{< tabs "101511a2-3555-43c8-9c49-6c7ce24695f1" >}}
{{< tab "Java" >}}
```java
pattern.where(new SimpleCondition<Event>() {
@Override
public boolean filter(Event value) {
return ... // some condition
}
}).or(new SimpleCondition<Event>() {
@Override
public boolean filter(Event value) {
return ... // or condition
}
});
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
pattern.where(event => ... /* some condition */).or(event => ... /* or condition */)
```
{{< /tab >}}
{{< /tabs >}}
**Stop condition:** In case of looping patterns (`oneOrMore()` and `oneOrMore().optional()`) you can
also specify a stop condition, e.g. accept events with value larger than 5 until the sum of values is smaller than 50.
To better understand it, have a look at the following example. Given
* pattern like `"(a+ until b)"` (one or more `"a"` until `"b"`)
* a sequence of incoming events `"a1" "c" "a2" "b" "a3"`
* the library will output results: `{a1 a2} {a1} {a2} {a3}`.
As you can see `{a1 a2 a3}` or `{a2 a3}` are not returned due to the stop condition.
#### `where(condition)`
Defines a condition for the current pattern. To match the pattern, an event must satisfy the condition.
Multiple consecutive where() clauses lead to their conditions being `AND`ed.
{{< tabs "where" >}}
{{< tab "Java" >}}
```java
pattern.where(new IterativeCondition<Event>() {
@Override
public boolean filter(Event value, Context ctx) throws Exception {
return ... // some condition
}
});
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
pattern.where(event => ... /* some condition */)
```
{{< /tab >}}
{{< /tabs >}}
#### `or(condition)`
Adds a new condition which is `OR`ed with an existing one. An event can match the pattern only if it passes at least one of the conditions.
{{< tabs orcondition >}}
{{< tab "Java" >}}
```java
pattern.where(new IterativeCondition<Event>() {
@Override
public boolean filter(Event value, Context ctx) throws Exception {
return ... // some condition
}
}).or(new IterativeCondition<Event>() {
@Override
public boolean filter(Event value, Context ctx) throws Exception {
return ... // alternative condition
}
});
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
pattern.where(event => ... /* some condition */)
.or(event => ... /* alternative condition */)
```
{{< /tab >}}
{{< /tabs >}}
#### `until(condition)`
Specifies a stop condition for a looping pattern. Meaning if event matching the given condition occurs, no more
events will be accepted into the pattern. Applicable only in conjunction with `oneOrMore()`
`NOTE:` It allows for cleaning state for corresponding pattern on event-based condition.
{{< tabs untilcond >}}
{{< tab "Java" >}}
```java
pattern.oneOrMore().until(new IterativeCondition<Event>() {
@Override
public boolean filter(Event value, Context ctx) throws Exception {
return ... // alternative condition
}
});
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
pattern.oneOrMore().until(event => ... /* some condition */)
```
{{< /tab >}}
{{< /tabs >}}
#### `subtype(subClass)`
Defines a subtype condition for the current pattern. An event can only match the pattern if it is of this subtype.
{{< tabs subtype >}}
{{< tab "Java" >}}
```java
pattern.subtype(SubEvent.class);
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
pattern.subtype(classOf[SubEvent])
```
{{< /tab >}}
{{< /tabs >}}
#### `oneOrMore()`
Defines a subtype condition for the current pattern. An event can only match the pattern if it is of this subtype.
Specifies that this pattern expects at least one occurrence of a matching event.
By default a relaxed internal contiguity (between subsequent events) is used. For more info on
internal contiguity see <a href="#consecutive_java">consecutive</a>.
It is advised to use either `until()` or `within()` to enable state clearing.
{{< tabs oneormoe >}}
{{< tab "Java" >}}
```java
pattern.oneOrMore();
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
pattern.oneOrMore()
```
{{< /tab >}}
{{< /tabs >}}
#### `timesOrMore(#times)`
Specifies that this pattern expects at least `#times` occurrences of a matching event.
By default a relaxed internal contiguity (between subsequent events) is used. For more info on
internal contiguity see <a href="#consecutive_java">consecutive</a>.
{{< tabs timesormore >}}
{{< tab "Java" >}}
```java
pattern.timesOrMore(2);
```
{{< /tab >}}
{{< /tabs >}}
#### `times(#ofTimes)`
Specifies that this pattern expects an exact number of occurrences of a matching event.
By default a relaxed internal contiguity (between subsequent events) is used.
For more info on internal contiguity see <a href="#consecutive_java">consecutive</a>.
{{< tabs times >}}
{{< tab "Java" >}}
```java
pattern.times(2);
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
pattern.times(2)
```
{{< /tab >}}
{{< /tabs >}}
#### `times(#fromTimes, #toTimes)`
Specifies that this pattern expects occurrences between `#fromTimes`
and `#toTimes` of a matching event.
By default a relaxed internal contiguity (between subsequent events) is used. For more info on
internal contiguity see <a href="#consecutive_java">consecutive</a>.
{{< tabs timesrange >}}
{{< tab "Java" >}}
```java
pattern.times(2, 4);
```
{{< /tab >}}
{{< tab "Scala" >}}
```java
pattern.times(2, 4)
```
{{< /tab >}}
{{< /tabs >}}
#### `optional()`
Specifies that this pattern is optional, i.e. it may not occur at all. This is applicable to all aforementioned quantifiers.
{{< tabs optional >}}
{{< tab "Java" >}}
```java
pattern.oneOrMore().optional();
```
{{< /tab >}}
{{< tab "Scala" >}}
```java
pattern.oneOrMore().optional()
```
{{< /tab >}}
{{< /tabs >}}
#### `greedy()`
Specifies that this pattern is greedy, i.e. it will repeat as many as possible. This is only applicable
to quantifiers and it does not support group pattern currently.
{{< tabs greedy >}}
{{< tab "Java" >}}
```java
pattern.oneOrMore().greedy();
```
{{< /tab >}}
{{< tab "Scala" >}}
```java
pattern.oneOrMore().greedy()
```
{{< /tab >}}
{{< /tabs >}}
### Combining Patterns
Now that you've seen what an individual pattern can look like, it is time to see how to combine them
into a full pattern sequence.
A pattern sequence has to start with an initial pattern, as shown below:
{{< tabs "fdd1a5fa-d96e-4616-b682-cac7a821e0bb" >}}
{{< tab "Java" >}}
```java
Pattern<Event, ?> start = Pattern.<Event>begin("start");
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
val start : Pattern[Event, _] = Pattern.begin("start")
```
{{< /tab >}}
{{< /tabs >}}
Next, you can append more patterns to your pattern sequence by specifying the desired *contiguity conditions* between
them. FlinkCEP supports the following forms of contiguity between events:
1. **Strict Contiguity**: Expects all matching events to appear strictly one after the other, without any non-matching events in-between.
2. **Relaxed Contiguity**: Ignores non-matching events appearing in-between the matching ones.
3. **Non-Deterministic Relaxed Contiguity**: Further relaxes contiguity, allowing additional matches
that ignore some matching events.
To apply them between consecutive patterns, you can use:
1. `next()`, for *strict*,
2. `followedBy()`, for *relaxed*, and
3. `followedByAny()`, for *non-deterministic relaxed* contiguity.
or
1. `notNext()`, if you do not want an event type to directly follow another
2. `notFollowedBy()`, if you do not want an event type to be anywhere between two other event types.
{{< hint warning >}}
A pattern sequence cannot end in `notFollowedBy()`.
{{< /hint >}}
{{< hint warning >}}
A **NOT** pattern cannot be preceded by an optional one.
{{< /hint >}}
{{< tabs "71aa0caf-8bc9-4f4f-a5d1-78139230ef48" >}}
{{< tab "Java" >}}
```java
// strict contiguity
Pattern<Event, ?> strict = start.next("middle").where(...);
// relaxed contiguity
Pattern<Event, ?> relaxed = start.followedBy("middle").where(...);
// non-deterministic relaxed contiguity
Pattern<Event, ?> nonDetermin = start.followedByAny("middle").where(...);
// NOT pattern with strict contiguity
Pattern<Event, ?> strictNot = start.notNext("not").where(...);
// NOT pattern with relaxed contiguity
Pattern<Event, ?> relaxedNot = start.notFollowedBy("not").where(...);
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
// strict contiguity
val strict: Pattern[Event, _] = start.next("middle").where(...)
// relaxed contiguity
val relaxed: Pattern[Event, _] = start.followedBy("middle").where(...)
// non-deterministic relaxed contiguity
val nonDetermin: Pattern[Event, _] = start.followedByAny("middle").where(...)
// NOT pattern with strict contiguity
val strictNot: Pattern[Event, _] = start.notNext("not").where(...)
// NOT pattern with relaxed contiguity
val relaxedNot: Pattern[Event, _] = start.notFollowedBy("not").where(...)
```
{{< /tab >}}
{{< /tabs >}}
Relaxed contiguity means that only the first succeeding matching event will be matched, while
with non-deterministic relaxed contiguity, multiple matches will be emitted for the same beginning. As an example,
a pattern `"a b"`, given the event sequence `"a", "c", "b1", "b2"`, will give the following results:
1. Strict Contiguity between `"a"` and `"b"`: `{}` (no match), the `"c"` after `"a"` causes `"a"` to be discarded.
2. Relaxed Contiguity between `"a"` and `"b"`: `{a b1}`, as relaxed continuity is viewed as "skip non-matching events
till the next matching one".
3. Non-Deterministic Relaxed Contiguity between `"a"` and `"b"`: `{a b1}`, `{a b2}`, as this is the most general form.
It's also possible to define a temporal constraint for the pattern to be valid.
For example, you can define that a pattern should occur within 10 seconds via the `pattern.within()` method.
Temporal patterns are supported for both [processing and event time]({{< ref "docs/concepts/time" >}}).
{{< hint info >}}
A pattern sequence can only have one temporal constraint. If multiple such constraints are defined on different individual patterns, then the smallest is applied.
{{< /hint >}}
{{< tabs "df27eb6d-c532-430a-b56f-98ad4082e6d5" >}}
{{< tab "Java" >}}
```java
next.within(Time.seconds(10));
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
next.within(Time.seconds(10))
```
{{< /tab >}}
{{< /tabs >}}
#### Contiguity within looping patterns
You can apply the same contiguity condition as discussed in the previous [section](#combining-patterns) within a looping pattern.
The contiguity will be applied between elements accepted into such a pattern.
To illustrate the above with an example, a pattern sequence `"a b+ c"` (`"a"` followed by any(non-deterministic relaxed) sequence of one or more `"b"`'s followed by a `"c"`) with
input `"a", "b1", "d1", "b2", "d2", "b3" "c"` will have the following results:
1. **Strict Contiguity**: `{a b3 c}` -- the `"d1"` after `"b1"` causes `"b1"` to be discarded, the same happens for `"b2"` because of `"d2"`.
2. **Relaxed Contiguity**: `{a b1 c}`, `{a b1 b2 c}`, `{a b1 b2 b3 c}`, `{a b2 c}`, `{a b2 b3 c}`, `{a b3 c}` - `"d"`'s are ignored.
3. **Non-Deterministic Relaxed Contiguity**: `{a b1 c}`, `{a b1 b2 c}`, `{a b1 b3 c}`, `{a b1 b2 b3 c}`, `{a b2 c}`, `{a b2 b3 c}`, `{a b3 c}` -
notice the `{a b1 b3 c}`, which is the result of relaxing contiguity between `"b"`'s.
For looping patterns (e.g. `oneOrMore()` and `times()`) the default is *relaxed contiguity*. If you want
strict contiguity, you have to explicitly specify it by using the `consecutive()` call, and if you want
*non-deterministic relaxed contiguity* you can use the `allowCombinations()` call.
#### `consecutive()`
Works in conjunction with `oneOrMore()` and `times()` and imposes strict contiguity between the matching
events, i.e. any non-matching element breaks the match (as in `next()`).
If not applied a relaxed contiguity (as in `followedBy()`) is used.
E.g. a pattern like:
{{< tabs consecutive >}}
{{< tab "Java" >}}
```java
Pattern.<Event>begin("start").where(new SimpleCondition<Event>() {
@Override
public boolean filter(Event value) throws Exception {
return value.getName().equals("c");
}
})
.followedBy("middle").where(new SimpleCondition<Event>() {
@Override
public boolean filter(Event value) throws Exception {
return value.getName().equals("a");
}
}).oneOrMore().consecutive()
.followedBy("end1").where(new SimpleCondition<Event>() {
@Override
public boolean filter(Event value) throws Exception {
return value.getName().equals("b");
}
});
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
Pattern.begin("start").where(_.getName().equals("c"))
.followedBy("middle").where(_.getName().equals("a"))
.oneOrMore().consecutive()
.followedBy("end1").where(_.getName().equals("b"))
```
{{< /tab >}}
{{< /tabs >}}
Will generate the following matches for an input sequence: `C D A1 A2 A3 D A4 B`
with consecutive applied: `{C A1 B}`, `{C A1 A2 B}`, `{C A1 A2 A3 B}`
without consecutive applied: `{C A1 B}`, `{C A1 A2 B}`, `{C A1 A2 A3 B}`, `{C A1 A2 A3 A4 B}`.
#### `allowCombinations()`
Works in conjunction with `oneOrMore()` and `times()` and imposes non-deterministic relaxed contiguity
between the matching events (as in `followedByAny()`).
If not applied a relaxed contiguity (as in `followedBy()`) is used.
E.g. a pattern like:
{{< tabs allowcombinations >}}
{{< tab "Java" >}}
```java
Pattern.<Event>begin("start").where(new SimpleCondition<Event>() {
@Override
public boolean filter(Event value) throws Exception {
return value.getName().equals("c");
}
})
.followedBy("middle").where(new SimpleCondition<Event>() {
@Override
public boolean filter(Event value) throws Exception {
return value.getName().equals("a");
}
}).oneOrMore().allowCombinations()
.followedBy("end1").where(new SimpleCondition<Event>() {
@Override
public boolean filter(Event value) throws Exception {
return value.getName().equals("b");
}
});
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
Pattern.begin("start").where(_.getName().equals("c"))
.followedBy("middle").where(_.getName().equals("a"))
.oneOrMore().allowCombinations()
.followedBy("end1").where(_.getName().equals("b"))
```
{{< /tab >}}
{{< /tabs >}}
Will generate the following matches for an input sequence: `C D A1 A2 A3 D A4 B`.
with combinations enabled: `{C A1 B}`, `{C A1 A2 B}`, `{C A1 A3 B}`, `{C A1 A4 B}`, `{C A1 A2 A3 B}`, `{C A1 A2 A4 B}`, `{C A1 A3 A4 B}`, `{C A1 A2 A3 A4 B}`
without combinations enabled: `{C A1 B}`, `{C A1 A2 B}`, `{C A1 A2 A3 B}`, `{C A1 A2 A3 A4 B}`.
### Groups of patterns
It's also possible to define a pattern sequence as the condition for `begin`, `followedBy`, `followedByAny` and
`next`. The pattern sequence will be considered as the matching condition logically and a `GroupPattern` will be
returned and it is possible to apply `oneOrMore()`, `times(#ofTimes)`, `times(#fromTimes, #toTimes)`, `optional()`,
`consecutive()`, `allowCombinations()` to the `GroupPattern`.
{{< tabs "68e62a8a-d33a-44c2-bcf1-be2f8b01f448" >}}
{{< tab "Java" >}}
```java
Pattern<Event, ?> start = Pattern.begin(
Pattern.<Event>begin("start").where(...).followedBy("start_middle").where(...)
);
// strict contiguity
Pattern<Event, ?> strict = start.next(
Pattern.<Event>begin("next_start").where(...).followedBy("next_middle").where(...)
).times(3);
// relaxed contiguity
Pattern<Event, ?> relaxed = start.followedBy(
Pattern.<Event>begin("followedby_start").where(...).followedBy("followedby_middle").where(...)
).oneOrMore();
// non-deterministic relaxed contiguity
Pattern<Event, ?> nonDetermin = start.followedByAny(
Pattern.<Event>begin("followedbyany_start").where(...).followedBy("followedbyany_middle").where(...)
).optional();
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
val start: Pattern[Event, _] = Pattern.begin(
Pattern.begin[Event]("start").where(...).followedBy("start_middle").where(...)
)
// strict contiguity
val strict: Pattern[Event, _] = start.next(
Pattern.begin[Event]("next_start").where(...).followedBy("next_middle").where(...)
).times(3)
// relaxed contiguity
val relaxed: Pattern[Event, _] = start.followedBy(
Pattern.begin[Event]("followedby_start").where(...).followedBy("followedby_middle").where(...)
).oneOrMore()
// non-deterministic relaxed contiguity
val nonDetermin: Pattern[Event, _] = start.followedByAny(
Pattern.begin[Event]("followedbyany_start").where(...).followedBy("followedbyany_middle").where(...)
).optional()
```
{{< /tab >}}
{{< /tab >}}
#### `begin(#name)`
Defines a starting pattern.
{{< tabs begin>}}
{{< tab "Java" >}}
```java
Pattern<Event, ?> start = Pattern.<Event>begin("start");
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
val start = Pattern.begin[Event]("start")
```
{{< /tab >}}
{{< /tabs >}}
#### `begin(#pattern_sequence)`
Defines a starting pattern
{{< tabs beginsequence >}}
{{< tab "Java" >}}
```java
Pattern<Event, ?> start = Pattern.<Event>begin(
Pattern.<Event>begin("start").where(...).followedBy("middle").where(...)
);
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
val start = Pattern.begin(
Pattern.begin[Event]("start").where(...).followedBy("middle").where(...)
)
```
{{< /tab >}}
{{< /tabs >}}
#### `next(#name)`
Appends a new pattern. A matching event has to directly succeed the previous matching event (strict contiguity).
{{< tabs next >}}
{{< tab "Java" >}}
```java
Pattern<Event, ?> next = start.next("middle");
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
val next = start.next("middle")
```
{{< /tab >}}
{{< /tabs >}}
#### `next(#pattern_sequence)`
Appends a new pattern. A sequence of matching events have to directly succeed the previous matching event (strict contiguity).
{{< tabs nextseq >}}
{{< tab "Java" >}}
```java
Pattern<Event, ?> next = start.next(
Pattern.<Event>begin("start").where(...).followedBy("middle").where(...)
);
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
val next = start.next(
Pattern.begin[Event]("start").where(...).followedBy("middle").where(...)
)
```
{{< /tab >}}
{{< /tabs >}}
#### `followedBy(#name)`
Appends a new pattern. Other events can occur between a matching event and the previous matching event (relaxed contiguity).
{{< tabs followedby >}}
{{< tab "Java" >}}
```java
Pattern<Event, ?> followedBy = start.followedBy("middle");
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
val followedBy = start.followedBy("middle")
```
{{< /tab >}}
{{< /tabs >}}
#### `followedBy(#pattern_sequence)`
Appends a new pattern. Other events can occur between a matching event and the previous matching event (relaxed contiguity).
{{< tabs followedbyseq >}}
{{< tab "Java" >}}
```java
Pattern<Event, ?> followedBy = start.followedBy(
Pattern.<Event>begin("start").where(...).followedBy("middle").where(...)
);
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
val followedBy = start.followedBy(
Pattern.begin[Event]("start").where(...).followedBy("middle").where(...)
)
```
{{< /tab >}}
{{< /tabs >}}
#### `followedByAny(#name)`
Appends a new pattern. Other events can occur between a matching event and the previous
matching event, and alternative matches will be presented for every alternative matching event
(non-deterministic relaxed contiguity).
{{< tabs followedbyany >}}
{{< tab "Java" >}}
```java
Pattern<Event, ?> followedByAny = start.followedByAny("middle");
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
val followedByAny = start.followedByAny("middle")
```
{{< /tab >}}
{{< /tabs >}}
#### `followedByAny(#pattern_sequence)`
Appends a new pattern. Other events can occur between a matching event and the previous
matching event, and alternative matches will be presented for every alternative matching event
(non-deterministic relaxed contiguity).
{{< tabs followedbyanyseq >}}
{{< tab "Java" >}}
```java
Pattern<Event, ?> next = start.next(
Pattern.<Event>begin("start").where(...).followedBy("middle").where(...)
);
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
val followedByAny = start.followedByAny(
Pattern.begin[Event]("start").where(...).followedBy("middle").where(...)
)
```
{{< /tab >}}
{{< /tabs >}}
#### `notNext()`
Appends a new negative pattern.
A matching (negative) event has to directly succeed the previous matching event (strict contiguity) for the partial match to be discarded.
{{< tabs notnext >}}
{{< tab "Java" >}}
```java
Pattern<Event, ?> notNext = start.notNext("not");
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
val notNext = start.notNext("not")
```
{{< /tab >}}
{{< /tabs >}}
#### `notFollowedBy()`
Appends a new negative pattern. A partial matching event sequence will be discarded even if other events occur between the matching (negative) event and the previous matching event (relaxed contiguity).
{{< tabs notfollowedby >}}
{{< tab "Java" >}}
```java
Pattern<Event, ?> notFollowedBy = start.notFollowedBy("not");
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
val notFollowedBy = start.notFollowedBy("not")
```
{{< /tab >}}
{{< /tabs >}}
#### `within(time)`
Defines the maximum time interval for an event sequence to match the pattern.
If a non-completed event sequence exceeds this time, it is discarded.
{{< tabs within >}}
{{< tab "Java" >}}
```java
pattern.within(Time.seconds(10));
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
pattern.within(Time.seconds(10))
```
{{< /tab >}}
{{< /tabs >}}
### After Match Skip Strategy
For a given pattern, the same event may be assigned to multiple successful matches. To control to how many matches an event will be assigned, you need to specify the skip strategy called `AfterMatchSkipStrategy`. There are five types of skip strategies, listed as follows:
* <strong>*NO_SKIP*</strong>: Every possible match will be emitted.
* <strong>*SKIP_TO_NEXT*</strong>: Discards every partial match that started with the same event, emitted match was started.
* <strong>*SKIP_PAST_LAST_EVENT*</strong>: Discards every partial match that started after the match started but before it ended.
* <strong>*SKIP_TO_FIRST*</strong>: Discards every partial match that started after the match started but before the first event of *PatternName* occurred.
* <strong>*SKIP_TO_LAST*</strong>: Discards every partial match that started after the match started but before the last event of *PatternName* occurred.
Notice that when using *SKIP_TO_FIRST* and *SKIP_TO_LAST* skip strategy, a valid *PatternName* should also be specified.
For example, for a given pattern `b+ c` and a data stream `b1 b2 b3 c`, the differences between these four skip strategies are as follows:
<table class="table table-bordered">
<tr>
<th class="text-left" style="width: 25%">Skip Strategy</th>
<th class="text-center" style="width: 25%">Result</th>
<th class="text-center"> Description</th>
</tr>
<tr>
<td><strong>NO_SKIP</strong></td>
<td>
<code>b1 b2 b3 c</code><br>
<code>b2 b3 c</code><br>
<code>b3 c</code><br>
</td>
<td>After found matching <code>b1 b2 b3 c</code>, the match process will not discard any result.</td>
</tr>
<tr>
<td><strong>SKIP_TO_NEXT</strong></td>
<td>
<code>b1 b2 b3 c</code><br>
<code>b2 b3 c</code><br>
<code>b3 c</code><br>
</td>
<td>After found matching <code>b1 b2 b3 c</code>, the match process will not discard any result, because no other match could start at b1.</td>
</tr>
<tr>
<td><strong>SKIP_PAST_LAST_EVENT</strong></td>
<td>
<code>b1 b2 b3 c</code><br>
</td>
<td>After found matching <code>b1 b2 b3 c</code>, the match process will discard all started partial matches.</td>
</tr>
<tr>
<td><strong>SKIP_TO_FIRST</strong>[<code>b</code>]</td>
<td>
<code>b1 b2 b3 c</code><br>
<code>b2 b3 c</code><br>
<code>b3 c</code><br>
</td>
<td>After found matching <code>b1 b2 b3 c</code>, the match process will try to discard all partial matches started before <code>b1</code>, but there are no such matches. Therefore nothing will be discarded.</td>
</tr>
<tr>
<td><strong>SKIP_TO_LAST</strong>[<code>b</code>]</td>
<td>
<code>b1 b2 b3 c</code><br>
<code>b3 c</code><br>
</td>
<td>After found matching <code>b1 b2 b3 c</code>, the match process will try to discard all partial matches started before <code>b3</code>. There is one such match <code>b2 b3 c</code></td>
</tr>
</table>
Have a look also at another example to better see the difference between NO_SKIP and SKIP_TO_FIRST:
Pattern: `(a | b | c) (b | c) c+.greedy d` and sequence: `a b c1 c2 c3 d` Then the results will be:
<table class="table table-bordered">
<tr>
<th class="text-left" style="width: 25%">Skip Strategy</th>
<th class="text-center" style="width: 25%">Result</th>
<th class="text-center"> Description</th>
</tr>
<tr>
<td><strong>NO_SKIP</strong></td>
<td>
<code>a b c1 c2 c3 d</code><br>
<code>b c1 c2 c3 d</code><br>
<code>c1 c2 c3 d</code><br>
</td>
<td>After found matching <code>a b c1 c2 c3 d</code>, the match process will not discard any result.</td>
</tr>
<tr>
<td><strong>SKIP_TO_FIRST</strong>[<code>c*</code>]</td>
<td>
<code>a b c1 c2 c3 d</code><br>
<code>c1 c2 c3 d</code><br>
</td>
<td>After found matching <code>a b c1 c2 c3 d</code>, the match process will discard all partial matches started before <code>c1</code>. There is one such match <code>b c1 c2 c3 d</code>.</td>
</tr>
</table>
To better understand the difference between NO_SKIP and SKIP_TO_NEXT take a look at following example:
Pattern: `a b+` and sequence: `a b1 b2 b3` Then the results will be:
<table class="table table-bordered">
<tr>
<th class="text-left" style="width: 25%">Skip Strategy</th>
<th class="text-center" style="width: 25%">Result</th>
<th class="text-center"> Description</th>
</tr>
<tr>
<td><strong>NO_SKIP</strong></td>
<td>
<code>a b1</code><br>
<code>a b1 b2</code><br>
<code>a b1 b2 b3</code><br>
</td>
<td>After found matching <code>a b1</code>, the match process will not discard any result.</td>
</tr>
<tr>
<td><strong>SKIP_TO_NEXT</strong></td>
<td>
<code>a b1</code><br>
</td>
<td>After found matching <code>a b1</code>, the match process will discard all partial matches started at <code>a</code>. This means neither <code>a b1 b2</code> nor <code>a b1 b2 b3</code> could be generated.</td>
</tr>
</table>
To specify which skip strategy to use, just create an `AfterMatchSkipStrategy` by calling:
<table class="table table-bordered">
<tr>
<th class="text-left" width="25%">Function</th>
<th class="text-center">Description</th>
</tr>
<tr>
<td><code>AfterMatchSkipStrategy.noSkip()</code></td>
<td>Create a <strong>NO_SKIP</strong> skip strategy </td>
</tr>
<tr>
<td><code>AfterMatchSkipStrategy.skipToNext()</code></td>
<td>Create a <strong>SKIP_TO_NEXT</strong> skip strategy </td>
</tr>
<tr>
<td><code>AfterMatchSkipStrategy.skipPastLastEvent()</code></td>
<td>Create a <strong>SKIP_PAST_LAST_EVENT</strong> skip strategy </td>
</tr>
<tr>
<td><code>AfterMatchSkipStrategy.skipToFirst(patternName)</code></td>
<td>Create a <strong>SKIP_TO_FIRST</strong> skip strategy with the referenced pattern name <i>patternName</i></td>
</tr>
<tr>
<td><code>AfterMatchSkipStrategy.skipToLast(patternName)</code></td>
<td>Create a <strong>SKIP_TO_LAST</strong> skip strategy with the referenced pattern name <i>patternName</i></td>
</tr>
</table>
Then apply the skip strategy to a pattern by calling:
{{< tabs "64a34dcc-47f8-443d-b31a-515f7fd17243" >}}
{{< tab "Java" >}}
```java
AfterMatchSkipStrategy skipStrategy = ...
Pattern.begin("patternName", skipStrategy);
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
val skipStrategy = ...
Pattern.begin("patternName", skipStrategy)
```
{{< /tab >}}
{{< /tabs >}}
{{< hint info >}}
For `SKIP_TO_FIRST`/`LAST` there are two options how to handle cases when there are no elements mapped to
the specified variable. By default a NO_SKIP strategy will be used in this case. The other option is to throw exception in such situation.
One can enable this option by:
{{< /hint >}}
{{< tabs "59e07b27-61d3-4348-ab60-c8a805500c87" >}}
{{< tab "Java" >}}
```java
AfterMatchSkipStrategy.skipToFirst(patternName).throwExceptionOnMiss()
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
AfterMatchSkipStrategy.skipToFirst(patternName).throwExceptionOnMiss()
```
{{< /tab >}}
{{< /tabs >}}
## Detecting Patterns
After specifying the pattern sequence you are looking for, it is time to apply it to your input stream to detect
potential matches. To run a stream of events against your pattern sequence, you have to create a `PatternStream`.
Given an input stream `input`, a pattern `pattern` and an optional comparator `comparator` used to sort events with the same timestamp in case of EventTime or that arrived at the same moment, you create the `PatternStream` by calling:
{{< tabs "79719c8a-f503-4f3e-9717-75540e637481" >}}
{{< tab "Java" >}}
```java
DataStream<Event> input = ...
Pattern<Event, ?> pattern = ...
EventComparator<Event> comparator = ... // optional
PatternStream<Event> patternStream = CEP.pattern(input, pattern, comparator);
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
val input : DataStream[Event] = ...
val pattern : Pattern[Event, _] = ...
var comparator : EventComparator[Event] = ... // optional
val patternStream: PatternStream[Event] = CEP.pattern(input, pattern, comparator)
```
{{< /tab >}}
{{< /tabs >}}
The input stream can be *keyed* or *non-keyed* depending on your use-case.
{{< hint info >}}
Applying your pattern on a non-keyed stream will result in a job with parallelism equal to 1.
{{< /hint >}}
### Selecting from Patterns
Once you have obtained a `PatternStream` you can apply transformation to detected event sequences. The suggested way of doing that
is by `PatternProcessFunction`.
A `PatternProcessFunction` has a `processMatch` method which is called for each matching event sequence.
It receives a match in the form of `Map<String, List<IN>>` where the key is the name of each pattern in your pattern
sequence and the value is a list of all accepted events for that pattern (`IN` is the type of your input elements).
The events for a given pattern are ordered by timestamp. The reason for returning a list of accepted events for each
pattern is that when using looping patterns (e.g. `oneToMany()` and `times()`), more than one event may be accepted for a given pattern.
```java
class MyPatternProcessFunction<IN, OUT> extends PatternProcessFunction<IN, OUT> {
@Override
public void processMatch(Map<String, List<IN>> match, Context ctx, Collector<OUT> out) throws Exception;
IN startEvent = match.get("start").get(0);
IN endEvent = match.get("end").get(0);
out.collect(OUT(startEvent, endEvent));
}
}
```
The `PatternProcessFunction` gives access to a `Context` object. Thanks to it, one can access time related
characteristics such as `currentProcessingTime` or `timestamp` of current match (which is the timestamp of the last element assigned to the match).
For more info see [Time context](#time-context).
Through this context one can also emit results to a [side-output]({{< ref "docs/dev/datastream/side_output" >}}).
#### Handling Timed Out Partial Patterns
Whenever a pattern has a window length attached via the `within` keyword, it is possible that partial event sequences
are discarded because they exceed the window length. To act upon a timed out partial match one can use `TimedOutPartialMatchHandler` interface.
The interface is supposed to be used in a mixin style. This mean you can additionally implement this interface with your `PatternProcessFunction`.
The `TimedOutPartialMatchHandler` provides the additional `processTimedOutMatch` method which will be called for every timed out partial match.
```java
class MyPatternProcessFunction<IN, OUT> extends PatternProcessFunction<IN, OUT> implements TimedOutPartialMatchHandler<IN> {
@Override
public void processMatch(Map<String, List<IN>> match, Context ctx, Collector<OUT> out) throws Exception;
...
}
@Override
public void processTimedOutMatch(Map<String, List<IN>> match, Context ctx) throws Exception;
IN startEvent = match.get("start").get(0);
ctx.output(outputTag, T(startEvent));
}
}
```
<span class="label label-info">Note</span> The `processTimedOutMatch` does not give one access to the main output. You can still emit results
through [side-outputs]({{< ref "docs/dev/datastream/side_output" >}}) though, through the `Context` object.
#### Convenience API
The aforementioned `PatternProcessFunction` was introduced in Flink 1.8 and since then it is the recommended way to interact with matches.
One can still use the old style API like `select`/`flatSelect`, which internally will be translated into a `PatternProcessFunction`.
{{< tabs "04d04e1c-3d3b-4e33-ad5f-1ce41f5fc025" >}}
{{< tab "Java" >}}
```java
PatternStream<Event> patternStream = CEP.pattern(input, pattern);
OutputTag<String> outputTag = new OutputTag<String>("side-output"){};
SingleOutputStreamOperator<ComplexEvent> flatResult = patternStream.flatSelect(
outputTag,
new PatternFlatTimeoutFunction<Event, TimeoutEvent>() {
public void timeout(
Map<String, List<Event>> pattern,
long timeoutTimestamp,
Collector<TimeoutEvent> out) throws Exception {
out.collect(new TimeoutEvent());
}
},
new PatternFlatSelectFunction<Event, ComplexEvent>() {
public void flatSelect(Map<String, List<IN>> pattern, Collector<OUT> out) throws Exception {
out.collect(new ComplexEvent());
}
}
);
DataStream<TimeoutEvent> timeoutFlatResult = flatResult.getSideOutput(outputTag);
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
val patternStream: PatternStream[Event] = CEP.pattern(input, pattern)
val outputTag = OutputTag[String]("side-output")
val result: SingleOutputStreamOperator[ComplexEvent] = patternStream.flatSelect(outputTag){
(pattern: Map[String, Iterable[Event]], timestamp: Long, out: Collector[TimeoutEvent]) =>
out.collect(TimeoutEvent())
} {
(pattern: mutable.Map[String, Iterable[Event]], out: Collector[ComplexEvent]) =>
out.collect(ComplexEvent())
}
val timeoutResult: DataStream[TimeoutEvent] = result.getSideOutput(outputTag)
```
{{< /tab >}}
{{< /tabs >}}
## Time in CEP library
### Handling Lateness in Event Time
In `CEP` the order in which elements are processed matters. To guarantee that elements are processed in the correct order when working in event time, an incoming element is initially put in a buffer where elements are *sorted in ascending order based on their timestamp*, and when a watermark arrives, all the elements in this buffer with timestamps smaller than that of the watermark are processed. This implies that elements between watermarks are processed in event-time order.
{{< hint info >}}
The library assumes correctness of the watermark when working in event time.
{{< /hint >}}
To guarantee that elements across watermarks are processed in event-time order, Flink's CEP library assumes
*correctness of the watermark*, and considers as *late* elements whose timestamp is smaller than that of the last
seen watermark. Late elements are not further processed. Also, you can specify a sideOutput tag to collect the late elements come after the last seen watermark, you can use it like this.
{{< tabs "fb816b4d-5aca-4afe-baad-bdaf34e5a0eb" >}}
{{< tab "Java" >}}
```java
PatternStream<Event> patternStream = CEP.pattern(input, pattern);
OutputTag<String> lateDataOutputTag = new OutputTag<String>("late-data"){};
SingleOutputStreamOperator<ComplexEvent> result = patternStream
.sideOutputLateData(lateDataOutputTag)
.select(
new PatternSelectFunction<Event, ComplexEvent>() {...}
);
DataStream<String> lateData = result.getSideOutput(lateDataOutputTag);
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
val patternStream: PatternStream[Event] = CEP.pattern(input, pattern)
val lateDataOutputTag = OutputTag[String]("late-data")
val result: SingleOutputStreamOperator[ComplexEvent] = patternStream
.sideOutputLateData(lateDataOutputTag)
.select{
pattern: Map[String, Iterable[ComplexEvent]] => ComplexEvent()
}
val lateData: DataStream[String] = result.getSideOutput(lateDataOutputTag)
```
{{< /tab >}}
{{< /tabs >}}
### Time context
In [PatternProcessFunction](#selecting-from-patterns) as well as in [IterativeCondition](#conditions) user has access to a context
that implements `TimeContext` as follows:
```java
/**
* Enables access to time related characteristics such as current processing time or timestamp of
* currently processed element. Used in {@link PatternProcessFunction} and
* {@link org.apache.flink.cep.pattern.conditions.IterativeCondition}
*/
@PublicEvolving
public interface TimeContext {
/**
* Timestamp of the element currently being processed.
*
* <p>In case of {@link org.apache.flink.streaming.api.TimeCharacteristic#ProcessingTime} this
* will be set to the time when event entered the cep operator.
*/
long timestamp();
/** Returns the current processing time. */
long currentProcessingTime();
}
```
This context gives user access to time characteristics of processed events (incoming records in case of `IterativeCondition` and matches in case of `PatternProcessFunction`).
Call to `TimeContext#currentProcessingTime` always gives you the value of current processing time and this call should be preferred to e.g. calling `System.currentTimeMillis()`.
In case of `TimeContext#timestamp()` the returned value is equal to assigned timestamp in case of `EventTime`. In `ProcessingTime` this will equal to the point of time when said event entered
cep operator (or when the match was generated in case of `PatternProcessFunction`). This means that the value will be consistent across multiple calls to that method.
## Examples
The following example detects the pattern `start, middle(name = "error") -> end(name = "critical")` on a keyed data
stream of `Events`. The events are keyed by their `id`s and a valid pattern has to occur within 10 seconds.
The whole processing is done with event time.
{{< tabs "573ac3c5-e8b9-4ffa-b7b6-e2db19611ff5" >}}
{{< tab "Java" >}}
```java
StreamExecutionEnvironment env = ...
DataStream<Event> input = ...
DataStream<Event> partitionedInput = input.keyBy(new KeySelector<Event, Integer>() {
@Override
public Integer getKey(Event value) throws Exception {
return value.getId();
}
});
Pattern<Event, ?> pattern = Pattern.<Event>begin("start")
.next("middle").where(new SimpleCondition<Event>() {
@Override
public boolean filter(Event value) throws Exception {
return value.getName().equals("error");
}
}).followedBy("end").where(new SimpleCondition<Event>() {
@Override
public boolean filter(Event value) throws Exception {
return value.getName().equals("critical");
}
}).within(Time.seconds(10));
PatternStream<Event> patternStream = CEP.pattern(partitionedInput, pattern);
DataStream<Alert> alerts = patternStream.select(new PatternSelectFunction<Event, Alert>() {
@Override
public Alert select(Map<String, List<Event>> pattern) throws Exception {
return createAlert(pattern);
}
});
```
{{< /tab >}}
{{< tab "Scala" >}}
```scala
val env : StreamExecutionEnvironment = ...
val input : DataStream[Event] = ...
val partitionedInput = input.keyBy(event => event.getId)
val pattern = Pattern.begin[Event]("start")
.next("middle").where(_.getName == "error")
.followedBy("end").where(_.getName == "critical")
.within(Time.seconds(10))
val patternStream = CEP.pattern(partitionedInput, pattern)
val alerts = patternStream.select(createAlert(_))
```
{{< /tab >}}
{{< /tabs >}}
## Migrating from an older Flink version(pre 1.3)
### Migrating to 1.4+
In Flink-1.4 the backward compatibility of CEP library with <= Flink 1.2 was dropped. Unfortunately
it is not possible to restore a CEP job that was once run with 1.2.x
### Migrating to 1.3.x
The CEP library in Flink-1.3 ships with a number of new features which have led to some changes in the API. Here we
describe the changes that you need to make to your old CEP jobs, in order to be able to run them with Flink-1.3. After
making these changes and recompiling your job, you will be able to resume its execution from a savepoint taken with the
old version of your job, *i.e.* without having to re-process your past data.
The changes required are:
1. Change your conditions (the ones in the `where(...)` clause) to extend the `SimpleCondition` class instead of
implementing the `FilterFunction` interface.
2. Change your functions provided as arguments to the `select(...)` and `flatSelect(...)` methods to expect a list of
events associated with each pattern (`List` in `Java`, `Iterable` in `Scala`). This is because with the addition of
the looping patterns, multiple input events can match a single (looping) pattern.
3. The `followedBy()` in Flink 1.1 and 1.2 implied `non-deterministic relaxed contiguity` (see
[here](#conditions-on-contiguity)). In Flink 1.3 this has changed and `followedBy()` implies `relaxed contiguity`,
while `followedByAny()` should be used if `non-deterministic relaxed contiguity` is required.
{{< top >}}
| {
"content_hash": "044b9ec5ce819a24580c9cd14d927220",
"timestamp": "",
"source": "github",
"line_count": 1601,
"max_line_length": 480,
"avg_line_length": 34.602748282323546,
"alnum_prop": 0.6790375277532086,
"repo_name": "kl0u/flink",
"id": "8abf6d3f534190bdbd5eb2bf60d457197258cbff",
"size": "55399",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/content/docs/libs/cep.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4722"
},
{
"name": "CSS",
"bytes": "58149"
},
{
"name": "Clojure",
"bytes": "93247"
},
{
"name": "Dockerfile",
"bytes": "12142"
},
{
"name": "FreeMarker",
"bytes": "28662"
},
{
"name": "HTML",
"bytes": "108850"
},
{
"name": "Java",
"bytes": "53696165"
},
{
"name": "JavaScript",
"bytes": "1829"
},
{
"name": "Makefile",
"bytes": "5134"
},
{
"name": "Python",
"bytes": "1132424"
},
{
"name": "Scala",
"bytes": "13885420"
},
{
"name": "Shell",
"bytes": "533455"
},
{
"name": "TSQL",
"bytes": "123113"
},
{
"name": "TypeScript",
"bytes": "249126"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/bg_circles"
android:tileMode="repeat"/>
| {
"content_hash": "d49b8b3814a29759701770b1dcd1c2d2",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 66,
"avg_line_length": 44.25,
"alnum_prop": 0.7005649717514124,
"repo_name": "GlobalTechnology/gma-android",
"id": "fdd23a2a4e53ddde54df70da928c1288e16e14c0",
"size": "177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "measurements-app/src/main/res/drawable/bg_main.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "758642"
}
],
"symlink_target": ""
} |
@interface SDLTBTState : SDLEnum {}
+(SDLTBTState*) valueOf:(NSString*) value;
+(NSMutableArray*) values;
+(SDLTBTState*) ROUTE_UPDATE_REQUEST;
+(SDLTBTState*) ROUTE_ACCEPTED;
+(SDLTBTState*) ROUTE_REFUSED;
+(SDLTBTState*) ROUTE_CANCELLED;
+(SDLTBTState*) ETA_REQUEST;
+(SDLTBTState*) NEXT_TURN_REQUEST;
+(SDLTBTState*) ROUTE_STATUS_REQUEST;
+(SDLTBTState*) ROUTE_SUMMARY_REQUEST;
+(SDLTBTState*) TRIP_STATUS_REQUEST;
+(SDLTBTState*) ROUTE_UPDATE_REQUEST_TIMEOUT;
@end
| {
"content_hash": "c21f26350089359d11687273803cf994",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 45,
"avg_line_length": 27.764705882352942,
"alnum_prop": 0.7457627118644068,
"repo_name": "kmilitel/sdl_ios",
"id": "b31eaf9bae74358bafa1fb7a9bcec5dad7e2e844",
"size": "632",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sdl_ios/Products/AppLink.framework/Versions/A/Headers/SDLTBTState.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Objective-C",
"bytes": "1158382"
}
],
"symlink_target": ""
} |