code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_07) on Fri Jan 04 13:17:38 PST 2013 -->
<title>Resolver (dnsjava documentation)</title>
<meta name="date" content="2013-01-04">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Resolver (dnsjava documentation)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="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>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/xbill/DNS/RelativeNameException.html" title="class in org.xbill.DNS"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../org/xbill/DNS/ResolverConfig.html" title="class in org.xbill.DNS"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/xbill/DNS/Resolver.html" target="_top">Frames</a></li>
<li><a href="Resolver.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.xbill.DNS</div>
<h2 title="Interface Resolver" class="title">Interface Resolver</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Known Implementing Classes:</dt>
<dd><a href="../../../org/xbill/DNS/ExtendedResolver.html" title="class in org.xbill.DNS">ExtendedResolver</a>, <a href="../../../org/xbill/DNS/SimpleResolver.html" title="class in org.xbill.DNS">SimpleResolver</a></dd>
</dl>
<hr>
<br>
<pre>public interface <span class="strong">Resolver</span></pre>
<div class="block">Interface describing a resolver.</div>
<dl><dt><span class="strong">Author:</span></dt>
<dd>Brian Wellington</dd></dl>
</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="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../org/xbill/DNS/Message.html" title="class in org.xbill.DNS">Message</a></code></td>
<td class="colLast"><code><strong><a href="../../../org/xbill/DNS/Resolver.html#send(org.xbill.DNS.Message)">send</a></strong>(<a href="../../../org/xbill/DNS/Message.html" title="class in org.xbill.DNS">Message</a> query)</code>
<div class="block">Sends a message and waits for a response.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></code></td>
<td class="colLast"><code><strong><a href="../../../org/xbill/DNS/Resolver.html#sendAsync(org.xbill.DNS.Message, org.xbill.DNS.ResolverListener)">sendAsync</a></strong>(<a href="../../../org/xbill/DNS/Message.html" title="class in org.xbill.DNS">Message</a> query,
<a href="../../../org/xbill/DNS/ResolverListener.html" title="interface in org.xbill.DNS">ResolverListener</a> listener)</code>
<div class="block">Asynchronously sends a message registering a listener to receive a callback
on success or exception.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../org/xbill/DNS/Resolver.html#setEDNS(int)">setEDNS</a></strong>(int level)</code>
<div class="block">Sets the EDNS version used on outgoing messages.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../org/xbill/DNS/Resolver.html#setEDNS(int, int, int, java.util.List)">setEDNS</a></strong>(int level,
int payloadSize,
int flags,
<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a> options)</code>
<div class="block">Sets the EDNS information on outgoing messages.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../org/xbill/DNS/Resolver.html#setIgnoreTruncation(boolean)">setIgnoreTruncation</a></strong>(boolean flag)</code>
<div class="block">Sets whether truncated responses will be ignored.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../org/xbill/DNS/Resolver.html#setPort(int)">setPort</a></strong>(int port)</code>
<div class="block">Sets the port to communicate with on the server</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../org/xbill/DNS/Resolver.html#setTCP(boolean)">setTCP</a></strong>(boolean flag)</code>
<div class="block">Sets whether TCP connections will be sent by default</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../org/xbill/DNS/Resolver.html#setTimeout(int)">setTimeout</a></strong>(int secs)</code>
<div class="block">Sets the amount of time to wait for a response before giving up.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../org/xbill/DNS/Resolver.html#setTimeout(int, int)">setTimeout</a></strong>(int secs,
int msecs)</code>
<div class="block">Sets the amount of time to wait for a response before giving up.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../org/xbill/DNS/Resolver.html#setTSIGKey(org.xbill.DNS.TSIG)">setTSIGKey</a></strong>(<a href="../../../org/xbill/DNS/TSIG.html" title="class in org.xbill.DNS">TSIG</a> key)</code>
<div class="block">Specifies the TSIG key that messages will be signed with</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="setPort(int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setPort</h4>
<pre>void setPort(int port)</pre>
<div class="block">Sets the port to communicate with on the server</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>port</code> - The port to send messages to</dd></dl>
</li>
</ul>
<a name="setTCP(boolean)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setTCP</h4>
<pre>void setTCP(boolean flag)</pre>
<div class="block">Sets whether TCP connections will be sent by default</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>flag</code> - Indicates whether TCP connections are made</dd></dl>
</li>
</ul>
<a name="setIgnoreTruncation(boolean)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setIgnoreTruncation</h4>
<pre>void setIgnoreTruncation(boolean flag)</pre>
<div class="block">Sets whether truncated responses will be ignored. If not, a truncated
response over UDP will cause a retransmission over TCP.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>flag</code> - Indicates whether truncated responses should be ignored.</dd></dl>
</li>
</ul>
<a name="setEDNS(int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setEDNS</h4>
<pre>void setEDNS(int level)</pre>
<div class="block">Sets the EDNS version used on outgoing messages.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>level</code> - The EDNS level to use. 0 indicates EDNS0 and -1 indicates no
EDNS.</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/IllegalArgumentException.html?is-external=true" title="class or interface in java.lang">IllegalArgumentException</a></code> - An invalid level was indicated.</dd></dl>
</li>
</ul>
<a name="setEDNS(int, int, int, java.util.List)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setEDNS</h4>
<pre>void setEDNS(int level,
int payloadSize,
int flags,
<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a> options)</pre>
<div class="block">Sets the EDNS information on outgoing messages.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>level</code> - The EDNS level to use. 0 indicates EDNS0 and -1 indicates no
EDNS.</dd><dd><code>payloadSize</code> - The maximum DNS packet size that this host is capable
of receiving over UDP. If 0 is specified, the default (1280) is used.</dd><dd><code>flags</code> - EDNS extended flags to be set in the OPT record.</dd><dd><code>options</code> - EDNS options to be set in the OPT record, specified as a
List of OPTRecord.Option elements.</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/IllegalArgumentException.html?is-external=true" title="class or interface in java.lang">IllegalArgumentException</a></code> - An invalid field was specified.</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../org/xbill/DNS/OPTRecord.html" title="class in org.xbill.DNS"><code>OPTRecord</code></a></dd></dl>
</li>
</ul>
<a name="setTSIGKey(org.xbill.DNS.TSIG)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setTSIGKey</h4>
<pre>void setTSIGKey(<a href="../../../org/xbill/DNS/TSIG.html" title="class in org.xbill.DNS">TSIG</a> key)</pre>
<div class="block">Specifies the TSIG key that messages will be signed with</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>key</code> - The key</dd></dl>
</li>
</ul>
<a name="setTimeout(int, int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setTimeout</h4>
<pre>void setTimeout(int secs,
int msecs)</pre>
<div class="block">Sets the amount of time to wait for a response before giving up.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>secs</code> - The number of seconds to wait.</dd><dd><code>msecs</code> - The number of milliseconds to wait.</dd></dl>
</li>
</ul>
<a name="setTimeout(int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setTimeout</h4>
<pre>void setTimeout(int secs)</pre>
<div class="block">Sets the amount of time to wait for a response before giving up.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>secs</code> - The number of seconds to wait.</dd></dl>
</li>
</ul>
<a name="send(org.xbill.DNS.Message)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>send</h4>
<pre><a href="../../../org/xbill/DNS/Message.html" title="class in org.xbill.DNS">Message</a> send(<a href="../../../org/xbill/DNS/Message.html" title="class in org.xbill.DNS">Message</a> query)
throws <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a></pre>
<div class="block">Sends a message and waits for a response.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>query</code> - The query to send.</dd>
<dt><span class="strong">Returns:</span></dt><dd>The response</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="http://download.oracle.com/javase/1.4.2/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a></code> - An error occurred while sending or receiving.</dd></dl>
</li>
</ul>
<a name="sendAsync(org.xbill.DNS.Message, org.xbill.DNS.ResolverListener)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>sendAsync</h4>
<pre><a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> sendAsync(<a href="../../../org/xbill/DNS/Message.html" title="class in org.xbill.DNS">Message</a> query,
<a href="../../../org/xbill/DNS/ResolverListener.html" title="interface in org.xbill.DNS">ResolverListener</a> listener)</pre>
<div class="block">Asynchronously sends a message registering a listener to receive a callback
on success or exception. Multiple asynchronous lookups can be performed
in parallel. Since the callback may be invoked before the function returns,
external synchronization is necessary.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>query</code> - The query to send</dd><dd><code>listener</code> - The object containing the callbacks.</dd>
<dt><span class="strong">Returns:</span></dt><dd>An identifier, which is also a parameter in the callback</dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="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>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/xbill/DNS/RelativeNameException.html" title="class in org.xbill.DNS"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../org/xbill/DNS/ResolverConfig.html" title="class in org.xbill.DNS"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/xbill/DNS/Resolver.html" target="_top">Frames</a></li>
<li><a href="Resolver.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 ======= -->
</body>
</html>
|
emacadie/dnsgroovy
|
doc/org/xbill/DNS/Resolver.html
|
HTML
|
bsd-2-clause
| 17,193 |
<!DOCTYPE html>
<html><head>
<meta charset="utf8">
<title>{% block htmltitle %}{% endblock %}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='bootstrap.min.css') }}">
<style type="text/css">
html { height: 100%; }
body {
background: #5298ad;
background-image: -moz-radial-gradient(#86b7c6, #396a79);
background-image: -webkit-radial-gradient(#86b6c6, #396a79);
color: white;
overflow: hidden;
min-height: 100%;
}
#bodily {
font-family: sans-serif;
width: 30em;
margin: 2em auto;
}
h1 {
text-shadow: #396a79 1px 1px 5px;
}
</style>
{% block htmlhead %}{% endblock %}
</head><body>
<div id="bodily">
{% block content %}{% endblock %}
</div>
</body></html>
|
markpasc/flid
|
templates/base.html
|
HTML
|
bsd-2-clause
| 889 |
shp2kml
=======
shp2kml converts shapefile data to KML and writes it to stdout. It expects a field called "FULLNAME" to exist in the shapefile, and uses that field for the name of each KML Placemark. It currently creates a KML Placemark object for each shape in the shapefile data, and adds a LineString to the Placemark for each point in the shape.
You'll need to pip install the following Python packages:
* pyshp
* lxml
* pykml
Usage: python shp2kml.py shp_file dbf_file
|
cthrall/shp2kml
|
README.md
|
Markdown
|
bsd-2-clause
| 477 |
#ifndef PROBLEMDATA_H
#define PROBLEMDATA_H
#include <QString>
#include <memory>
namespace problemdata {
enum class CellType {
CellAnswer,
CellClue
};
const static int CLOSED_CLUE = 0;
class ProblemData_int;
class ProblemData
{
std::unique_ptr<ProblemData_int> m_;
// ctor - only accessible from factory method
ProblemData(std::unique_ptr<ProblemData_int> m);
public:
~ProblemData();
int getNumCols() const;
// returns # of columns; includes leftmost clue only columns
int getNumRows() const;
// return # of rows; includes topmost clue only rows
CellType getCellType(int col, int row) const;
// returns the cell type of specified cell
int getClueRight(int col, int row) const;
int getClueDown(int col, int row) const;
// get clue; only valid for clue cells
int getAnswer(int col, int row) const;
// return answer of cell; only valid for answer cells
static ProblemData *problemLoader(const QString &filename);
// factory method; load problem data from a file
// delete unnecessary default methods to make this immutable
ProblemData(const ProblemData&) = delete;
ProblemData & operator=(const ProblemData&) = delete;
};
} // namespace problemdata
#endif // PROBLEMDATA_H
|
hideki1234/Kakuro
|
Kakuro/problemdata.h
|
C
|
bsd-2-clause
| 1,295 |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'ProductOption'
db.create_table('shop_productoption', (
('type', self.gf('django.db.models.fields.IntegerField')()),
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('cartridge.shop.fields.OptionField')(max_length=50, null=True)),
))
db.send_create_signal('shop', ['ProductOption'])
# Adding model 'Category'
db.create_table('shop_category', (
('content', self.gf('mezzanine.core.fields.HtmlField')()),
('page_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['pages.Page'], unique=True, primary_key=True)),
))
db.send_create_signal('shop', ['Category'])
# Adding model 'Product'
db.create_table('shop_product', (
('status', self.gf('django.db.models.fields.IntegerField')(default=1)),
('sale_to', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
('available', self.gf('django.db.models.fields.BooleanField')(default=False, blank=True)),
('description', self.gf('mezzanine.core.fields.HtmlField')(blank=True)),
('_keywords', self.gf('django.db.models.fields.CharField')(max_length=500)),
('title', self.gf('django.db.models.fields.CharField')(max_length=100)),
('short_url', self.gf('django.db.models.fields.URLField')(max_length=200, null=True, blank=True)),
('image', self.gf('django.db.models.fields.CharField')(max_length=100, null=True, blank=True)),
('sale_id', self.gf('django.db.models.fields.IntegerField')(null=True)),
('unit_price', self.gf('cartridge.shop.fields.MoneyField')(null=True, max_digits=10, decimal_places=2, blank=True)),
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('content', self.gf('mezzanine.core.fields.HtmlField')()),
('expiry_date', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
('publish_date', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
('date_added', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, null=True, blank=True)),
('sale_price', self.gf('cartridge.shop.fields.MoneyField')(null=True, max_digits=10, decimal_places=2, blank=True)),
('slug', self.gf('django.db.models.fields.CharField')(max_length=100, null=True, blank=True)),
('sale_from', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
))
db.send_create_signal('shop', ['Product'])
# Adding M2M table for field keywords on 'Product'
db.create_table('shop_product_keywords', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('product', models.ForeignKey(orm['shop.product'], null=False)),
('keyword', models.ForeignKey(orm['core.keyword'], null=False))
))
db.create_unique('shop_product_keywords', ['product_id', 'keyword_id'])
# Adding M2M table for field categories on 'Product'
db.create_table('shop_product_categories', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('product', models.ForeignKey(orm['shop.product'], null=False)),
('category', models.ForeignKey(orm['shop.category'], null=False))
))
db.create_unique('shop_product_categories', ['product_id', 'category_id'])
# Adding model 'ProductImage'
db.create_table('shop_productimage', (
('product', self.gf('django.db.models.fields.related.ForeignKey')(related_name='images', to=orm['shop.Product'])),
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('file', self.gf('django.db.models.fields.files.ImageField')(max_length=100)),
('description', self.gf('django.db.models.fields.CharField')(max_length=100, blank=True)),
))
db.send_create_signal('shop', ['ProductImage'])
# Adding model 'ProductVariation'
db.create_table('shop_productvariation', (
('sale_to', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
('sku', self.gf('cartridge.shop.fields.SKUField')(unique=True, max_length=20)),
('product', self.gf('django.db.models.fields.related.ForeignKey')(related_name='variations', to=orm['shop.Product'])),
('sale_from', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
('default', self.gf('django.db.models.fields.BooleanField')(default=False, blank=True)),
('image', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['shop.ProductImage'], null=True, blank=True)),
('sale_id', self.gf('django.db.models.fields.IntegerField')(null=True)),
('unit_price', self.gf('cartridge.shop.fields.MoneyField')(null=True, max_digits=10, decimal_places=2, blank=True)),
('num_in_stock', self.gf('django.db.models.fields.IntegerField')(null=True, blank=True)),
('sale_price', self.gf('cartridge.shop.fields.MoneyField')(null=True, max_digits=10, decimal_places=2, blank=True)),
('option2', self.gf('cartridge.shop.fields.OptionField')(max_length=50, null=True)),
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('option1', self.gf('cartridge.shop.fields.OptionField')(max_length=50, null=True)),
))
db.send_create_signal('shop', ['ProductVariation'])
# Adding model 'Order'
db.create_table('shop_order', (
('status', self.gf('django.db.models.fields.IntegerField')(default=1)),
('shipping_detail_country', self.gf('django.db.models.fields.CharField')(max_length=100)),
('additional_instructions', self.gf('django.db.models.fields.TextField')(blank=True)),
('billing_detail_city', self.gf('django.db.models.fields.CharField')(max_length=100)),
('shipping_type', self.gf('django.db.models.fields.CharField')(max_length=50, blank=True)),
('billing_detail_country', self.gf('django.db.models.fields.CharField')(max_length=100)),
('shipping_detail_phone', self.gf('django.db.models.fields.CharField')(max_length=20)),
('shipping_detail_city', self.gf('django.db.models.fields.CharField')(max_length=100)),
('total', self.gf('cartridge.shop.fields.MoneyField')(null=True, max_digits=10, decimal_places=2, blank=True)),
('shipping_detail_postcode', self.gf('django.db.models.fields.CharField')(max_length=10)),
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('billing_detail_phone', self.gf('django.db.models.fields.CharField')(max_length=20)),
('shipping_detail_last_name', self.gf('django.db.models.fields.CharField')(max_length=100)),
('billing_detail_street', self.gf('django.db.models.fields.CharField')(max_length=100)),
('shipping_detail_first_name', self.gf('django.db.models.fields.CharField')(max_length=100)),
('billing_detail_last_name', self.gf('django.db.models.fields.CharField')(max_length=100)),
('discount_code', self.gf('cartridge.shop.fields.DiscountCodeField')(max_length=20, blank=True)),
('billing_detail_postcode', self.gf('django.db.models.fields.CharField')(max_length=10)),
('shipping_total', self.gf('cartridge.shop.fields.MoneyField')(null=True, max_digits=10, decimal_places=2, blank=True)),
('shipping_detail_state', self.gf('django.db.models.fields.CharField')(max_length=100)),
('item_total', self.gf('cartridge.shop.fields.MoneyField')(null=True, max_digits=10, decimal_places=2, blank=True)),
('billing_detail_state', self.gf('django.db.models.fields.CharField')(max_length=100)),
('key', self.gf('django.db.models.fields.CharField')(max_length=40)),
('user_id', self.gf('django.db.models.fields.IntegerField')(null=True, blank=True)),
('billing_detail_first_name', self.gf('django.db.models.fields.CharField')(max_length=100)),
('shipping_detail_street', self.gf('django.db.models.fields.CharField')(max_length=100)),
('billing_detail_email', self.gf('django.db.models.fields.EmailField')(max_length=75)),
('time', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, null=True, blank=True)),
('discount_total', self.gf('cartridge.shop.fields.MoneyField')(null=True, max_digits=10, decimal_places=2, blank=True)),
))
db.send_create_signal('shop', ['Order'])
# Adding model 'Cart'
db.create_table('shop_cart', (
('last_updated', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, null=True, blank=True)),
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
))
db.send_create_signal('shop', ['Cart'])
# Adding model 'CartItem'
db.create_table('shop_cartitem', (
('sku', self.gf('cartridge.shop.fields.SKUField')(max_length=20)),
('total_price', self.gf('cartridge.shop.fields.MoneyField')(default='0', null=True, max_digits=10, decimal_places=2, blank=True)),
('description', self.gf('django.db.models.fields.CharField')(max_length=200)),
('url', self.gf('django.db.models.fields.CharField')(max_length=200)),
('image', self.gf('django.db.models.fields.CharField')(max_length=200, null=True)),
('unit_price', self.gf('cartridge.shop.fields.MoneyField')(default='0', null=True, max_digits=10, decimal_places=2, blank=True)),
('cart', self.gf('django.db.models.fields.related.ForeignKey')(related_name='items', to=orm['shop.Cart'])),
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('quantity', self.gf('django.db.models.fields.IntegerField')(default=0)),
))
db.send_create_signal('shop', ['CartItem'])
# Adding model 'OrderItem'
db.create_table('shop_orderitem', (
('sku', self.gf('cartridge.shop.fields.SKUField')(max_length=20)),
('total_price', self.gf('cartridge.shop.fields.MoneyField')(default='0', null=True, max_digits=10, decimal_places=2, blank=True)),
('description', self.gf('django.db.models.fields.CharField')(max_length=200)),
('unit_price', self.gf('cartridge.shop.fields.MoneyField')(default='0', null=True, max_digits=10, decimal_places=2, blank=True)),
('order', self.gf('django.db.models.fields.related.ForeignKey')(related_name='items', to=orm['shop.Order'])),
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('quantity', self.gf('django.db.models.fields.IntegerField')(default=0)),
))
db.send_create_signal('shop', ['OrderItem'])
# Adding model 'ProductAction'
db.create_table('shop_productaction', (
('timestamp', self.gf('django.db.models.fields.IntegerField')()),
('product', self.gf('django.db.models.fields.related.ForeignKey')(related_name='actions', to=orm['shop.Product'])),
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('total_purchase', self.gf('django.db.models.fields.IntegerField')(default=0)),
('total_cart', self.gf('django.db.models.fields.IntegerField')(default=0)),
))
db.send_create_signal('shop', ['ProductAction'])
# Adding unique constraint on 'ProductAction', fields ['product', 'timestamp']
db.create_unique('shop_productaction', ['product_id', 'timestamp'])
# Adding model 'Sale'
db.create_table('shop_sale', (
('valid_from', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
('title', self.gf('django.db.models.fields.CharField')(max_length=100)),
('valid_to', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
('discount_percent', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=4, decimal_places=2, blank=True)),
('active', self.gf('django.db.models.fields.BooleanField')(default=False, blank=True)),
('discount_exact', self.gf('cartridge.shop.fields.MoneyField')(null=True, max_digits=10, decimal_places=2, blank=True)),
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('discount_deduct', self.gf('cartridge.shop.fields.MoneyField')(null=True, max_digits=10, decimal_places=2, blank=True)),
))
db.send_create_signal('shop', ['Sale'])
# Adding M2M table for field products on 'Sale'
db.create_table('shop_sale_products', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('sale', models.ForeignKey(orm['shop.sale'], null=False)),
('product', models.ForeignKey(orm['shop.product'], null=False))
))
db.create_unique('shop_sale_products', ['sale_id', 'product_id'])
# Adding M2M table for field categories on 'Sale'
db.create_table('shop_sale_categories', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('sale', models.ForeignKey(orm['shop.sale'], null=False)),
('category', models.ForeignKey(orm['shop.category'], null=False))
))
db.create_unique('shop_sale_categories', ['sale_id', 'category_id'])
# Adding model 'DiscountCode'
db.create_table('shop_discountcode', (
('free_shipping', self.gf('django.db.models.fields.BooleanField')(default=False, blank=True)),
('valid_from', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
('title', self.gf('django.db.models.fields.CharField')(max_length=100)),
('valid_to', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
('code', self.gf('cartridge.shop.fields.DiscountCodeField')(unique=True, max_length=20)),
('min_purchase', self.gf('cartridge.shop.fields.MoneyField')(null=True, max_digits=10, decimal_places=2, blank=True)),
('discount_percent', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=4, decimal_places=2, blank=True)),
('active', self.gf('django.db.models.fields.BooleanField')(default=False, blank=True)),
('discount_exact', self.gf('cartridge.shop.fields.MoneyField')(null=True, max_digits=10, decimal_places=2, blank=True)),
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('discount_deduct', self.gf('cartridge.shop.fields.MoneyField')(null=True, max_digits=10, decimal_places=2, blank=True)),
))
db.send_create_signal('shop', ['DiscountCode'])
# Adding M2M table for field products on 'DiscountCode'
db.create_table('shop_discountcode_products', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('discountcode', models.ForeignKey(orm['shop.discountcode'], null=False)),
('product', models.ForeignKey(orm['shop.product'], null=False))
))
db.create_unique('shop_discountcode_products', ['discountcode_id', 'product_id'])
# Adding M2M table for field categories on 'DiscountCode'
db.create_table('shop_discountcode_categories', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('discountcode', models.ForeignKey(orm['shop.discountcode'], null=False)),
('category', models.ForeignKey(orm['shop.category'], null=False))
))
db.create_unique('shop_discountcode_categories', ['discountcode_id', 'category_id'])
from cartridge.shop.management import create_initial_product
from cartridge.shop.models import Product
from atexit import register
register(create_initial_product, None, (Product,), 1, interactive=True)
def backwards(self, orm):
# Deleting model 'ProductOption'
db.delete_table('shop_productoption')
# Deleting model 'Category'
db.delete_table('shop_category')
# Deleting model 'Product'
db.delete_table('shop_product')
# Removing M2M table for field keywords on 'Product'
db.delete_table('shop_product_keywords')
# Removing M2M table for field categories on 'Product'
db.delete_table('shop_product_categories')
# Deleting model 'ProductImage'
db.delete_table('shop_productimage')
# Deleting model 'ProductVariation'
db.delete_table('shop_productvariation')
# Deleting model 'Order'
db.delete_table('shop_order')
# Deleting model 'Cart'
db.delete_table('shop_cart')
# Deleting model 'CartItem'
db.delete_table('shop_cartitem')
# Deleting model 'OrderItem'
db.delete_table('shop_orderitem')
# Deleting model 'ProductAction'
db.delete_table('shop_productaction')
# Removing unique constraint on 'ProductAction', fields ['product', 'timestamp']
db.delete_unique('shop_productaction', ['product_id', 'timestamp'])
# Deleting model 'Sale'
db.delete_table('shop_sale')
# Removing M2M table for field products on 'Sale'
db.delete_table('shop_sale_products')
# Removing M2M table for field categories on 'Sale'
db.delete_table('shop_sale_categories')
# Deleting model 'DiscountCode'
db.delete_table('shop_discountcode')
# Removing M2M table for field products on 'DiscountCode'
db.delete_table('shop_discountcode_products')
# Removing M2M table for field categories on 'DiscountCode'
db.delete_table('shop_discountcode_categories')
models = {
'core.keyword': {
'Meta': {'object_name': 'Keyword'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'pages.page': {
'Meta': {'object_name': 'Page'},
'_keywords': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
'_order': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'content_model': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True'}),
'description': ('mezzanine.core.fields.HtmlField', [], {'blank': 'True'}),
'expiry_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'in_footer': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'in_navigation': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'keywords': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['core.Keyword']", 'symmetrical': 'False', 'blank': 'True'}),
'login_required': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['pages.Page']"}),
'publish_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'short_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '1'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'titles': ('django.db.models.fields.CharField', [], {'max_length': '1000', 'null': 'True'})
},
'shop.cart': {
'Meta': {'object_name': 'Cart'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'})
},
'shop.cartitem': {
'Meta': {'object_name': 'CartItem'},
'cart': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'items'", 'to': "orm['shop.Cart']"}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True'}),
'quantity': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'sku': ('cartridge.shop.fields.SKUField', [], {'max_length': '20'}),
'total_price': ('cartridge.shop.fields.MoneyField', [], {'default': "'0'", 'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'unit_price': ('cartridge.shop.fields.MoneyField', [], {'default': "'0'", 'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'url': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
'shop.category': {
'Meta': {'object_name': 'Category', '_ormbases': ['pages.Page']},
'content': ('mezzanine.core.fields.HtmlField', [], {}),
'page_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['pages.Page']", 'unique': 'True', 'primary_key': 'True'})
},
'shop.discountcode': {
'Meta': {'object_name': 'DiscountCode'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'categories': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['shop.Category']", 'symmetrical': 'False', 'blank': 'True'}),
'code': ('cartridge.shop.fields.DiscountCodeField', [], {'unique': 'True', 'max_length': '20'}),
'discount_deduct': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'discount_exact': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'discount_percent': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '4', 'decimal_places': '2', 'blank': 'True'}),
'free_shipping': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'min_purchase': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'products': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['shop.Product']", 'symmetrical': 'False', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'valid_from': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'valid_to': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'})
},
'shop.order': {
'Meta': {'object_name': 'Order'},
'additional_instructions': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'billing_detail_city': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'billing_detail_country': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'billing_detail_email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
'billing_detail_first_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'billing_detail_last_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'billing_detail_phone': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'billing_detail_postcode': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
'billing_detail_state': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'billing_detail_street': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'discount_code': ('cartridge.shop.fields.DiscountCodeField', [], {'max_length': '20', 'blank': 'True'}),
'discount_total': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'item_total': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'shipping_detail_city': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'shipping_detail_country': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'shipping_detail_first_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'shipping_detail_last_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'shipping_detail_phone': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'shipping_detail_postcode': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
'shipping_detail_state': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'shipping_detail_street': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'shipping_total': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'shipping_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '1'}),
'time': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'total': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'user_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'})
},
'shop.orderitem': {
'Meta': {'object_name': 'OrderItem'},
'description': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'order': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'items'", 'to': "orm['shop.Order']"}),
'quantity': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'sku': ('cartridge.shop.fields.SKUField', [], {'max_length': '20'}),
'total_price': ('cartridge.shop.fields.MoneyField', [], {'default': "'0'", 'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'unit_price': ('cartridge.shop.fields.MoneyField', [], {'default': "'0'", 'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'})
},
'shop.product': {
'Meta': {'object_name': 'Product'},
'_keywords': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
'available': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'categories': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'products'", 'blank': 'True', 'to': "orm['shop.Category']"}),
'content': ('mezzanine.core.fields.HtmlField', [], {}),
'date_added': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'description': ('mezzanine.core.fields.HtmlField', [], {'blank': 'True'}),
'expiry_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'keywords': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['core.Keyword']", 'symmetrical': 'False', 'blank': 'True'}),
'publish_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'sale_from': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'sale_id': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'sale_price': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'sale_to': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'short_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '1'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'unit_price': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'})
},
'shop.productaction': {
'Meta': {'unique_together': "(('product', 'timestamp'),)", 'object_name': 'ProductAction'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'product': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'actions'", 'to': "orm['shop.Product']"}),
'timestamp': ('django.db.models.fields.IntegerField', [], {}),
'total_cart': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'total_purchase': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
'shop.productimage': {
'Meta': {'object_name': 'ProductImage'},
'description': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'file': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'product': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'images'", 'to': "orm['shop.Product']"})
},
'shop.productoption': {
'Meta': {'object_name': 'ProductOption'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('cartridge.shop.fields.OptionField', [], {'max_length': '50', 'null': 'True'}),
'type': ('django.db.models.fields.IntegerField', [], {})
},
'shop.productvariation': {
'Meta': {'object_name': 'ProductVariation'},
'default': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['shop.ProductImage']", 'null': 'True', 'blank': 'True'}),
'num_in_stock': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'option1': ('cartridge.shop.fields.OptionField', [], {'max_length': '50', 'null': 'True'}),
'option2': ('cartridge.shop.fields.OptionField', [], {'max_length': '50', 'null': 'True'}),
'product': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'variations'", 'to': "orm['shop.Product']"}),
'sale_from': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'sale_id': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'sale_price': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'sale_to': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'sku': ('cartridge.shop.fields.SKUField', [], {'unique': 'True', 'max_length': '20'}),
'unit_price': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'})
},
'shop.sale': {
'Meta': {'object_name': 'Sale'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'categories': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['shop.Category']", 'symmetrical': 'False', 'blank': 'True'}),
'discount_deduct': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'discount_exact': ('cartridge.shop.fields.MoneyField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'discount_percent': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '4', 'decimal_places': '2', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'products': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['shop.Product']", 'symmetrical': 'False', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'valid_from': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'valid_to': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'})
}
}
complete_apps = ['shop']
|
readevalprint/cartridge
|
cartridge/shop/migrations/0001_initial.py
|
Python
|
bsd-2-clause
| 35,099 |
###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, [email protected]
#
import unittest
from io import StringIO
from ..helperfunctions import _xml_to_list
from ...table import Table
from ...worksheet import Worksheet
from ...workbook import WorksheetMeta
from ...sharedstrings import SharedStringTable
class TestAssembleTable(unittest.TestCase):
"""
Test assembling a complete Table file.
"""
def test_assemble_xml_file(self):
"""Test writing a table"""
self.maxDiff = None
worksheet = Worksheet()
worksheet.worksheet_meta = WorksheetMeta()
worksheet.str_table = SharedStringTable()
# Set the table properties.
worksheet.add_table('C2:F13', {'name': 'MyTable'})
worksheet._prepare_tables(1, {})
fh = StringIO()
table = Table()
table._set_filehandle(fh)
table._set_properties(worksheet.tables[0])
table._assemble_xml_file()
exp = _xml_to_list("""
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" id="1" name="MyTable" displayName="MyTable" ref="C2:F13" totalsRowShown="0">
<autoFilter ref="C2:F13"/>
<tableColumns count="4">
<tableColumn id="1" name="Column1"/>
<tableColumn id="2" name="Column2"/>
<tableColumn id="3" name="Column3"/>
<tableColumn id="4" name="Column4"/>
</tableColumns>
<tableStyleInfo name="TableStyleMedium9" showFirstColumn="0" showLastColumn="0" showRowStripes="1" showColumnStripes="0"/>
</table>
""")
got = _xml_to_list(fh.getvalue())
self.assertEqual(got, exp)
|
jmcnamara/XlsxWriter
|
xlsxwriter/test/table/test_table10.py
|
Python
|
bsd-2-clause
| 1,978 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PVPNetConnect.RiotObjects.Platform.Game
{
public class GameDTO : RiotGamesObject
{
public override string TypeName
{
get
{
return this.type;
}
}
private string type = "com.riotgames.platform.game.GameDTO";
public GameDTO()
{
}
public GameDTO(Callback callback)
{
this.callback = callback;
}
public GameDTO(TypedObject result)
{
base.SetFields(this, result);
}
public delegate void Callback(GameDTO result);
private Callback callback;
public override void DoCallback(TypedObject result)
{
base.SetFields(this, result);
callback(this);
}
[InternalName("spectatorsAllowed")]
public String SpectatorsAllowed { get; set; }
[InternalName("passwordSet")]
public Boolean PasswordSet { get; set; }
[InternalName("gameType")]
public String GameType { get; set; }
[InternalName("gameTypeConfigId")]
public Int32 GameTypeConfigId { get; set; }
[InternalName("glmGameId")]
public object GlmGameId { get; set; }
[InternalName("gameState")]
public String GameState { get; set; }
[InternalName("glmHost")]
public object GlmHost { get; set; }
[InternalName("observers")]
public List<GameObserver> Observers { get; set; }
[InternalName("statusOfParticipants")]
public object StatusOfParticipants { get; set; }
[InternalName("glmSecurePort")]
public Int32 GlmSecurePort { get; set; }
[InternalName("id")]
public Double Id { get; set; }
[InternalName("ownerSummary")]
public PlayerParticipant OwnerSummary { get; set; }
[InternalName("teamTwo")]
public List<Participant> TeamTwo { get; set; }
[InternalName("bannedChampions")]
public List<BannedChampion> BannedChampions { get; set; }
[InternalName("roomName")]
public String RoomName { get; set; }
[InternalName("name")]
public String Name { get; set; }
[InternalName("spectatorDelay")]
public Int32 SpectatorDelay { get; set; }
[InternalName("teamOne")]
public List<Participant> TeamOne { get; set; }
[InternalName("terminatedCondition")]
public String TerminatedCondition { get; set; }
[InternalName("queueTypeName")]
public String QueueTypeName { get; set; }
[InternalName("glmPort")]
public Int32 GlmPort { get; set; }
[InternalName("passbackUrl")]
public object PassbackUrl { get; set; }
[InternalName("roomPassword")]
public String RoomPassword { get; set; }
[InternalName("optimisticLock")]
public Double OptimisticLock { get; set; }
[InternalName("maxNumPlayers")]
public Int32 MaxNumPlayers { get; set; }
[InternalName("queuePosition")]
public Int32 QueuePosition { get; set; }
[InternalName("gameMode")]
public String GameMode { get; set; }
[InternalName("expiryTime")]
public Double ExpiryTime { get; set; }
[InternalName("mapId")]
public Int32 MapId { get; set; }
[InternalName("banOrder")]
public List<Int32> BanOrder { get; set; }
[InternalName("pickTurn")]
public Int32 PickTurn { get; set; }
[InternalName("gameStateString")]
public String GameStateString { get; set; }
[InternalName("playerChampionSelections")]
public List<PlayerChampionSelectionDTO> PlayerChampionSelections { get; set; }
[InternalName("joinTimerDuration")]
public Int32 JoinTimerDuration { get; set; }
[InternalName("passbackDataPacket")]
public object PassbackDataPacket { get; set; }
}
}
|
semtize/LegendaryClient
|
GitPVP/RiotObjects/Platform/Game/GameDTO.cs
|
C#
|
bsd-2-clause
| 3,249 |
/*********************************************************************
*
* $Id: yocto_lightsensor.cpp 15253 2014-03-06 10:15:50Z seb $
*
* Implements yFindLightSensor(), the high-level API for LightSensor functions
*
* - - - - - - - - - License information: - - - - - - - - -
*
* Copyright (C) 2011 and beyond by Yoctopuce Sarl, Switzerland.
*
* Yoctopuce Sarl (hereafter Licensor) grants to you a perpetual
* non-exclusive license to use, modify, copy and integrate this
* file into your software for the sole purpose of interfacing
* with Yoctopuce products.
*
* You may reproduce and distribute copies of this file in
* source or object form, as long as the sole purpose of this
* code is to interface with Yoctopuce products. You must retain
* this notice in the distributed source file.
*
* You should refer to Yoctopuce General Terms and Conditions
* for additional information regarding your rights and
* obligations.
*
* THE SOFTWARE AND DOCUMENTATION ARE PROVIDED 'AS IS' WITHOUT
* WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
* WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO
* EVENT SHALL LICENSOR BE LIABLE FOR ANY INCIDENTAL, SPECIAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA,
* COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR
* SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT
* LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
* CONTRIBUTION, OR OTHER SIMILAR COSTS, WHETHER ASSERTED ON THE
* BASIS OF CONTRACT, TORT (INCLUDING NEGLIGENCE), BREACH OF
* WARRANTY, OR OTHERWISE.
*
*********************************************************************/
#define _CRT_SECURE_NO_DEPRECATE //do not use windows secure crt
#include "yocto3d/yocto_lightsensor.h"
#include "yocto3d/yapi/yjson.h"
#include "yocto3d/yapi/yapi.h"
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
YLightSensor::YLightSensor(const string& func): YSensor(func)
//--- (LightSensor initialization)
,_valueCallbackLightSensor(NULL)
,_timedReportCallbackLightSensor(NULL)
//--- (end of LightSensor initialization)
{
_className="LightSensor";
}
YLightSensor::~YLightSensor()
{
//--- (YLightSensor cleanup)
//--- (end of YLightSensor cleanup)
}
//--- (YLightSensor implementation)
// static attributes
int YLightSensor::set_currentValue(double newval)
{
string rest_val;
char buf[32]; sprintf(buf,"%d", (int)floor(newval*65536.0 +0.5)); rest_val = string(buf);
return _setAttr("currentValue", rest_val);
}
/**
* Changes the sensor-specific calibration parameter so that the current value
* matches a desired target (linear scaling).
*
* @param calibratedVal : the desired target value.
*
* Remember to call the saveToFlash() method of the module if the
* modification must be kept.
*
* @return YAPI_SUCCESS if the call succeeds.
*
* On failure, throws an exception or returns a negative error code.
*/
int YLightSensor::calibrate(double calibratedVal)
{
string rest_val;
char buf[32]; sprintf(buf,"%d", (int)floor(calibratedVal*65536.0 +0.5)); rest_val = string(buf);
return _setAttr("currentValue", rest_val);
}
/**
* Retrieves $AFUNCTION$ for a given identifier.
* The identifier can be specified using several formats:
* <ul>
* <li>FunctionLogicalName</li>
* <li>ModuleSerialNumber.FunctionIdentifier</li>
* <li>ModuleSerialNumber.FunctionLogicalName</li>
* <li>ModuleLogicalName.FunctionIdentifier</li>
* <li>ModuleLogicalName.FunctionLogicalName</li>
* </ul>
*
* This function does not require that $THEFUNCTION$ is online at the time
* it is invoked. The returned object is nevertheless valid.
* Use the method YLightSensor.isOnline() to test if $THEFUNCTION$ is
* indeed online at a given time. In case of ambiguity when looking for
* $AFUNCTION$ by logical name, no error is notified: the first instance
* found is returned. The search is performed first by hardware name,
* then by logical name.
*
* @param func : a string that uniquely characterizes $THEFUNCTION$
*
* @return a YLightSensor object allowing you to drive $THEFUNCTION$.
*/
YLightSensor* YLightSensor::FindLightSensor(string func)
{
YLightSensor* obj = NULL;
obj = (YLightSensor*) YFunction::_FindFromCache("LightSensor", func);
if (obj == NULL) {
obj = new YLightSensor(func);
YFunction::_AddToCache("LightSensor", func, obj);
}
return obj;
}
/**
* Registers the callback function that is invoked on every change of advertised value.
* The callback is invoked only during the execution of ySleep or yHandleEvents.
* This provides control over the time when the callback is triggered. For good responsiveness, remember to call
* one of these two functions periodically. To unregister a callback, pass a null pointer as argument.
*
* @param callback : the callback function to call, or a null pointer. The callback function should take two
* arguments: the function object of which the value has changed, and the character string describing
* the new advertised value.
* @noreturn
*/
int YLightSensor::registerValueCallback(YLightSensorValueCallback callback)
{
string val;
if (callback != NULL) {
YFunction::_UpdateValueCallbackList(this, true);
} else {
YFunction::_UpdateValueCallbackList(this, false);
}
_valueCallbackLightSensor = callback;
// Immediately invoke value callback with current value
if (callback != NULL && this->isOnline()) {
val = _advertisedValue;
if (!(val == "")) {
this->_invokeValueCallback(val);
}
}
return 0;
}
int YLightSensor::_invokeValueCallback(string value)
{
if (_valueCallbackLightSensor != NULL) {
_valueCallbackLightSensor(this, value);
} else {
YSensor::_invokeValueCallback(value);
}
return 0;
}
/**
* Registers the callback function that is invoked on every periodic timed notification.
* The callback is invoked only during the execution of ySleep or yHandleEvents.
* This provides control over the time when the callback is triggered. For good responsiveness, remember to call
* one of these two functions periodically. To unregister a callback, pass a null pointer as argument.
*
* @param callback : the callback function to call, or a null pointer. The callback function should take two
* arguments: the function object of which the value has changed, and an YMeasure object describing
* the new advertised value.
* @noreturn
*/
int YLightSensor::registerTimedReportCallback(YLightSensorTimedReportCallback callback)
{
if (callback != NULL) {
YFunction::_UpdateTimedReportCallbackList(this, true);
} else {
YFunction::_UpdateTimedReportCallbackList(this, false);
}
_timedReportCallbackLightSensor = callback;
return 0;
}
int YLightSensor::_invokeTimedReportCallback(YMeasure value)
{
if (_timedReportCallbackLightSensor != NULL) {
_timedReportCallbackLightSensor(this, value);
} else {
YSensor::_invokeTimedReportCallback(value);
}
return 0;
}
YLightSensor *YLightSensor::nextLightSensor(void)
{
string hwid;
if(YISERR(_nextFunction(hwid)) || hwid=="") {
return NULL;
}
return YLightSensor::FindLightSensor(hwid);
}
YLightSensor* YLightSensor::FirstLightSensor(void)
{
vector<YFUN_DESCR> v_fundescr;
YDEV_DESCR ydevice;
string serial, funcId, funcName, funcVal, errmsg;
if(YISERR(YapiWrapper::getFunctionsByClass("LightSensor", 0, v_fundescr, sizeof(YFUN_DESCR), errmsg)) ||
v_fundescr.size() == 0 ||
YISERR(YapiWrapper::getFunctionInfo(v_fundescr[0], ydevice, serial, funcId, funcName, funcVal, errmsg))) {
return NULL;
}
return YLightSensor::FindLightSensor(serial+"."+funcId);
}
//--- (end of YLightSensor implementation)
//--- (LightSensor functions)
//--- (end of LightSensor functions)
|
lucasroitman/rosyocto3d
|
yocto3d/src/lib/yocto_lightsensor.cpp
|
C++
|
bsd-2-clause
| 8,097 |
package adf.component.module.complex;
import adf.agent.communication.MessageManager;
import adf.agent.develop.DevelopData;
import adf.agent.info.AgentInfo;
import adf.agent.info.ScenarioInfo;
import adf.agent.info.WorldInfo;
import adf.agent.module.ModuleManager;
import adf.agent.precompute.PrecomputeData;
import rescuecore2.standard.entities.Road;
public abstract class RoadDetector extends TargetDetector<Road> {
public RoadDetector(AgentInfo ai, WorldInfo wi, ScenarioInfo si, ModuleManager moduleManager, DevelopData developData) {
super(ai, wi, si, moduleManager, developData);
}
@Override
public RoadDetector precompute(PrecomputeData precomputeData) {
super.precompute(precomputeData);
return this;
}
@Override
public RoadDetector resume(PrecomputeData precomputeData) {
super.resume(precomputeData);
return this;
}
@Override
public RoadDetector preparate() {
super.preparate();
return this;
}
@Override
public RoadDetector updateInfo(MessageManager messageManager) {
super.updateInfo(messageManager);
return this;
}
@Override
public abstract RoadDetector calc();
}
|
RCRS-ADF/core
|
src/main/java/adf/component/module/complex/RoadDetector.java
|
Java
|
bsd-2-clause
| 1,220 |
package org.kodejava.example.swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Date;
public class CreateJListDemo extends JFrame {
public CreateJListDemo() {
initialize();
}
// Initialize the components and configuration of our CreateJListDemo.
private void initialize() {
// Define the window title, size and the default close operation.
this.setTitle("Create JList Demo");
this.setSize(300, 175);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// Create an array of arbitrary objects for the JList to display.
Object[] data = new Object[] {
new Date(), "One", 1, Long.valueOf("12345"), "Four", "Five"
};
// Create an instance of JList and pass data variable as the
// initial content of it. By default the JList does not have a
// scrolling behaviour, so we create a JScrollPane as the container
// for the JList.
JList list = new JList(data);
JScrollPane scrollPane = new JScrollPane(list);
// Add a button to close the program.
JButton button = new JButton("Close");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// Set the panel layout to BorderLayout and place the list on the
// center and the button on the south.
this.setLayout(new BorderLayout(5, 5));
getContentPane().add(scrollPane, BorderLayout.CENTER);
getContentPane().add(button, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CreateJListDemo().setVisible(true);
}
});
}
}
|
kodejava/kodejava.project
|
kodejava-swing/src/main/java/org/kodejava/example/swing/CreateJListDemo.java
|
Java
|
bsd-2-clause
| 1,925 |
๏ปฟ/* Copyright (c) Citrix Systems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System.Collections.Generic;
using XenAdmin.Actions;
using XenAdmin.Core;
using XenAPI;
using XenAdmin.Dialogs;
namespace XenAdmin.Commands
{
/// <summary>
/// Detaches the selected SRs. Shows a confirmation dialog.
/// </summary>
internal class DetachSRCommand : Command
{
/// <summary>
/// Initializes a new instance of this Command. The parameter-less constructor is required in the derived
/// class if it is to be attached to a ToolStrip menu item or button. It should not be used in any other scenario.
/// </summary>
public DetachSRCommand()
{
}
public DetachSRCommand(IMainWindow mainWindow, IEnumerable<SelectedItem> selection)
: base(mainWindow, selection)
{
}
public DetachSRCommand(IMainWindow mainWindow, SR selection)
: base(mainWindow, selection)
{
}
protected override void ExecuteCore(SelectedItemCollection selection)
{
List<AsyncAction> actions = new List<AsyncAction>();
foreach (SR sr in selection.AsXenObjects<SR>(CanExecute))
{
actions.Add(new SrAction(SrActionKind.Detach, sr));
}
RunMultipleActions(actions, Messages.ACTION_SRS_DETACHING, Messages.ACTION_SRS_DETACHING, Messages.ACTION_SRS_DETACH_SUCCESSFUL, true);
}
protected override bool CanExecuteCore(SelectedItemCollection selection)
{
return selection.AllItemsAre<SR>() && selection.AtLeastOneXenObjectCan<SR>(CanExecute);
}
private static bool CanExecute(SR sr)
{
return sr != null && sr.IsDetachable() && !HelpersGUI.GetActionInProgress(sr);
}
public override string MenuText
{
get
{
return Messages.MAINWINDOW_DETACH_SR;
}
}
protected override bool ConfirmationRequired
{
get
{
return true;
}
}
protected override string ConfirmationDialogText
{
get
{
SelectedItemCollection selection = GetSelection();
if (selection.Count == 1)
{
return Messages.MESSAGEBOX_DETACH_SR_CONTINUE;
}
return Messages.MESSAGEBOX_DETACH_SRS_CONTINUE;
}
}
protected override string ConfirmationDialogTitle
{
get
{
if (GetSelection().Count == 1)
{
return Messages.MESSAGEBOX_DETACH_SR_CONTINUE_TITLE;
}
return Messages.MESSAGEBOX_DETACH_SRS_CONTINUE_TITLE;
}
}
protected override CommandErrorDialog GetErrorDialogCore(IDictionary<SelectedItem, string> cantExecuteReasons)
{
return new CommandErrorDialog(Messages.ERROR_DIALOG_DETACH_SR_TITLE, Messages.ERROR_DIALOG_DETACH_SR_TEXT, cantExecuteReasons);
}
protected override string GetCantExecuteReasonCore(SelectedItem item)
{
SR sr = item.XenObject as SR;
if (sr == null)
{
return base.GetCantExecuteReasonCore(item);
}
if (sr.IsDetached)
{
return Messages.SR_DETACHED;
}
if (sr.HasRunningVMs())
{
return Messages.SR_HAS_RUNNING_VMS;
}
if (!sr.CanCreateWithXenCenter)
{
return Messages.SR_CANNOT_BE_DETACHED_WITH_XC;
}
if (HelpersGUI.GetActionInProgress(sr))
{
return Messages.SR_ACTION_IN_PROGRESS;
}
return base.GetCantExecuteReasonCore(item);
}
}
}
|
aftabahmedsajid/XenCenter-Complete-dependencies-
|
XenAdmin/Commands/DetachSRCommand.cs
|
C#
|
bsd-2-clause
| 5,340 |
#ifndef _hk332_15_94_HPP_
#define _hk332_15_94_HPP_
// This is an automatically generated file from gen.py.
#include "common.hpp"
namespace hk332_15_94 {
template <typename Scalar>
void S_Add1(Matrix<Scalar>& S1, Matrix<Scalar>& S2, Matrix<Scalar>& S3, Matrix<Scalar>& C, double x, bool sequential) {
const int strideS1 = S1.stride();
const int strideS2 = S2.stride();
const int strideS3 = S3.stride();
const int strideC = C.stride();
const Scalar *dataS1 = S1.data();
const Scalar *dataS2 = S2.data();
const Scalar *dataS3 = S3.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataS1[i + j * strideS1] -dataS2[i + j * strideS2] + dataS3[i + j * strideS3];
}
}
}
template <typename Scalar>
void S_Add2(Matrix<Scalar>& S1, Matrix<Scalar>& S2, Matrix<Scalar>& S3, Matrix<Scalar>& C, double x, bool sequential) {
const int strideS1 = S1.stride();
const int strideS2 = S2.stride();
const int strideS3 = S3.stride();
const int strideC = C.stride();
const Scalar *dataS1 = S1.data();
const Scalar *dataS2 = S2.data();
const Scalar *dataS3 = S3.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataS1[i + j * strideS1] + dataS2[i + j * strideS2] -dataS3[i + j * strideS3];
}
}
}
template <typename Scalar>
void S_Add3(Matrix<Scalar>& S1, Matrix<Scalar>& S2, Matrix<Scalar>& S3, Matrix<Scalar>& C, double x, bool sequential) {
const int strideS1 = S1.stride();
const int strideS2 = S2.stride();
const int strideS3 = S3.stride();
const int strideC = C.stride();
const Scalar *dataS1 = S1.data();
const Scalar *dataS2 = S2.data();
const Scalar *dataS3 = S3.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = -dataS1[i + j * strideS1] + dataS2[i + j * strideS2] + dataS3[i + j * strideS3];
}
}
}
template <typename Scalar>
void S_Add4(Matrix<Scalar>& S1, Matrix<Scalar>& C, double x, bool sequential) {
const int strideS1 = S1.stride();
const int strideC = C.stride();
const Scalar *dataS1 = S1.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataS1[i + j * strideS1];
}
}
}
template <typename Scalar>
void S_Add5(Matrix<Scalar>& S1, Matrix<Scalar>& S2, Matrix<Scalar>& C, double x, bool sequential) {
const int strideS1 = S1.stride();
const int strideS2 = S2.stride();
const int strideC = C.stride();
const Scalar *dataS1 = S1.data();
const Scalar *dataS2 = S2.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataS1[i + j * strideS1] -dataS2[i + j * strideS2];
}
}
}
template <typename Scalar>
void S_Add6(Matrix<Scalar>& S1, Matrix<Scalar>& C, double x, bool sequential) {
const int strideS1 = S1.stride();
const int strideC = C.stride();
const Scalar *dataS1 = S1.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = -dataS1[i + j * strideS1];
}
}
}
template <typename Scalar>
void S_Add7(Matrix<Scalar>& S1, Matrix<Scalar>& S2, Matrix<Scalar>& S3, Matrix<Scalar>& C, double x, bool sequential) {
const int strideS1 = S1.stride();
const int strideS2 = S2.stride();
const int strideS3 = S3.stride();
const int strideC = C.stride();
const Scalar *dataS1 = S1.data();
const Scalar *dataS2 = S2.data();
const Scalar *dataS3 = S3.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataS1[i + j * strideS1] + dataS2[i + j * strideS2] + dataS3[i + j * strideS3];
}
}
}
template <typename Scalar>
void S_Add8(Matrix<Scalar>& S1, Matrix<Scalar>& S2, Matrix<Scalar>& C, double x, bool sequential) {
const int strideS1 = S1.stride();
const int strideS2 = S2.stride();
const int strideC = C.stride();
const Scalar *dataS1 = S1.data();
const Scalar *dataS2 = S2.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataS1[i + j * strideS1] -dataS2[i + j * strideS2];
}
}
}
template <typename Scalar>
void S_Add9(Matrix<Scalar>& S1, Matrix<Scalar>& S2, Matrix<Scalar>& S3, Matrix<Scalar>& C, double x, bool sequential) {
const int strideS1 = S1.stride();
const int strideS2 = S2.stride();
const int strideS3 = S3.stride();
const int strideC = C.stride();
const Scalar *dataS1 = S1.data();
const Scalar *dataS2 = S2.data();
const Scalar *dataS3 = S3.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataS1[i + j * strideS1] -dataS2[i + j * strideS2] -dataS3[i + j * strideS3];
}
}
}
template <typename Scalar>
void S_Add10(Matrix<Scalar>& S1, Matrix<Scalar>& C, double x, bool sequential) {
const int strideS1 = S1.stride();
const int strideC = C.stride();
const Scalar *dataS1 = S1.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataS1[i + j * strideS1];
}
}
}
template <typename Scalar>
void S_Add11(Matrix<Scalar>& S1, Matrix<Scalar>& C, double x, bool sequential) {
const int strideS1 = S1.stride();
const int strideC = C.stride();
const Scalar *dataS1 = S1.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = -dataS1[i + j * strideS1];
}
}
}
template <typename Scalar>
void S_Add12(Matrix<Scalar>& S1, Matrix<Scalar>& S2, Matrix<Scalar>& S3, Matrix<Scalar>& C, double x, bool sequential) {
const int strideS1 = S1.stride();
const int strideS2 = S2.stride();
const int strideS3 = S3.stride();
const int strideC = C.stride();
const Scalar *dataS1 = S1.data();
const Scalar *dataS2 = S2.data();
const Scalar *dataS3 = S3.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataS1[i + j * strideS1] + dataS2[i + j * strideS2] + dataS3[i + j * strideS3];
}
}
}
template <typename Scalar>
void S_Add13(Matrix<Scalar>& S1, Matrix<Scalar>& C, double x, bool sequential) {
const int strideS1 = S1.stride();
const int strideC = C.stride();
const Scalar *dataS1 = S1.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = -dataS1[i + j * strideS1];
}
}
}
template <typename Scalar>
void S_Add14(Matrix<Scalar>& S1, Matrix<Scalar>& S2, Matrix<Scalar>& C, double x, bool sequential) {
const int strideS1 = S1.stride();
const int strideS2 = S2.stride();
const int strideC = C.stride();
const Scalar *dataS1 = S1.data();
const Scalar *dataS2 = S2.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = -dataS1[i + j * strideS1] + dataS2[i + j * strideS2];
}
}
}
template <typename Scalar>
void S_Add15(Matrix<Scalar>& S1, Matrix<Scalar>& C, double x, bool sequential) {
const int strideS1 = S1.stride();
const int strideC = C.stride();
const Scalar *dataS1 = S1.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataS1[i + j * strideS1];
}
}
}
template <typename Scalar>
void T_Add1(Matrix<Scalar>& T1, Matrix<Scalar>& C, double x, bool sequential) {
const int strideT1 = T1.stride();
const int strideC = C.stride();
const Scalar *dataT1 = T1.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataT1[i + j * strideT1];
}
}
}
template <typename Scalar>
void T_Add2(Matrix<Scalar>& T1, Matrix<Scalar>& T2, Matrix<Scalar>& C, double x, bool sequential) {
const int strideT1 = T1.stride();
const int strideT2 = T2.stride();
const int strideC = C.stride();
const Scalar *dataT1 = T1.data();
const Scalar *dataT2 = T2.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataT1[i + j * strideT1] -dataT2[i + j * strideT2];
}
}
}
template <typename Scalar>
void T_Add3(Matrix<Scalar>& T1, Matrix<Scalar>& C, double x, bool sequential) {
const int strideT1 = T1.stride();
const int strideC = C.stride();
const Scalar *dataT1 = T1.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataT1[i + j * strideT1];
}
}
}
template <typename Scalar>
void T_Add4(Matrix<Scalar>& T1, Matrix<Scalar>& T2, Matrix<Scalar>& C, double x, bool sequential) {
const int strideT1 = T1.stride();
const int strideT2 = T2.stride();
const int strideC = C.stride();
const Scalar *dataT1 = T1.data();
const Scalar *dataT2 = T2.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataT1[i + j * strideT1] + dataT2[i + j * strideT2];
}
}
}
template <typename Scalar>
void T_Add5(Matrix<Scalar>& T1, Matrix<Scalar>& T2, Matrix<Scalar>& C, double x, bool sequential) {
const int strideT1 = T1.stride();
const int strideT2 = T2.stride();
const int strideC = C.stride();
const Scalar *dataT1 = T1.data();
const Scalar *dataT2 = T2.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataT1[i + j * strideT1] + dataT2[i + j * strideT2];
}
}
}
template <typename Scalar>
void T_Add6(Matrix<Scalar>& T1, Matrix<Scalar>& T2, Matrix<Scalar>& C, double x, bool sequential) {
const int strideT1 = T1.stride();
const int strideT2 = T2.stride();
const int strideC = C.stride();
const Scalar *dataT1 = T1.data();
const Scalar *dataT2 = T2.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = -dataT1[i + j * strideT1] + dataT2[i + j * strideT2];
}
}
}
template <typename Scalar>
void T_Add7(Matrix<Scalar>& T1, Matrix<Scalar>& C, double x, bool sequential) {
const int strideT1 = T1.stride();
const int strideC = C.stride();
const Scalar *dataT1 = T1.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataT1[i + j * strideT1];
}
}
}
template <typename Scalar>
void T_Add8(Matrix<Scalar>& T1, Matrix<Scalar>& T2, Matrix<Scalar>& T3, Matrix<Scalar>& C, double x, bool sequential) {
const int strideT1 = T1.stride();
const int strideT2 = T2.stride();
const int strideT3 = T3.stride();
const int strideC = C.stride();
const Scalar *dataT1 = T1.data();
const Scalar *dataT2 = T2.data();
const Scalar *dataT3 = T3.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = -dataT1[i + j * strideT1] + dataT2[i + j * strideT2] + dataT3[i + j * strideT3];
}
}
}
template <typename Scalar>
void T_Add9(Matrix<Scalar>& T1, Matrix<Scalar>& T2, Matrix<Scalar>& C, double x, bool sequential) {
const int strideT1 = T1.stride();
const int strideT2 = T2.stride();
const int strideC = C.stride();
const Scalar *dataT1 = T1.data();
const Scalar *dataT2 = T2.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataT1[i + j * strideT1] -dataT2[i + j * strideT2];
}
}
}
template <typename Scalar>
void T_Add10(Matrix<Scalar>& T1, Matrix<Scalar>& T2, Matrix<Scalar>& C, double x, bool sequential) {
const int strideT1 = T1.stride();
const int strideT2 = T2.stride();
const int strideC = C.stride();
const Scalar *dataT1 = T1.data();
const Scalar *dataT2 = T2.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataT1[i + j * strideT1] + dataT2[i + j * strideT2];
}
}
}
template <typename Scalar>
void T_Add11(Matrix<Scalar>& T1, Matrix<Scalar>& T2, Matrix<Scalar>& C, double x, bool sequential) {
const int strideT1 = T1.stride();
const int strideT2 = T2.stride();
const int strideC = C.stride();
const Scalar *dataT1 = T1.data();
const Scalar *dataT2 = T2.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = -dataT1[i + j * strideT1] + dataT2[i + j * strideT2];
}
}
}
template <typename Scalar>
void T_Add12(Matrix<Scalar>& T1, Matrix<Scalar>& C, double x, bool sequential) {
const int strideT1 = T1.stride();
const int strideC = C.stride();
const Scalar *dataT1 = T1.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataT1[i + j * strideT1];
}
}
}
template <typename Scalar>
void T_Add13(Matrix<Scalar>& T1, Matrix<Scalar>& T2, Matrix<Scalar>& T3, Matrix<Scalar>& T4, Matrix<Scalar>& C, double x, bool sequential) {
const int strideT1 = T1.stride();
const int strideT2 = T2.stride();
const int strideT3 = T3.stride();
const int strideT4 = T4.stride();
const int strideC = C.stride();
const Scalar *dataT1 = T1.data();
const Scalar *dataT2 = T2.data();
const Scalar *dataT3 = T3.data();
const Scalar *dataT4 = T4.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = -dataT1[i + j * strideT1] + dataT2[i + j * strideT2] + dataT3[i + j * strideT3] -dataT4[i + j * strideT4];
}
}
}
template <typename Scalar>
void T_Add14(Matrix<Scalar>& T1, Matrix<Scalar>& T2, Matrix<Scalar>& T3, Matrix<Scalar>& C, double x, bool sequential) {
const int strideT1 = T1.stride();
const int strideT2 = T2.stride();
const int strideT3 = T3.stride();
const int strideC = C.stride();
const Scalar *dataT1 = T1.data();
const Scalar *dataT2 = T2.data();
const Scalar *dataT3 = T3.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataT1[i + j * strideT1] -dataT2[i + j * strideT2] + dataT3[i + j * strideT3];
}
}
}
template <typename Scalar>
void T_Add15(Matrix<Scalar>& T1, Matrix<Scalar>& T2, Matrix<Scalar>& T3, Matrix<Scalar>& T4, Matrix<Scalar>& C, double x, bool sequential) {
const int strideT1 = T1.stride();
const int strideT2 = T2.stride();
const int strideT3 = T3.stride();
const int strideT4 = T4.stride();
const int strideC = C.stride();
const Scalar *dataT1 = T1.data();
const Scalar *dataT2 = T2.data();
const Scalar *dataT3 = T3.data();
const Scalar *dataT4 = T4.data();
Scalar *dataC = C.data();
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = -dataT1[i + j * strideT1] + dataT2[i + j * strideT2] + dataT3[i + j * strideT3] -dataT4[i + j * strideT4];
}
}
}
template <typename Scalar>
void M_Add1(Matrix<Scalar>& M1, Matrix<Scalar>& M2, Matrix<Scalar>& M3, Matrix<Scalar>& M4, Matrix<Scalar>& M5, Matrix<Scalar>& M6, Matrix<Scalar>& C, double x, bool sequential, Scalar beta) {
const int strideM1 = M1.stride();
const int strideM2 = M2.stride();
const int strideM3 = M3.stride();
const int strideM4 = M4.stride();
const int strideM5 = M5.stride();
const int strideM6 = M6.stride();
const int strideC = C.stride();
const Scalar *dataM1 = M1.data();
const Scalar *dataM2 = M2.data();
const Scalar *dataM3 = M3.data();
const Scalar *dataM4 = M4.data();
const Scalar *dataM5 = M5.data();
const Scalar *dataM6 = M6.data();
Scalar *dataC = C.data();
if (beta != Scalar(0.0)) {
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataM1[i + j * strideM1] + dataM2[i + j * strideM2] + dataM3[i + j * strideM3] + dataM4[i + j * strideM4] -dataM5[i + j * strideM5] + dataM6[i + j * strideM6] + beta * dataC[i + j * strideC];
}
}
} else {
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataM1[i + j * strideM1] + dataM2[i + j * strideM2] + dataM3[i + j * strideM3] + dataM4[i + j * strideM4] -dataM5[i + j * strideM5] + dataM6[i + j * strideM6];
}
}
}
}
template <typename Scalar>
void M_Add2(Matrix<Scalar>& M1, Matrix<Scalar>& M2, Matrix<Scalar>& M3, Matrix<Scalar>& M4, Matrix<Scalar>& M5, Matrix<Scalar>& C, double x, bool sequential, Scalar beta) {
const int strideM1 = M1.stride();
const int strideM2 = M2.stride();
const int strideM3 = M3.stride();
const int strideM4 = M4.stride();
const int strideM5 = M5.stride();
const int strideC = C.stride();
const Scalar *dataM1 = M1.data();
const Scalar *dataM2 = M2.data();
const Scalar *dataM3 = M3.data();
const Scalar *dataM4 = M4.data();
const Scalar *dataM5 = M5.data();
Scalar *dataC = C.data();
if (beta != Scalar(0.0)) {
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataM1[i + j * strideM1] -dataM2[i + j * strideM2] + dataM3[i + j * strideM3] + dataM4[i + j * strideM4] -dataM5[i + j * strideM5] + beta * dataC[i + j * strideC];
}
}
} else {
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataM1[i + j * strideM1] -dataM2[i + j * strideM2] + dataM3[i + j * strideM3] + dataM4[i + j * strideM4] -dataM5[i + j * strideM5];
}
}
}
}
template <typename Scalar>
void M_Add3(Matrix<Scalar>& M1, Matrix<Scalar>& M2, Matrix<Scalar>& M3, Matrix<Scalar>& M4, Matrix<Scalar>& M5, Matrix<Scalar>& C, double x, bool sequential, Scalar beta) {
const int strideM1 = M1.stride();
const int strideM2 = M2.stride();
const int strideM3 = M3.stride();
const int strideM4 = M4.stride();
const int strideM5 = M5.stride();
const int strideC = C.stride();
const Scalar *dataM1 = M1.data();
const Scalar *dataM2 = M2.data();
const Scalar *dataM3 = M3.data();
const Scalar *dataM4 = M4.data();
const Scalar *dataM5 = M5.data();
Scalar *dataC = C.data();
if (beta != Scalar(0.0)) {
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataM1[i + j * strideM1] + dataM2[i + j * strideM2] -dataM3[i + j * strideM3] -dataM4[i + j * strideM4] -dataM5[i + j * strideM5] + beta * dataC[i + j * strideC];
}
}
} else {
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataM1[i + j * strideM1] + dataM2[i + j * strideM2] -dataM3[i + j * strideM3] -dataM4[i + j * strideM4] -dataM5[i + j * strideM5];
}
}
}
}
template <typename Scalar>
void M_Add4(Matrix<Scalar>& M1, Matrix<Scalar>& M2, Matrix<Scalar>& M3, Matrix<Scalar>& M4, Matrix<Scalar>& M5, Matrix<Scalar>& M6, Matrix<Scalar>& C, double x, bool sequential, Scalar beta) {
const int strideM1 = M1.stride();
const int strideM2 = M2.stride();
const int strideM3 = M3.stride();
const int strideM4 = M4.stride();
const int strideM5 = M5.stride();
const int strideM6 = M6.stride();
const int strideC = C.stride();
const Scalar *dataM1 = M1.data();
const Scalar *dataM2 = M2.data();
const Scalar *dataM3 = M3.data();
const Scalar *dataM4 = M4.data();
const Scalar *dataM5 = M5.data();
const Scalar *dataM6 = M6.data();
Scalar *dataC = C.data();
if (beta != Scalar(0.0)) {
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataM1[i + j * strideM1] -dataM2[i + j * strideM2] + dataM3[i + j * strideM3] + dataM4[i + j * strideM4] -dataM5[i + j * strideM5] -dataM6[i + j * strideM6] + beta * dataC[i + j * strideC];
}
}
} else {
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataM1[i + j * strideM1] -dataM2[i + j * strideM2] + dataM3[i + j * strideM3] + dataM4[i + j * strideM4] -dataM5[i + j * strideM5] -dataM6[i + j * strideM6];
}
}
}
}
template <typename Scalar>
void M_Add5(Matrix<Scalar>& M1, Matrix<Scalar>& M2, Matrix<Scalar>& M3, Matrix<Scalar>& M4, Matrix<Scalar>& M5, Matrix<Scalar>& C, double x, bool sequential, Scalar beta) {
const int strideM1 = M1.stride();
const int strideM2 = M2.stride();
const int strideM3 = M3.stride();
const int strideM4 = M4.stride();
const int strideM5 = M5.stride();
const int strideC = C.stride();
const Scalar *dataM1 = M1.data();
const Scalar *dataM2 = M2.data();
const Scalar *dataM3 = M3.data();
const Scalar *dataM4 = M4.data();
const Scalar *dataM5 = M5.data();
Scalar *dataC = C.data();
if (beta != Scalar(0.0)) {
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataM1[i + j * strideM1] + dataM2[i + j * strideM2] + dataM3[i + j * strideM3] + dataM4[i + j * strideM4] + dataM5[i + j * strideM5] + beta * dataC[i + j * strideC];
}
}
} else {
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataM1[i + j * strideM1] + dataM2[i + j * strideM2] + dataM3[i + j * strideM3] + dataM4[i + j * strideM4] + dataM5[i + j * strideM5];
}
}
}
}
template <typename Scalar>
void M_Add6(Matrix<Scalar>& M1, Matrix<Scalar>& M2, Matrix<Scalar>& M3, Matrix<Scalar>& M4, Matrix<Scalar>& M5, Matrix<Scalar>& C, double x, bool sequential, Scalar beta) {
const int strideM1 = M1.stride();
const int strideM2 = M2.stride();
const int strideM3 = M3.stride();
const int strideM4 = M4.stride();
const int strideM5 = M5.stride();
const int strideC = C.stride();
const Scalar *dataM1 = M1.data();
const Scalar *dataM2 = M2.data();
const Scalar *dataM3 = M3.data();
const Scalar *dataM4 = M4.data();
const Scalar *dataM5 = M5.data();
Scalar *dataC = C.data();
if (beta != Scalar(0.0)) {
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataM1[i + j * strideM1] -dataM2[i + j * strideM2] + dataM3[i + j * strideM3] + dataM4[i + j * strideM4] + dataM5[i + j * strideM5] + beta * dataC[i + j * strideC];
}
}
} else {
#ifdef _PARALLEL_
# pragma omp parallel for if(!sequential)
#endif
for (int j = 0; j < C.n(); ++j) {
for (int i = 0; i < C.m(); ++i) {
dataC[i + j * strideC] = dataM1[i + j * strideM1] -dataM2[i + j * strideM2] + dataM3[i + j * strideM3] + dataM4[i + j * strideM4] + dataM5[i + j * strideM5];
}
}
}
}
template <typename Scalar>
void FastMatmulRecursive(LockAndCounter& locker, MemoryManager<Scalar>& mem_mngr, Matrix<Scalar>& A, Matrix<Scalar>& B, Matrix<Scalar>& C, int total_steps, int steps_left, int start_index, double x, int num_threads, Scalar beta) {
// Update multipliers
C.UpdateMultiplier(A.multiplier());
C.UpdateMultiplier(B.multiplier());
A.set_multiplier(Scalar(1.0));
B.set_multiplier(Scalar(1.0));
// Base case for recursion
if (steps_left == 0) {
MatMul(A, B, C);
return;
}
Matrix<Scalar> A11 = A.Subblock(3, 3, 1, 1);
Matrix<Scalar> A12 = A.Subblock(3, 3, 1, 2);
Matrix<Scalar> A13 = A.Subblock(3, 3, 1, 3);
Matrix<Scalar> A21 = A.Subblock(3, 3, 2, 1);
Matrix<Scalar> A22 = A.Subblock(3, 3, 2, 2);
Matrix<Scalar> A23 = A.Subblock(3, 3, 2, 3);
Matrix<Scalar> A31 = A.Subblock(3, 3, 3, 1);
Matrix<Scalar> A32 = A.Subblock(3, 3, 3, 2);
Matrix<Scalar> A33 = A.Subblock(3, 3, 3, 3);
Matrix<Scalar> B11 = B.Subblock(3, 2, 1, 1);
Matrix<Scalar> B12 = B.Subblock(3, 2, 1, 2);
Matrix<Scalar> B21 = B.Subblock(3, 2, 2, 1);
Matrix<Scalar> B22 = B.Subblock(3, 2, 2, 2);
Matrix<Scalar> B31 = B.Subblock(3, 2, 3, 1);
Matrix<Scalar> B32 = B.Subblock(3, 2, 3, 2);
Matrix<Scalar> C11 = C.Subblock(3, 2, 1, 1);
Matrix<Scalar> C12 = C.Subblock(3, 2, 1, 2);
Matrix<Scalar> C21 = C.Subblock(3, 2, 2, 1);
Matrix<Scalar> C22 = C.Subblock(3, 2, 2, 2);
Matrix<Scalar> C31 = C.Subblock(3, 2, 3, 1);
Matrix<Scalar> C32 = C.Subblock(3, 2, 3, 2);
// Matrices to store the results of multiplications.
#ifdef _PARALLEL_
Matrix<Scalar> M1(mem_mngr.GetMem(start_index, 1, total_steps - steps_left, M), C11.m(), C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M2(mem_mngr.GetMem(start_index, 2, total_steps - steps_left, M), C11.m(), C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M3(mem_mngr.GetMem(start_index, 3, total_steps - steps_left, M), C11.m(), C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M4(mem_mngr.GetMem(start_index, 4, total_steps - steps_left, M), C11.m(), C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M5(mem_mngr.GetMem(start_index, 5, total_steps - steps_left, M), C11.m(), C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M6(mem_mngr.GetMem(start_index, 6, total_steps - steps_left, M), C11.m(), C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M7(mem_mngr.GetMem(start_index, 7, total_steps - steps_left, M), C11.m(), C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M8(mem_mngr.GetMem(start_index, 8, total_steps - steps_left, M), C11.m(), C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M9(mem_mngr.GetMem(start_index, 9, total_steps - steps_left, M), C11.m(), C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M10(mem_mngr.GetMem(start_index, 10, total_steps - steps_left, M), C11.m(), C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M11(mem_mngr.GetMem(start_index, 11, total_steps - steps_left, M), C11.m(), C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M12(mem_mngr.GetMem(start_index, 12, total_steps - steps_left, M), C11.m(), C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M13(mem_mngr.GetMem(start_index, 13, total_steps - steps_left, M), C11.m(), C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M14(mem_mngr.GetMem(start_index, 14, total_steps - steps_left, M), C11.m(), C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M15(mem_mngr.GetMem(start_index, 15, total_steps - steps_left, M), C11.m(), C11.m(), C11.n(), C.multiplier());
#else
Matrix<Scalar> M1(C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M2(C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M3(C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M4(C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M5(C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M6(C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M7(C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M8(C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M9(C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M10(C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M11(C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M12(C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M13(C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M14(C11.m(), C11.n(), C.multiplier());
Matrix<Scalar> M15(C11.m(), C11.n(), C.multiplier());
#endif
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
bool sequential1 = should_launch_task(15, total_steps, steps_left, start_index, 1, num_threads);
bool sequential2 = should_launch_task(15, total_steps, steps_left, start_index, 2, num_threads);
bool sequential3 = should_launch_task(15, total_steps, steps_left, start_index, 3, num_threads);
bool sequential4 = should_launch_task(15, total_steps, steps_left, start_index, 4, num_threads);
bool sequential5 = should_launch_task(15, total_steps, steps_left, start_index, 5, num_threads);
bool sequential6 = should_launch_task(15, total_steps, steps_left, start_index, 6, num_threads);
bool sequential7 = should_launch_task(15, total_steps, steps_left, start_index, 7, num_threads);
bool sequential8 = should_launch_task(15, total_steps, steps_left, start_index, 8, num_threads);
bool sequential9 = should_launch_task(15, total_steps, steps_left, start_index, 9, num_threads);
bool sequential10 = should_launch_task(15, total_steps, steps_left, start_index, 10, num_threads);
bool sequential11 = should_launch_task(15, total_steps, steps_left, start_index, 11, num_threads);
bool sequential12 = should_launch_task(15, total_steps, steps_left, start_index, 12, num_threads);
bool sequential13 = should_launch_task(15, total_steps, steps_left, start_index, 13, num_threads);
bool sequential14 = should_launch_task(15, total_steps, steps_left, start_index, 14, num_threads);
bool sequential15 = should_launch_task(15, total_steps, steps_left, start_index, 15, num_threads);
#else
bool sequential1 = false;
bool sequential2 = false;
bool sequential3 = false;
bool sequential4 = false;
bool sequential5 = false;
bool sequential6 = false;
bool sequential7 = false;
bool sequential8 = false;
bool sequential9 = false;
bool sequential10 = false;
bool sequential11 = false;
bool sequential12 = false;
bool sequential13 = false;
bool sequential14 = false;
bool sequential15 = false;
#endif
// M1 = (1 * A11 + -1 * A12 + 1 * A31) * (1 * B12)
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
# pragma omp task if(sequential1) shared(mem_mngr, locker) untied
{
#endif
#ifdef _PARALLEL_
Matrix<Scalar> S1(mem_mngr.GetMem(start_index, 1, total_steps - steps_left, S), A11.m(), A11.m(), A11.n());
#else
Matrix<Scalar> S1(A11.m(), A11.n());
#endif
S_Add1(A11, A12, A31, S1, x, sequential1);
M1.UpdateMultiplier(Scalar(1));
FastMatmulRecursive(locker, mem_mngr, S1, B12, M1, total_steps, steps_left - 1, (start_index + 1 - 1) * 15, x, num_threads, Scalar(0.0));
#ifndef _PARALLEL_
S1.deallocate();
#endif
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
locker.Decrement();
}
if (should_task_wait(15, total_steps, steps_left, start_index, 1, num_threads)) {
# pragma omp taskwait
# if defined(_PARALLEL_) && (_PARALLEL_ == _HYBRID_PAR_)
SwitchToDFS(locker, num_threads);
# endif
}
#endif
// M2 = (1 * A11 + 1 * A13 + -1 * A21) * (1 * B11 + -1 * B12)
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
# pragma omp task if(sequential2) shared(mem_mngr, locker) untied
{
#endif
#ifdef _PARALLEL_
Matrix<Scalar> S2(mem_mngr.GetMem(start_index, 2, total_steps - steps_left, S), A11.m(), A11.m(), A11.n());
#else
Matrix<Scalar> S2(A11.m(), A11.n());
#endif
S_Add2(A11, A13, A21, S2, x, sequential2);
#ifdef _PARALLEL_
Matrix<Scalar> T2(mem_mngr.GetMem(start_index, 2, total_steps - steps_left, T), B11.m(), B11.m(), B11.n());
#else
Matrix<Scalar> T2(B11.m(), B11.n());
#endif
T_Add2(B11, B12, T2, x, sequential2);
FastMatmulRecursive(locker, mem_mngr, S2, T2, M2, total_steps, steps_left - 1, (start_index + 2 - 1) * 15, x, num_threads, Scalar(0.0));
#ifndef _PARALLEL_
S2.deallocate();
T2.deallocate();
#endif
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
locker.Decrement();
}
if (should_task_wait(15, total_steps, steps_left, start_index, 2, num_threads)) {
# pragma omp taskwait
# if defined(_PARALLEL_) && (_PARALLEL_ == _HYBRID_PAR_)
SwitchToDFS(locker, num_threads);
# endif
}
#endif
// M3 = (-1 * A21 + 1 * A22 + 1 * A32) * (1 * B21)
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
# pragma omp task if(sequential3) shared(mem_mngr, locker) untied
{
#endif
#ifdef _PARALLEL_
Matrix<Scalar> S3(mem_mngr.GetMem(start_index, 3, total_steps - steps_left, S), A11.m(), A11.m(), A11.n());
#else
Matrix<Scalar> S3(A11.m(), A11.n());
#endif
S_Add3(A21, A22, A32, S3, x, sequential3);
M3.UpdateMultiplier(Scalar(1));
FastMatmulRecursive(locker, mem_mngr, S3, B21, M3, total_steps, steps_left - 1, (start_index + 3 - 1) * 15, x, num_threads, Scalar(0.0));
#ifndef _PARALLEL_
S3.deallocate();
#endif
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
locker.Decrement();
}
if (should_task_wait(15, total_steps, steps_left, start_index, 3, num_threads)) {
# pragma omp taskwait
# if defined(_PARALLEL_) && (_PARALLEL_ == _HYBRID_PAR_)
SwitchToDFS(locker, num_threads);
# endif
}
#endif
// M4 = (1 * A21) * (1 * B11 + 1 * B21)
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
# pragma omp task if(sequential4) shared(mem_mngr, locker) untied
{
#endif
#ifdef _PARALLEL_
Matrix<Scalar> T4(mem_mngr.GetMem(start_index, 4, total_steps - steps_left, T), B11.m(), B11.m(), B11.n());
#else
Matrix<Scalar> T4(B11.m(), B11.n());
#endif
T_Add4(B11, B21, T4, x, sequential4);
M4.UpdateMultiplier(Scalar(1));
FastMatmulRecursive(locker, mem_mngr, A21, T4, M4, total_steps, steps_left - 1, (start_index + 4 - 1) * 15, x, num_threads, Scalar(0.0));
#ifndef _PARALLEL_
T4.deallocate();
#endif
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
locker.Decrement();
}
if (should_task_wait(15, total_steps, steps_left, start_index, 4, num_threads)) {
# pragma omp taskwait
# if defined(_PARALLEL_) && (_PARALLEL_ == _HYBRID_PAR_)
SwitchToDFS(locker, num_threads);
# endif
}
#endif
// M5 = (1 * A12 + -1 * A21) * (1 * B12 + 1 * B21)
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
# pragma omp task if(sequential5) shared(mem_mngr, locker) untied
{
#endif
#ifdef _PARALLEL_
Matrix<Scalar> S5(mem_mngr.GetMem(start_index, 5, total_steps - steps_left, S), A11.m(), A11.m(), A11.n());
#else
Matrix<Scalar> S5(A11.m(), A11.n());
#endif
S_Add5(A12, A21, S5, x, sequential5);
#ifdef _PARALLEL_
Matrix<Scalar> T5(mem_mngr.GetMem(start_index, 5, total_steps - steps_left, T), B11.m(), B11.m(), B11.n());
#else
Matrix<Scalar> T5(B11.m(), B11.n());
#endif
T_Add5(B12, B21, T5, x, sequential5);
FastMatmulRecursive(locker, mem_mngr, S5, T5, M5, total_steps, steps_left - 1, (start_index + 5 - 1) * 15, x, num_threads, Scalar(0.0));
#ifndef _PARALLEL_
S5.deallocate();
T5.deallocate();
#endif
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
locker.Decrement();
}
if (should_task_wait(15, total_steps, steps_left, start_index, 5, num_threads)) {
# pragma omp taskwait
# if defined(_PARALLEL_) && (_PARALLEL_ == _HYBRID_PAR_)
SwitchToDFS(locker, num_threads);
# endif
}
#endif
// M6 = (-1 * A31) * (-1 * B11 + 1 * B31)
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
# pragma omp task if(sequential6) shared(mem_mngr, locker) untied
{
#endif
#ifdef _PARALLEL_
Matrix<Scalar> T6(mem_mngr.GetMem(start_index, 6, total_steps - steps_left, T), B11.m(), B11.m(), B11.n());
#else
Matrix<Scalar> T6(B11.m(), B11.n());
#endif
T_Add6(B11, B31, T6, x, sequential6);
M6.UpdateMultiplier(Scalar(-1));
FastMatmulRecursive(locker, mem_mngr, A31, T6, M6, total_steps, steps_left - 1, (start_index + 6 - 1) * 15, x, num_threads, Scalar(0.0));
#ifndef _PARALLEL_
T6.deallocate();
#endif
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
locker.Decrement();
}
if (should_task_wait(15, total_steps, steps_left, start_index, 6, num_threads)) {
# pragma omp taskwait
# if defined(_PARALLEL_) && (_PARALLEL_ == _HYBRID_PAR_)
SwitchToDFS(locker, num_threads);
# endif
}
#endif
// M7 = (1 * A23 + 1 * A31 + 1 * A33) * (1 * B31)
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
# pragma omp task if(sequential7) shared(mem_mngr, locker) untied
{
#endif
#ifdef _PARALLEL_
Matrix<Scalar> S7(mem_mngr.GetMem(start_index, 7, total_steps - steps_left, S), A11.m(), A11.m(), A11.n());
#else
Matrix<Scalar> S7(A11.m(), A11.n());
#endif
S_Add7(A23, A31, A33, S7, x, sequential7);
M7.UpdateMultiplier(Scalar(1));
FastMatmulRecursive(locker, mem_mngr, S7, B31, M7, total_steps, steps_left - 1, (start_index + 7 - 1) * 15, x, num_threads, Scalar(0.0));
#ifndef _PARALLEL_
S7.deallocate();
#endif
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
locker.Decrement();
}
if (should_task_wait(15, total_steps, steps_left, start_index, 7, num_threads)) {
# pragma omp taskwait
# if defined(_PARALLEL_) && (_PARALLEL_ == _HYBRID_PAR_)
SwitchToDFS(locker, num_threads);
# endif
}
#endif
// M8 = (1 * A13 + -1 * A31) * (-1 * B11 + 1 * B12 + 1 * B31)
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
# pragma omp task if(sequential8) shared(mem_mngr, locker) untied
{
#endif
#ifdef _PARALLEL_
Matrix<Scalar> S8(mem_mngr.GetMem(start_index, 8, total_steps - steps_left, S), A11.m(), A11.m(), A11.n());
#else
Matrix<Scalar> S8(A11.m(), A11.n());
#endif
S_Add8(A13, A31, S8, x, sequential8);
#ifdef _PARALLEL_
Matrix<Scalar> T8(mem_mngr.GetMem(start_index, 8, total_steps - steps_left, T), B11.m(), B11.m(), B11.n());
#else
Matrix<Scalar> T8(B11.m(), B11.n());
#endif
T_Add8(B11, B12, B31, T8, x, sequential8);
FastMatmulRecursive(locker, mem_mngr, S8, T8, M8, total_steps, steps_left - 1, (start_index + 8 - 1) * 15, x, num_threads, Scalar(0.0));
#ifndef _PARALLEL_
S8.deallocate();
T8.deallocate();
#endif
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
locker.Decrement();
}
if (should_task_wait(15, total_steps, steps_left, start_index, 8, num_threads)) {
# pragma omp taskwait
# if defined(_PARALLEL_) && (_PARALLEL_ == _HYBRID_PAR_)
SwitchToDFS(locker, num_threads);
# endif
}
#endif
// M9 = (1 * A12 + -1 * A22 + -1 * A23) * (1 * B21 + -1 * B22)
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
# pragma omp task if(sequential9) shared(mem_mngr, locker) untied
{
#endif
#ifdef _PARALLEL_
Matrix<Scalar> S9(mem_mngr.GetMem(start_index, 9, total_steps - steps_left, S), A11.m(), A11.m(), A11.n());
#else
Matrix<Scalar> S9(A11.m(), A11.n());
#endif
S_Add9(A12, A22, A23, S9, x, sequential9);
#ifdef _PARALLEL_
Matrix<Scalar> T9(mem_mngr.GetMem(start_index, 9, total_steps - steps_left, T), B11.m(), B11.m(), B11.n());
#else
Matrix<Scalar> T9(B11.m(), B11.n());
#endif
T_Add9(B21, B22, T9, x, sequential9);
FastMatmulRecursive(locker, mem_mngr, S9, T9, M9, total_steps, steps_left - 1, (start_index + 9 - 1) * 15, x, num_threads, Scalar(0.0));
#ifndef _PARALLEL_
S9.deallocate();
T9.deallocate();
#endif
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
locker.Decrement();
}
if (should_task_wait(15, total_steps, steps_left, start_index, 9, num_threads)) {
# pragma omp taskwait
# if defined(_PARALLEL_) && (_PARALLEL_ == _HYBRID_PAR_)
SwitchToDFS(locker, num_threads);
# endif
}
#endif
// M10 = (1 * A12) * (1 * B12 + 1 * B22)
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
# pragma omp task if(sequential10) shared(mem_mngr, locker) untied
{
#endif
#ifdef _PARALLEL_
Matrix<Scalar> T10(mem_mngr.GetMem(start_index, 10, total_steps - steps_left, T), B11.m(), B11.m(), B11.n());
#else
Matrix<Scalar> T10(B11.m(), B11.n());
#endif
T_Add10(B12, B22, T10, x, sequential10);
M10.UpdateMultiplier(Scalar(1));
FastMatmulRecursive(locker, mem_mngr, A12, T10, M10, total_steps, steps_left - 1, (start_index + 10 - 1) * 15, x, num_threads, Scalar(0.0));
#ifndef _PARALLEL_
T10.deallocate();
#endif
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
locker.Decrement();
}
if (should_task_wait(15, total_steps, steps_left, start_index, 10, num_threads)) {
# pragma omp taskwait
# if defined(_PARALLEL_) && (_PARALLEL_ == _HYBRID_PAR_)
SwitchToDFS(locker, num_threads);
# endif
}
#endif
// M11 = (-1 * A32) * (-1 * B22 + 1 * B32)
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
# pragma omp task if(sequential11) shared(mem_mngr, locker) untied
{
#endif
#ifdef _PARALLEL_
Matrix<Scalar> T11(mem_mngr.GetMem(start_index, 11, total_steps - steps_left, T), B11.m(), B11.m(), B11.n());
#else
Matrix<Scalar> T11(B11.m(), B11.n());
#endif
T_Add11(B22, B32, T11, x, sequential11);
M11.UpdateMultiplier(Scalar(-1));
FastMatmulRecursive(locker, mem_mngr, A32, T11, M11, total_steps, steps_left - 1, (start_index + 11 - 1) * 15, x, num_threads, Scalar(0.0));
#ifndef _PARALLEL_
T11.deallocate();
#endif
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
locker.Decrement();
}
if (should_task_wait(15, total_steps, steps_left, start_index, 11, num_threads)) {
# pragma omp taskwait
# if defined(_PARALLEL_) && (_PARALLEL_ == _HYBRID_PAR_)
SwitchToDFS(locker, num_threads);
# endif
}
#endif
// M12 = (1 * A13 + 1 * A32 + 1 * A33) * (1 * B32)
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
# pragma omp task if(sequential12) shared(mem_mngr, locker) untied
{
#endif
#ifdef _PARALLEL_
Matrix<Scalar> S12(mem_mngr.GetMem(start_index, 12, total_steps - steps_left, S), A11.m(), A11.m(), A11.n());
#else
Matrix<Scalar> S12(A11.m(), A11.n());
#endif
S_Add12(A13, A32, A33, S12, x, sequential12);
M12.UpdateMultiplier(Scalar(1));
FastMatmulRecursive(locker, mem_mngr, S12, B32, M12, total_steps, steps_left - 1, (start_index + 12 - 1) * 15, x, num_threads, Scalar(0.0));
#ifndef _PARALLEL_
S12.deallocate();
#endif
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
locker.Decrement();
}
if (should_task_wait(15, total_steps, steps_left, start_index, 12, num_threads)) {
# pragma omp taskwait
# if defined(_PARALLEL_) && (_PARALLEL_ == _HYBRID_PAR_)
SwitchToDFS(locker, num_threads);
# endif
}
#endif
// M13 = (-1 * A23) * (-1 * B21 + 1 * B22 + 1 * B31 + -1 * B32)
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
# pragma omp task if(sequential13) shared(mem_mngr, locker) untied
{
#endif
#ifdef _PARALLEL_
Matrix<Scalar> T13(mem_mngr.GetMem(start_index, 13, total_steps - steps_left, T), B11.m(), B11.m(), B11.n());
#else
Matrix<Scalar> T13(B11.m(), B11.n());
#endif
T_Add13(B21, B22, B31, B32, T13, x, sequential13);
M13.UpdateMultiplier(Scalar(-1));
FastMatmulRecursive(locker, mem_mngr, A23, T13, M13, total_steps, steps_left - 1, (start_index + 13 - 1) * 15, x, num_threads, Scalar(0.0));
#ifndef _PARALLEL_
T13.deallocate();
#endif
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
locker.Decrement();
}
if (should_task_wait(15, total_steps, steps_left, start_index, 13, num_threads)) {
# pragma omp taskwait
# if defined(_PARALLEL_) && (_PARALLEL_ == _HYBRID_PAR_)
SwitchToDFS(locker, num_threads);
# endif
}
#endif
// M14 = (-1 * A23 + 1 * A32) * (1 * B21 + -1 * B22 + 1 * B32)
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
# pragma omp task if(sequential14) shared(mem_mngr, locker) untied
{
#endif
#ifdef _PARALLEL_
Matrix<Scalar> S14(mem_mngr.GetMem(start_index, 14, total_steps - steps_left, S), A11.m(), A11.m(), A11.n());
#else
Matrix<Scalar> S14(A11.m(), A11.n());
#endif
S_Add14(A23, A32, S14, x, sequential14);
#ifdef _PARALLEL_
Matrix<Scalar> T14(mem_mngr.GetMem(start_index, 14, total_steps - steps_left, T), B11.m(), B11.m(), B11.n());
#else
Matrix<Scalar> T14(B11.m(), B11.n());
#endif
T_Add14(B21, B22, B32, T14, x, sequential14);
FastMatmulRecursive(locker, mem_mngr, S14, T14, M14, total_steps, steps_left - 1, (start_index + 14 - 1) * 15, x, num_threads, Scalar(0.0));
#ifndef _PARALLEL_
S14.deallocate();
T14.deallocate();
#endif
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
locker.Decrement();
}
if (should_task_wait(15, total_steps, steps_left, start_index, 14, num_threads)) {
# pragma omp taskwait
# if defined(_PARALLEL_) && (_PARALLEL_ == _HYBRID_PAR_)
SwitchToDFS(locker, num_threads);
# endif
}
#endif
// M15 = (1 * A13) * (-1 * B11 + 1 * B12 + 1 * B31 + -1 * B32)
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
# pragma omp task if(sequential15) shared(mem_mngr, locker) untied
{
#endif
#ifdef _PARALLEL_
Matrix<Scalar> T15(mem_mngr.GetMem(start_index, 15, total_steps - steps_left, T), B11.m(), B11.m(), B11.n());
#else
Matrix<Scalar> T15(B11.m(), B11.n());
#endif
T_Add15(B11, B12, B31, B32, T15, x, sequential15);
M15.UpdateMultiplier(Scalar(1));
FastMatmulRecursive(locker, mem_mngr, A13, T15, M15, total_steps, steps_left - 1, (start_index + 15 - 1) * 15, x, num_threads, Scalar(0.0));
#ifndef _PARALLEL_
T15.deallocate();
#endif
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
locker.Decrement();
}
if (should_task_wait(15, total_steps, steps_left, start_index, 15, num_threads)) {
# pragma omp taskwait
}
#endif
M_Add1(M1, M2, M4, M5, M6, M8, C11, x, false, beta);
M_Add2(M1, M6, M8, M10, M15, C12, x, false, beta);
M_Add3(M3, M4, M11, M13, M14, C21, x, false, beta);
M_Add4(M3, M5, M9, M10, M11, M14, C22, x, false, beta);
M_Add5(M6, M7, M11, M13, M14, C31, x, false, beta);
M_Add6(M6, M8, M11, M12, M15, C32, x, false, beta);
// Handle edge cases with dynamic peeling
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_ || _PARALLEL_ == _HYBRID_PAR_)
if (total_steps == steps_left) {
mkl_set_num_threads_local(num_threads);
mkl_set_dynamic(0);
}
#endif
DynamicPeeling(A, B, C, 3, 3, 2, beta);
}
// C := alpha * A * B + beta * C
template <typename Scalar>
double FastMatmul(Matrix<Scalar>& A, Matrix<Scalar>& B, Matrix<Scalar>& C,
int num_steps, double x=1e-8, Scalar alpha=Scalar(1.0), Scalar beta=Scalar(0.0)) {
MemoryManager<Scalar> mem_mngr;
#ifdef _PARALLEL_
mem_mngr.Allocate(3, 3, 2, 15, num_steps, A.m(), A.n(), B.n());
#endif
A.set_multiplier(alpha);
int num_multiplies_per_step = 15;
int total_multiplies = pow(num_multiplies_per_step, num_steps);
// Set parameters needed for all types of parallelism.
int num_threads = 0;
#ifdef _PARALLEL_
# pragma omp parallel
{
if (omp_get_thread_num() == 0) { num_threads = omp_get_num_threads(); }
}
omp_set_nested(1);
#endif
#if defined(_PARALLEL_) && (_PARALLEL_ == _BFS_PAR_)
# pragma omp parallel
{
mkl_set_num_threads_local(1);
mkl_set_dynamic(0);
}
#endif
#if defined(_PARALLEL_) && (_PARALLEL_ == _DFS_PAR_)
mkl_set_dynamic(0);
#endif
#if defined(_PARALLEL_) && (_PARALLEL_ == _HYBRID_PAR_)
if (num_threads > total_multiplies) {
mkl_set_dynamic(0);
} else {
# pragma omp parallel
{
mkl_set_num_threads_local(1);
mkl_set_dynamic(0);
}
}
#endif
LockAndCounter locker(total_multiplies - (total_multiplies % num_threads));
using FpMilliseconds = std::chrono::duration<float, std::chrono::milliseconds::period>;
auto t1 = std::chrono::high_resolution_clock::now();
#ifdef _PARALLEL_
# pragma omp parallel
{
# pragma omp single
#endif
FastMatmulRecursive(locker, mem_mngr, A, B, C, num_steps, num_steps, 0, x, num_threads, beta);
#ifdef _PARALLEL_
}
#endif
auto t2 = std::chrono::high_resolution_clock::now();
return FpMilliseconds(t2 - t1).count();
}
} // namespace hk332_15_94
#endif // _hk332_15_94_HPP_
|
arbenson/fast-matmul
|
algorithms/hk332_15_94.hpp
|
C++
|
bsd-2-clause
| 52,540 |
export default function extendType<T>(value: T) {
return <TExtra>() => value as T & TExtra;
}
|
ashmind/SharpLab
|
source/WebApp/ts/helpers/extend-type.ts
|
TypeScript
|
bsd-2-clause
| 99 |
class PhpCsFixer < Formula
desc "Tool to automatically fix PHP coding standards issues"
homepage "https://cs.symfony.com/"
url "https://github.com/FriendsOfPHP/PHP-CS-Fixer/releases/download/v3.3.2/php-cs-fixer.phar"
sha256 "8a7cb6fcbf916f01d4b423b7850b4401bc687275011b6f437322679a4fc4613f"
license "MIT"
revision 1
bottle do
sha256 cellar: :any_skip_relocation, all: "1c7ae560f6187651f5517778dc71c6e3be71fd4cf50bf49c2091bf7f3f6811d2"
end
depends_on "[email protected]"
def install
libexec.install "php-cs-fixer.phar"
(bin/"php-cs-fixer").write <<~EOS
#!#{Formula["[email protected]"].opt_bin}/php
<?php require '#{libexec}/php-cs-fixer.phar';
EOS
end
test do
(testpath/"test.php").write <<~EOS
<?php $this->foo( 'homebrew rox' );
EOS
(testpath/"correct_test.php").write <<~EOS
<?php
$this->foo('homebrew rox');
EOS
system "#{bin}/php-cs-fixer", "fix", "test.php"
assert compare_file("test.php", "correct_test.php")
end
end
|
makigumo/homebrew-core
|
Formula/php-cs-fixer.rb
|
Ruby
|
bsd-2-clause
| 1,011 |
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2021 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwo/core/util/factory.h>
namespace inviwo {
FactoryBase::FactoryBase() = default;
FactoryBase::~FactoryBase() = default;
} // namespace inviwo
|
inviwo/inviwo
|
src/core/util/factory.cpp
|
C++
|
bsd-2-clause
| 1,740 |
package com.pineone.icbms.sda.kb.context.routine;
public class ICBMSPersonalContext extends ICBMSContext{
}
|
iotoasis/SDA
|
src/main/java/com/pineone/icbms/sda/kb/context/routine/ICBMSPersonalContext.java
|
Java
|
bsd-2-clause
| 116 |
# -*- coding: utf-8 -*-
"""Handles the instrospection of REST Framework Views and ViewSets."""
import inspect
import itertools
import re
import yaml
import importlib
from .compat import OrderedDict, strip_tags, get_pagination_attribures
from abc import ABCMeta, abstractmethod
from django.http import HttpRequest
from django.contrib.admindocs.utils import trim_docstring
from django.utils.encoding import smart_text
import rest_framework
from rest_framework import viewsets, filters
from rest_framework.request import Request
from rest_framework.compat import apply_markdown
try:
from rest_framework.fields import CurrentUserDefault
except ImportError:
# FIXME once we drop support of DRF 2.x .
CurrentUserDefault = None
from rest_framework.utils import formatting
from rest_framework.serializers import BaseSerializer
from django.utils import six
try:
import django_filters
except ImportError:
django_filters = None
def get_view_description(view_cls, html=False, docstring=None):
if docstring is not None:
view_cls = type(
view_cls.__name__ + '_fake',
(view_cls,),
{'__doc__': docstring})
return rest_framework.settings.api_settings \
.VIEW_DESCRIPTION_FUNCTION(view_cls, html)
def get_default_value(field):
default_value = getattr(field, 'default', None)
if rest_framework.VERSION >= '3.0.0':
from rest_framework.fields import empty
if default_value == empty:
default_value = None
if callable(default_value):
if CurrentUserDefault is not None and isinstance(default_value,
CurrentUserDefault):
default_value.user = None
default_value = default_value()
return default_value
class IntrospectorHelper(object):
__metaclass__ = ABCMeta
@staticmethod
def strip_yaml_from_docstring(docstring):
"""
Strips YAML from the docstring.
"""
split_lines = trim_docstring(docstring).split('\n')
cut_off = None
for index in range(len(split_lines) - 1, -1, -1):
line = split_lines[index]
line = line.strip()
if line == '---':
cut_off = index
break
if cut_off is not None:
split_lines = split_lines[0:cut_off]
return "\n".join(split_lines)
@staticmethod
def strip_params_from_docstring(docstring):
"""
Strips the params from the docstring (ie. myparam -- Some param) will
not be removed from the text body
"""
params_pattern = re.compile(r' -- ')
split_lines = trim_docstring(docstring).split('\n')
cut_off = None
for index, line in enumerate(split_lines):
line = line.strip()
if params_pattern.search(line):
cut_off = index
break
if cut_off is not None:
split_lines = split_lines[0:cut_off]
return "\n".join(split_lines)
@staticmethod
def get_serializer_name(serializer):
if serializer is None:
return None
if rest_framework.VERSION >= '3.0.0':
from rest_framework.serializers import ListSerializer
assert serializer != ListSerializer, "uh oh, what now?"
if isinstance(serializer, ListSerializer):
serializer = serializer.child
if inspect.isclass(serializer):
return serializer.__name__
return serializer.__class__.__name__
@staticmethod
def get_summary(callback, docstring=None):
"""
Returns the first sentence of the first line of the class docstring
"""
description = get_view_description(
callback, html=False, docstring=docstring) \
.split("\n")[0].split(".")[0]
description = IntrospectorHelper.strip_yaml_from_docstring(
description)
description = IntrospectorHelper.strip_params_from_docstring(
description)
description = strip_tags(get_view_description(
callback, html=True, docstring=description))
return description
class BaseViewIntrospector(object):
__metaclass__ = ABCMeta
def __init__(self, callback, path, pattern, user):
self.callback = callback
self.path = path
self.pattern = pattern
self.user = user
def get_yaml_parser(self):
parser = YAMLDocstringParser(self)
return parser
@abstractmethod
def __iter__(self):
pass
def get_iterator(self):
return self.__iter__()
def get_description(self):
"""
Returns the first sentence of the first line of the class docstring
"""
return IntrospectorHelper.get_summary(self.callback)
def get_docs(self):
return get_view_description(self.callback)
class BaseMethodIntrospector(object):
__metaclass__ = ABCMeta
ENUMS = [
'choice',
'multiple choice',
]
PRIMITIVES = {
'integer': ['int32', 'int64'],
'number': ['float', 'double'],
'string': ['string', 'byte', 'date', 'date-time'],
'boolean': ['boolean'],
}
def __init__(self, view_introspector, method):
self.method = method
self.parent = view_introspector
self.callback = view_introspector.callback
self.path = view_introspector.path
self.user = view_introspector.user
@property
def is_array_response(self):
""" Support definition of array responses with the 'many' attr """
return self.get_yaml_parser().object.get('many')
def get_module(self):
return self.callback.__module__
def check_yaml_methods(self, yaml_methods):
missing_set = set()
for key in yaml_methods:
if key not in self.parent.methods():
missing_set.add(key)
if missing_set:
raise Exception(
"methods %s in class docstring are not in view methods %s"
% (list(missing_set), list(self.parent.methods())))
def get_yaml_parser(self):
parser = YAMLDocstringParser(self)
parent_parser = YAMLDocstringParser(self.parent)
self.check_yaml_methods(parent_parser.object.keys())
new_object = {}
new_object.update(parent_parser.object.get(self.method, {}))
new_object.update(parser.object)
parser.object = new_object
return parser
def get_extra_serializer_classes(self):
return self.get_yaml_parser().get_extra_serializer_classes(
self.callback)
def ask_for_serializer_class(self, is_get_response=False):
if hasattr(self.callback, 'get_serializer_class'):
view = self.create_view()
parser = self.get_yaml_parser()
mock_view = parser.get_view_mocker(self.callback)
view = mock_view(view)
if view is not None:
if parser.should_omit_serializer():
return None
if '{' in self.path:
lookup_url_kwarg = view.lookup_url_kwarg or view.lookup_field
view.kwargs[lookup_url_kwarg] = ''
view._docs_gen = True
if is_get_response and hasattr(view, 'get_serializer_class_response'):
ret = view.get_serializer_class_response()
if ret is not None:
return ret
try:
serializer_class = view.get_serializer_class()
except AssertionError as e:
if "should either include a `serializer_class` attribute, or override the `get_serializer_class()` method." in str(e): # noqa
serializer_class = None
else:
raise
return serializer_class
def create_view(self):
view = self.callback()
if not hasattr(view, 'kwargs'):
view.kwargs = dict()
if hasattr(self.parent.pattern, 'default_args'):
view.kwargs.update(self.parent.pattern.default_args)
request_django = HttpRequest()
request_django.user = self.user
request_django.method = self.method
view.request = Request(request_django)
return view
def get_serializer_class(self, is_get_response=False):
parser = self.get_yaml_parser()
serializer = parser.get_serializer_class(self.callback)
if serializer is None:
serializer = self.ask_for_serializer_class(is_get_response=is_get_response)
if is_get_response and self.get_http_method() in ['DELETE']:
serializer = None
return serializer
def get_response_serializer_class(self):
parser = self.get_yaml_parser()
serializer = parser.get_response_serializer_class(self.callback)
if serializer is None:
serializer = self.get_serializer_class(is_get_response=True)
return serializer
def get_request_serializer_class(self):
parser = self.get_yaml_parser()
serializer = parser.get_request_serializer_class(self.callback)
if serializer is None:
serializer = self.get_serializer_class()
return serializer
def get_summary(self):
# If there is no docstring on the method, get class docs
return IntrospectorHelper.get_summary(
self.callback,
self.get_docs() or self.parent.get_description())
def get_nickname(self):
""" Returns the APIView's nickname """
return rest_framework.settings.api_settings \
.VIEW_NAME_FUNCTION(self.callback, self.method).replace(' ', '_')
def get_notes(self):
"""
Returns the body of the docstring trimmed before any parameters are
listed. First, get the class docstring and then get the method's. The
methods will always inherit the class comments.
"""
docstring = ""
class_docs = get_view_description(self.callback)
class_docs = IntrospectorHelper.strip_yaml_from_docstring(class_docs)
class_docs = IntrospectorHelper.strip_params_from_docstring(class_docs)
method_docs = self.get_docs()
if class_docs is not None:
docstring += class_docs + " \n"
if method_docs is not None:
method_docs = formatting.dedent(smart_text(method_docs))
method_docs = IntrospectorHelper.strip_yaml_from_docstring(
method_docs
)
method_docs = IntrospectorHelper.strip_params_from_docstring(
method_docs
)
docstring += '\n' + method_docs
docstring = docstring.strip()
return do_markdown(docstring)
def get_parameters(self):
"""
Returns parameters for an API. Parameters are a combination of HTTP
query parameters as well as HTTP body parameters that are defined by
the DRF serializer fields
"""
params = []
path_params = self.build_path_parameters()
body_params = self.build_body_parameters()
form_params = self.build_form_parameters()
query_params = self.build_query_parameters()
if django_filters is not None:
if self.method == 'list':
query_params.extend(
self.build_query_parameters_from_django_filters())
query_params.extend(
self.build_query_parameters_from_drf_search_filter())
if path_params:
params += path_params
if self.get_http_method() not in ["GET", "DELETE", "HEAD"]:
params += form_params
if not form_params and body_params is not None:
params.append(body_params)
if query_params:
params += query_params
return params
def get_http_method(self):
return self.method
@abstractmethod
def get_docs(self):
return ''
def retrieve_docstring(self):
"""
Attempts to fetch the docs for a class method. Returns None
if the method does not exist
"""
method = str(self.method).lower()
if not hasattr(self.callback, method):
return None
return get_view_description(getattr(self.callback, method))
def build_body_parameters(self):
parser = self.get_yaml_parser()
if parser.should_omit_serializer():
return
serializer = self.get_request_serializer_class()
serializer_name = IntrospectorHelper.get_serializer_name(serializer)
if serializer_name is None:
return
return {
'name': serializer_name,
'type': serializer_name,
'paramType': 'body',
}
def build_path_parameters(self):
"""
Gets the parameters from the URL
"""
url_params = re.findall('/{([^}]*)}', self.path)
params = []
for param in url_params:
params.append({
'name': param,
'type': 'string',
'paramType': 'path',
'required': True
})
return params
def build_query_parameters(self):
params = []
docstring = self.retrieve_docstring() or ''
docstring += "\n" + get_view_description(self.callback)
if docstring is None:
return params
split_lines = docstring.split('\n')
for line in split_lines:
param = line.split(' -- ')
if len(param) == 2:
params.append({'paramType': 'query',
'name': param[0].strip(),
'description': param[1].strip(),
'type': 'string'})
return params
def build_query_parameters_from_django_filters(self):
"""
introspect ``django_filters.FilterSet`` instances.
"""
params = []
filter_class = getattr(self.callback, 'filter_class', None)
if (filter_class is not None and
issubclass(filter_class, django_filters.FilterSet)):
descriptions = getattr(filter_class.Meta, 'descriptions', {})
for name, filter_ in filter_class.base_filters.items():
data_type = 'string'
parameter = {
'paramType': 'query',
'name': name,
'description': descriptions.get(name, filter_.label),
'defaultValue': '',
"required": False,
}
normalize_data_format(data_type, None, parameter)
multiple_choices = filter_.extra.get('choices', {})
if isinstance(filter_, django_filters.BooleanFilter):
# should we use boolean type here instead?
multiple_choices = zip(["True", "False"], ["True", "False"])
if multiple_choices:
parameter['enum'] = [choice[0] for choice
in itertools.chain(multiple_choices)]
if isinstance(filter_, django_filters.MultipleChoiceFilter):
parameter['allowMultiple'] = True
if parameter['description'] is None:
del parameter['description']
params.append(parameter)
return params
def build_query_parameters_from_drf_search_filter(self):
params = []
filter_backends = getattr(self.callback, 'filter_backends', [])
def issubclass_safe(klass, classinfo):
try:
return issubclass(klass, classinfo)
except TypeError:
return False
for search_filter in [x for x in filter_backends if issubclass_safe(x, filters.SearchFilter)]:
search_filter_instance = search_filter()
search_fields_name = getattr(search_filter_instance, 'search_fields_name', None) or 'search_fields'
search_fields = getattr(self.callback, search_fields_name, [])
description = "Search the %s." % (", ".join(search_fields))
parameter = {
'paramType': 'query',
'name': search_filter_instance.search_param,
'allowMultiple': True,
'description': description,
'type': 'string',
'required': False,
}
params.append(parameter)
return params
def build_form_parameters(self):
"""
Builds form parameters from the serializer class
"""
parser = self.get_yaml_parser()
if parser.should_omit_serializer():
return
data = []
serializer = self.get_request_serializer_class()
if serializer is None:
return data
fields = serializer().get_fields()
for name, field in fields.items():
if getattr(field, 'read_only', False):
continue
data_type, data_format = get_data_type(field, is_form=True) or ('string', 'string')
if data_type == 'hidden':
continue
# guess format
# data_format = 'string'
# if data_type in self.PRIMITIVES:
# data_format = self.PRIMITIVES.get(data_type)[0]
choices = []
if data_type in BaseMethodIntrospector.ENUMS:
if isinstance(field.choices, list):
choices = [k for k, v in field.choices]
elif isinstance(field.choices, dict):
choices = [k for k, v in field.choices.items()]
if choices:
# guest data type and format
data_type, data_format = get_primitive_type(choices[0]) or ('string', 'string')
# Support for complex types
if isinstance(field, BaseSerializer):
field_serializer = IntrospectorHelper.get_serializer_name(field)
field_serializer = "Write{}".format(field_serializer)
data_type = field_serializer
data_format = None
f = {
'paramType': 'form',
'name': name,
'description': getattr(field, 'help_text', '') or '',
'type': data_type,
'format': data_format,
'required': getattr(field, 'required', False),
'defaultValue': get_default_value(field),
}
# Swagger type is a primitive, format is more specific
if f['type'] == f['format']:
f['format'] = None
if f['format'] is None:
del f['format']
# defaultValue of null is not allowed, it is specific to type
if f['defaultValue'] is None:
del f['defaultValue']
# Min/Max values
max_value = getattr(field, 'max_value', None)
min_value = getattr(field, 'min_value', None)
if max_value is not None and data_type == 'integer':
f['minimum'] = min_value
if max_value is not None and data_type == 'integer':
f['maximum'] = max_value
# ENUM options
if choices:
f['enum'] = choices
# Format is not allowed for enums
f.pop('format', None)
f['type'] = 'string'
data.append(f)
return data
def get_primitive_type(var):
if isinstance(var, bool):
return 'boolean', 'boolean'
elif isinstance(var, int):
return 'integer', 'int32'
elif isinstance(var, float):
return 'number', 'float'
elif isinstance(var, six.string_types):
return 'string', 'string'
else:
return 'string', 'string' # 'default'
def get_data_type(field, is_form=False):
# (in swagger 2.0 we might get to use the descriptive types..
from rest_framework import fields
if isinstance(field, fields.BooleanField):
return 'boolean', 'boolean'
elif hasattr(fields, 'NullBooleanField') and isinstance(field, fields.NullBooleanField):
return 'boolean', 'boolean'
# elif isinstance(field, fields.URLField):
# return 'string', 'string' # 'url'
# elif isinstance(field, fields.SlugField):
# return 'string', 'string', # 'slug'
elif isinstance(field, fields.ChoiceField):
return 'choice', 'choice' # We deal with this invalid value elsewhere
# elif isinstance(field, fields.EmailField):
# return 'string', 'string' # 'email'
# elif isinstance(field, fields.RegexField):
# return 'string', 'string' # 'regex'
elif isinstance(field, fields.DateField):
return 'string', 'date'
elif isinstance(field, fields.DateTimeField):
return 'string', 'date-time' # 'datetime'
# elif isinstance(field, fields.TimeField):
# return 'string', 'string' # 'time'
elif isinstance(field, fields.IntegerField):
return 'integer', 'int64' # 'integer'
elif isinstance(field, fields.FloatField):
return 'number', 'float' # 'float'
# elif isinstance(field, fields.DecimalField):
# return 'string', 'string' #'decimal'
elif isinstance(field, fields.ImageField):
if is_form:
return 'File', None
return 'string', 'string' # 'image upload'
elif isinstance(field, fields.FileField):
if is_form:
return 'File', None
return 'string', 'string' # 'file upload'
# elif isinstance(field, fields.CharField):
# return 'string', 'string'
elif rest_framework.VERSION >= '3.0.0':
if isinstance(field, fields.HiddenField):
return 'hidden', 'hidden'
elif isinstance(field, fields.ListField):
return 'array', 'array'
else:
return 'string', 'string'
else:
return 'string', 'string'
class APIViewIntrospector(BaseViewIntrospector):
def __iter__(self):
for method in self.methods():
yield APIViewMethodIntrospector(self, method)
def methods(self):
return self.callback().allowed_methods
class WrappedAPIViewIntrospector(BaseViewIntrospector):
def __iter__(self):
for method in self.methods():
yield WrappedAPIViewMethodIntrospector(self, method)
def methods(self):
return self.callback().allowed_methods
def get_notes(self):
class_docs = get_view_description(self.callback)
class_docs = IntrospectorHelper.strip_yaml_from_docstring(
class_docs)
class_docs = IntrospectorHelper.strip_params_from_docstring(
class_docs)
return get_view_description(
self.callback, html=True, docstring=class_docs)
def do_markdown(docstring):
# Markdown is optional
if apply_markdown:
return apply_markdown(docstring)
else:
return docstring.replace("\n\n", "<br/>")
class APIViewMethodIntrospector(BaseMethodIntrospector):
def get_docs(self):
"""
Attempts to retrieve method specific docs for an
endpoint. If none are available, the class docstring
will be used
"""
return self.retrieve_docstring()
class WrappedAPIViewMethodIntrospector(BaseMethodIntrospector):
def get_docs(self):
"""
Attempts to retrieve method specific docs for an
endpoint. If none are available, the class docstring
will be used
"""
return get_view_description(self.callback)
def get_module(self):
from rest_framework_swagger.decorators import wrapper_to_func
func = wrapper_to_func(self.callback)
return func.__module__
def get_notes(self):
return self.parent.get_notes()
def get_yaml_parser(self):
parser = YAMLDocstringParser(self)
return parser
class ViewSetIntrospector(BaseViewIntrospector):
"""Handle ViewSet introspection."""
def __init__(self, callback, path, pattern, user, patterns=None):
super(ViewSetIntrospector, self).__init__(callback, path, pattern, user)
if not issubclass(callback, viewsets.ViewSetMixin):
raise Exception("wrong callback passed to ViewSetIntrospector")
self.patterns = patterns or [pattern]
def __iter__(self):
methods = self._resolve_methods()
for method in methods:
yield ViewSetMethodIntrospector(self, methods[method], method)
def methods(self):
stuff = []
for pattern in self.patterns:
if pattern.callback:
stuff.extend(self._resolve_methods(pattern).values())
return stuff
def _resolve_methods(self, pattern=None):
from .decorators import closure_n_code, get_closure_var
if pattern is None:
pattern = self.pattern
callback = pattern.callback
try:
x = closure_n_code(callback)
while getattr(x.code, 'co_name') != 'view':
# lets unwrap!
callback = get_closure_var(callback)
x = closure_n_code(callback)
freevars = x.code.co_freevars
except (AttributeError, IndexError):
raise RuntimeError(
'Unable to use callback invalid closure/function ' +
'specified.')
else:
return x.closure[freevars.index('actions')].cell_contents
class ViewSetMethodIntrospector(BaseMethodIntrospector):
def __init__(self, view_introspector, method, http_method):
super(ViewSetMethodIntrospector, self) \
.__init__(view_introspector, method)
self.http_method = http_method.upper()
@property
def is_array_response(self):
""" ViewSet.list methods always return array responses """
return (self.method == 'list' or
super(ViewSetMethodIntrospector, self).is_array_response)
def get_http_method(self):
return self.http_method
def get_docs(self):
"""
Attempts to retrieve method specific docs for an
endpoint. If none are available, the class docstring
will be used
"""
return self.retrieve_docstring()
def create_view(self):
view = super(ViewSetMethodIntrospector, self).create_view()
if not hasattr(view, 'action'):
setattr(view, 'action', self.method)
view.request._request.method = self.http_method
return view
def build_query_parameters(self):
parameters = super(ViewSetMethodIntrospector, self) \
.build_query_parameters()
view = self.create_view()
page_size, page_query_param, page_size_query_param = get_pagination_attribures(view)
if self.method == 'list' and page_size:
data_type = 'integer'
if page_query_param:
parameters.append({
'paramType': 'query',
'name': page_query_param,
})
normalize_data_format(data_type, None, parameters[-1])
if page_size_query_param:
parameters.append({
'paramType': 'query',
'name': page_size_query_param,
})
normalize_data_format(data_type, None, parameters[-1])
return parameters
def multi_getattr(obj, attr, default=None):
"""
Get a named attribute from an object; multi_getattr(x, 'a.b.c.d') is
equivalent to x.a.b.c.d. When a default argument is given, it is
returned when any attribute in the chain doesn't exist; without
it, an exception is raised when a missing attribute is encountered.
"""
attributes = attr.split(".")
for i in attributes:
try:
obj = getattr(obj, i)
except AttributeError:
if default:
return default
else:
raise
return obj
def normalize_data_format(data_type, data_format, obj):
"""
sets 'type' on obj
sets a valid 'format' on obj if appropriate
uses data_format only if valid
"""
if data_type == 'array':
data_format = None
flatten_primitives = [
val for sublist in BaseMethodIntrospector.PRIMITIVES.values()
for val in sublist
]
if data_format not in flatten_primitives:
formats = BaseMethodIntrospector.PRIMITIVES.get(data_type, None)
if formats:
data_format = formats[0]
else:
data_format = None
if data_format == data_type:
data_format = None
obj['type'] = data_type
if data_format is None and 'format' in obj:
del obj['format']
elif data_format is not None:
obj['format'] = data_format
class YAMLDocstringParser(object):
"""
Docstring parser powered by YAML syntax
This parser allows you override some parts of automatic method inspection
behaviours which are not always correct.
See the following documents for more information about YAML and Swagger:
- https://github.com/wordnik/swagger-core/wiki
- http://www.yaml.org/spec/1.2/spec.html
- https://github.com/wordnik/swagger-codegen/wiki/Creating-Swagger-JSON-from-YAML-files
1. Control over parameters
============================================================================
Define parameters and its properties in docstrings:
parameters:
- name: some_param
description: Foobar long description goes here
required: true
type: integer
paramType: form
minimum: 10
maximum: 100
- name: other_foo
paramType: query
- name: avatar
type: file
It is possible to override parameters discovered by method inspector by
defining:
`parameters_strategy` option to either `merge` or `replace`
To define different strategies for different `paramType`'s use the
following syntax:
parameters_strategy:
form: replace
query: merge
By default strategy is set to `merge`
Sometimes method inspector produces wrong list of parameters that
you might not won't to see in SWAGGER form. To handle this situation
define `paramTypes` that should be omitted
omit_parameters:
- form
2. Control over serializers
============================================================================
Once in a while you are using different serializers inside methods
but automatic method inspector cannot detect this. For that purpose there
is two explicit parameters that allows you to discard serializer detected
by method inspector OR replace it with another one
serializer: some.package.FooSerializer
omit_serializer: true
3. Custom Response Class
============================================================================
If your view is not using serializer at all but instead outputs simple
data type such as JSON you may define custom response object in method
signature like follows:
type:
name:
required: true
type: string
url:
required: false
type: url
4. Response Messages (Error Codes)
============================================================================
If you'd like to share common response errors that your APIView might throw
you can define them in docstring using following format:
responseMessages:
- code: 401
message: Not authenticated
- code: 403
message: Insufficient rights to call this procedure
5. Different models for reading and writing operations
============================================================================
Since REST Framework won't output write_only fields in responses as well as
does not require read_only fields to be provided it is worth to
automatically register 2 separate models for reading and writing operations.
Discovered serializer will be registered with `Write` or `Read` prefix.
Response Class will be automatically adjusted if serializer class was
detected by method inspector.
You can also refer to this models in your parameters:
parameters:
- name: CigarSerializer
type: WriteCigarSerializer
paramType: body
SAMPLE DOCSTRING:
============================================================================
---
# API Docs
# Note: YAML always starts with `---`
type:
name:
required: true
type: string
url:
required: false
type: url
created_at:
required: true
type: string
format: date-time
serializer: .serializers.FooSerializer
omit_serializer: false
parameters_strategy: merge
omit_parameters:
- path
parameters:
- name: name
description: Foobar long description goes here
required: true
type: string
paramType: form
- name: other_foo
paramType: query
- name: other_bar
paramType: query
- name: avatar
type: file
responseMessages:
- code: 401
message: Not authenticated
"""
PARAM_TYPES = ['header', 'path', 'form', 'body', 'query']
yaml_error = None
def __init__(self, method_introspector):
self.method_introspector = method_introspector
self.object = self.load_obj_from_docstring(
docstring=self.method_introspector.get_docs())
if self.object is None:
self.object = {}
def load_obj_from_docstring(self, docstring):
"""Loads YAML from docstring"""
split_lines = trim_docstring(docstring).split('\n')
# Cut YAML from rest of docstring
for index, line in enumerate(split_lines):
line = line.strip()
if line.startswith('---'):
cut_from = index
break
else:
return None
yaml_string = "\n".join(split_lines[cut_from:])
yaml_string = formatting.dedent(yaml_string)
try:
return yaml.load(yaml_string)
except yaml.YAMLError as e:
raise
self.yaml_error = e
return None
def _load_class(self, cls_path, callback):
"""
Dynamically load a class from a string
"""
if not cls_path or not callback or not hasattr(callback, '__module__'):
return None
package = None
if '.' not in cls_path:
# within current module/file
class_name = cls_path
module_path = self.method_introspector.get_module()
else:
# relative or fully qualified path import
class_name = cls_path.split('.')[-1]
module_path = ".".join(cls_path.split('.')[:-1])
if cls_path.startswith('.'):
# relative lookup against current package
# ..serializers.FooSerializer
package = self.method_introspector.get_module()
class_obj = None
# Try to perform local or relative/fq import
try:
module = importlib.import_module(module_path, package=package)
class_obj = getattr(module, class_name, None)
except ImportError:
pass
# Class was not found, maybe it was imported to callback module?
# from app.serializers import submodule
# serializer: submodule.FooSerializer
if class_obj is None:
try:
module = importlib.import_module(
self.method_introspector.get_module())
class_obj = multi_getattr(module, cls_path, None)
except (ImportError, AttributeError):
raise Exception("Could not find %s, looked in %s" % (cls_path, module))
return class_obj
def get_serializer_class(self, callback):
"""
Retrieves serializer class from YAML object
"""
serializer = self.object.get('serializer', None)
try:
return self._load_class(serializer, callback)
except (ImportError, ValueError):
pass
return None
def get_extra_serializer_classes(self, callback):
"""
Retrieves serializer classes from pytype YAML objects
"""
parameters = self.object.get('parameters', [])
serializers = []
for parameter in parameters:
serializer = parameter.get('pytype', None)
if serializer is not None:
try:
serializer = self._load_class(serializer, callback)
serializers.append(serializer)
except (ImportError, ValueError):
pass
return serializers
def get_request_serializer_class(self, callback):
"""
Retrieves request serializer class from YAML object
"""
serializer = self.object.get('request_serializer', None)
try:
return self._load_class(serializer, callback)
except (ImportError, ValueError):
pass
return None
def get_response_serializer_class(self, callback):
"""
Retrieves response serializer class from YAML object
"""
serializer = self.object.get('response_serializer', None)
if isinstance(serializer, list):
serializer = serializer[0]
try:
return self._load_class(serializer, callback)
except (ImportError, ValueError):
pass
return None
def get_response_type(self):
"""
Docstring may define custom response class
"""
return self.object.get('type', None)
def get_consumes(self):
"""
Retrieves media type supported as input
"""
return self.object.get('consumes', [])
def get_produces(self):
"""
Retrieves media type supported as output
"""
return self.object.get('produces', [])
def get_response_messages(self):
"""
Retrieves response error codes from YAML object
"""
messages = []
response_messages = self.object.get('responseMessages', [])
for message in response_messages:
entry = {
'code': message.get('code', None),
'message': message.get('message', None),
'responseModel': message.get('responseModel', None),
}
# responseModel of null is not allowed
if entry['responseModel'] is None:
del entry['responseModel']
messages.append(entry)
return messages
def get_view_mocker(self, callback):
view_mocker = self.object.get('view_mocker', lambda a: a)
if isinstance(view_mocker, six.string_types):
view_mocker = self._load_class(view_mocker, callback)
return view_mocker
def get_parameters(self, callback):
"""
Retrieves parameters from YAML object
"""
params = []
fields = self.object.get('parameters', [])
for field in fields:
param_type = field.get('paramType', None)
if param_type not in self.PARAM_TYPES:
param_type = 'form'
# Data Type & Format
# See:
# https://github.com/wordnik/swagger-core/wiki/1.2-transition#wiki-additions-2
# https://github.com/wordnik/swagger-core/wiki/Parameters
data_type = field.get('type', 'string')
pytype = field.get('pytype', None)
if pytype is not None:
try:
serializer = self._load_class(pytype, callback)
data_type = IntrospectorHelper.get_serializer_name(
serializer)
except (ImportError, ValueError):
pass
if param_type in ['path', 'query', 'header']:
if data_type not in BaseMethodIntrospector.PRIMITIVES:
data_type = 'string'
# Data Format
data_format = field.get('format', None)
f = {
'paramType': param_type,
'name': field.get('name', None),
'description': field.get('description', ''),
'required': field.get('required', False),
}
normalize_data_format(data_type, data_format, f)
if field.get('defaultValue', None) is not None:
f['defaultValue'] = field.get('defaultValue', None)
# Swagger type is a primitive, format is more specific
if 'format' in f and f['type'] == f['format']:
f['format'] = None
# description of null is not allowed
if f['description'] is None:
del f['description']
if 'format' in f and f['format'] is None:
del f['format']
# Allow Multiple Values &f=1,2,3,4
if field.get('allowMultiple'):
f['allowMultiple'] = True
if f['type'] == 'array':
items = field.get('items', {})
elt_data_type = items.get('type', 'string')
elt_data_format = items.get('type', 'format')
f['items'] = {
}
normalize_data_format(elt_data_type, elt_data_format, f['items'])
uniqueItems = field.get('uniqueItems', None)
if uniqueItems is not None:
f['uniqueItems'] = uniqueItems
# Min/Max are optional
if 'minimum' in field and data_type == 'integer':
f['minimum'] = str(field.get('minimum', 0))
if 'maximum' in field and data_type == 'integer':
f['maximum'] = str(field.get('maximum', 0))
# enum options
enum = field.get('enum', [])
if enum:
f['enum'] = enum
# File support
if f['type'] == 'file':
f['paramType'] = 'body'
params.append(f)
return params
def discover_parameters(self, inspector):
"""
Applies parameters strategy for parameters discovered
from method and docstring
"""
parameters = []
docstring_params = self.get_parameters(inspector.callback)
method_params = inspector.get_parameters()
# paramType may differ, overwrite first
# so strategy can be applied
for meth_param in method_params:
for doc_param in docstring_params:
if doc_param['name'] == meth_param['name']:
if 'paramType' in doc_param:
meth_param['paramType'] = doc_param['paramType']
for param_type in self.PARAM_TYPES:
if self.should_omit_parameters(param_type):
continue
parameters += self._apply_strategy(
param_type, method_params, docstring_params
)
# PATCH requests expects all fields except path fields to be optional
if inspector.get_http_method() == "PATCH":
for param in parameters:
if param['paramType'] != 'path':
param['required'] = False
return parameters
def should_omit_parameters(self, param_type):
"""
Checks if particular parameter types should be omitted explicitly
"""
return param_type in self.object.get('omit_parameters', [])
def should_omit_serializer(self):
"""
Checks if serializer should be intentionally omitted
"""
return self.object.get('omit_serializer', False)
def _apply_strategy(self, param_type, method_params, docstring_params):
"""
Applies strategy for subset of parameters filtered by `paramType`
"""
strategy = self.get_parameters_strategy(param_type=param_type)
method_params = self._filter_params(
params=method_params,
key='paramType',
val=param_type
)
docstring_params = self._filter_params(
params=docstring_params,
key='paramType',
val=param_type
)
if strategy == 'replace':
return docstring_params or method_params
elif strategy == 'merge':
return self._merge_params(
method_params,
docstring_params,
key='name',
)
return []
@staticmethod
def _filter_params(params, key, val):
"""
Returns filter function for parameters structure
"""
def filter_by(o):
return o.get(key, None) == val
return filter(filter_by, params)
@staticmethod
def _merge_params(params1, params2, key):
"""
Helper method.
Merges parameters lists by key
"""
import itertools
merged = OrderedDict()
for item in itertools.chain(params1, params2):
merged[item[key]] = item
return [val for (_, val) in merged.items()]
def get_parameters_strategy(self, param_type=None):
"""
Get behaviour strategy for parameter types.
It can be either `merge` or `replace`:
- `merge` overwrites duplicate parameters signatures
discovered by inspector with the ones defined explicitly in
docstring
- `replace` strategy completely overwrites parameters discovered
by inspector with the ones defined explicitly in docstring.
Note: Strategy can be defined per `paramType` so `path` parameters can
use `merge` strategy while `form` parameters will use `replace`
strategy.
Default strategy: `merge`
"""
default = 'merge'
strategy = self.object.get('parameters_strategy', default)
if hasattr(strategy, 'get') and param_type is not None:
strategy = strategy.get(param_type, default)
if strategy not in ['merge', 'replace']:
strategy = default
return strategy
|
cancan101/django-rest-swagger
|
rest_framework_swagger/introspectors.py
|
Python
|
bsd-2-clause
| 46,711 |
/*
* Copyright (c) 2014, Roberto Capuano <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package debug.gui.command;
import javax.swing.*;
import java.io.File;
import java.awt.event.*;
import agents.*;
import debug.gate.GateManager;
import debug.exec.Reply;
import debug.bridge.BridgeException;
import debug.model.classobject.*;
import debug.gui.event.*;
import tools.*;
public class NewClassCommand extends AbstractAction implements DebugOff, GUIListener
{
protected GateManager gateMgr;
protected String fqcn;
public NewClassCommand( GateManager _gateMgr )
{
super( " New Class " );
gateMgr = _gateMgr;
fqcn = null;
}
//// inter-gui communication :)
public void selected( Object selection )
{
if (selection==null)
{
return;
}
else
if (selection instanceof String)
{
fqcn = (String) selection;
DC.log( LEVEL, fqcn );
}
}
////
public void actionPerformed( ActionEvent e)
{
if ( ((e.getModifiers()&ActionEvent.ALT_MASK) != 0) || fqcn==null)
{
String class_s = JOptionPane.showInputDialog("Insert fqcn:", fqcn);
if (class_s==null) return;
fqcn = class_s;
}
if (fqcn!=null)
{
Runnable r = new Runnable()
{
public void run()
{
try
{
NewClass new_class = new NewClass( fqcn );
Reply reply = gateMgr.cross( new_class );
DC.log( LEVEL, reply );
}
catch( BridgeException be )
{
DC.log( be );
}
}
};
new Thread( r ).start();
}
}
}
|
robertocapuano/jink
|
jink/src/main/java/debug/gui/command/NewClassCommand.java
|
Java
|
bsd-2-clause
| 2,793 |
package com.hunterdavis.jsongamelistmanager.tasks;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.hunterdavis.jsongamelistmanager.JsonGameListActivity;
import com.hunterdavis.jsongamelistmanager.types.DuckDuckGo;
import com.hunterdavis.jsongamelistmanager.types.JsonGameList;
import com.hunterdavis.jsongamelistmanager.types.Youtube;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;
import org.w3c.dom.Text;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.net.URLEncoder;
/**
* Created by hunter on 3/29/15.
*/
public class DuckDuckGoTask extends AsyncTask<String, Void, DuckDuckGo> {
private final WeakReference imageViewReference;
private final WeakReference textViewReference;
private String tag;
private Context context;
public DuckDuckGoTask(Context context, ImageView imageView, TextView textview, String tag) {
imageViewReference = new WeakReference(imageView);
textViewReference = new WeakReference(textview);
this.tag = tag;
this.context = context;
}
@Override
// Actual download method, run in the task thread
protected DuckDuckGo doInBackground(String... params) {
// params comes from the execute() call: params[0] is the url.
return getDuckDuckGoInfo();
}
@Override
// Once the image is downloaded, associates it to the imageView
protected void onPostExecute(final DuckDuckGo duckDuckInfo) {
if(isCancelled()) {
return;
}
if(!TextUtils.isEmpty(duckDuckInfo.Image)) {
if (imageViewReference != null) {
ImageView imageView = (ImageView) imageViewReference.get();
if (imageView != null) {
if (imageView.getTag() == tag) {
imageView.setVisibility(View.VISIBLE);
Picasso.with(context)
.load(duckDuckInfo.Image)
.into(imageView);
}
}
}
}
if(textViewReference != null) {
TextView textView = (TextView) textViewReference.get();
if(textView != null) {
if(TextUtils.isEmpty(duckDuckInfo.Abstract)) {
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}else {
String ogText = textView.getText().toString();
String textForTextView = ogText + "\n(Results from DuckDuckGo)\n";
textForTextView += duckDuckInfo.Abstract;
textView.setText(textForTextView);
textView.setVisibility(View.VISIBLE);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!TextUtils.isEmpty(duckDuckInfo.AbstractURL)) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(duckDuckInfo.AbstractURL));
context.startActivity(browserIntent);
}
}
});
}
}
}
}
public DuckDuckGo getDuckDuckGoInfo() {
try {
String prefix = "http://api.duckduckgo.com/?q=";
String suffix = "&format=json&t=jsongamelistmanagerandroid";
String fullUrl = prefix + URLEncoder.encode(tag, "UTF-8") + suffix;
URL url = new URL(fullUrl);
Request request = new Request.Builder()
.url(url)
.build();
Response response = JsonGameListActivity.client.newCall(request).execute();
InputStream input = response.body().byteStream();
JsonReader reader = new JsonReader(new InputStreamReader(input, "UTF-8"));
Gson gson = new Gson();
DuckDuckGo duck = gson.fromJson(reader, DuckDuckGo.class);
return duck;
} catch (Exception e) {
return new DuckDuckGo();
}
}
}
|
huntergdavis/json_game_list
|
JsonGameList/app/src/main/java/com/hunterdavis/jsongamelistmanager/tasks/DuckDuckGoTask.java
|
Java
|
bsd-2-clause
| 4,792 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>NuoDataSet.AddLinkedObject</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
</head>
<body bgcolor="#ffffff">
<table border="0" width="100%" bgcolor="#F0F0FF">
<tr>
<td>Concept Framework 2.2 documentation</td>
<td align="right"><a href="index.html">Contents</a> | <a href="index_fun.html">Index</a></td>
</tr>
</table>
<h2><a href="NuoDataSet.html">NuoDataSet</a>.AddLinkedObject</h2>
<table border="0" cellspacing="0" cellpadding="0" width="500" style="border-style:solid;border-width:1px;border-color:#D0D0D0;">
<tr bgcolor="#f0f0f0">
<td><i>Name</i></td>
<td><i>Type</i></td>
<td><i>Access</i></td>
<td><i>Version</i></td>
<td><i>Deprecated</i></td>
</tr>
<tr bgcolor="#fafafa">
<td><b>AddLinkedObject</b></td>
<td>function</td>
<td>public</td>
<td>version 2</td>
<td>no</td>
</tr>
</table>
<br />
<b>Prototype:</b><br />
<table bgcolor="#F0F0F0" width="100%" style="border-style:solid;border-width:1px;border-color:#D0D0D0;"><tr><td><b>public function AddLinkedObject(Object)</b></td></tr></table>
<br />
<b>Parameters:</b><br />
<table bgcolor="#FFFFFF" style="border-style:solid;border-width:1px;border-color:#D0D0D0;">
<tr>
<td>
<i>Object</i>
</td>
<td>
// TO DO
</td>
</tr>
</table>
<br />
<b>Description:</b><br />
<table width="100%" bgcolor="#FAFAFF" style="border-style:solid;border-width:1px;border-color:#D0D0D0;">
<tr><td>
TODO: Document this
</td></tr>
</table>
<br />
<b>Returns:</b><br />
// TO DO
<br />
<br />
<!--
<p>
<a href="http://validator.w3.org/check?uri=referer"><img
src="http://www.w3.org/Icons/valid-html40"
alt="Valid HTML 4.0 Transitional" height="31" width="88" border="0"></a>
<a href="http://jigsaw.w3.org/css-validator/">
<img style="border:0;width:88px;height:31px"
src="http://jigsaw.w3.org/css-validator/images/vcss"
alt="Valid CSS!" border="0"/>
</a>
</p>
-->
<table bgcolor="#F0F0F0" width="100%"><tr><td>Documented by Devronium Autodocumenter Alpha, generation time: Sun Jan 27 18:15:36 2013
GMT</td><td align="right">(c)2013 <a href="http://www.devronium.com">Devronium Applications</a></td></tr></table>
</body>
</html>
|
Devronium/ConceptApplicationServer
|
core/server/Samples/CIDE/Help/NuoDataSet.AddLinkedObject.html
|
HTML
|
bsd-2-clause
| 2,517 |
//
// BEInAppPurchaser.h
//
// Copyright (c) 2015 Bracing Effect, LLC. See LICENSE for details.
//
#import <StoreKit/StoreKit.h>
UIKIT_EXTERN NSString *const BEInAppPurchaserProductPurchasedNotification;
UIKIT_EXTERN NSString *const BEInAppPurchaserParsnipPro;
typedef void (^ProductCompletion)(SKProduct *product, NSError *error);
typedef void (^SuccessCompletion)(BOOL success);
@interface BEInAppPurchaser : NSObject
+ (BEInAppPurchaser *)parsnipPurchaser;
- (id)initWithProductIdentifiers:(NSSet *)productIdentifiers;
- (void)purchaseProduct:(SKProduct *)product;
- (BOOL)isProductPurchased:(NSString *)productIdentifier;
- (void)checkForProduct:(NSString *)productIdentifier completion:(SuccessCompletion)completion;
- (void)restoreCompletedTransactions;
@end
|
BracingEffect/Parsnip
|
Parsnip/Source/Parsnip/BEInAppPurchaser.h
|
C
|
bsd-2-clause
| 777 |
//ๅฅๅบทๆกฃๆก ๆฃ่
ไฟกๆฏ
define(['app'], function (app) {
function controllerInit(param){
app.controller('CheckModuleViewController', ['$scope', '$http', 'Ajax', '$compile', '$location', '$controller', '$rootScope', '$timeout',
function ($scope, $http, Ajax, $compile, $location, $controller, $rootScope, $timeout) {
var scope = $rootScope.$new();
alert(11);
$http.get('views/checkModule.html?version='+SYSTEM_VERSION).then(function (res) {
var dialog = angular.element(res.data);
var controller = $controller('CheckViewController', {
$scope: scope,
$element: dialog
}, true, 1);
$timeout(function () {
$compile(dialog)(scope);
param.dom.append(dialog);
});
});
}]);
app.controller('CheckViewController', ['$scope', 'Ajax', '$location', '$controller', '$rootScope',
function ($scope, Ajax, $location, $controller) {
$scope.clockObj = function(){
alert(98);
}
}]);
}
return {
controllerInit : controllerInit
}
});
|
oGZo/zjgsu-abroadStu-web
|
build/scripts/controllers/CheckModuleViewController.js
|
JavaScript
|
bsd-2-clause
| 1,313 |
# User Resource
Users can connect through Web GUI and use API(s).
## Example Usage
Creating a User:
```
resource "solidserver_user" "myFirstUser" {
login = "jsmith"
password = "a_very_c0mpl3x_P@ssw0rd"
description = "My Very First User Resource"
last_name = "Smith"
first_name = "John"
email = "[email protected]"
groups = [ "${solidserver_usergroup.grp_admin.name}" ]
}
```
## Argument Reference
* `login` - (Required) The login of the user
* `password` - (Required) The password of the user
* `groups` - (Required) A list of groups the user belongs to
* `description` - The description of the user
* `last_name` - The last name of the user
* `first_name` - The first name of the user
* `email` - The email address of the user
|
alexissavin/terraform-provider-solidserver
|
docs/resources/user.md
|
Markdown
|
bsd-2-clause
| 759 |
from spfeeds import app
app.run(debug=True)
|
Juanlu001/scipy-feeds
|
run.py
|
Python
|
bsd-2-clause
| 44 |
var React = require('react');
var Promo = require('../components/ios-promo.js')
module.exports = {
render: function () {
$('.ios-promo-container').each(function (idx, element) {
React.render(<Promo/>, element);
});
}
}
|
AllMyChanges/allmychanges.com
|
allmychanges/static/allmychanges/js/views/ios-promo.js
|
JavaScript
|
bsd-2-clause
| 256 |
class Gflags < Formula
desc "Library for processing command-line flags"
homepage "https://gflags.github.io/gflags/"
url "https://github.com/gflags/gflags/archive/v2.2.1.tar.gz"
sha256 "ae27cdbcd6a2f935baa78e4f21f675649271634c092b1be01469440495609d0e"
bottle do
cellar :any
sha256 "a00d8dd8f4674384e722f0f07b0eaeaac201c0fcea789e6fe3232686993dc747" => :mojave
sha256 "db36aa60a2c383dddad4774a0e0129c5cf2183f6ae813afffa9b0311ed81d8a3" => :high_sierra
sha256 "519562ecebe66cf89803786d0b0ba9ac02cfa2376c822c8726fa274c1e380d0a" => :sierra
sha256 "9e9c1a067b324ccd372ac00cd0ac00545415cb4407ea90b15c181cbfb67a4260" => :el_capitan
sha256 "5e6fcff184b2d6caf333a74cb24222da11bc1721eb6ab12a31bda7802cf8dfd9" => :yosemite
end
option "with-debug", "Build debug version"
option "with-static", "Build gflags as a static (instead of shared) library."
depends_on "cmake" => :build
def install
args = std_cmake_args
if build.with? "static"
args << "-DBUILD_SHARED_LIBS=OFF"
else
args << "-DBUILD_SHARED_LIBS=ON"
end
mkdir "buildroot" do
system "cmake", "..", *args
system "make", "install"
end
end
test do
(testpath/"test.cpp").write <<~EOS
#include <iostream>
#include "gflags/gflags.h"
DEFINE_bool(verbose, false, "Display program name before message");
DEFINE_string(message, "Hello world!", "Message to print");
static bool IsNonEmptyMessage(const char *flagname, const std::string &value)
{
return value[0] != '\0';
}
DEFINE_validator(message, &IsNonEmptyMessage);
int main(int argc, char *argv[])
{
gflags::SetUsageMessage("some usage message");
gflags::SetVersionString("1.0.0");
gflags::ParseCommandLineFlags(&argc, &argv, true);
if (FLAGS_verbose) std::cout << gflags::ProgramInvocationShortName() << ": ";
std::cout << FLAGS_message;
gflags::ShutDownCommandLineFlags();
return 0;
}
EOS
system ENV.cxx, "-L#{lib}", "-lgflags", "test.cpp", "-o", "test"
assert_match "Hello world!", shell_output("./test")
assert_match "Foo bar!", shell_output("./test --message='Foo bar!'")
end
end
|
DomT4/homebrew-core
|
Formula/gflags.rb
|
Ruby
|
bsd-2-clause
| 2,227 |
<?php
namespace PageWeb\Model;
use Illuminate\Database\Eloquent\Model;
/**
* @author Laju Morrison <[email protected]>
*/
class SiteEvent extends Model
{
protected $table = 'sites_events';
protected $fillable = [
'id',
'site_id',
'title',
'start_time',
'end_time',
'description',
'photo'
];
public $timestamps = false;
/**
* @return mixed
*/
public function getId()
{
return $this->getKey();
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function site()
{
return $this->belongsTo('PageWeb\Model\Site', 'site_id', 'id');
}
}
|
asm-products/pageweb
|
app/library/Model/SiteEvent.php
|
PHP
|
bsd-2-clause
| 706 |
#ifndef FILENAME_H
#define FILENAME_H
#include <windows.h>
#include "File.h" // for isExist
class FileName {
TCHAR mFileName[MAX_PATH+1];
public:
FileName() { mFileName[0]='\0'; }
FileName(const char* iFileName) { assert(strlen(iFileName)<=MAX_PATH); strcpy(mFileName, iFileName); }
FileName& operator=(const char* iFileName) { assert(strlen(iFileName)<=MAX_PATH); strcpy(mFileName, iFileName); return *this; }
bool operator==(const char* iFileName) { assert(strlen(iFileName)<=MAX_PATH); return strcmp(mFileName, iFileName)==0; }
bool operator!=(const char* iFileName) { assert(strlen(iFileName)<=MAX_PATH); return strcmp(mFileName, iFileName)!=0; }
operator char*() { return mFileName; }
operator [](int n) { return mFileName[n]; }
const char* c_str() { return mFileName; }
bool isValid() { return mFileName[0] != '\0'; }
bool isExist() { return ::isExist(mFileName); }
};
#endif // FILENAME_H
|
yagi/satori
|
_/FileName.h
|
C
|
bsd-2-clause
| 932 |
๏ปฟusing System;
using System.Collections.Generic;
using System.Management.Automation;
using PSPlus.Windows.Diagnostics.EventTracing;
namespace PSPlus.Modules.Windows.Diagnostics.EventTracing
{
[Cmdlet(VerbsCommon.Watch, "EtwEvents")]
public class WatchEtwEventsCmdlet : Cmdlet
{
#region Parameters
[Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)]
public EventWatcherOptions[] WatcherOptions { get; set; }
[Parameter(ValueFromPipelineByPropertyName = true, Mandatory = false)]
public ScriptBlock AfterWatchStarted { get; set; }
#endregion
#region Member variables
private List<EventWatcherOptions> _allWatcherOptions = new List<EventWatcherOptions>();
#endregion
protected override void ProcessRecord()
{
if (WatcherOptions.Length == 0)
{
throw new PSArgumentException("No watcher options is specified.");
}
_allWatcherOptions.AddRange(WatcherOptions);
}
protected override void EndProcessing()
{
using (EventWatcherManager watcherManager = new EventWatcherManager(AfterWatchStarted))
{
foreach (var watcherOptions in _allWatcherOptions)
{
watcherManager.AddWatcher(watcherOptions);
}
Console.CancelKeyPress += (sender, e) =>
{
watcherManager.RequestStop();
};
watcherManager.RunAllWatchersAndProcessCallbacks();
}
}
}
}
|
r12f/PSPlus
|
PSPlus.Modules/PSPlus.Modules.Windows/Diagnostics/EventTracing/WatchETWEventsCmdlet.cs
|
C#
|
bsd-2-clause
| 1,637 |
#include "Bound.h"
namespace pipeline {
Bound::Bound()
{
}
Bound::Bound(const Vector3f& minpt, const Vector3f& maxpt)
{
}
}
|
shanysheng/RenderPipeline
|
engine/Bound.cpp
|
C++
|
bsd-2-clause
| 177 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>local::basic_endpoint::path (3 of 3 overloads)</title>
<link rel="stylesheet" href="../../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../../../index.html" title="Asio">
<link rel="up" href="../path.html" title="local::basic_endpoint::path">
<link rel="prev" href="overload2.html" title="local::basic_endpoint::path (2 of 3 overloads)">
<link rel="next" href="../protocol.html" title="local::basic_endpoint::protocol">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr><td valign="top"><img alt="asio C++ library" width="250" height="60" src="../../../../asio.png"></td></tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload2.html"><img src="../../../../prev.png" alt="Prev"></a><a accesskey="u" href="../path.html"><img src="../../../../up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../home.png" alt="Home"></a><a accesskey="n" href="../protocol.html"><img src="../../../../next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h5 class="title">
<a name="asio.reference.local__basic_endpoint.path.overload3"></a><a class="link" href="overload3.html" title="local::basic_endpoint::path (3 of 3 overloads)">local::basic_endpoint::path
(3 of 3 overloads)</a>
</h5></div></div></div>
<p>
Set the path associated with the endpoint.
</p>
<pre class="programlisting"><span class="keyword">void</span> <span class="identifier">path</span><span class="special">(</span>
<span class="keyword">const</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">string</span> <span class="special">&</span> <span class="identifier">p</span><span class="special">);</span>
</pre>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2013 Christopher M. Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload2.html"><img src="../../../../prev.png" alt="Prev"></a><a accesskey="u" href="../path.html"><img src="../../../../up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../home.png" alt="Home"></a><a accesskey="n" href="../protocol.html"><img src="../../../../next.png" alt="Next"></a>
</div>
</body>
</html>
|
laeotropic/HTTP-Proxy
|
deps/asio-1.10.1/doc/asio/reference/local__basic_endpoint/path/overload3.html
|
HTML
|
bsd-2-clause
| 2,891 |
//
// TextureNode.cpp
// WordShift
//
// Created by David Wicks on 5/3/13.
// Copyright (c) 2013 __MyCompanyName__. All rights reserved.
//
#include "TextureNode.h"
#include "cinder/gl/draw.h"
using namespace cinder;
using namespace pockets;
using namespace cobweb;
TextureNode::TextureNode( const gl::TextureRef &texture ):
mTexture( texture )
{}
TextureNode::~TextureNode()
{}
void TextureNode::draw()
{
gl::draw( mTexture, app::toPoints( mTexture->getBounds() ) );
}
|
sansumbrella/Choreograph
|
samples/src/pockets/cobweb/TextureNode.cpp
|
C++
|
bsd-2-clause
| 483 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_seq_packet_socket::open (2 of 2 overloads)</title>
<link rel="stylesheet" href="../../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../../../index.html" title="Asio">
<link rel="up" href="../open.html" title="basic_seq_packet_socket::open">
<link rel="prev" href="overload1.html" title="basic_seq_packet_socket::open (1 of 2 overloads)">
<link rel="next" href="../operator_eq_.html" title="basic_seq_packet_socket::operator=">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr><td valign="top"><img alt="asio C++ library" width="250" height="60" src="../../../../asio.png"></td></tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload1.html"><img src="../../../../prev.png" alt="Prev"></a><a accesskey="u" href="../open.html"><img src="../../../../up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../home.png" alt="Home"></a><a accesskey="n" href="../operator_eq_.html"><img src="../../../../next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h5 class="title">
<a name="asio.reference.basic_seq_packet_socket.open.overload2"></a><a class="link" href="overload2.html" title="basic_seq_packet_socket::open (2 of 2 overloads)">basic_seq_packet_socket::open
(2 of 2 overloads)</a>
</h5></div></div></div>
<p>
<span class="emphasis"><em>Inherited from basic_socket.</em></span>
</p>
<p>
Open the socket using the specified protocol.
</p>
<pre class="programlisting"><span class="identifier">asio</span><span class="special">::</span><span class="identifier">error_code</span> <span class="identifier">open</span><span class="special">(</span>
<span class="keyword">const</span> <span class="identifier">protocol_type</span> <span class="special">&</span> <span class="identifier">protocol</span><span class="special">,</span>
<span class="identifier">asio</span><span class="special">::</span><span class="identifier">error_code</span> <span class="special">&</span> <span class="identifier">ec</span><span class="special">);</span>
</pre>
<p>
This function opens the socket so that it will use the specified protocol.
</p>
<h6>
<a name="asio.reference.basic_seq_packet_socket.open.overload2.h0"></a>
<span><a name="asio.reference.basic_seq_packet_socket.open.overload2.parameters"></a></span><a class="link" href="overload2.html#asio.reference.basic_seq_packet_socket.open.overload2.parameters">Parameters</a>
</h6>
<div class="variablelist">
<p class="title"><b></b></p>
<dl>
<dt><span class="term">protocol</span></dt>
<dd><p>
An object specifying which protocol is to be used.
</p></dd>
<dt><span class="term">ec</span></dt>
<dd><p>
Set to indicate what error occurred, if any.
</p></dd>
</dl>
</div>
<h6>
<a name="asio.reference.basic_seq_packet_socket.open.overload2.h1"></a>
<span><a name="asio.reference.basic_seq_packet_socket.open.overload2.example"></a></span><a class="link" href="overload2.html#asio.reference.basic_seq_packet_socket.open.overload2.example">Example</a>
</h6>
<pre class="programlisting"><span class="identifier">asio</span><span class="special">::</span><span class="identifier">ip</span><span class="special">::</span><span class="identifier">tcp</span><span class="special">::</span><span class="identifier">socket</span> <span class="identifier">socket</span><span class="special">(</span><span class="identifier">io_service</span><span class="special">);</span>
<span class="identifier">asio</span><span class="special">::</span><span class="identifier">error_code</span> <span class="identifier">ec</span><span class="special">;</span>
<span class="identifier">socket</span><span class="special">.</span><span class="identifier">open</span><span class="special">(</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">ip</span><span class="special">::</span><span class="identifier">tcp</span><span class="special">::</span><span class="identifier">v4</span><span class="special">(),</span> <span class="identifier">ec</span><span class="special">);</span>
<span class="keyword">if</span> <span class="special">(</span><span class="identifier">ec</span><span class="special">)</span>
<span class="special">{</span>
<span class="comment">// An error occurred.</span>
<span class="special">}</span>
</pre>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2013 Christopher M. Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload1.html"><img src="../../../../prev.png" alt="Prev"></a><a accesskey="u" href="../open.html"><img src="../../../../up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../home.png" alt="Home"></a><a accesskey="n" href="../operator_eq_.html"><img src="../../../../next.png" alt="Next"></a>
</div>
</body>
</html>
|
laeotropic/HTTP-Proxy
|
deps/asio-1.10.1/doc/asio/reference/basic_seq_packet_socket/open/overload2.html
|
HTML
|
bsd-2-clause
| 5,637 |
package me.pavo.logic;
import me.pavo.NewPost;
import me.pavo.server.Connection;
import me.pavo.server.Params;
import me.pavo.ui.CapturePhoto;
import me.pavo.ui.PreviewPhoto;
import me.pavo.ui.Waiting;
public class TakePhotoWF extends Workflow {
public void run() {
Params result = show(new CapturePhoto());
if(isOk(result)) {
show(new Waiting("Generating preview..."));
Params preview;
if(result.has("snapshot")) {
preview = (Params) Connection.getInstance().sendImageForPreview((byte[]) result.get("snapshot")).getResult();
} else {
preview = (Params) Connection.getInstance().sendFileForPreview(result).getResult();
}
Params previewResult = show(new PreviewPhoto(preview.getImage("preview")));
if(isOk(previewResult)) {
NewPost post = new NewPost();
post.set(NewPost.ATTACHMENT, "image");
post.set(NewPost.PREVIEW_ID, preview.getInt("preview_id"));
post.set(NewPost.BODY, previewResult.getString("text"));
post.set(NewPost.ROTATION, previewResult.getInt("rotation"));
Connection.getInstance().sendPost(post);
}
}
showCurrentScreen();
}
}
|
ak1394/pavome-client
|
src/me/pavo/logic/TakePhotoWF.java
|
Java
|
bsd-2-clause
| 1,144 |
package github
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"testing"
"github.com/google/go-github/github"
)
func TestInstallation_isEnabled(t *testing.T) {
var i *Installation
if want := false; i.IsEnabled() != want {
t.Errorf("want: %v, have: %v", want, i.IsEnabled())
}
i = &Installation{}
if want := true; i.IsEnabled() != want {
t.Errorf("want: %v, have: %v", want, i.IsEnabled())
}
}
func TestInstallation_diff(t *testing.T) {
var (
wantDiff = []byte("diff")
api []byte
)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.RequestURI {
case "/repositories/11/pulls/10":
// API response for pull requests
w.Write(api)
case "/repositories/11/compare/zzzct":
// API response for first pushes
w.Write(api)
case "/repositories/11/compare/zzzct~3...zzzct":
// API response for pushes
w.Write(api)
case "/diff.diff":
w.Write(wantDiff)
default:
t.Logf(r.RequestURI)
}
}))
defer ts.Close()
api = []byte(fmt.Sprintf(`{"diff_url": "%v/diff.diff"}`, ts.URL))
i := Installation{client: github.NewClient(nil)}
i.client.BaseURL, _ = url.Parse(ts.URL)
tests := []struct {
commitFrom string
commitTo string
requestNum int
}{
{"zzzct~3", "zzzct", 0},
{"", "", 10},
}
for _, test := range tests {
body, err := i.Diff(context.Background(), 11, test.commitFrom, test.commitTo, test.requestNum)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
haveDiff, err := ioutil.ReadAll(body)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !reflect.DeepEqual(haveDiff, wantDiff) {
t.Errorf("diff have: %s, want: %s", haveDiff, wantDiff)
}
}
}
|
bradleyfalzon/gopherci
|
internal/github/installation_test.go
|
GO
|
bsd-2-clause
| 1,750 |
๏ปฟ@echo OFF
echo Creating a 'Results' folder if it does not exist...
if not exist "%~dp0TestResults" mkdir "%~dp0TestResults"
echo Creating a 'GeneratedReports' folder if it does not exist...
if not exist "%~dp0GeneratedReports" mkdir "%~dp0GeneratedReports"
echo Removing any previous test execution files to prevent issues overwriting...
IF EXIST "%~dp0TestResults\AutomatedSimTemplateTests.trx" del "%~dp0TestResults\AutomatedSimTemplateTests.trx%"
echo Removing any previously created test output directories...
CD %~dp0\TestResults
FOR /D /R %%X IN (%USERNAME%*) DO RD /S /Q "%%X"
CD %~dp0
echo Running the tests against the targeted output...
call :RunOpenCoverUnitTestMetrics
echo Generating the report output based on the test results...
if %errorlevel% equ 0 (
call :RunReportGeneratorOutput
)
REM Launch the report
if %errorlevel% equ 0 (
call :RunLaunchReport
)
exit /b %errorlevel%
:RunOpenCoverUnitTestMetrics
"%~dp0..\packages\OpenCover.4.6.519\tools\OpenCover.Console.exe" ^
-register:user ^
-target:"%VS140COMNTOOLS%\..\IDE\mstest.exe" ^
-targetargs:"/testcontainer:\"%~dp0AutomatedSimTemplateTests\bin\Debug\AutomatedSimTemplateTests.dll\" /resultsfile:\"%~dp0TestResults\AutomatedSimTemplateTests.trx\"" ^
-filter:"+[SimTemplate*]* -[SimTemplate.*Tests]* -[*]SimTemplate.RouteConfig" ^
-mergebyhash ^
-skipautoprops ^
-output:"%~dp0GeneratedReports\AutomatedSimTemplateTests.xml"
exit /b %errorlevel%
:RunReportGeneratorOutput
"%~dp0..\packages\ReportGenerator.2.4.5.0\tools\ReportGenerator.exe" ^
-reports:"%~dp0GeneratedReports\AutomatedSimTemplateTests.xml" ^
-reporttypes:"Html;HtmlSummary" ^
-targetdir:"%~dp0GeneratedReports\ReportGenerator Output"
exit /b %errorlevel%
:RunLaunchReport
start "report" "%~dp0GeneratedReports\ReportGenerator Output\index.htm"
exit /b %errorlevel%
|
SimPrints/SimTemplate
|
UnitTests/RunCodeCoverage.bat
|
Batchfile
|
bsd-2-clause
| 1,872 |
package com.conveyal.gtfs.loader;
import com.conveyal.gtfs.GTFSFeed;
import com.conveyal.gtfs.model.Calendar;
import com.conveyal.gtfs.model.CalendarDate;
import com.conveyal.gtfs.model.ScheduleException;
import com.conveyal.gtfs.model.Service;
import org.apache.commons.dbutils.DbUtils;
import org.postgresql.copy.CopyManager;
import org.postgresql.core.BaseConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.DataSource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* Handles exporting a feed contained in the database to a GTFS zip file.
*/
public class JdbcGtfsExporter {
private static final Logger LOG = LoggerFactory.getLogger(JdbcGtfsExporter.class);
private final String outFile;
private final DataSource dataSource;
private final boolean fromEditor;
// These fields will be filled in once feed snapshot begins.
private Connection connection;
private ZipOutputStream zipOutputStream;
// The reference feed ID (namespace) to copy.
private final String feedIdToExport;
private List<String> emptyTableList = new ArrayList<>();
public JdbcGtfsExporter(String feedId, String outFile, DataSource dataSource, boolean fromEditor) {
this.feedIdToExport = feedId;
this.outFile = outFile;
this.dataSource = dataSource;
this.fromEditor = fromEditor;
}
/**
* Export primary entity tables as well as Pattern and PatternStops tables.
*
* FIXME: This should probably only export main GTFS tables... unless there is a benefit to keeping editor fields or
* tables intact for future editing. Maybe this could be an option provided to the function (e.g., specTablesOnly).
*/
public FeedLoadResult exportTables() {
// This result object will be returned to the caller to summarize the feed and report any critical errors.
// FIXME: use feed export result object?
FeedLoadResult result = new FeedLoadResult();
try {
zipOutputStream = new ZipOutputStream(new FileOutputStream(outFile));
long startTime = System.currentTimeMillis();
// We get a single connection object and share it across several different methods.
// This ensures that actions taken in one method are visible to all subsequent SQL statements.
// If we create a schema or table on one connection, then access it in a separate connection, we have no
// guarantee that it exists when the accessing statement is executed.
connection = dataSource.getConnection();
if (!connection.getMetaData().getDatabaseProductName().equals("PostgreSQL")) {
// This code path currently requires the Postgres text "copy to" format.
throw new RuntimeException("Export from SQL database not implemented for non-PostgreSQL databases.");
}
// Construct where clause for routes table to filter only "approved" routes (and entities related to routes)
// if exporting a feed/schema that represents an editor snapshot.
String whereRouteIsApproved = String.format("where %s.%s.status = 2", feedIdToExport, Table.ROUTES.name);
// Export each table in turn (by placing entry in zip output stream).
result.agency = export(Table.AGENCY, connection);
if (fromEditor) {
// only export calendar entries that have at least one day of service set
// this could happen in cases where a feed was imported that only had calendar_dates.txt
result.calendar = export(
Table.CALENDAR,
String.join(
" ",
Table.CALENDAR.generateSelectSql(feedIdToExport, Requirement.OPTIONAL),
"WHERE monday=1 OR tuesday=1 OR wednesday=1 OR thursday=1 OR friday=1 OR saturday=1 OR sunday=1"
)
);
} else {
result.calendar = export(Table.CALENDAR, connection);
}
if (fromEditor) {
// Export schedule exceptions in place of calendar dates if exporting a feed/schema that represents an editor snapshot.
GTFSFeed feed = new GTFSFeed();
// FIXME: The below table readers should probably just share a connection with the exporter.
JDBCTableReader<ScheduleException> exceptionsReader =
new JDBCTableReader(Table.SCHEDULE_EXCEPTIONS, dataSource, feedIdToExport + ".",
EntityPopulator.SCHEDULE_EXCEPTION);
JDBCTableReader<Calendar> calendarsReader =
new JDBCTableReader(Table.CALENDAR, dataSource, feedIdToExport + ".",
EntityPopulator.CALENDAR);
Iterable<Calendar> calendars = calendarsReader.getAll();
Iterable<ScheduleException> exceptionsIterator = exceptionsReader.getAll();
List<ScheduleException> exceptions = new ArrayList<>();
// FIXME: Doing this causes the connection to stay open, but it is closed in the finalizer so it should
// not be a big problem.
for (ScheduleException exception : exceptionsIterator) {
exceptions.add(exception);
}
// check whether the feed is organized in a format with the calendars.txt file
if (calendarsReader.getRowCount() > 0) {
// feed does have calendars.txt file, continue export with strategy of matching exceptions
// to calendar to output calendar_dates.txt
int calendarDateCount = 0;
for (Calendar cal : calendars) {
Service service = new Service(cal.service_id);
service.calendar = cal;
for (ScheduleException ex : exceptions) {
if (ex.exemplar.equals(ScheduleException.ExemplarServiceDescriptor.SWAP) &&
(!ex.addedService.contains(cal.service_id) && !ex.removedService.contains(cal.service_id))) {
// Skip swap exception if cal is not referenced by added or removed service.
// This is not technically necessary, but the output is cleaner/more intelligible.
continue;
}
for (LocalDate date : ex.dates) {
if (date.isBefore(cal.start_date) || date.isAfter(cal.end_date)) {
// No need to write dates that do not apply
continue;
}
CalendarDate calendarDate = new CalendarDate();
calendarDate.date = date;
calendarDate.service_id = cal.service_id;
calendarDate.exception_type = ex.serviceRunsOn(cal) ? 1 : 2;
LOG.info("Adding exception {} (type={}) for calendar {} on date {}", ex.name, calendarDate.exception_type, cal.service_id, date.toString());
if (service.calendar_dates.containsKey(date))
throw new IllegalArgumentException("Duplicate schedule exceptions on " + date.toString());
service.calendar_dates.put(date, calendarDate);
calendarDateCount += 1;
}
}
feed.services.put(cal.service_id, service);
}
if (calendarDateCount == 0) {
LOG.info("No calendar dates found. Skipping table.");
} else {
LOG.info("Writing {} calendar dates from schedule exceptions", calendarDateCount);
new CalendarDate.Writer(feed).writeTable(zipOutputStream);
}
} else {
// No calendar records exist, export calendar_dates as is and hope for the best.
// This situation will occur in at least 2 scenarios:
// 1. A GTFS has been loaded into the editor that had only the calendar_dates.txt file
// and no further edits were made before exporting to a snapshot
// 2. A new GTFS has been created from scratch and calendar information has yet to be added.
// This will result in an invalid GTFS, but it was what the user wanted so ยฏ\_(ใ)_/ยฏ
result.calendarDates = export(Table.CALENDAR_DATES, connection);
}
} else {
// Otherwise, simply export the calendar dates as they were loaded in.
result.calendarDates = export(Table.CALENDAR_DATES, connection);
}
result.fareAttributes = export(Table.FARE_ATTRIBUTES, connection);
result.fareRules = export(Table.FARE_RULES, connection);
result.feedInfo = export(Table.FEED_INFO, connection);
// Only write frequencies for "approved" routes using COPY TO with results of select query
if (fromEditor) {
// Generate filter SQL for trips if exporting a feed/schema that represents an editor snapshot.
// The filter clause for frequencies requires two joins to reach the routes table and a where filter on
// route status.
// FIXME Replace with string literal query instead of clause generators
result.frequencies = export(
Table.FREQUENCIES,
String.join(
" ",
// Convert start_time and end_time values from seconds to time format (HH:MM:SS).
Table.FREQUENCIES.generateSelectSql(feedIdToExport, Requirement.OPTIONAL),
Table.FREQUENCIES.generateJoinSql(Table.TRIPS, feedIdToExport),
Table.TRIPS.generateJoinSql(
Table.ROUTES,
feedIdToExport,
"route_id",
false
),
whereRouteIsApproved
)
);
} else {
result.frequencies = export(Table.FREQUENCIES, connection);
}
// Only write "approved" routes using COPY TO with results of select query
if (fromEditor) {
// The filter clause for routes is simple. We're just checking that the route is APPROVED.
result.routes = export(
Table.ROUTES,
String.join(
" ",
Table.ROUTES.generateSelectSql(feedIdToExport, Requirement.OPTIONAL),
whereRouteIsApproved
)
);
} else {
result.routes = export(Table.ROUTES, connection);
}
// FIXME: Find some place to store errors encountered on export for patterns and pattern stops.
// FIXME: Is there a need to export patterns or pattern stops? Should these be iterated over to ensure that
// frequency-based pattern travel times match stop time arrivals/departures?
// export(Table.PATTERNS);
// export(Table.PATTERN_STOP);
// Only write shapes for "approved" routes using COPY TO with results of select query
if (fromEditor) {
// Generate filter SQL for shapes if exporting a feed/schema that represents an editor snapshot.
// The filter clause for shapes requires joining to trips and then to routes table and a where filter on
// route status.
// FIXME: I'm not sure that shape_id is indexed for the trips table. This could cause slow downs.
// FIXME: this is exporting point_type, which is not a GTFS field, but its presence shouldn't hurt.
String shapeFieldsToExport = Table.commaSeparatedNames(
Table.SHAPES.specFields(),
String.join(".", feedIdToExport, Table.SHAPES.name + "."),
true
);
// NOTE: The below substitution uses relative indexing. All values "%<s" reference the same arg as the
// previous format specifier (i.e., feedIdToExport).
result.shapes = export(
Table.SHAPES,
String.format(
"select %s " +
"from (select distinct %s.trips.shape_id " +
"from %<s.trips, %<s.routes " +
"where %<s.trips.route_id = %<s.routes.route_id and " +
"%<s.routes.status = 2) as unique_approved_shape_ids, " +
"%<s.shapes where unique_approved_shape_ids.shape_id = %<s.shapes.shape_id",
shapeFieldsToExport,
feedIdToExport
)
);
} else {
result.shapes = export(Table.SHAPES, connection);
}
result.stops = export(Table.STOPS, connection);
// Only write stop times for "approved" routes using COPY TO with results of select query
if (fromEditor) {
// Generate filter SQL for trips if exporting a feed/schema that represents an editor snapshot.
// The filter clause for stop times requires two joins to reach the routes table and a where filter on
// route status.
// FIXME Replace with string literal query instead of clause generators
result.stopTimes = export(
Table.STOP_TIMES,
String.join(" ",
Table.STOP_TIMES.generateSelectSql(feedIdToExport, Requirement.OPTIONAL),
Table.STOP_TIMES.generateJoinSql(Table.TRIPS, feedIdToExport),
Table.TRIPS.generateJoinSql(
Table.ROUTES,
feedIdToExport,
"route_id",
false
),
whereRouteIsApproved
)
);
} else {
result.stopTimes = export(Table.STOP_TIMES, connection);
}
result.transfers = export(Table.TRANSFERS, connection);
if (fromEditor) {
// Generate filter SQL for trips if exporting a feed/schema that represents an editor snapshot.
// The filter clause for trips requires an inner join on the routes table and the same where check on
// route status.
// FIXME Replace with string literal query instead of clause generators
result.trips = export(
Table.TRIPS,
String.join(" ",
Table.TRIPS.generateSelectSql(feedIdToExport, Requirement.OPTIONAL),
Table.TRIPS.generateJoinSql(
Table.ROUTES,
feedIdToExport,
"route_id",
false
),
whereRouteIsApproved
)
);
} else {
result.trips = export(Table.TRIPS, connection);
}
zipOutputStream.close();
// Run clean up on the resulting zip file.
cleanUpZipFile();
result.completionTime = System.currentTimeMillis();
result.loadTimeMillis = result.completionTime - startTime;
// Exporting primary GTFS tables for GRTA Xpress = 12 sec
LOG.info("Exporting tables took {} sec", (result.loadTimeMillis) / 1000);
LOG.info("Exported feed {} to zip file: {}", feedIdToExport, outFile);
} catch (Exception ex) {
// Note: Exceptions that occur during individual table loads are separately caught and stored in
// TableLoadResult.
LOG.error("Exception while creating snapshot: {}", ex.toString());
ex.printStackTrace();
result.fatalException = ex.toString();
} finally {
if (connection != null) DbUtils.closeQuietly(connection);
}
return result;
}
/**
* Removes any empty zip files from the final zip file.
*/
private void cleanUpZipFile() {
long startTime = System.currentTimeMillis();
// Define ZIP File System Properties in HashMap
Map<String, String> zip_properties = new HashMap<>();
// We want to read an existing ZIP File, so we set this to False
zip_properties.put("create", "false");
// Specify the path to the ZIP File that you want to read as a File System
// (File#toURI allows this to work across different operating systems, including Windows)
URI zip_disk = URI.create("jar:" + new File(outFile).toURI());
// Create ZIP file System
try (FileSystem fileSystem = FileSystems.newFileSystem(zip_disk, zip_properties)) {
// Get the Path inside ZIP File to delete the ZIP Entry
for (String fileName : emptyTableList) {
Path filePath = fileSystem.getPath(fileName);
// Execute Delete
Files.delete(filePath);
LOG.info("Empty file {} successfully deleted", fileName);
}
} catch (IOException e) {
LOG.error("Could not remove empty zip files");
e.printStackTrace();
}
LOG.info("Deleted {} empty files in {} ms", emptyTableList.size(), System.currentTimeMillis() - startTime);
}
private TableLoadResult export (Table table, Connection connection) {
if (fromEditor) {
// Default behavior for exporting editor snapshot tables is to select only the spec fields.
return export(table, table.generateSelectSql(feedIdToExport, Requirement.OPTIONAL));
} else {
String existingFieldsSelect = null;
try {
existingFieldsSelect = table.generateSelectAllExistingFieldsSql(connection, feedIdToExport);
} catch (SQLException e) {
LOG.error("failed to generate select statement for existing fields");
TableLoadResult tableLoadResult = new TableLoadResult();
tableLoadResult.fatalException = e.toString();
e.printStackTrace();
return tableLoadResult;
}
return export(table, existingFieldsSelect);
}
}
/**
* Export a table to the zipOutputStream to be written to the GTFS.
*/
private TableLoadResult export (Table table, String filterSql) {
long startTime = System.currentTimeMillis();
TableLoadResult tableLoadResult = new TableLoadResult();
try {
if (filterSql == null) {
throw new IllegalArgumentException("filterSql argument cannot be null");
} else {
// Surround filter SQL in parentheses.
filterSql = String.format("(%s)", filterSql);
}
// Create entry for table
String textFileName = table.name + ".txt";
ZipEntry zipEntry = new ZipEntry(textFileName);
zipOutputStream.putNextEntry(zipEntry);
// don't let CSVWriter close the stream when it is garbage-collected
OutputStream protectedOut = new FilterOutputStream(zipOutputStream);
String copySql = String.format("copy %s to STDOUT DELIMITER ',' CSV HEADER", filterSql);
LOG.info(copySql);
// Our connection pool wraps the Connection objects, so we need to unwrap the Postgres connection interface.
CopyManager copyManager = new CopyManager(connection.unwrap(BaseConnection.class));
tableLoadResult.rowCount = (int) copyManager.copyOut(copySql, protectedOut);
if (tableLoadResult.rowCount == 0) {
// If no rows were exported, keep track of table name for later removal.
emptyTableList.add(textFileName);
}
zipOutputStream.closeEntry();
LOG.info("Copied {} {} in {} ms.", tableLoadResult.rowCount, table.name, System.currentTimeMillis() - startTime);
connection.commit();
} catch (SQLException | IOException | IllegalArgumentException e) {
// Rollback connection so that fatal exception does not impact loading of other tables.
try {
connection.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
tableLoadResult.fatalException = e.toString();
LOG.error("Exception while exporting tables", e);
}
return tableLoadResult;
}
}
|
conveyal/gtfs-lib
|
src/main/java/com/conveyal/gtfs/loader/JdbcGtfsExporter.java
|
Java
|
bsd-2-clause
| 21,986 |
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2015, Anima Istanbul
#
# This module is part of anima-tools and is released under the BSD 2
# License: http://www.opensource.org/licenses/BSD-2-Clause
from anima import logger
from anima.env import empty_reference_resolution
from anima.ui.base import AnimaDialogBase, ui_caller
from anima.ui.models import VersionTreeModel
from anima.ui.lib import QtGui, QtCore, QtWidgets
from anima.ui import IS_PYSIDE, IS_PYSIDE2, IS_PYQT4
if IS_PYSIDE():
from anima.ui.ui_compiled import version_updater_UI_pyside as version_updater_UI
elif IS_PYSIDE2():
from anima.ui.ui_compiled import version_updater_UI_pyside2 as version_updater_UI
elif IS_PYQT4():
from anima.ui.ui_compiled import version_updater_UI_pyqt4 as version_updater_UI
def UI(app_in=None, executor=None, **kwargs):
"""
:param environment: The
:class:`~stalker.models.env.EnvironmentBase` can be None to let the UI to
work in "environmentless" mode in which it only creates data in database
and copies the resultant version file path to clipboard.
:param app_in: A Qt Application instance, which you can pass to let the UI
be attached to the given applications event process.
:param executor: Instead of calling app.exec_ the UI will call this given
function. It also passes the created app instance to this executor.
"""
return ui_caller(app_in, executor, MainDialog, **kwargs)
class MainDialog(QtWidgets.QDialog, version_updater_UI.Ui_Dialog, AnimaDialogBase):
"""The main dialog of the version updater system
The version_tuple list consist of a Version instance and a reference
object.
For Maya environment the reference object is the PyMel Reference node,
for other environments reference object type will be as native as it can be
"""
def __init__(self, environment=None, parent=None,
reference_resolution=None):
super(MainDialog, self).__init__(parent)
self.setupUi(self)
# change the window title
self.setWindowTitle(self.windowTitle())
# center to the window
self.center_window()
self.new_versions = []
# setup the environment
self.environment = self._validate_environment(environment)
if reference_resolution is None:
# generate from environment
if self.environment:
reference_resolution = \
self.environment.check_referenced_versions()
else:
# create an empty one
reference_resolution = empty_reference_resolution()
self.reference_resolution = reference_resolution
self.setup_signals()
self._fill_UI()
def _validate_environment(self, environment):
"""validates the given environment value
"""
if environment:
current_version = environment.get_current_version()
if not current_version:
# there is no version so warn the user
error_message = 'Please save the current scene with Version ' \
'Creator first!!!'
QtWidgets.QMessageBox.critical(
self,
"Error",
error_message,
QtWidgets.QMessageBox.Ok
)
self.close()
raise RuntimeError(error_message)
return environment
def setup_signals(self):
"""sets up the signals
"""
# SIGNALS
# cancel button
QtCore.QObject.connect(
self.cancel_pushButton,
QtCore.SIGNAL("clicked()"),
self.close
)
# select all button
QtCore.QObject.connect(
self.selectAll_pushButton,
QtCore.SIGNAL("clicked()"),
self._select_all_versions
)
# select none button
QtCore.QObject.connect(
self.selectNone_pushButton,
QtCore.SIGNAL("clicked()"),
self._select_no_version
)
# update button
QtCore.QObject.connect(
self.update_pushButton,
QtCore.SIGNAL("clicked()"),
self.update_versions
)
# fit column 0 on expand/collapse
QtCore.QObject.connect(
self.versions_treeView,
QtCore.SIGNAL('expanded(QModelIndex)'),
self.versions_treeView_auto_fit_column
)
QtCore.QObject.connect(
self.versions_treeView,
QtCore.SIGNAL('collapsed(QModelIndex)'),
self.versions_treeView_auto_fit_column
)
# custom context menu for the version_treeView
self.versions_treeView.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu
)
QtCore.QObject.connect(
self.versions_treeView,
QtCore.SIGNAL("customContextMenuRequested(const QPoint&)"),
self._show_versions_treeView_context_menu
)
def versions_treeView_auto_fit_column(self):
"""fits columns to content
"""
self.versions_treeView.resizeColumnToContents(0)
self.versions_treeView.resizeColumnToContents(1)
self.versions_treeView.resizeColumnToContents(2)
self.versions_treeView.resizeColumnToContents(3)
self.versions_treeView.resizeColumnToContents(4)
self.versions_treeView.resizeColumnToContents(5)
self.versions_treeView.resizeColumnToContents(6)
def fill_versions_treeView(self):
"""sets up the versions_treeView
"""
logger.debug('start filling versions_treeView')
logger.debug('creating a new model')
version_tree_model = VersionTreeModel()
version_tree_model.reference_resolution = self.reference_resolution
# populate with all update items
version_tree_model.populateTree(self.reference_resolution['root'])
self.versions_treeView.setModel(version_tree_model)
logger.debug('setting up signals for versions_treeView_changed')
# versions_treeView
# QtCore.QObject.connect(
# self.versions_treeView.selectionModel(),
# QtCore.SIGNAL('selectionChanged(const QItemSelection &, '
# 'const QItemSelection &)'),
# self.versions_treeView_changed
# )
self.versions_treeView.is_updating = False
self.versions_treeView_auto_fit_column()
logger.debug('finished filling versions_treeView')
def _fill_UI(self):
"""fills the UI with the asset data
"""
# set the row count
self.fill_versions_treeView()
def _select_all_versions(self):
"""selects all the versions in the tableWidget
"""
version_tree_model = self.versions_treeView.model()
for i in range(version_tree_model.rowCount()):
index = version_tree_model.index(i, 0)
version_item = version_tree_model.itemFromIndex(index)
version_item.setCheckState(QtCore.Qt.Checked)
def _select_no_version(self):
"""deselects all versions in the tableWidget
"""
version_tree_model = self.versions_treeView.model()
for i in range(version_tree_model.rowCount()):
index = version_tree_model.index(i, 0)
version_item = version_tree_model.itemFromIndex(index)
version_item.setCheckState(QtCore.Qt.Unchecked)
def _show_versions_treeView_context_menu(self, position):
"""the custom context menu for the versions_treeView
"""
# convert the position to global screen position
global_position = \
self.versions_treeView.mapToGlobal(position)
index = self.versions_treeView.indexAt(position)
model = self.versions_treeView.model()
# get the column 0 item which holds the Version instance
# index = self.versions_treeView.model().index(index.row(), 0)
item = model.itemFromIndex(index)
logger.debug('itemAt(position) : %s' % item)
if not item:
return
if not hasattr(item, 'version'):
return
version = item.version
latest_published_version = None
if version:
latest_published_version = version.latest_published_version
item_action = item.action
# if item_action != 'create':
# return
from stalker import Version
if not isinstance(version, Version):
return
# create the menu
menu = QtWidgets.QMenu()
# Add "Open..." action
# Always open the latest published version
absolute_full_path = version.absolute_full_path
if absolute_full_path:
action = menu.addAction('Open...')
if latest_published_version:
action.version = latest_published_version
else:
action.version = version
selected_action = menu.exec_(global_position)
if selected_action:
choice = selected_action.text()
if choice == 'Open...':
self.open_version(selected_action.version)
def open_version(self, version):
"""opens the given version in a new environment
:param version: :class:`~stalker.model.version.Version` instance.
"""
import subprocess
import platform
platform_name = platform.system().lower()
# store the latest published version
prev_lpv = version.latest_published_version
process = subprocess.Popen(
[self.environment.executable[platform_name],
version.absolute_full_path],
stderr=subprocess.PIPE
)
# wait until the process finishes
process.wait()
# check the latest published version again
next_lpv = version.latest_published_version
if prev_lpv != next_lpv:
# a new version has been created so tell the environment to update
# the references to this version
self.reference_resolution = \
self.environment.check_referenced_versions()
# and then refresh the UI
self._fill_UI()
def update_versions(self):
"""updates the versions if it is checked in the UI
"""
reference_resolution = self.generate_reference_resolution()
# send them back to environment
try:
self.environment.update_versions(reference_resolution)
except RuntimeError as e:
# display as a Error message and return without doing anything
message_box = QtWidgets.QMessageBox(self)
message_box.critical(
self,
"Error",
str(e),
QtWidgets.QMessageBox.Ok
)
return
# close the interface
self.close()
def generate_reference_resolution(self):
"""Generates a new reference_resolution dictionary from the UI
:return: dictionary
"""
generated_reference_resolution = empty_reference_resolution()
# append anything that is checked
version_tree_model = self.versions_treeView.model()
for i in range(version_tree_model.rowCount()):
index = version_tree_model.index(i, 0)
version_item = version_tree_model.itemFromIndex(index)
if version_item.checkState() == QtCore.Qt.Checked:
version = version_item.version
generated_reference_resolution['update'].append(version)
return generated_reference_resolution
def show(self):
"""overridden show method
"""
logger.debug('MainDialog.show is started')
logged_in_user = self.get_logged_in_user()
if not logged_in_user:
self.close()
return_val = None
else:
return_val = super(MainDialog, self).show()
logger.debug('MainDialog.show is finished')
return return_val
|
sergeneren/anima
|
anima/ui/version_updater.py
|
Python
|
bsd-2-clause
| 12,135 |
<?php
namespace Torann\GeoIP\Services;
use GeoIp2\WebService\Client;
class MaxMindWebService extends AbstractService
{
/**
* Service client instance.
*
* @var \GeoIp2\WebService\Client
*/
protected $client;
/**
* The "booting" method of the service.
*
* @return void
*/
public function boot()
{
$this->client = new Client(
$this->config('user_id'),
$this->config('license_key'),
$this->config('locales', ['en'])
);
}
/**
* {@inheritdoc}
*/
public function locate($ip)
{
$record = $this->client->city($ip);
return $this->hydrate([
'ip' => $ip,
'iso_code' => $record->country->isoCode,
'country' => $record->country->name,
'city' => $record->city->name,
'state' => $record->mostSpecificSubdivision->isoCode,
'state_name' => $record->mostSpecificSubdivision->name,
'postal_code' => $record->postal->code,
'lat' => $record->location->latitude,
'lon' => $record->location->longitude,
'timezone' => $record->location->timeZone,
'continent' => $record->continent->code,
]);
}
}
|
Torann/laravel-geoip
|
src/Services/MaxMindWebService.php
|
PHP
|
bsd-2-clause
| 1,274 |
<?php
namespace ws\loewe\Woody\Event;
use \ws\loewe\Woody\Components\Windows\MainWindow;
use \ws\loewe\Woody\Components\Controls\EditBox;
use \ws\loewe\Utils\Geom\Point;
use \ws\loewe\Utils\Geom\Dimension;
/**
* Test class for ActionEvent.
* Generated by PHPUnit on 2012-07-04 at 22:19:40.
*/
class ActionEventTest extends \PHPUnit_Framework_TestCase {
/**
* @var ActionEvent the event to be tested
*/
private $event = null;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp() {
$eventInfo = $this->getMockBuilder('\ws\loewe\Woody\Event\EventInfo')
->disableOriginalConstructor()
->getMock();
$this->event = new ActionEvent($eventInfo);
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown() {
}
/**
* This method tests creating the event.
*
* @covers \ws\loewe\Woody\Event\ActionEvent::__construct
* @covers \ws\loewe\Woody\Event\Event::__construct
*/
public function testConstruct() {
$this->assertInstanceOf('\ws\loewe\Woody\Event\ActionEvent', $this->event);
}
/**
* This method tests dispatching the event.
*
* @covers \ws\loewe\Woody\Event\ActionEvent::dispatch
*/
public function testDispatch() {
$window = new MainWindow('MainWindow', Point::createInstance(50, 50), Dimension::createInstance(300, 200));
$editbox = new EditBox('', Point::createInstance(20, 20), Dimension::createInstance(100, 18));
$window->create()->getRootPane()->add($editbox);
$actionListener = $this->getMockBuilder('\ws\loewe\Woody\Event\ActionAdapter')
->disableOriginalConstructor()
->getMock();
$actionListener->expects($this->once())->method('actionPerformed');
$editbox->addActionListener($actionListener);
$event = new ActionEvent(new EventInfo(0, $editbox->getID(), $editbox, 0, 0));
$event->dispatch();
$window->close();
}
/**
* This method tests the string representation of the action event.
*
* @covers \ws\loewe\Woody\Event\ActionEvent::__toString
* @covers \ws\loewe\Woody\Event\Event::__toString
*/
public function testToString() {
$this->assertTrue(strpos($this->event->__toString(), 'A/C/S = ') !== FALSE);
}
}
|
stefan-loewe/Woody
|
test/source/Woody/Event/ActionEventTest.php
|
PHP
|
bsd-2-clause
| 2,484 |
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
/**
* PHP version 5.3.
*
* Copyright (c) 2011 KUBO Atsuhiro <[email protected]>,
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @copyright 2011 KUBO Atsuhiro <[email protected]>
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
*
* @version Release: @package_version@
*
* @since File available since Release 3.0.0
*/
namespace Stagehand\TestRunner\DependencyInjection\Configuration;
use Symfony\Component\Config\Definition\Builder\NodeBuilder;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
/**
* @copyright 2011 KUBO Atsuhiro <[email protected]>
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
*
* @version Release: @package_version@
*
* @since Class available since Release 3.0.0
*/
abstract class Configuration implements ConfigurationInterface
{
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$this->defineGrammar($treeBuilder->root($this->getConfigurationID())->children());
return $treeBuilder;
}
/**
* @param \Symfony\Component\Config\Definition\Builder\NodeBuilder $nodeBuilder
*/
abstract protected function defineGrammar(NodeBuilder $nodeBuilder);
}
/*
* Local Variables:
* mode: php
* coding: iso-8859-1
* tab-width: 4
* c-basic-offset: 4
* c-hanging-comment-ender-p: nil
* indent-tabs-mode: nil
* End:
*/
|
piece/stagehand-testrunner
|
src/DependencyInjection/Configuration/Configuration.php
|
PHP
|
bsd-2-clause
| 2,777 |
# -*- coding: UTF-8 -*-
# Copyright 2020 Rumma & Ko Ltd
# License: GNU Affero General Public License v3 (see file COPYING for details)
import datetime
from django.conf import settings
from lino.api import dd, rt, _
from lino_xl.lib.ledger.choicelists import DC, CommonAccounts
from lino.utils import Cycler
REQUEST = settings.SITE.login() # BaseRequest()
def objects():
if dd.plugins.vat.declaration_plugin is None:
return
JournalEntryItem = rt.models.finan.JournalEntryItem
USERS = Cycler(settings.SITE.user_model.objects.all())
PARTNERS = Cycler(rt.models.contacts.Partner.objects.order_by("-id"))
jnl = rt.models.ledger.Journal.objects.get(preliminary=True)
voucher = jnl.create_voucher(
user=USERS.pop(),
entry_date=datetime.date(dd.plugins.ledger.start_year, 1, 1))
yield voucher
# seqno = 0
def vi(ca, amount, **kwargs):
# seqno += 1
kwargs.update(account=ca.get_object(), voucher=voucher)
if jnl.dc == DC.debit:
amount = -amount
kwargs.update(amount=amount)
return JournalEntryItem(**kwargs)
# yield vi(CommonAccounts.net_income_loss, 100)
yield vi(CommonAccounts.vat_due, 10)
yield vi(CommonAccounts.suppliers, 50, partner=PARTNERS.pop())
yield vi(CommonAccounts.customers, -100, partner=PARTNERS.pop())
yield vi(CommonAccounts.best_bank, 40)
voucher.register(REQUEST)
voucher.full_clean()
voucher.save()
|
lino-framework/xl
|
lino_xl/lib/sheets/fixtures/demo_bookings.py
|
Python
|
bsd-2-clause
| 1,469 |
package com.porcupine.ion;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import com.porcupine.math.Calc;
/**
* Universal data storage system
*
* @author Ondลej Hruลกka (MightyPork)
*/
public class Ion {
/** Ionizables<Mark, Class> */
private static Map<Byte, Class<?>> customIonizables = new HashMap<Byte, Class<?>>();
// register default ionizables
static {
registerIonizable(IonMarks.MAP, IonMap.class);
registerIonizable(IonMarks.LIST, IonList.class);
}
/**
* Register new Ionizable for direct reconstructing.
*
* @param mark byte mark to be used, see {@link IonMarks} for reference.
* @param objClass class of the registered Ionizable
*/
public static void registerIonizable(byte mark, Class<?> objClass) {
if (customIonizables.containsKey(mark)) {
throw new RuntimeException("IonMark " + mark + " is already used @ " + objClass.getSimpleName());
}
customIonizables.put(mark, objClass);
}
/**
* Load Ion object from file.
*
* @param file file path
* @return the loaded object
*/
public static Object fromFile(String file) {
return fromFile(new File(file));
}
/**
* Load Ion object from file.
*
* @param file file
* @return the loaded object
*/
public static Object fromFile(File file) {
try {
InputStream in = new FileInputStream(file);
Object obj = fromStream(in);
in.close();
return obj;
} catch (FileNotFoundException e) {
System.err.println("Could not find ION file " + file);
return null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Load Ion object from stream.
*
* @param in input stream
* @return the loaded object
*/
public static Object fromStream(InputStream in) {
try {
return readObject(in);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Store Ion object to file.
*
* @param path file path
* @param obj object to store
*/
public static void toFile(String path, Object obj) {
toFile(new File(path), obj);
}
/**
* Store Ion object to file.
*
* @param path file path
* @param obj object to store
*/
public static void toFile(File path, Object obj) {
try {
String f = path.toString();
File dir = new File(f.substring(0, f.lastIndexOf(File.separator)));
dir.mkdirs();
OutputStream out = new FileOutputStream(path);
toStream(out, obj);
out.flush();
out.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Store Ion object to output stream.
*
* @param out output stream *
* @param obj object to store
*/
public static void toStream(OutputStream out, Object obj) {
try {
writeObject(out, obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Read single ionizable or primitive object from input stream
*
* @param in input stream
* @return the loaded object
*/
public static Object readObject(InputStream in) {
try {
int bi = in.read();
if (bi == -1) throw new RuntimeException("Unexpected end of stream.");
byte b = (byte) bi;
if (customIonizables.containsKey(b)) {
Ionizable ion = ((Ionizable) customIonizables.get(b).newInstance());
ion.ionRead(in);
return ion;
}
switch (b) {
case IonMarks.BOOLEAN:
return StreamUtils.readBoolean(in);
case IonMarks.BYTE:
return StreamUtils.readByte(in);
case IonMarks.CHAR:
return StreamUtils.readChar(in);
case IonMarks.SHORT:
return StreamUtils.readShort(in);
case IonMarks.INT:
return StreamUtils.readInt(in);
case IonMarks.LONG:
return StreamUtils.readLong(in);
case IonMarks.FLOAT:
return StreamUtils.readFloat(in);
case IonMarks.DOUBLE:
return StreamUtils.readDouble(in);
case IonMarks.STRING:
String s = StreamUtils.readString(in);
return s;
default:
throw new RuntimeException("Invalid Ion mark " + Integer.toHexString(bi));
}
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
/**
* Write single ionizable or primitive object to output stream
*
* @param out output stream
* @param obj stored object
*/
public static void writeObject(OutputStream out, Object obj) {
try {
if (obj instanceof Ionizable) {
out.write(((Ionizable) obj).ionMark());
((Ionizable) obj).ionWrite(out);
return;
}
if (obj instanceof Boolean) {
out.write(IonMarks.BOOLEAN);
StreamUtils.writeBoolean(out, (Boolean) obj);
return;
}
if (obj instanceof Byte) {
out.write(IonMarks.BYTE);
StreamUtils.writeByte(out, (Byte) obj);
return;
}
if (obj instanceof Character) {
out.write(IonMarks.CHAR);
StreamUtils.writeChar(out, (Character) obj);
return;
}
if (obj instanceof Short) {
out.write(IonMarks.SHORT);
StreamUtils.writeShort(out, (Short) obj);
return;
}
if (obj instanceof Integer) {
out.write(IonMarks.INT);
StreamUtils.writeInt(out, (Integer) obj);
return;
}
if (obj instanceof Long) {
out.write(IonMarks.LONG);
StreamUtils.writeLong(out, (Long) obj);
return;
}
if (obj instanceof Float) {
out.write(IonMarks.FLOAT);
StreamUtils.writeFloat(out, (Float) obj);
return;
}
if (obj instanceof Double) {
out.write(IonMarks.DOUBLE);
StreamUtils.writeDouble(out, (Double) obj);
return;
}
if (obj instanceof String) {
out.write(IonMarks.STRING);
StreamUtils.writeString(out, (String) obj);
return;
}
throw new RuntimeException(Calc.className(obj) + " can't be stored to Ion storage.");
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
}
|
MightyPork/tortuga-spritegen
|
src/com/porcupine/ion/Ion.java
|
Java
|
bsd-2-clause
| 5,679 |
// Copyright (c) 2014, ์๊ฒฝํ
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @file MainWnd.h
* @date 2015. 9. 17.
* @author dlarudgus20
* @copyright The BSD (2-Clause) License
*/
#ifndef MAINWND_H_
#define MAINWND_H_
#include "Camera.h"
class ShadowMap;
class Scene;
class MainWnd : private ext::noncopyable
{
public:
static std::unique_ptr<MainWnd> createInstance();
private:
GLFWwindow *m_wnd;
GLsizei m_width, m_height;
std::unique_ptr<ShadowMap> m_pShadowMap;
glm::mat4 m_projection;
Camera m_camera;
double m_deltaTime = 0.0;
int m_fps = 0;
bool m_isFirstMouse = true;
float m_prevMouseX = 0.0f, m_prevMouseY = 0.0f;
std::unique_ptr<Scene> m_pScene;
MainWnd();
public:
~MainWnd();
bool create();
bool initialize();
void loop();
void loopManualFPS();
private:
void initCallback();
void render();
void idle();
void calcProjection();
void onMouseCursorPos(double xpos, double ypos);
void onFrameBufferSize(int width, int height);
void onWindowClose();
};
#endif /* MAINWND_H_ */
|
dlarudgus20/cpfps
|
src/MainWnd.h
|
C
|
bsd-2-clause
| 2,398 |
/*
* Copyright (c) 2010 .SE (The Internet Infrastructure Foundation)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*****************************************************************************
RandomTests.cpp
Contains test cases to C_SeedRandom and C_GenerateRandom
*****************************************************************************/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <cppunit/extensions/HelperMacros.h>
#include "RandomTests.h"
#include "testconfig.h"
CPPUNIT_TEST_SUITE_REGISTRATION(RandomTests);
void RandomTests::setUp()
{
// printf("\nRandomTests\n");
#ifndef _WIN32
setenv("SOFTHSM2_CONF", "./softhsm2.conf", 1);
#else
setenv("SOFTHSM2_CONF", ".\\softhsm2.conf", 1);
#endif
CK_UTF8CHAR pin[] = SLOT_0_SO1_PIN;
CK_ULONG pinLength = sizeof(pin) - 1;
CK_UTF8CHAR label[32];
memset(label, ' ', 32);
memcpy(label, "token1", strlen("token1"));
// (Re)initialize the token
CK_RV rv = C_Initialize(NULL_PTR);
CPPUNIT_ASSERT(rv == CKR_OK);
rv = C_InitToken(SLOT_INIT_TOKEN, pin, pinLength, label);
CPPUNIT_ASSERT(rv == CKR_OK);
C_Finalize(NULL_PTR);
}
void RandomTests::tearDown()
{
C_Finalize(NULL_PTR);
}
void RandomTests::testSeedRandom()
{
CK_RV rv;
CK_SESSION_HANDLE hSession;
CK_BYTE seed[] = {"Some random data"};
// Just make sure that we finalize any previous tests
C_Finalize(NULL_PTR);
rv = C_SeedRandom(CK_INVALID_HANDLE, seed, sizeof(seed));
CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED);
rv = C_Initialize(NULL_PTR);
CPPUNIT_ASSERT(rv == CKR_OK);
rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession);
CPPUNIT_ASSERT(rv == CKR_OK);
rv = C_SeedRandom(hSession, NULL_PTR, sizeof(seed));
CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD);
rv = C_SeedRandom(hSession, seed, sizeof(seed));
CPPUNIT_ASSERT(rv == CKR_OK);
rv = C_SeedRandom(hSession, seed, sizeof(seed));
CPPUNIT_ASSERT(rv == CKR_OK);
}
void RandomTests::testGenerateRandom()
{
CK_RV rv;
CK_SESSION_HANDLE hSession;
CK_BYTE randomData[40];
// Just make sure that we finalize any previous tests
C_Finalize(NULL_PTR);
rv = C_GenerateRandom(CK_INVALID_HANDLE, randomData, 40);
CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED);
rv = C_Initialize(NULL_PTR);
CPPUNIT_ASSERT(rv == CKR_OK);
rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession);
CPPUNIT_ASSERT(rv == CKR_OK);
rv = C_GenerateRandom(hSession, NULL_PTR, 40);
CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD);
rv = C_GenerateRandom(hSession, randomData, 40);
CPPUNIT_ASSERT(rv == CKR_OK);
rv = C_GenerateRandom(hSession, randomData, 40);
CPPUNIT_ASSERT(rv == CKR_OK);
}
|
Doctor-love/SoftHSMv2
|
src/lib/test/RandomTests.cpp
|
C++
|
bsd-2-clause
| 3,911 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: |
Returns a boolean value (not a Boolean object) computed by
ToBoolean(value)
esid: sec-terms-and-definitions-boolean-value
es5id: 15.6.1.1_A1_T1
description: >
Used values 1, new String("1"), new Object(1) and called without
argument
---*/
//CHECK#1
if (typeof Boolean() !== "boolean") {
$ERROR('#1: typeof Boolean() should be "boolean", actual is "' + typeof Boolean() + '"');
}
//CHECK#2
if (typeof Boolean(1) !== "boolean") {
$ERROR('#2: typeof Boolean(1) should be "boolean", actual is "' + typeof Boolean(1) + '"');
}
//CHECK#3
if (typeof Boolean(new String("1")) !== "boolean") {
$ERROR('#3: typeof Boolean(new String("1")) should be "boolean", actual is "' + typeof Boolean(new String("1")) + '"');
}
//CHECK#4
if (typeof Boolean(new Object(1)) !== "boolean") {
$ERROR('#4: typeof Boolean(new Object(1)) should be "boolean", actual is "' + typeof Boolean(new Object(1)) + '"');
}
|
sebastienros/jint
|
Jint.Tests.Test262/test/built-ins/Boolean/S15.6.1.1_A1_T1.js
|
JavaScript
|
bsd-2-clause
| 1,061 |
{% extends "core/base.html" %}
{% load i18n %}
{% block headtitle %}
<h1>{% trans "Scope Management" %}</h1>
<p>{{organisation.name}}</p>
{% endblock %}
{% block js %}
$(document).ready(function(){
$("table#scopeManagementTable").tablesorter({ sortList: [[0,0]], headers: {4:{sorter: false}}});
});
{% endblock %}
{% block content %}
{% include "organisation/navigation.html" %}
<script type="text/javascript" src="{{MEDIA_URL}}js/jquery.tablesorter.min.js"></script>
<div style="margin-bottom:10px;float:left">
<fieldset style="padding:0px;">
<input type="text" style="width:200px;" id="filter" value="{% trans "Filter by any field.." %}" />
</input>
</fieldset>
</div>
<script type="text/javascript">
cache = [];
cache['_all'] = $.parseJSON('{{json_cache|safe}}');
cache['terms'] = []
updateTable = function(response, all) {
$('table#scopeManagementTable tbody').html('');
$.each(response, function(index, obj){
var html = '<tr style="cursor:pointer;" onclick="document.location=\'/_/organisation/{{organisation.pk}}/scope_mgmt/'+obj.pk+'\';">';
html+= '<td>'+obj.pk+'</td>';
html+= '<th>'+obj.name+'</th>';
html+= '<td>'+obj.courses+'</td>';
html+= '<td style="text-align:right">'+obj.users+'</td>';
html+= '</tr>';
$('table#scopeManagementTable tbody').append(html);
});
};
$('#filter').click(function() {
$(this).val('');
}).keyup(function()ย {
term_value = $(this).val();
if (term_value == '') {
updateTable(cache['_all'], true);
return;
}
if (typeof(cache['terms'][term_value]) != 'undefined') {
updateTable(cache['terms'][term_value]);
} else {
$.ajax({
url: '{% url organisation-scope-mgmt-filter organisation.pk %}',
dataType: 'json',
data: 'term='+term_value,
success: function(response) {
cache['terms'][term_value] = response
updateTable(response);
}
});
}
});
</script>
<div style="margin-bottom:10px;float:right;"><a class="btn" href="{% url organisation-scope-mgmt-create organisation.pk %}">{% trans "Create new scope" %}</a></div>
<br style="clear:both" />
<table class="zebra-striped condensed-table" id="scopeManagementTable">
<thead>
<tr>
<th style="width:15px" class="header">#</th>
<th style="width:175px" class="blue header">{% trans "Name" %}</th>
<th class="blue header">{% trans "Courses" %}</th>
<th style="width:50px;text-align:right" class="blue header">{% trans "Users" %}</th>
</tr>
</thead>
<tbody>
{% for scope in scopes %}
<tr style="cursor:pointer;" onclick="document.location='{% url organisation-scope-mgmt-edit organisation.pk scope.pk %}';">
<td>{{scope.pk}}</td>
<th>{{scope.name}}</th>
<td style="font-size:small">
{% for course in scope.getCourses %}
{{course.name}}{% if not forloop.last %}, {% endif %}
{% endfor %}
</td>
<td style="text-align:right">
{{scope.getUsersAssigned}}
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
|
vLj2/docman
|
templates/organisation/scope_mgmt.html
|
HTML
|
bsd-2-clause
| 2,957 |
/* Generated By:JJTree: Do not edit this line. ASTLTNode.java */
public class ASTLTNode extends SimpleNode {
public ASTLTNode(int id) {
super(id);
}
public ASTLTNode(SPLParser p, int id) {
super(p, id);
}
}
|
aijunbai/skipoominijool
|
doc/javacc/javacc-examples/Interpreter/ASTLTNode.java
|
Java
|
bsd-2-clause
| 226 |
/*
* Copyright (c) 2014. Real Time Genomics Limited.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rtg.util.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import com.rtg.util.diagnostic.Diagnostic;
import com.rtg.util.test.FileHelper;
import junit.framework.TestCase;
/**
*/
public class AsynchInputStreamTest extends TestCase {
private static final String EXAMPLE1 = "abc\ndef ghi\n";
AsynchInputStream getStream(File file, String text) throws IOException {
if (text != null) {
FileUtils.stringToFile(text, file);
}
return new AsynchInputStream(new FileInputStream(file));
}
public void testReadSmall() throws IOException {
final File file = File.createTempFile("test", "gzipasynch");
try {
try (AsynchInputStream input = getStream(file, EXAMPLE1)) {
final byte[] buf = new byte[100];
assertEquals(12, input.read(buf));
for (int i = 0; i < EXAMPLE1.length(); ++i) {
assertEquals(EXAMPLE1.charAt(i), (char) buf[i]);
}
final int exp = -1;
assertEquals(exp, input.read(buf));
}
} finally {
assertTrue(FileHelper.deleteAll(file));
}
}
public void testEarlyClose() throws IOException {
Diagnostic.setLogStream();
final File file = File.createTempFile("test", "gzipasynch");
try {
final AsynchInputStream input = getStream(file, EXAMPLE1);
input.close(); // check that this does not throw an exception
// Note: it would be nice to check that the close has stopped the
// input from being read, but we do not know how far the thread has
// already read, so there is a race condition if we uncomment the
// following lines. (It fails on some linux machines, but not others).
// Is there any nice way of checking that the early close is working?
// final byte[] buf = new byte[100];
// assertEquals(-1, input.read(buf));
} finally {
assertTrue(FileHelper.deleteAll(file));
}
}
public void testMarkNotSupported() throws IOException {
Diagnostic.setLogStream();
final File file = File.createTempFile("test", "gzipasynch");
try {
try (AsynchInputStream input = getStream(file, EXAMPLE1)) {
assertFalse(input.markSupported());
}
} finally {
assertTrue(FileHelper.deleteAll(file));
}
}
public void testEmpty() throws IOException {
Diagnostic.setLogStream();
final File file = File.createTempFile("test", "gzipasynch");
try {
try (AsynchInputStream in = getStream(file, null)) {
assertEquals(1024 * 1024, in.mQueue.maxSize());
final byte[] buf = new byte[1];
assertEquals(-1, in.read(buf, 0, 1));
}
} finally {
assertTrue(FileHelper.deleteAll(file));
}
}
//Testing the Self-suppression problem
public void testExceptionHandling() {
final byte[] buff = new byte[3];
try {
try (final AsynchInputStream stream = new AsynchInputStream(new InputStream() {
int mNum = 2;
@Override
public int read() throws IOException {
if (mNum > 0) {
return mNum--;
} else {
throw new IOException("Expected");
}
}
})) {
final int b = stream.read(buff, 0, 3);
final int n = stream.read(buff, 0, 1);
//These assert statements should not be reached, the second read statement should be throwing an exception
//They are here because findbugs does not like ignoring the return value of a method
assertEquals(2, b);
assertEquals(-1, n);
}
fail("Should have thrown an IOException");
} catch (IOException e) {
assertEquals("Expected", e.getMessage());
}
}
}
|
RealTimeGenomics/rtg-tools
|
test/com/rtg/util/io/AsynchInputStreamTest.java
|
Java
|
bsd-2-clause
| 5,118 |
---
layout: post
title: "Writing my first gem - Bit Price"
date: 2014-02-12 17:40:41
comments: true
---
At the Flatiron School weโve been taught that the structures and syntax of programming are just that, structures. Just like a building is only as valuable as the people you put in it and what you use it for, the structures of programming are only as valuable as the programs you make with them.
Over the last couple days we covered diverse topics such as web scraping and RubyGems. I decided to implement both of these skills in one project in order to reinforce what weโve covered in lectures.
Web scraping is a broad topic that Iโll definitely be writing about more thoroughly in future posts, but for now letโs just define it as โgathering data from a website and bringing it into your program.โ Anything that can be viewed through a browser can (theoretically) be scraped. In the Ruby community, most web scraping is done through a gem called Nokogiri.
A RubyGem, or gem for short, is a packaged piece of code that can be passed around to different computers. If I write a ruby file that I want to share with the world, I want to make it as convenient as possible for others to access and utilize my code. Thereโs a fantastic project called RubyGems that allows people to easily publish their gems for others to use. In this post, Iโm going to explore how I published my first gem and what improvements I still need to make.
First, before publishing a gem weโre going to assume that you have a working Ruby file that you want to share with the world. The gem can be as simple as printing โHello Worldโ to the screen or complicated as a Ruby on Rails project. For this project, I decided to write a small scraper that uses Nokogiri to grab the Bitcoin buy and sell prices from Coinbaseโs website.
## Bit_Price: My First Gem
Below is the actual Ruby code that is run when you execute the gem I created. The file is called bit_price.rb and is packaged up with the gem. If youโve never seen Ruby code (or any code at all) this might look a little unfamiliar to you but thatโs OK, you donโt have to understand this code to learn how to create a gem.
```ruby
require "nokogiri"
require "open-uri"
def bit_price
page = Nokogiri::HTML(open("https://coinbase.com/charts"))
prices = page.css("div.page-header h2.pull-right strong").text.split("$").reject(&:empty?)
puts
puts "The Current Bitcoin Prices Are:"
puts "Buy Price: $#{prices[0]}"
puts "Sell Price: $#{prices [1]}"
puts
puts "Prices provided by www.coinbase.com/charts"
end
```
The Nokigiri gem scrapes the prices from the Coinbase site using their HTML tags and CSS selectors. For a quick recap, every website has โtagsโ which tells your browser how to render the page and CSS selectors which allow you to style your content. Coinbase actually names their CSS selectors for buy and sell prices with identical names, which meant that when I tried to get the text of the name I was given both the buy and sell prices. To get around this, I had to split the text into an array using the โ$โ as the delimiter and delete the blank string that it added to the array.
If none of that made sense to you, thatโs OK. Just keep in mind that your gem can do anything that you want it to, mine just happens to grab two numbers from a website and prints them to a screen.
Getting Started with RubyGems
To get started with RubyGems, I did a Google search and landed on the official instruction page for RubyGems. The guide is very helpfully written and made it easy to push up the gem.
The first thing I had to was reorganize my code. I called my main folder โbitcoin_priceโ. The RubyGems website expects that you will have a folder at the root of your project (the main folder where your project files are) called lib/ where your the Ruby file you just created will live. Additionally, you will need a .gemspec file in your main project directory with the Gem name so letโs create that now. To create a blank file just run:
```bash
$ touch bit_price.gemspec
```
Once youโve reorganized your files, your structure should look something like this:
```bash
% bitcoin_price
โโโ bit_price.gemspec
โโโ lib
โโโ bit_price.rb
```
Next you should open up the blank .gemspec file in your favorite text editor (I use Sublime Text) and edit it with the following code, substituting your information where appropriate.
```ruby
Gem::Specification.new do |s|
s.name = "bit_price"
s.version = "0.0.2"
s.executables << "bit_price"
s.date = "2014-02-12"
s.summary = "Bitcoin Prices from Your Terminal"
s.description = "Get the Bitcoin price easily from your terminal"
s.authors = ["Daniel Spector"]
s.email = '[email protected]'
s.files = ["lib/bit_price.rb"]
s.homepage =
"http://rubygems.org/gems/bit_price"
s.license = 'MIT'
s.add_runtime_dependency "nokogiri", [">=0"]
end
```
One thing to note is the version name. If you previously pushed your gem up to RubyGems with an identical version number and then make changes, it will reject your update. Each push has to have a unique version number. You'll notice that thereโs an executables file right under version. Weโll cover that in a bit. Mostly you want to fill out the information for your gem including your personal information such as author and email. Youโll also see that weโre adding a runtime dependency for Nokogiri. This will install Nokogiri on the userโs computer if itโs not installed already.
Weโre going to create one more file which will make it much more convenient for people to access our gem. We need to create an executable file in a bin/ folder simply called โbit_priceโ that will allow people to run the code from the command line. For my project I created the following structure:
```bash
% bitcoin_price
โโโ bin
โ โโโ bit_price
โโโ bit_price.gemspec
โโโ lib
โโโ bit_price.rb
```
In bin/bit_price I created a simple file that called our bit_price.rb file and executed it.
```ruby
#!/usr/bin/env ruby
require "bit_price"
bit_price
```
Notice that I named my method bit_price in my ```bit_price.rb``` file which has to match the executable call shown above. This will be equivalent to people running
```bash
$ ruby bit_price.rb
```
on their command line.
Now weโre all set up and weโre ready to test our gem!
To setup my gem and allow me to test it, I ran the following two commands at the root of my project directory.
```bash
$ gem build bit_price.gemspec
$ gem install ./bit_price-0.0.2.gem
```
Note that the version number has to match what you put in your bit_price.gemspec file.
Now you should be able to run your file simply by typing ```$ bit_price```.
If that doesnโt work, you might have to enter irb, require the gem, and then run it.
```bash
$ irb
>> require 'bit_price'
=> true
>> bit_price
```
Assuming you get the output youโre looking for, you should be ready to distribute your gem.
## Distributing Your Gem: Getting your gems up on RubyGems
Now weโre going to get our gems up on RubyGems so anyone can find and download it. First, navigate to the RubyGems and sign up. Remember the handle and password that you enterโโโit will be important in a minute. Once you sign up, open a new tab in your browser and go the following link:
https://rubygems.org/api/v1/api_key.yaml
Youโll be brought to an authentication screen. Type in the handle/username that you set up before. This should automatically download a file called api_key.yaml file to your computer. Youโre going to need to move this file to your .gem folder and rename it to CREDENTIALS with the following commands. Assuming your download defaulted to your Downloads folder, run the following:
```bash
$ mv ~/Downloads/api_key.yaml ~/.gem
$ cd ~/.gem
$ mv api_key.yaml CREDENTIALS
```
Once youโve run those commands you should be all set up to push your gem to RubyGems! Simply run the command below and you should see the following output.
```bash
$ gem push bit_price-0.0.2.gem
```
which should (hopefully) result in:
```bash
Pushing gem to RubyGems.orgโฆ
Successfully registered gem: bit_price(0.0.2)
```
Take a small break. Youโve accomplished a lot. Once you come back, your gem should be available for everyone to see on the RubyGems website. A simple way to ensure that youโve successfully published your gem is to type:
```bash
$ gem list -r bit_price
*** REMOTE GEMS ***
bit_price (0.0.2)
```
Once youโve confirmed that your gem has been successfully uploaded, anyone with the RubyGems package manager installed (it comes standard with Ruby) should be able to run
```bash
$ gem install bit_price
```
and then
```bash
$ bit_price
```
to run the program. Now all anyone has to do is to type your method name and see the output of of your program from anywhere in their terminal.
```bash
$ bit_price
The Current Bitcoin Prices Are:
Buy Price: $676.69
Sell Price: $674.66
Prices provided by www.coinbase.com/charts
```
Great job! Your gem is now live for anyone to download. Make sure to put your code up on Github so others can comment and improve on your work. The power of open source is incredible.
## A To-Do list for this gem
A couple quick caveats and some things to consider when writing your own gem.
It has no tests and you should always test your code in a separate spec file before you publish. I like RSpec, itโs nearly magical.
It depends on Nokogiri to run. Since I already have Nokogiri installed, I had no issues with the program but other people might have issues installing Nokogiri when they run your program. If anyone has any feedback on this I would love to hear it.
Make sure your gem name isnโt taken already before you try to publish! Your push to RubyGems will not work if the name is taken.
You should add a license and a README to the file so you protect yourself and be able to guide new users with how to run your program.
I had a lot of fun learning gems and I hope you found this useful. You can find the completed source code at https://github.com/danielspector/bitcoin_price
As always I would love your feedback on the post. Follow me on Twitter [@danielspecs](https://www.twitter.com/danielspecs).
A huge thanks to Sam Schlinkert for reviewing this post and fixing my sometimes inelegant choice of words.
Thanks for reading!
|
danielspector/danielspector.github.io
|
_posts/2014-02-12-writing-my-first-gem-bit-price.markdown
|
Markdown
|
bsd-2-clause
| 10,391 |
// Copyright 2012 Google Inc. All Rights Reserved.
//
// This file declares INTERNAL parts of the Split API that are inline/templated
// or otherwise need to be available at compile time. The main two abstractions
// defined in here are
//
// - SplitIterator<>
// - Splitter<>
//
// Everything else is plumbing for those two.
//
// DO NOT INCLUDE THIS FILE DIRECTLY. Use this file by including
// strings/split.h.
//
// IWYU pragma: private, include "strings/split.h"
#ifndef STRINGS_SPLIT_INTERNAL_H_
#define STRINGS_SPLIT_INTERNAL_H_
#include <iterator>
#include <map>
using std::map;
#include <vector>
using std::vector;
#include "base/port.h"
#include "base/type_traits.h" // for LANG_CXX11
#include "strings/stringpiece.h"
#ifdef LANG_CXX11
// This must be included after "base/port.h", which defines LANG_CXX11.
#include <initializer_list> // NOLINT(build/include_order)
#endif // LANG_CXX11
namespace strings {
namespace internal {
// The default Predicate object, which doesn't filter out anything.
struct NoFilter {
bool operator()(StringPiece /* ignored */) {
return true;
}
};
// This class splits a string using the given delimiter, returning the split
// substrings via an iterator interface. An optional Predicate functor may be
// supplied, which will be used to filter the split strings: strings for which
// the predicate returns false will be skipped. A Predicate object is any
// functor that takes a StringPiece and returns bool. By default, the NoFilter
// Predicate is used, which does not filter out anything.
//
// This class is NOT part of the public splitting API.
//
// Usage:
//
// using strings::delimiter::Literal;
// Literal d(",");
// for (SplitIterator<Literal> it("a,b,c", d), end(d); it != end; ++it) {
// StringPiece substring = *it;
// DoWork(substring);
// }
//
// The explicit single-argument constructor is used to create an "end" iterator.
// The two-argument constructor is used to split the given text using the given
// delimiter.
template <typename Delimiter, typename Predicate = NoFilter>
class SplitIterator
: public std::iterator<std::input_iterator_tag, StringPiece> {
public:
// Two constructors for "end" iterators.
explicit SplitIterator(Delimiter d)
: delimiter_(d), predicate_(), is_end_(true) {}
SplitIterator(Delimiter d, Predicate p)
: delimiter_(d), predicate_(p), is_end_(true) {}
// Two constructors taking the text to iterator.
SplitIterator(StringPiece text, Delimiter d)
: text_(text), delimiter_(d), predicate_(), is_end_(false) {
++(*this);
}
SplitIterator(StringPiece text, Delimiter d, Predicate p)
: text_(text), delimiter_(d), predicate_(p), is_end_(false) {
++(*this);
}
StringPiece operator*() { return curr_piece_; }
StringPiece* operator->() { return &curr_piece_; }
SplitIterator& operator++() {
do {
if (text_.end() == curr_piece_.end()) {
// Already consumed all of text_, so we're done.
is_end_ = true;
return *this;
}
StringPiece found_delimiter = delimiter_.Find(text_);
assert(found_delimiter.data() != NULL);
assert(text_.begin() <= found_delimiter.begin());
assert(found_delimiter.end() <= text_.end());
// found_delimiter is allowed to be empty.
// Sets curr_piece_ to all text up to but excluding the delimiter itself.
// Sets text_ to remaining data after the delimiter.
curr_piece_.set(text_.begin(), found_delimiter.begin() - text_.begin());
text_.remove_prefix(found_delimiter.end() - text_.begin());
} while (!predicate_(curr_piece_));
return *this;
}
SplitIterator operator++(int /* postincrement */) {
SplitIterator old(*this);
++(*this);
return old;
}
bool operator==(const SplitIterator& other) const {
// Two "end" iterators are always equal. If the two iterators being compared
// aren't both end iterators, then we fallback to comparing their fields.
// Importantly, the text being split must be equal and the current piece
// within the text being split must also be equal. The delimiter_ and
// predicate_ fields need not be checked here because they're template
// parameters that are already part of the SplitIterator's type.
return (is_end_ && other.is_end_) ||
(is_end_ == other.is_end_ &&
text_ == other.text_ &&
text_.data() == other.text_.data() &&
curr_piece_ == other.curr_piece_ &&
curr_piece_.data() == other.curr_piece_.data());
}
bool operator!=(const SplitIterator& other) const {
return !(*this == other);
}
private:
// The text being split. Modified as delimited pieces are consumed.
StringPiece text_;
Delimiter delimiter_;
Predicate predicate_;
bool is_end_;
// Holds the currently split piece of text. Will always refer to string data
// within text_. This value is returned when the iterator is dereferenced.
StringPiece curr_piece_;
};
// Declares a functor that can convert a StringPiece to another type. This works
// for any type that has a constructor (explicit or not) taking a single
// StringPiece argument. A specialization exists for converting to string
// because the underlying data needs to be copied. In theory, these
// specializations could be extended to work with other types (e.g., int32), but
// then a solution for error reporting would need to be devised.
template <typename To>
struct StringPieceTo {
To operator()(StringPiece from) const {
return To(from);
}
};
// Specialization for converting to string.
template <>
struct StringPieceTo<std::string> {
std::string operator()(StringPiece from) const {
return from.ToString();
}
};
// Specialization for converting to *const* std::string.
template <>
struct StringPieceTo<const std::string> {
std::string operator()(StringPiece from) const {
return from.ToString();
}
};
#ifdef LANG_CXX11
// IsNotInitializerList<T>::type exists iff T is not an initializer_list. More
// details below in Splitter<> where this is used.
template <typename T>
struct IsNotInitializerList {
typedef void type;
};
template <typename T>
struct IsNotInitializerList<std::initializer_list<T> > {};
#endif // LANG_CXX11
// This class implements the behavior of the split API by giving callers access
// to the underlying split substrings in various convenient ways, such as
// through iterators or implicit conversion functions. Do not construct this
// class directly, rather use the Split() function instead.
//
// Output containers can be collections of either StringPiece or string objects.
// StringPiece is more efficient because the underlying data will not need to be
// copied; the returned StringPieces will all refer to the data within the
// original input string. If a collection of string objects is used, then each
// substring will be copied.
//
// An optional Predicate functor may be supplied. This predicate will be used to
// filter the split strings: only strings for which the predicate returns true
// will be kept. A Predicate object is any unary functor that takes a
// StringPiece and returns bool. By default, the NoFilter predicate is used,
// which does not filter out anything.
template <typename Delimiter, typename Predicate = NoFilter>
class Splitter {
public:
typedef internal::SplitIterator<Delimiter, Predicate> Iterator;
Splitter(StringPiece text, Delimiter d)
: begin_(text, d), end_(d) {}
Splitter(StringPiece text, Delimiter d, Predicate p)
: begin_(text, d, p), end_(d, p) {}
// Range functions that iterate the split substrings as StringPiece objects.
// These methods enable a Splitter to be used in a range-based for loop in
// C++11, for example:
//
// for (StringPiece sp : my_splitter) {
// DoWork(sp);
// }
const Iterator& begin() const { return begin_; }
const Iterator& end() const { return end_; }
#ifdef LANG_CXX11
// Support for default template arguments for function templates was added in
// C++11, but it is not allowed if compiled in C++98 compatibility mode. Since
// this code is under a LANG_CXX11 guard, we can safely ignore the
// -Wc++98-compat flag and use default template arguments on the implicit
// conversion operator below.
//
// This use of default template arguments on a function template was approved
// by tgs and sanjay on behalf of the c-style-arbiters in email thread
//
// All compiler flags are first saved with a diagnostic push and restored with a
// diagnostic pop below.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpragmas"
#pragma GCC diagnostic ignored "-Wc++98-compat"
// Uses SFINAE to restrict conversion to container-like types (by testing for
// the presence of a const_iterator member type) and also to disable
// conversion to an initializer_list (which also has a const_iterator).
// Otherwise, code compiled in C++11 will get an error due to ambiguous
// conversion paths (in C++11 vector<T>::operator= is overloaded to take
// either a vector<T> or an initializer_list<T>).
//
// This trick was taken from util/gtl/container_literal.h
template <typename Container,
typename IsNotInitializerListChecker =
typename IsNotInitializerList<Container>::type,
typename ContainerChecker =
typename Container::const_iterator>
operator Container() {
return SelectContainer<Container, is_map<Container>::value>()(this);
}
// Restores diagnostic settings, i.e., removes the "ignore" on -Wpragmas and
// -Wc++98-compat.
#pragma GCC diagnostic pop
#else
// Not under LANG_CXX11
template <typename Container>
operator Container() {
return SelectContainer<Container, is_map<Container>::value>()(this);
}
#endif // LANG_CXX11
template <typename First, typename Second>
operator std::pair<First, Second>() {
return ToPair<First, Second>();
}
private:
// is_map<T>::value is true iff there exists a type T::mapped_type. This is
// used to dispatch to one of the SelectContainer<> functors (below) from the
// implicit conversion operator (above).
template <typename T>
struct is_map {
template <typename U> static base::big_ test(typename U::mapped_type*);
template <typename> static base::small_ test(...);
static const bool value = (sizeof(test<T>(0)) == sizeof(base::big_));
};
// Base template handles splitting to non-map containers
template <typename Container, bool>
struct SelectContainer {
Container operator()(Splitter* splitter) const {
return splitter->template ToContainer<Container>();
}
};
// Partial template specialization for splitting to map-like containers.
template <typename Container>
struct SelectContainer<Container, true> {
Container operator()(Splitter* splitter) const {
return splitter->template ToMap<Container>();
}
};
// Inserts split results into the container. To do this the results are first
// stored in a vector<StringPiece>. This is where the input text is actually
// "parsed". The elements in this vector are then converted to the requested
// type and inserted into the requested container. This is handled by the
// ConvertContainer() function.
//
// The reason to use an intermediate vector of StringPiece is so we can learn
// the needed capacity of the output container. This is needed when the output
// container is a vector<string> in which case resizes can be expensive due to
// copying of the ::string objects.
//
// At some point in the future we might add a C++11 move constructor to
// ::string, in which case the vector resizes are much less expensive and the
// use of this intermediate vector "v" can be removed.
template <typename Container>
Container ToContainer() {
vector<StringPiece> v;
for (Iterator it = begin(); it != end_; ++it) {
v.push_back(*it);
}
Container c;
ConvertContainer(v, &c);
return c;
}
// The algorithm is to insert a new pair into the map for each even-numbered
// item, with the even-numbered item as the key with a default-constructed
// value. Each odd-numbered item will then be assigned to the last pair's
// value.
template <typename Map>
Map ToMap() {
typedef typename Map::key_type Key;
typedef typename Map::mapped_type Data;
Map m;
StringPieceTo<Key> key_converter;
StringPieceTo<Data> val_converter;
typename Map::iterator curr_pair;
bool is_even = true;
for (Iterator it = begin(); it != end_; ++it) {
if (is_even) {
curr_pair = InsertInMap(std::make_pair(key_converter(*it), Data()), &m);
} else {
curr_pair->second = val_converter(*it);
}
is_even = !is_even;
}
return m;
}
// Returns a pair with its .first and .second members set to the first two
// strings returned by the begin() iterator. Either/both of .first and .second
// will be empty strings if the iterator doesn't have a corresponding value.
template <typename First, typename Second>
std::pair<First, Second> ToPair() {
StringPieceTo<First> first_converter;
StringPieceTo<Second> second_converter;
StringPiece first, second;
Iterator it = begin();
if (it != end()) {
first = *it;
if (++it != end()) {
second = *it;
}
}
return std::make_pair(first_converter(first), second_converter(second));
}
// Overloaded InsertInMap() function. The first overload is the commonly used
// one for most map-like objects. The second overload is a special case for
// multimap, because multimap's insert() member function directly returns an
// iterator, rather than a pair<iterator, bool> like map's.
template <typename Map>
typename Map::iterator InsertInMap(
const typename Map::value_type& value, Map* map) {
return map->insert(value).first;
}
// InsertInMap overload for multimap.
template <typename K, typename T, typename C, typename A>
typename std::multimap<K, T, C, A>::iterator InsertInMap(
const typename std::multimap<K, T, C, A>::value_type& value,
typename std::multimap<K, T, C, A>* map) {
return map->insert(value);
}
// Converts the container and elements to the specified types. This is the
// generic case. There is an overload of this function to optimize for the
// common case of a vector<string>.
template <typename Container>
void ConvertContainer(const std::vector<StringPiece>& vin, Container* c) {
typedef typename Container::value_type ToType;
internal::StringPieceTo<ToType> converter;
std::insert_iterator<Container> inserter(*c, c->begin());
for (size_t i = 0; i < vin.size(); ++i) {
*inserter++ = converter(vin[i]);
}
}
// Overload of ConvertContainer() that is optimized for the common case of a
// vector<string>. In this case, vector space is reserved, and a temp string
// is lifted outside the loop and reused inside the loop to minimize
// constructor calls and allocations. This resulted in about a 10% performance
// improvement in the Split2SplitStringUsing benchmark. We can revisit the
// need for this optimization in the future if/when ::string gains support for
// move semantics.
template <typename A>
void ConvertContainer(const vector<StringPiece>& vin,
vector<string, A>* vout) {
vout->reserve(vin.size());
string tmp; // reused inside the loop
for (size_t i = 0; i < vin.size(); ++i) {
vin[i].CopyToString(&tmp);
vout->push_back(tmp);
}
}
const Iterator begin_;
const Iterator end_;
};
} // namespace internal
} // namespace strings
#endif // STRINGS_SPLIT_INTERNAL_H_
|
romange/beeri
|
strings/split_internal.h
|
C
|
bsd-2-clause
| 15,731 |
{% extends "shop/base.html" %}
{% load staticfiles mezzanine_tags shop_tags rating_tags i18n %}
{% load likes_inclusion_tags %}
{% block meta_title %}{{ product.meta_title }}{% endblock %}
{% block body_id %}category{% endblock %}
{% block meta_keywords %}{% metablock %}
{% for keyword in product.keywords.all %}
{% if not forloop.first %}, {% endif %}
{{ keyword }}
{% endfor %}
{% endmetablock %}{% endblock %}
{% block meta_description %}{% metablock %}
{{ product.description }}
{% endmetablock %}{% endblock %}
{% block extra_css %}
{{ block.super }}
<link rel="stylesheet" href="{% static "mezzanine/css/magnific-popup.css" %}">
{% endblock %}
{% block extra_js %}
{{ block.super }}
<script>var variations = {{ variations_json|safe }};</script>
<script src="{% static "cartridge/js/product_variations.js" %}"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<script src="{% static "mezzanine/js/magnific-popup.js" %}"></script>
<script>
$(document).ready(function() {
$('#product-images-large').magnificPopup({
delegate: 'a',
type: 'image',
gallery: {
enabled: true,
}
});
});
</script>
{% endblock %}
{% block extra_head %}
<script>var variations = {{ variations_json|safe }};</script>
<script src="{% static "cartridge/js/product_variations.js" %}"></script>
{% endblock %}
{% block breadcrumb_menu %}
{% endblock %}
{% block main %}
{{ block.super }}
{% block title %}
{% editable product.title %}<h2>{{ product.title }}</h2>{% endeditable %}
{% endblock %}
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">
{% if images %}
{% spaceless %}
<ul id="product-images-large" class="list-unstyled list-inline">
{% for image in images %}
<li id="image-{{ image.id }}-large"{% if not forloop.first %}style="display:none;"{% endif %}>
<a class="product-image-large" href="{{ MEDIA_URL }}{{ image.file }}">
<img alt="{{ image.description }}" style="height:400px;width:360px;" src="{{ MEDIA_URL }}{% thumbnail image.file 0 300 %}" class="img-thumbnail img-responsive col-xs-12">
</a>
</li>
{% endfor %}
</ul>
{% if images|length != 1 %}
<ul id="product-images-thumb" class="list-unstyled list-inline">
{% for image in images %}
<li>
<a class="thumbnail" id="image-{{ image.id }}" href="{{ MEDIA_URL }}{{ image.file }}">
<img alt="{{ image.description }}" src="{{ MEDIA_URL }}{% thumbnail image.file 75 75 %}">
</a>
</li>
{% endfor %}
</ul>
{% endif %}
{% endspaceless %}
{% endif %}
<!-- {% likes product %} -->
<!-- AddThis Pro BEGIN -->
<!-- AddToAny BEGIN -->
<div class="a2a_kit a2a_kit_size_32 a2a_default_style">
<a class="a2a_dd" href="http://www.addtoany.com/share_save"></a>
<a class="a2a_button_facebook"></a>
<a class="a2a_button_twitter"></a>
<a class="a2a_button_google_plus"></a>
</div>
<script type="text/javascript" src="//static.addtoany.com/menu/page.js"></script>
<!-- AddToAny END -->
<!-- AddThis Pro END -->
</div>
<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">
<div class="panel panel-default checkout-panel">
{% if product.available and has_available_variations %}
<ul id="variations" class="list-unstyled">
{% for variation in variations %}
<li id="variation-{{ variation.sku }}"
{% if not variation.default %}style="display:none;"{% endif %}>
{% if variation.has_price %}
{% if variation.on_sale %}
<span class="old-price">{{ variation.unit_price|currency }}</span>
<div class ="insert"></div>
{% trans "On sale:" %}
{% endif %}
<span class="price">{{ variation.price|currency }}</span>
{% else %}
{% if has_available_variations %}
<span class="error-msg">
{% trans "The selected options are currently unavailable." %}
</span>
{% endif %}
{% endif %}
</li>
{% endfor %}
</ul>
{% errors_for add_product_form %}
<form method="post" id="add-cart" class="shop-form">
{% fields_for add_product_form %}
<div class="form-actions">
<input type="submit" class="btn btn-primary btn-lg pull-right" name="add_cart" value="{% trans "Buy" %}">
{% if settings.SHOP_USE_WISHLIST %}
<input type="submit" class="btn btn-default btn-lg pull-left" name="add_wishlist" value="{% trans "Save for later" %}">
{% endif %}
</div>
</form>
{% else %}
<p class="error-msg">{% trans "This product is currently unavailable." %}</p>
{% endif %}
</div>
<!--{% if settings.SHOP_USE_RATINGS %}
<div class="panel panel-default rating">
<div class="panel-body">{% rating_for product %}</div>
</div>
{% endif %} -->
<div class="panel panel-default checkout-panel">
{% editable product.content %}
{{ product.content|richtext_filters|safe }}
{% endeditable %}
</div>
<!-- end of the row-->
</div>
</div>
{% if related_products %}
<h2>{% trans "Related Products" %}</h2>
<div class="row related-products">
{% for product in related_products %}
<div class="col-xs-6 col-sm-4 col-md-3 product-thumb">
<a class="thumbnail" href="{{ product.get_absolute_url }}">
{% if product.image %}
<img src="{{ MEDIA_URL }}{% thumbnail product.image 90 90 %}">
{% endif %}
<div class="caption">
<h6>{{ product }}</h6>
<div class="price-info">
{% if product.has_price %}
{% if product.on_sale %}
<span class="old-price">{{ product.unit_price|currency }}</span>
{% trans "On sale:" %}
{% endif %}
<span class="price">{{ product.price|currency }}</span>
{% else %}
<span class="coming-soon">{% trans "Coming soon" %}</span>
{% endif %}
</div>
</div>
</a>
</div>
{% endfor %}
</div>
{% endif %}
{% endblock %}
|
BigAN/OztrendDelpoy
|
mezzanine_themes/oztrend/templates/shop/product.html
|
HTML
|
bsd-2-clause
| 6,494 |
/* @LICENSE(MUSLC_MIT) */
#include "libc.h"
void sethostent(int x)
{
}
void *gethostent()
{
return 0;
}
void endhostent(void)
{
}
weak_alias(sethostent, setnetent);
weak_alias(gethostent, getnetent);
weak_alias(endhostent, endnetent);
weak_alias(sethostent, setservent);
weak_alias(gethostent, getservent);
weak_alias(endhostent, endservent);
weak_alias(sethostent, setprotoent);
weak_alias(gethostent, getprotoent);
weak_alias(endhostent, endprotoent);
|
gapry/refos
|
libs/libmuslc/src/network/ent.c
|
C
|
bsd-2-clause
| 462 |
PY_VERSIONS = 2.6 2.7 3.2
.PHONY : .envs
test:
python setup.py test
$(eval .envs : $(foreach v,$(PY_VERSIONS),.envs/py$(v)))
$(eval test-envs : $(foreach v,$(PY_VERSIONS),test-$(v)))
.envs/py%:
mkdir -p .envs
virtualenv --distribute -p `which python$*` .envs/py$*
test-% :
./.envs/py$*/bin/python setup.py test
|
ericmoritz/boxmath
|
Makefile
|
Makefile
|
bsd-2-clause
| 320 |
๏ปฟusing System.Data.SqlClient;
using System.Linq;
using EIDSS.Reports.BaseControls.BaseDataSetTableAdapters;
namespace EIDSS.Reports.Document.Lim.Case {
public partial class TestValidationDataSet {
}
}
namespace EIDSS.Reports.Document.Lim.Case.TestValidationDataSetTableAdapters
{
public partial class sp_rep_LIM_CaseTestsValidationTableAdapter
{
private SqlTransaction m_Transaction;
internal SqlTransaction Transaction
{
get { return m_Transaction; }
set
{
m_Transaction = value;
sprepGetBaseParametersTableAdapter.SetTransaction(Adapter, CommandCollection, value);
}
}
internal int CommandTimeout
{
get { return CommandCollection.Select(c => c.CommandTimeout).FirstOrDefault(); }
set
{
foreach (SqlCommand command in CommandCollection)
{
command.CommandTimeout = value;
}
}
}
}
}
|
EIDSS/EIDSS-Legacy
|
EIDSS v5/vb/EIDSS/EIDSS.Reports/Document/Lim/Case/TestValidationDataSet.cs
|
C#
|
bsd-2-clause
| 1,112 |
๏ปฟ// Copyright (c) Wiesลaw ล oltรฉs. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// (from https://github.com/wieslawsoltes/ColorBlender)
namespace PaintLab.ColorBlender.Algorithms
{
public class Square : IAlgorithm
{
public Blend Match(HSV hsv)
{
Blend outp = new Blend();
outp.Colors[0] = new HSV(hsv);
var w = MathHelpers.HueToWheel(hsv.H);
HSV z = new HSV
{
H = MathHelpers.WheelToHue((w + 90) % 360),
S = hsv.S,
V = hsv.V
};
outp.Colors[1] = new HSV(z);
z.H = MathHelpers.WheelToHue((w + 180) % 360);
z.S = hsv.S;
z.V = hsv.V;
outp.Colors[2] = new HSV(z);
z.H = MathHelpers.WheelToHue((w + 270) % 360);
z.S = hsv.S;
z.V = hsv.V;
outp.Colors[3] = new HSV(z);
z.S = 0;
outp.Colors[4] = new HSV(z);
z.V = 100 - z.V;
outp.Colors[5] = new HSV(z);
return outp;
}
}
}
|
LayoutFarm/PixelFarm
|
src/PixelFarm/PaintLab.Color/ColorBlender/Algorithms/Square.cs
|
C#
|
bsd-2-clause
| 1,177 |
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* Pagination Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Pagination
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/libraries/pagination.html
*/
class Mypagination
{
//ๅบๆฌ้พๆฅๅฐๅ
var $base_url = '';
//ๆฐๆฎๆปๆฐ
var $total_rows = '';
//ๆฏ้กตๆกๆฐ
var $per_page = 20;
//่ฆๆพ็คบ็ๅทฆๅณ้พๆฅ็ไธชๆฐ
var $num_links = 5;
//ๅฝๅ้กตๆฐ
var $cur_page = 1;
//้ฆ้กตๅญ็ฌฆ
var $first_link = '';
//ไธไธ้กต็ๅญ็ฌฆ
var $next_link = 'ไธไธ้กต';
//ไธไธ้กต็ๅญ็ฌฆ
var $prev_link = 'ไธไธ้กต';
//ๆซ้กต็ๅญ็ฌฆ
var $last_link = '';
//ๅ้กตๆฐๆๅจ็uri็ๆฎตไฝ็ฝฎ
var $uri_segment = 3;
//ๅ้กตๅบๅๅผๅง็htmlๆ ็ญพ
var $full_tag_open = '<ul>';
//ๅ้กตๅบๅ็ปๆ็ๅhtmlๆ ็ญพ
var $full_tag_close = '</ul>';
//้ฆ้กตๅผๅง็htmlๆ ็ญพ
var $first_tag_open = '';
//้ฆ้กต็ปๆ็htmlๆ ็ญพ
var $first_tag_close = ' ';
//ๆซ้กตๅผๅง็htmlๆ ็ญพ
var $last_tag_open = ' ';
//ๆซ้กต็ปๆ็htmlๆ ็ญพ
var $last_tag_close = '';
//ๅฝๅ้กตๅผๅง็htmlๆ ็ญพ
var $cur_tag_open = ' <li>';
//ๅฝๅ้กต็ปๆ็htmlๆ ็ญพ
var $cur_tag_close = '</li>';
//ไธไธ้กตๅผๅง็htmlๆ ็ญพ
var $next_tag_open = '<li>';
//ไธไธ้กต็ปๆ็htmlๆ ็ญพ
var $next_tag_close = '</li>';
//ไธไธ้กตๅผๅง็htmlๆ ็ญพ
var $prev_tag_open = '<li>';
//ไธไธ้กต็ปๆ็htmlๆ ็ญพ
var $prev_tag_close = '</li>';
//โๆฐๅญโ้พๆฅ็ๆๅผๆ ็ญพ
var $num_tag_open = '<li>';
//โๆฐๅญโ้พๆฅ็็ปๆๆ ็ญพ
var $num_tag_close = '</li>';
var $page_query_string = TRUE;
var $query_string_segment = 'page';
var $page_mode = 'default';
//ๅญๅจไธๅ็บฟๆถ,้กต็ ๆๅจๆฐ็ปไธๆ ไฝ็ฝฎ
var $underline_uri_seg = -1;
//่ชๅฎไนๅฝๅ้กต็ ๏ผๅญๅจๆญคๅผๆฏ๏ผ็ณป็ปๅฐไธ่ชๅจๅคๆญๅฝๅ้กตๆฐ๏ผ้ป่ฎคไธๅฏ็จ
var $custom_cur_page = 0;
function __construct()
{
$this->Mypagination();
}
/**
* Constructor
*
* @access public
*/
function Mypagination()
{
if (file_exists(APPPATH . 'config/pagination.php')) {
require_once(APPPATH . 'config/pagination.php');
foreach ($config as $key => $val) {
$this->{$key} = $val;
}
}
log_message('debug', "MY_Pagination Class Initialized");
}
// ------------------------------------------------------------------------
/**
* ๅๅงๅๅๆฐ
* @see init()
* @param <array> $params ๅพ
ๅๅงๅ็ๅๆฐ
*/
function init($params = array())
{
if (count($params) > 0) {
foreach ($params as $key => $val) {
if (isset($this->$key)) {
$this->$key = $val;
}
}
}
}
// ------------------------------------------------------------------------
/**
* ๅๅปบๅ้กต้พๆฅ
* @see create_links()
* @param <boolean> $show_info ๆฏๅฆๆพ็คบๆปๆกๆฐ็ญไฟกๆฏ
* @return <string> $output
*/
function create_links($show_info = false, $top_info = false)
{
//ๅฆๆๆฒกๆ่ฎฐๅฝๆ่
ๆฏ้กตๆกๆฐไธบ0,ๅ่ฟๅ็ฉบ
if ($this->total_rows == 0 || $this->per_page == 0) {
return '';
}
//่ฎก็ฎๆป้กตๆฐ
$num_pages = ceil($this->total_rows / $this->per_page);
//ๅชๆไธ้กต,่ฟๅ็ฉบ
if ($num_pages == 1 && !$show_info) {
return '';
}
$CI = &get_instance();
//่ทๅๅฝๅ้กต็ผๅท
if ($CI->config->item('enable_query_strings') === TRUE || $this->page_query_string === TRUE) {
if ($CI->input->get($this->query_string_segment) != 0) {
$this->cur_page = $CI->input->get($this->query_string_segment);
$this->cur_page = (int)$this->cur_page;
}
} else {
if (intval($this->custom_cur_page) > 0) {
$this->cur_page = (int)$this->custom_cur_page;
} else {
$uri_segment = $CI->uri->segment($this->uri_segment, 0);
if (!empty($uri_segment)) {
$this->cur_page = $uri_segment;
//ๅฆๆๆไธๅ็บฟ
if ($this->underline_uri_seg >= 0) {
if (strpos($this->cur_page, '-') !== false) {
$arr = explode('-', $this->cur_page);
} else {
$arr = explode('_', $this->cur_page);
}
$this->cur_page = $arr[$this->underline_uri_seg];
unset($arr);
}
$this->cur_page = (int)$this->cur_page;
}
}
}
//ๅทฆๅณๆพ็คบ็้กต็ ไธชๆฐ
$this->num_links = (int)$this->num_links;
if ($this->num_links < 1) {
show_error('Your number of links must be a positive number.');
}
if (!is_numeric($this->cur_page) || $this->cur_page < 1) {
$this->cur_page = 1;
}
//ๅฆๆๅฝๅ้กตๆฐๅคงไบๆป้กตๆฐ,ๅ่ตๅผ็ปๅฝๅ้กตๆฐๆๅคงๅผ
if ($this->cur_page > $num_pages) {
$this->cur_page = $num_pages;
}
if ($CI->config->item('enable_query_strings') === TRUE || $this->page_query_string === TRUE) {
$this->base_url = rtrim($this->base_url) . '&' . $this->query_string_segment . '=';
} else {
$this->base_url = rtrim($this->base_url, '/') . '/';
}
if (strpos($this->base_url, "{page}") !== false) {
$this->page_mode = 'replace';
}
$output = $top_output = '';
//ๆฐๆฎๆป้ไฟกๆฏ
if ($show_info) {
$output = " ๅ
ฑ<b>" . $this->total_rows . "</b>ๆก่ฎฐๅฝ <span style='color:#ff0000;font-weight:bold'>{$this->cur_page}</span>/<b>" . $num_pages . "</b>้กต ๆฏ้กต<b>{$this->per_page}</b>ๆก ";
}
//ๆฐๆฎไฟกๆฏ๏ผๆพ็คบๅจไธ้ข๏ผไปฅไพๆ้
if ($top_info) {
$top_output = " ๅ
ฑ <b>" . $this->total_rows . "</b> ๆก่ฎฐๅฝ ็ฌฌ<span style='color:#ff0000;font-weight:bold'>{$this->cur_page}</span>้กต/ๅ
ฑ<b>" . $num_pages . "</b>้กต ";
}
//ๅคๆญๆฏๅฆ่ฆๆพ็คบ้ฆ้กต
// if ($this -> cur_page > $this -> num_links + 1) {
//
// $output .= $this -> first_tag_open . '<a href="' . $this -> makelink() . '">' . $this -> first_link . '</a>' . $this -> first_tag_close;
//
// }
//ๆพ็คบไธไธ้กต
if (!empty($this->cur_page)) {
$j = $this->cur_page - 1;
if ($j == 0) {
$output .= '<li class="active"><a href="#">' . $this->prev_link . '</a>' . $this->prev_tag_close;
} else {
$output .= $this->prev_tag_open . '<a href="' . $this->makelink($j) . '">' . $this->prev_link . '</a>' . $this->prev_tag_close;
}
}
//ๆพ็คบไธญ้ด้กต
for ($i = 1; $i <= $num_pages; $i++) {
if ($i < $this->cur_page - $this->num_links || $i > $this->cur_page + $this->num_links) {
continue;
}
//ๆพ็คบไธญ้ด้กตๆฐ
if ($this->cur_page == $i) {
//ๅฝๅ้กต
$output .= '<li class="active"><a href="#">' . $i . '</a>' . $this->num_tag_close;
} else {
$output .= $this->num_tag_open . '<a href="' . $this->makelink($i) . '">' . $i . '</a>' . $this->num_tag_close;
}
}
//ๆพ็คบไธไธ้กต
if ($this->cur_page < $num_pages) {
$k = $this->cur_page + 1;
$output .= $this->next_tag_open . '<a href="' . $this->makelink($k) . '">' . $this->next_link . '</a>' . $this->next_tag_close;
} else {
$output .= '<li class="active"><a href="#">' . $this->next_link . '</a>' . $this->next_tag_close;
}
//ๆพ็คบๅฐพ้กต
// if (($this -> cur_page + $this -> num_links) < $num_pages) {
//
// $output .= $this -> last_tag_open . '<a href="' . $this -> makelink($num_pages) . '">' . $this -> last_link . '</a>' . $this -> last_tag_close;
//
// }
$output = preg_replace("#([^:])//+#", "\\1/", $output);
$output = $this->full_tag_open . $output . $this->full_tag_close;
if ($top_info) {
return array($output, $top_output);
} else {
return $output;
}
}
// ------------------------------------------------------------------------
/**
* ๅๅปบ้พๆฅurlๅฐๅ
* @param <string> $str
* @return <string>
*/
function makelink($str = '')
{
if ($this->page_mode == 'default') {
return $this->_forsearch($this->base_url . $str);
} else {
$url = $this->base_url;
if ($str == 1) {
$url = str_replace('/{page}', '', $this->base_url);
}
$url = str_replace("{page}", $str, $url);
return $this->_forsearch($url);
}
}
// ------------------------------------------------------------------------
/**
* ๅค็urlๅฐๅ
* @see _forsearch()
* @param <string> $string pInfo
* @return <string>
*/
function _forsearch($string)
{
$length = strlen($string) - 1;
if ($string{$length} == '/') {
$string = rtrim($string, '/');
}
return site_url($string);
return $string;
}
// ------------------------------------------------------------------------
}
// ------------------------------------------------------------------------
// End Mypagination Class
/* End of file Mypagination.php */
/* Location: ./app/admin/libraries/Mypagination.php*/
|
Rand01ph/mondacm
|
app/admin/libraries/Mypagination.php
|
PHP
|
bsd-2-clause
| 10,698 |
#pragma once
#include <opencv2/core/core.hpp>
#include <string>
#include <vector>
#include "Frame.h"
using namespace std;
using namespace cv;
class ImageAnnotate
{
private:
ImageAnnotate(void);
~ImageAnnotate(void);
public:
static void annotate();
static void on_mouse(int event,int x,int y,int flags,void *ustc);
static int nextFrame();
static void draw();
static Mat image_display; //display image
static Mat image_tmp; //temp display image
static Frame frame; //current frame
static string filePath; //image file path
static string title; //window title
static int total_num; //totle image numbers
static int current_num; //current image number
};
|
zhongchong/OpenPD
|
Source/Annotation/ImageAnnotate.h
|
C
|
bsd-2-clause
| 702 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_raw_socket::shutdown_type</title>
<link rel="stylesheet" href="../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../../index.html" title="Asio">
<link rel="up" href="../basic_raw_socket.html" title="basic_raw_socket">
<link rel="prev" href="shutdown/overload2.html" title="basic_raw_socket::shutdown (2 of 2 overloads)">
<link rel="next" href="../basic_seq_packet_socket.html" title="basic_seq_packet_socket">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr><td valign="top"><img alt="asio C++ library" width="250" height="60" src="../../../asio.png"></td></tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="shutdown/overload2.html"><img src="../../../prev.png" alt="Prev"></a><a accesskey="u" href="../basic_raw_socket.html"><img src="../../../up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../home.png" alt="Home"></a><a accesskey="n" href="../basic_seq_packet_socket.html"><img src="../../../next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="asio.reference.basic_raw_socket.shutdown_type"></a><a class="link" href="shutdown_type.html" title="basic_raw_socket::shutdown_type">basic_raw_socket::shutdown_type</a>
</h4></div></div></div>
<p>
<span class="emphasis"><em>Inherited from socket_base.</em></span>
</p>
<p>
<a class="indexterm" name="idp102682304"></a>
Different ways a socket may be shutdown.
</p>
<pre class="programlisting"><span class="keyword">enum</span> <span class="identifier">shutdown_type</span>
</pre>
<p>
<a class="indexterm" name="idp102685840"></a>
<a class="indexterm" name="idp102686944"></a>
<a class="indexterm" name="idp102688048"></a>
</p>
<h6>
<a name="asio.reference.basic_raw_socket.shutdown_type.h0"></a>
<span><a name="asio.reference.basic_raw_socket.shutdown_type.values"></a></span><a class="link" href="shutdown_type.html#asio.reference.basic_raw_socket.shutdown_type.values">Values</a>
</h6>
<div class="variablelist">
<p class="title"><b></b></p>
<dl>
<dt><span class="term">shutdown_receive</span></dt>
<dd><p>
Shutdown the receive side of the socket.
</p></dd>
<dt><span class="term">shutdown_send</span></dt>
<dd><p>
Shutdown the send side of the socket.
</p></dd>
<dt><span class="term">shutdown_both</span></dt>
<dd><p>
Shutdown both send and receive on the socket.
</p></dd>
</dl>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2013 Christopher M. Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="shutdown/overload2.html"><img src="../../../prev.png" alt="Prev"></a><a accesskey="u" href="../basic_raw_socket.html"><img src="../../../up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../home.png" alt="Home"></a><a accesskey="n" href="../basic_seq_packet_socket.html"><img src="../../../next.png" alt="Next"></a>
</div>
</body>
</html>
|
laeotropic/HTTP-Proxy
|
deps/asio-1.10.1/doc/asio/reference/basic_raw_socket/shutdown_type.html
|
HTML
|
bsd-2-clause
| 3,692 |
#pragma once
#include <string>
#include <tuple>
namespace rc {
namespace detail {
/// Disables copying
#define RC_DISABLE_COPY(Class) \
Class(const Class &) = delete; \
Class &operator=(const Class &) = delete;
/// Disables moving
#define RC_DISABLE_MOVE(Class) \
Class(Class &&) = delete; \
Class &operator=(Class &&) = delete;
#define RC_GLUE2(a, b) a##b
/// Paste together the given arguments.
#define RC_GLUE(a, b) RC_GLUE2(a, b)
/// Unique identifier helper.
#define RC_UNIQUE(prefix) RC_GLUE(prefix, __LINE__)
/// Demangles a mangled C++
std::string demangle(const char *name);
/// Base case for `pushBackAll`
template <typename Collection>
void pushBackAll(Collection &collection) {
// Base case
}
/// Appends the given items to the end of the given collection.
///
/// @param collection The collection to append to.
/// @param item The first item.
/// @param items The rest of the items.
template <typename Collection, typename Item, typename... Items>
void pushBackAll(Collection &collection, Item &&item, Items &&... items) {
collection.push_back(std::forward<Item>(item));
pushBackAll(collection, std::forward<Items>(items)...);
}
/// Base case for `join`.
inline std::string join(const std::string &sep, const std::string str) {
return str;
}
/// Joins the given strings using the given separator.
///
/// @param sep The separator.
/// @param str The first string.
/// @param strings The rest of the strings.
template <typename... Strings>
std::string
join(const std::string &sep, const std::string &str, Strings... strings) {
return str + sep + join(sep, strings...);
}
template <typename TupleT, typename... Types>
struct TupleTailHelper;
template <typename TupleT>
struct TupleTailHelper<TupleT> {
static std::tuple<> tail(const TupleT &tuple) { return std::tuple<>(); }
};
template <typename TupleT, typename Type, typename... Types>
struct TupleTailHelper<TupleT, Type, Types...> {
static std::tuple<Type, Types...> tail(const TupleT &tuple) {
constexpr std::size_t tailHead =
std::tuple_size<TupleT>::value - (sizeof...(Types) + 1);
return std::tuple_cat(std::make_tuple(std::get<tailHead>(tuple)),
TupleTailHelper<TupleT, Types...>::tail(tuple));
}
};
/// Returns a copy of the given tuple without the first element.
template <typename Type, typename... Types>
std::tuple<Types...> tupleTail(const std::tuple<Type, Types...> &tuple) {
return TupleTailHelper<std::tuple<Type, Types...>, Types...>::tail(tuple);
}
/// Avalanching function.
/// Written in 2014 by Sebastiano Vigna ([email protected])
inline uint64_t avalanche(uint64_t x) {
x ^= x >> 33;
x *= 0xff51afd7ed558ccdULL;
x ^= x >> 33;
x *= 0xc4ceb9fe1a85ec53ULL;
return x ^= x >> 33;
}
/// Returns a bitmask of the given type with the lowest `nbits` bits set to 1
/// and the rest set to 0.
template <typename T>
constexpr T bitMask(int nbits) {
return ~((~static_cast<T>(0) - 1) << static_cast<T>(nbits - 1));
}
// TODO separate into header and implementation file
} // namespace detail
} // namespace rc
|
whoshuu/rapidcheck
|
include/rapidcheck/detail/Utility.h
|
C
|
bsd-2-clause
| 3,301 |
package stefanholzmueller.pp2.util
import org.testng.annotations._
import org.hamcrest.MatcherAssert._
import org.hamcrest.Matchers._
class DiceTest {
@Test(expectedExceptions = Array(classOf[IllegalArgumentException]))
def requireSaneValues1 {
new Dice(1, 2, -3)
}
@Test(expectedExceptions = Array(classOf[IllegalArgumentException]))
def requireSaneValues2 {
new Dice(111, 2, 3)
}
@Test(expectedExceptions = Array(classOf[IllegalArgumentException]))
def requireSaneValues3 {
new Dice(0, Int.MaxValue, Int.MinValue)
}
@Test
def applyReturnsDice {
val dice = new Dice(1, 2, 3)
assertThat(dice(0), is(1))
assertThat(dice(1), is(2))
assertThat(dice(2), is(3))
}
@Test
def allEqualTo {
assertThat(new Dice(3, 3, 3).allEqualTo(1), is(false))
assertThat(new Dice(1, 2, 3).allEqualTo(1), is(false))
assertThat(new Dice(1, 1, 1).allEqualTo(1), is(true))
}
@Test
def twoEqualTo {
assertThat(new Dice(3, 3, 3).twoEqualTo(1), is(false))
assertThat(new Dice(1, 2, 3).twoEqualTo(1), is(false))
assertThat(new Dice(1, 1, 2).twoEqualTo(1), is(true))
assertThat(new Dice(1, 1, 1).twoEqualTo(1), is(true))
}
@Test
def twoSameValues {
assertThat(new Dice(1, 2, 3).twoSameValues(), is(false))
assertThat(new Dice(1, 1, 2).twoSameValues(), is(true))
assertThat(new Dice(1, 1, 1).twoSameValues(), is(true))
}
@Test
def sum {
assertThat(new Dice(1, 2, 3).sum, is(6))
}
@Test
def compareWithAttributes {
val diff = new Dice(1, 12, 20).compareWithAttributes(List(11, 12, 13))
assertThat(diff(0), is(-10))
assertThat(diff(1), is(0))
assertThat(diff(2), is(7))
}
}
|
stefanholzmueller/pp2scala
|
src/test/scala/stefanholzmueller/pp2/util/DiceTest.scala
|
Scala
|
bsd-2-clause
| 1,689 |
#!/usr/bin/env ruby
# frozen_string_literal: true
$LOAD_PATH.unshift File.expand_path(File.dirname(__FILE__) + '/../lib/')
require 'messagebird'
# ACCESS_KEY = ''
# MESSAGE_ID = ''
unless defined?(ACCESS_KEY)
puts 'You need to set an ACCESS_KEY constant in this file'
exit 1
end
unless defined?(MESSAGE_ID)
puts 'You need to set an MESSAGE_ID constant in this file'
end
begin
# Create a MessageBird client with the specified ACCESS_KEY.
client = MessageBird::Client.new(ACCESS_KEY)
# Fetch the VoiceMessage object for the specified MESSAGE_ID.
vmsg = client.voice_message(MESSAGE_ID)
# Print the object information.
puts
puts 'The following information was returned as a VoiceMessage object:'
puts
puts " id : #{vmsg.id}"
puts " href : #{vmsg.href}"
puts " originator : #{vmsg.originator}"
puts " body : #{vmsg.body}"
puts " reference : #{vmsg.reference}"
puts " language : #{vmsg.language}"
puts " voice : #{vmsg.voice}"
puts " repeat : #{vmsg.repeat}"
puts " ifMachine : #{vmsg.if_machine}"
puts " scheduledDateTime : #{vmsg.scheduled_date_time}"
puts " createdDatetime : #{vmsg.created_datetime}"
puts " recipients : #{vmsg.recipients}"
puts
rescue MessageBird::ErrorException => e
puts
puts 'An error occured while requesting an VoiceMessage object:'
puts
e.errors.each do |error|
puts " code : #{error.code}"
puts " description : #{error.description}"
puts " parameter : #{error.parameter}"
puts
end
end
|
messagebird/ruby-rest-api
|
examples/voice_message.rb
|
Ruby
|
bsd-2-clause
| 1,644 |
project "OpenAL"
SetupNativeDependencyProject()
local version = "1.14"
local repo = "git://repo.or.cz/openal-soft.git"
local archive = "http://kcat.strangesoft.net/openal-releases/openal-soft-1.14.tar.bz2"
local license = "LGPL"
kind "StaticLib"
language "C"
files { "src/OpenAL32/*.c", "src/Alc/*.c" }
files { "src/Alc/backends/null.c", "src/Alc/backends/loopback.c" }
includedirs { "include", "src/OpenAL32/Include" }
defines { "AL_LIBTYPE_STATIC", "AL_ALEXT_PROTOTYPES", "AL_BUILD_LIBRARY" }
configuration "windows"
files { "src/Alc/backends/mmdevapi.c", "src/Alc/backends/winmm.c" }
defines
{
"strcasecmp=_stricmp",
"strncasecmp=_strnicmp",
"snprintf=_snprintf",
"isfinite=_finite",
"isnan=_isnan"
}
configuration "linux"
files { "src/Alc/backends/alsa.c", "src/Alc/backends/pulseaudio.c" }
configuration "macosx or ios"
files { "src/Alc/backends/coreaudio.c" }
configuration "android"
files { "src/Alc/backends/opensl.c" }
configuration "pnacl"
files { "src/Alc/backends/ppapi.c" }
configuration "not vs*"
defines { "HAVE_GCC_DESTRUCTOR" }
configuration { "not vs*", "windows" }
excludes { "src/Alc/backends/mmdevapi.c" } -- mingw does not ship with MMdev headers
configuration ""
|
FloodProject/flood
|
deps/OpenAL/premake4.lua
|
Lua
|
bsd-2-clause
| 1,257 |
#!/bin/bash
path="$(dirname "$(dirname "$(realpath $0)")")"
function nope {
return
}
#compile helloworld:
$path/bin/bfpp -i "$path/common/helloworld.bfk" -o "$path/helloworld.out" || exit 1
$path/bin/bfrun -f "$path/helloworld.out" | grep -q 'Hello World!' || exit 1
$path/bin/bfpp -i "$path/common/pi.bfk" -o "$path/pi.out" || exit 1
$path/bin/bfrun -f "$path/pi.out" | grep -q '3.141' || exit 1
#check dpcrun:
$path/bin/dpcrun -f "$path/common/helloworld.bfk" | grep -q 'Hello World!' || exit 1
$path/bin/dpcrun -f "$path/common/pi.bfk" | grep -q '3.141' || exit 1
exit 0
|
radiolok/bfutils
|
test/test.sh
|
Shell
|
bsd-2-clause
| 585 |
#include "mdaqled.h"
/* Initialize LEDs */
void mdaqled_init(void)
{
#ifndef MATLAB_MEX_FILE
#endif
}
/* Set LED status */
/* led: 1/2 (D1/D2); state: 0/1 (on/off) */
void mdaqled_set(unsigned char led, unsigned char state)
{
#ifndef MATLAB_MEX_FILE
if (led == 1)
/* D1 */
if (state == 1)
/* ON */
GPIO_setOutput(GP2_6, GPIO_LOW);
else
GPIO_setOutput(GP2_6, GPIO_HIGH);
else if (led == 2)
/* D2 */
if (state == 1)
/* ON */
GPIO_setOutput(GP2_7, GPIO_LOW);
else
GPIO_setOutput(GP2_7, GPIO_HIGH);
else
{
/* Shouldn't get here, but switch off LEDs for good */
GPIO_setOutput(GP2_7, GPIO_HIGH);
GPIO_setOutput(GP2_6, GPIO_HIGH);
}
#endif
}
|
kyak/microdaq_ert
|
blocks/mdaqled.c
|
C
|
bsd-2-clause
| 802 |
๏ปฟusing System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Wilson.Scheduler.Data;
using Wilson.Scheduler.Core.Enumerations;
namespace Wilson.Scheduler.Data.Migrations
{
[DbContext(typeof(SchedulerDbContext))]
[Migration("20170625075429_Paycheck")]
partial class Paycheck
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasDefaultSchema("Scheduler")
.HasAnnotation("ProductVersion", "1.1.2")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Wilson.Scheduler.Core.Entities.Employee", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd()
.HasMaxLength(36);
b.Property<int>("EmployeePosition");
b.Property<string>("FirstName")
.IsRequired()
.HasMaxLength(70);
b.Property<bool>("IsFired");
b.Property<string>("LastName")
.IsRequired()
.HasMaxLength(70);
b.Property<string>("PayRateId")
.IsRequired()
.HasMaxLength(36);
b.HasKey("Id");
b.HasIndex("PayRateId");
b.ToTable("Employees");
});
modelBuilder.Entity("Wilson.Scheduler.Core.Entities.Paycheck", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd()
.HasMaxLength(36);
b.Property<DateTime>("Date");
b.Property<string>("DaysOff")
.IsRequired()
.HasMaxLength(250);
b.Property<string>("EmployeeId")
.IsRequired()
.HasMaxLength(36);
b.Property<string>("Period")
.IsRequired()
.HasMaxLength(80);
b.Property<string>("SubTotals")
.IsRequired()
.HasMaxLength(250);
b.Property<decimal>("Total")
.HasColumnType("decimal(18,4)");
b.Property<string>("WorkingHours")
.IsRequired()
.HasMaxLength(250);
b.HasKey("Id");
b.HasIndex("EmployeeId");
b.ToTable("Paychecks");
});
modelBuilder.Entity("Wilson.Scheduler.Core.Entities.PayRate", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd()
.HasMaxLength(36);
b.Property<decimal>("BusinessTripHour")
.HasColumnType("decimal(18,4)");
b.Property<decimal>("ExtraHour")
.HasColumnType("decimal(18,4)");
b.Property<decimal>("HoidayHour")
.HasColumnType("decimal(18,4)");
b.Property<decimal>("Hour")
.HasColumnType("decimal(18,4)");
b.Property<bool>("IsBaseRate");
b.HasKey("Id");
b.ToTable("PayRates");
});
modelBuilder.Entity("Wilson.Scheduler.Core.Entities.Project", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd()
.HasMaxLength(36);
b.Property<bool>("IsActive")
.ValueGeneratedOnAdd()
.HasDefaultValue(true);
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(900);
b.Property<string>("ShortName")
.IsRequired()
.HasMaxLength(4);
b.HasKey("Id");
b.ToTable("Projects");
});
modelBuilder.Entity("Wilson.Scheduler.Core.Entities.Schedule", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd()
.HasMaxLength(36);
b.Property<DateTime>("Date");
b.Property<string>("EmployeeId")
.IsRequired()
.HasMaxLength(36);
b.Property<int>("ExtraWorkHours");
b.Property<string>("ProjectId")
.HasMaxLength(36);
b.Property<int>("ScheduleOption");
b.Property<int>("WorkHours");
b.HasKey("Id");
b.HasIndex("EmployeeId");
b.HasIndex("ProjectId");
b.ToTable("Schedules");
});
modelBuilder.Entity("Wilson.Scheduler.Core.Entities.Employee", b =>
{
b.HasOne("Wilson.Scheduler.Core.Entities.PayRate", "PayRate")
.WithMany()
.HasForeignKey("PayRateId");
});
modelBuilder.Entity("Wilson.Scheduler.Core.Entities.Paycheck", b =>
{
b.HasOne("Wilson.Scheduler.Core.Entities.Employee", "Employee")
.WithMany("Paychecks")
.HasForeignKey("EmployeeId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Wilson.Scheduler.Core.Entities.Schedule", b =>
{
b.HasOne("Wilson.Scheduler.Core.Entities.Employee", "Employee")
.WithMany("Schedules")
.HasForeignKey("EmployeeId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Wilson.Scheduler.Core.Entities.Project", "Project")
.WithMany()
.HasForeignKey("ProjectId");
});
}
}
}
|
KostaVlev/Wilson
|
Scheduler/Wilson.Scheduler.Data/Migrations/20170625075429_Paycheck.Designer.cs
|
C#
|
bsd-2-clause
| 6,529 |
๏ปฟ//-----------------------------------------------------------------------
// <copyright file="StagePractice.cs" company="None">
// Copyright (c) IIHOSHI Yoshinori.
// Licensed under the BSD-2-Clause license. See LICENSE.txt file in the project root for full license information.
// </copyright>
//-----------------------------------------------------------------------
namespace ThScoreFileConverter.Models.Th14
{
/// <summary>
/// Represents stages of spell practice for DDC and later works.
/// </summary>
public enum StagePractice
{
/// <summary>
/// Represents stage 1.
/// </summary>
[EnumAltName("1")]
One,
/// <summary>
/// Represents stage 2.
/// </summary>
[EnumAltName("2")]
Two,
/// <summary>
/// Represents stage 3.
/// </summary>
[EnumAltName("3")]
Three,
/// <summary>
/// Represents stage 4.
/// </summary>
[EnumAltName("4")]
Four,
/// <summary>
/// Represents stage 5.
/// </summary>
[EnumAltName("5")]
Five,
/// <summary>
/// Represents stage 6.
/// </summary>
[EnumAltName("6")]
Six,
/// <summary>
/// Represents Extra stage.
/// </summary>
[EnumAltName("X")]
Extra,
/// <summary>
/// Not used.
/// </summary>
[EnumAltName("-")]
NotUsed,
}
}
|
y-iihoshi/ThScoreFileConverter
|
ThScoreFileConverter/Models/Th14/StagePractice.cs
|
C#
|
bsd-2-clause
| 1,515 |
// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
package jodd.json.fixtures.model.cat;
import jodd.datetime.JDateTime;
import java.util.List;
public class Performance {
private Long eventId;
private Long id;
private String logo;
private String name;
private List<Price> prices;
private List<SeatCategory> seatCategories;
private String seatMapImage;
private JDateTime start;
private String venueCode;
public Long getEventId() {
return eventId;
}
public void setEventId(Long eventId) {
this.eventId = eventId;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Price> getPrices() {
return prices;
}
public void setPrices(List<Price> prices) {
this.prices = prices;
}
public List<SeatCategory> getSeatCategories() {
return seatCategories;
}
public void setSeatCategories(List<SeatCategory> seatCategories) {
this.seatCategories = seatCategories;
}
public String getSeatMapImage() {
return seatMapImage;
}
public void setSeatMapImage(String seatMapImage) {
this.seatMapImage = seatMapImage;
}
public JDateTime getStart() {
return start;
}
public void setStart(JDateTime start) {
this.start = start;
}
public String getVenueCode() {
return venueCode;
}
public void setVenueCode(String venueCode) {
this.venueCode = venueCode;
}
}
|
vilmospapp/jodd
|
jodd-json/src/test/java/jodd/json/fixtures/model/cat/Performance.java
|
Java
|
bsd-2-clause
| 2,897 |
$( document ).ready(function() {
var cW = calendarWidget('.mycalendar_wrapper', {
monthes: ['ะฏะฝะฒะฐัั', 'ะคะตะฒัะฐะปั', 'ะะฐัั', 'ะะฟัะตะปั', 'ะะฐะน', 'ะัะฝั', 'ะัะปั', 'ะะฒะณััั', 'ะกะตะฝััะฑัั', 'ะะบััะฑัั', 'ะะพัะฑัั', 'ะะตะบะฐะฑัั'],
wdays: ['ะะฝ', 'ะั', 'ะกั', 'ะงั', 'ะั', 'ะกะฑ', 'ะั'],
draw_day: function($daydiv, day) {
// $daydiv.empty()
$daydiv.css('text-align', 'center');
// $daydiv.html(day.getMonth()+1 + '/' + day.getDate() )
},
draw_after: function(days) {
var period_start = days[0].day.getFullYear() + '/' + (days[0].day.getMonth()+1) + '/' + days[0].day.getDate();
var period_end = days[days.length-1].day.getFullYear() + '/' + (days[days.length-1].day.getMonth()+1) + '/' + days[days.length-1].day.getDate();
console.log('DAYS: ' + period_start + ' - ' + period_end);
}
});
//cW.redraw(2016, 4);
});
|
procool/osteola-flask
|
assets/js/calend.js
|
JavaScript
|
bsd-2-clause
| 1,001 |
#!/usr/bin/env python
#coding=utf8
"""
Contains classes to read Doom style patch graphics, and Doom PLAYPAL lump palette data.
"""
import struct
import wx
class Palette(object):
"""
A 256 color RGB palette.
"""
def __init__(self, data):
self.colors = []
if len(data) < 768:
raise Exception('Not enough data for a 256 RGB color palette.')
data = bytearray(data)
offset = 0
while offset < 768:
entry = (data[offset], data[offset + 1], data[offset + 2], 255)
self.colors.append(entry)
offset += 3
class Image(object):
"""
A Doom style patch.
"""
S_HEADER = struct.Struct('<HHhh')
def __init__(self, data, palette, mirror=False):
self.set_empty()
self.invalid = False
width, height, left, top = self.S_HEADER.unpack_from(data)
# Attempt to detect invalid data.
if width > 2048 or height > 2048 or top > 2048 or left > 2048:
self.set_invalid()
return
if width <= 0 or height <= 0:
self.set_invalid()
return
# Initialize an empty bitmap.
image_data = bytearray([0, 0, 0, 0] * width * height)
# Read column offsets.
offset_struct = struct.Struct('<' + ('I' * width))
offsets = offset_struct.unpack_from(data[8:8 + (width * 4)])
# Read columns.
data = bytearray(data)
column_index = 0
while column_index < width:
offset = offsets[column_index]
# Attempt to detect invalid data.
if offset < 0 or offset > len(data):
self.set_invalid()
return
prev_delta = 0
while True:
column_top = data[offset]
# Column end.
if column_top == 255:
break
# Tall columns are extended.
if column_top <= prev_delta:
column_top += prev_delta
prev_delta = column_top
pixel_count = data[offset + 1]
offset += 3
pixel_index = 0
while pixel_index < pixel_count:
pixel = data[offset + pixel_index]
if mirror:
dest = ((pixel_index + column_top) * width + ((width - 1) - column_index)) * 4
else:
dest = ((pixel_index + column_top) * width + column_index) * 4
# Plot pixel from palette.
image_data[dest] = palette.colors[pixel][0]
image_data[dest + 1] = palette.colors[pixel][1]
image_data[dest + 2] = palette.colors[pixel][2]
image_data[dest + 3] = 255
pixel_index += 1
offset += pixel_count + 1
column_index += 1
self.width = width
self.height = height
self.top = top
self.left = left
# Create usable bitmap.
self.image = wx.Bitmap.FromBufferRGBA(width, height, image_data)
def set_empty(self):
self.width = 0
self.height = 0
self.top = 0
self.left = 0
self.image = None
def set_invalid(self):
self.set_empty()
self.invalid = True
|
GitExl/WhackEd4
|
src/whacked4/doom/graphics.py
|
Python
|
bsd-2-clause
| 3,378 |
---
chapter: "GitHub Pages"
cover: true
heading: false
layout: hydeslides
tags:
- "pages/pages"
---
## How Does it Work?
GitHub Pages is triggered automagically™ by pushing to specially named branches of GitHub repositories
For most repositories, the branch should be named `gh-pages`
|
youpeiban/youpeiban.github.io
|
presentations/_posts/pages/pages/0002-01-01-how-does-it-work.md
|
Markdown
|
bsd-2-clause
| 297 |
/*
* #%L
* ImageJ2 software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2014 - 2021 ImageJ2 developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package net.imagej.ops.filter.sigma;
import net.imagej.ops.Ops;
import net.imagej.ops.special.computer.UnaryComputerOp;
import net.imglib2.IterableInterval;
import net.imglib2.RandomAccessibleInterval;
/**
* A typed "sigma" filter.
*
* @author Jonathan Hale (University of Konstanz)
*/
public interface SigmaFilterOp<T, V> extends Ops.Filter.Sigma,
UnaryComputerOp<RandomAccessibleInterval<T>, IterableInterval<V>>
{
// NB: Marker interface.
}
|
imagej/imagej-ops
|
src/main/java/net/imagej/ops/filter/sigma/SigmaFilterOp.java
|
Java
|
bsd-2-clause
| 1,913 |
/*******************************************************************************
log11
https://github.com/ombre5733/log11
Copyright (c) 2016, Manuel Freiberger
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#ifndef LOG11_LOGGER_HPP
#define LOG11_LOGGER_HPP
#include "Config.hpp"
#include "LogBuffer.hpp"
#include "LogCore.hpp"
#include "Severity.hpp"
#include "TypeTraits.hpp"
#include "Utility.hpp"
#ifdef LOG11_USE_WEOS
#include <weos/utility.hpp>
#endif // LOG11_USE_WEOS
namespace log11
{
//! \brief A logger.
//!
//! The Logger is the front-end of the logging facility.
class Logger
{
public:
#ifdef LOG11_USE_WEOS
explicit
Logger(const weos::thread_attributes& attrs, std::size_t bufferSizeExponent);
#else
explicit
Logger(std::size_t bufferSizeExponent);
#endif // LOG11_USE_WEOS
//! Creates a new logger which attaches to a given core.
explicit
Logger(LogCore* core);
Logger(const Logger&) = delete;
Logger& operator=(const Logger&) = delete;
//! Destroys the logger.
~Logger();
// Configuration
//! \brief Enables or disables the logger.
//!
//! If \p enable is set, the logger is enabled. By default, the logger is
//! enabled.
void setEnabled(bool enable) noexcept;
//! \brief Checks if the sink is enabled.
//!
//! Returns \p true, if the sink is enabled.
bool isEnabled() const noexcept;
//! \brief Sets the logging level.
//!
//! Sets the logging level to the given \p threshold. Log messages with
//! a severity lower than the threshold are discarded. By default, the
//! threshold is set to Severity::Info.
void setLevel(Severity threshold) noexcept;
//! \brief Returns the logging level.
Severity level() const noexcept;
//! If the level of this logger is lower or equal to the \p severity of
//! the message, a new log entry is created by interpolating the
//! \p message with the given \p args.
//! The caller is blocked until there is sufficient space in the FIFO,
//! which connects the logger front-ends to the sinks.
template <typename... TArgs>
void log(Severity severity, const char* message, TArgs&&... args)
{
if (canLog(severity))
{
m_core->log(LogCore::ClaimPolicy::Block, severity,
log11_detail::makeFormatTuple(
message, log11_detail::decayArgument(args)...));
}
}
template <typename TArg, typename... TArgs>
void logRaw(Severity severity, TArg&& arg, TArgs&&... args)
{
if (canLog(severity))
{
m_core->log(LogCore::ClaimPolicy::Block, severity,
log11_detail::decayArgument(arg),
log11_detail::decayArgument(args)...);
}
}
LogBuffer logBuffer(Severity severity, std::size_t size);
//! If the level of this logger is lower or equal to the \p severity of
//! the message, a new log entry is created by interpolating the
//! \p message with the given \p args.
//! If there is not sufficient space in the FIFO, which connects the logger
//! front-ends to the sinks, the entire message is discarded but the
//! caller is not blocked.
template <typename... TArgs>
void log(may_discard_t, Severity severity, const char* message,
TArgs&&... args)
{
if (canLog(severity))
{
m_core->log(LogCore::ClaimPolicy::Discard, severity,
log11_detail::makeFormatTuple(
message, log11_detail::decayArgument(args)...));
}
}
//! If the level of this logger is lower or equal to the \p severity of
//! the message, a new log entry is created by interpolating the
//! \p message with the given \p args.
//! If there is not sufficient space in the FIFO, which connects the logger
//! front-ends to the sinks, the message may be either truncated or even
//! discarded but the caller is not blocked.
template <typename... TArgs>
void log(may_truncate_or_discard_t, Severity severity, const char* message,
TArgs&&... args)
{
if (canLog(severity))
{
m_core->log(LogCore::ClaimPolicy::Truncate, severity,
log11_detail::makeFormatTuple(
message, log11_detail::decayArgument(args)...));
}
}
// //! Creates a log stream with the given \p severity. The resulting object
// //! can be used to create a log entry using C++ stream notation as in
// //! \code
// //! log(Severity::Error) << "The input" << someVar << "is too large";
// //! log(Severity::Debug) << "a:" << a << "b:" << b << "sum:" << a + b;
// //! \endcode
// log11_detail::LogStreamStatement<> log(Severity severity);
// trace()
//! \brief A convenience function for trace log entries.
//!
//! This function is equivalent to calling
//! \code
//! log(Severity::Trace, message, args...);
//! \endcode
template <typename... TArgs>
void trace(const char* message, TArgs&&... args)
{
this->log(Severity::Trace, message, std::forward<TArgs>(args)...);
}
//! \brief A convenience function for trace log entries.
//!
//! This function is equivalent to calling
//! \code
//! log(may_discard, Severity::Trace, message, args...);
//! \endcode
template <typename... TArgs>
void trace(may_discard_t, const char* message, TArgs&&... args)
{
this->log(may_discard, Severity::Trace,
message, std::forward<TArgs>(args)...);
}
//! \brief A convenience function for trace log entries.
//!
//! This function is equivalent to calling
//! \code
//! log(may_truncate_or_discard, Severity::Trace, message, args...);
//! \endcode
template <typename... TArgs>
void trace(may_truncate_or_discard_t, const char* message, TArgs&&... args)
{
this->log(may_truncate_or_discard, Severity::Trace,
message, std::forward<TArgs>(args)...);
}
// //! \brief A convenience function for trace streams.
// //!
// //! Creates a trace stream equivalent to
// //! \code
// //! log(Severity::Trace)
// //! \endcode
// log11_detail::LogStreamStatement<> trace()
// {
// return log(Severity::Trace);
// }
// debug()
//! \brief A convenience function for debug log entries.
//!
//! This function is equivalent to calling
//! \code
//! log(Severity::Debug, message, args...);
//! \endcode
template <typename... TArgs>
void debug(const char* message, TArgs&&... args)
{
this->log(Severity::Debug, message, std::forward<TArgs>(args)...);
}
//! \brief A convenience function for debug log entries.
//!
//! This function is equivalent to calling
//! \code
//! log(may_discard, Severity::Debug, message, args...);
//! \endcode
template <typename... TArgs>
void debug(may_discard_t, const char* message, TArgs&&... args)
{
this->log(may_discard, Severity::Debug,
message, std::forward<TArgs>(args)...);
}
//! \brief A convenience function for debug log entries.
//!
//! This function is equivalent to calling
//! \code
//! log(may_truncate_or_discard, Severity::Debug, message, args...);
//! \endcode
template <typename... TArgs>
void debug(may_truncate_or_discard_t, const char* message, TArgs&&... args)
{
this->log(may_truncate_or_discard, Severity::Debug,
message, std::forward<TArgs>(args)...);
}
// //! \brief A convenience function for debug streams.
// //!
// //! Creates a debug stream equivalent to
// //! \code
// //! log(Severity::Debug)
// //! \endcode
// log11_detail::LogStreamStatement<> debug()
// {
// return log(Severity::Debug);
// }
// info()
//! \brief A convenience function for info log entries.
//!
//! This function is equivalent to calling
//! \code
//! log(Severity::Info, message, args...);
//! \endcode
template <typename... TArgs>
void info(const char* message, TArgs&&... args)
{
this->log(Severity::Info, message, std::forward<TArgs>(args)...);
}
//! \brief A convenience function for info log entries.
//!
//! This function is equivalent to calling
//! \code
//! log(may_discard, Severity::Info, message, args...);
//! \endcode
template <typename... TArgs>
void info(may_discard_t, const char* message, TArgs&&... args)
{
this->log(may_discard, Severity::Info,
message, std::forward<TArgs>(args)...);
}
//! \brief A convenience function for info log entries.
//!
//! This function is equivalent to calling
//! \code
//! log(may_truncate_or_discard, Severity::Info, message, args...);
//! \endcode
template <typename... TArgs>
void info(may_truncate_or_discard_t, const char* message, TArgs&&... args)
{
this->log(may_truncate_or_discard, Severity::Info,
message, std::forward<TArgs>(args)...);
}
// //! \brief A convenience function for info streams.
// //!
// //! Creates an info stream equivalent to
// //! \code
// //! log(Severity::Info)
// //! \endcode
// log11_detail::LogStreamStatement<> info()
// {
// return log(Severity::Info);
// }
// warn()
//! \brief A convenience function for warning log entries.
//!
//! This function is equivalent to calling
//! \code
//! log(Severity::Warn, message, args...);
//! \endcode
template <typename... TArgs>
void warn(const char* message, TArgs&&... args)
{
this->log(Severity::Warn, message, std::forward<TArgs>(args)...);
}
//! \brief A convenience function for warning log entries.
//!
//! This function is equivalent to calling
//! \code
//! log(may_discard, Severity::Warn, message, args...);
//! \endcode
template <typename... TArgs>
void warn(may_discard_t, const char* message, TArgs&&... args)
{
this->log(may_discard, Severity::Warn,
message, std::forward<TArgs>(args)...);
}
//! \brief A convenience function for warning log entries.
//!
//! This function is equivalent to calling
//! \code
//! log(may_truncate_or_discard, Severity::Warn, message, args...);
//! \endcode
template <typename... TArgs>
void warn(may_truncate_or_discard_t, const char* message, TArgs&&... args)
{
this->log(may_truncate_or_discard, Severity::Warn,
message, std::forward<TArgs>(args)...);
}
// //! \brief A convenience function for warning streams.
// //!
// //! Creates a warning stream equivalent to
// //! \code
// //! log(Severity::Warn)
// //! \endcode
// log11_detail::LogStreamStatement<> warn()
// {
// return log(Severity::Warn);
// }
// error()
//! \brief A convenience function for error log entries.
//!
//! This function is equivalent to calling
//! \code
//! log(Severity::Error, message, args...);
//! \endcode
template <typename... TArgs>
void error(const char* message, TArgs&&... args)
{
this->log(Severity::Error, message, std::forward<TArgs>(args)...);
}
//! \brief A convenience function for error log entries.
//!
//! This function is equivalent to calling
//! \code
//! log(may_discard, Severity::Error, message, args...);
//! \endcode
template <typename... TArgs>
void error(may_discard_t, const char* message, TArgs&&... args)
{
this->log(may_discard, Severity::Error,
message, std::forward<TArgs>(args)...);
}
//! \brief A convenience function for error log entries.
//!
//! This function is equivalent to calling
//! \code
//! log(may_truncate_or_discard, Severity::Error, message, args...);
//! \endcode
template <typename... TArgs>
void error(may_truncate_or_discard_t, const char* message, TArgs&&... args)
{
this->log(may_truncate_or_discard, Severity::Error,
message, std::forward<TArgs>(args)...);
}
// //! \brief A convenience function for error streams.
// //!
// //! Creates an error stream equivalent to
// //! \code
// //! log(Severity::Error)
// //! \endcode
// log11_detail::LogStreamStatement<> error()
// {
// return log(Severity::Error);
// }
private:
//! The core which is in charge of the actual logging.
LogCore* m_core;
//! The severity threshold which log levels must reach or exceed in order
//! to be forwarded to the core. The MSB is used to keep track of the
//! enabled state.
std::atomic<unsigned char> m_configuration;
//! Returns \p true, if a message with level \p severity can be logged.
bool canLog(Severity severity) const noexcept
{
auto config = m_configuration.load();
return (config & 0x80) != 0 && severity >= Severity(config & 0x7F);
}
};
} // namespace log11
#endif // LOG11_LOGGER_HPP
|
ombre5733/log11
|
src/Logger.hpp
|
C++
|
bsd-2-clause
| 14,674 |
# pro-forma settings file.
#~ from djangosite import NoLocalSite as Site
from djangosite import Site
#~ SITE = Site(__file__,globals(),languages="en de fr nl et",no_local=True)
SITE = Site(globals(),no_local=True)
SECRET_KEY = "20227" # see :djangoticket:`20227`
|
lsaffre/djangosite
|
docs/settings.py
|
Python
|
bsd-2-clause
| 263 |
#pragma once
#include <map>
#include <thread>
#include <vector>
#include <ncs/sim/FactoryMap.h>
#include <ncs/sim/InputBuffer.h>
#include <ncs/sim/InputSimulator.h>
#include <ncs/sim/SimulationProperties.h>
#include <ncs/sim/StepSignal.h>
namespace ncs {
namespace sim {
template<DeviceType::Type MType>
class InputUpdater : public SpecificPublisher<InputBuffer<MType>> {
public:
InputUpdater();
bool init(SpecificPublisher<StepSignal>* signal_publisher,
size_t num_buffers,
size_t device_neuron_vector_size,
FactoryMap<InputSimulator>* input_plugins,
const spec::SimulationParameters* simulation_parameters);
bool addInputs(const std::vector<Input*>& inputs,
void* instantiator,
const std::string& type,
float start_time,
float end_time);
bool start(std::function<bool()> thread_init,
std::function<bool()> thread_destroy);
~InputUpdater();
private:
typename SpecificPublisher<StepSignal>::Subscription* step_subscription_;
std::vector<InputSimulator<MType>*> simulators_;
std::map<std::string, unsigned int> simulator_type_indices_;
std::vector<std::thread> worker_threads_;
std::thread master_thread_;
size_t num_buffers_;
const spec::SimulationParameters* simulation_parameters_;
};
} // namespace sim
} // namespace ncs
#include <ncs/sim/InputUpdater.hpp>
|
BrainComputationLab/ncs
|
base/include/ncs/sim/InputUpdater.h
|
C
|
bsd-2-clause
| 1,421 |
#include <stdio.h>
int global = 0;
int calc_pos(int b) {
global += 1;
global += 1;
return b+10;
}
int main()
{
int a[100];
a[calc_pos(12)] = 100;
}
|
axt/angr-utils
|
examples/samples/simple0.c
|
C
|
bsd-2-clause
| 159 |
SHELL=/bin/bash
FIGS := $(shell find ../technical_documentation/figures -not -path '*/\.*')
LIPS := $(shell find Lips -name '*.tex' -not -path '*/\.*')
all: lips_technical_documentation.pdf
lips_technical_documentation.pdf: lips_technical_documentation.tex technical_documentation_main.tex $(FIGS) $(LIPS)
NAME=$$(basename "$<" .tex); \
latexmk -pdf "$$NAME".tex
technical_documentation_main.tex: ../technical_documentation/technical_documentation.rst
@echo "Running rst2latex"
@NAME=$$(basename "$@" .tex); \
rst2latex --no-section-numbering --use-latex-toc --use-latex-citations "$<" | \
sed 's/\\hyperref\[\([^]]\+\)\]{[^}]\+}/\\ref{\1}/g' | \
sed 's/\\phantomsection//g' | \
perl -pe 'BEGIN{undef $$/;} s/\\section\{[^a-zA-Z]*Referenser[^}]*\\label\{referenser\}[^}]*\}//smg' | \
perl -pe 'BEGIN{undef $$/;} s/(\\label\{[^}]*\})\s*\\caption\{(.*?)\}\s*\\end\{figure\}/\n\\caption{\2\1}\n\\end{figure}/smg' | \
awk '/\\section{Bakgrund/{flag=1} /\\end{document}/{flag=0}flag' | \
cat <(echo -e '% ******************************************************************************************************************\n' \
'% ****** !!!WARNING!!! DO NOT EDIT THIS FILE, IT IS AUTOMATICALLY GENERATED FROM technical_documentation.rst ******\n' \
'% ******************************************************************************************************************\n\n') - > "$$NAME".tex;
clean:
rm -f *~
latexmk -c lips_technical_documentation.tex
rm -f technical_documentation_main.tex
|
rartino/ENVISIoN
|
docs/lips/Makefile
|
Makefile
|
bsd-2-clause
| 1,598 |
/* Generated By:JJTree: Do not edit this line. ASTVarDeclaration.cc Version 7.0 */
/* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=true,NODE_PREFIX=AST,NODE_EXTENDS=MyNode,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
#include "ASTVarDeclaration.h"
#include "Boolean.h"
#include "Integer.h"
#include "SPLParserConstants.h"
ASTVarDeclaration::ASTVarDeclaration(int id) : SimpleNode(id) {
}
ASTVarDeclaration::ASTVarDeclaration(SPLParser *parser, int id) : SimpleNode(parser, id) {
}
ASTVarDeclaration::~ASTVarDeclaration() {
}
void ASTVarDeclaration::interpret()
{
if (type == BOOL)
symtab[name] = new Boolean(false);
else
symtab[name] = new Integer(0);
}
|
jtb-javacc/SPLC
|
JJTree/AST/jjt/ASTVarDeclaration.cc
|
C++
|
bsd-2-clause
| 738 |
<div class="col2">
<h4 class="heading colr">Ranking</h4>
<blockquote>
<form name="Gerate_Ranking" id="Gerate_Ranking">
<table width="100%" border="0">
<tr>
<td width="190"><strong><label>Ranking:</label></strong> <select name="Ranking" id="Ranking">
<option value="" disabled="disabled" selected="selected">Selecione</option>
<option value="1">Resets Gerais</option>
<option value="2">Resets Diarios</option>
<option value="3">Resets Semanais</option>
<option value="4">Resets Mensais</option>
<option value="5">Master Resets</option>
<option value="6">Guilds</option>
<option value="7">Top PK</option>
<option value="8">Top Hero</option>
<?php
global $_Ranking;
if($_Ranking["Gens"]["Enable"] == true)
{
?>
<option value="9">Gens</option>
<? } ?>
</select></td>
<td width="171"><strong><label>Top:</label></strong> <select name="Top_Rank" id="Top_Rank">
<option value="" disabled="disabled" selected="selected">Selecione</option>
{TopRank_List}
</select></td>
<td width="122"><input type="button" value="Gerar Ranking" onclick="CTM_Load('?pag=ranking&cmd=true','Ranking_Result','POST',BuscaElementosForm('Gerate_Ranking'));"></td>
</tr>
</table>
</form>
</blockquote>
<div id="Ranking_Result">{Ranking_Result}</div>
</div>
|
effectweb/effectweb-v1.8.5
|
src/templates/Default/pages/ranking.pag.php
|
PHP
|
bsd-2-clause
| 1,425 |
[](https://github.com/newrelic/open-source-office/blob/master/examples/categories/index.md#archived)

[](LICENSE)
supervisor-remote-logging
=========================
This is a [supervisord](http://supervisord.org/) plugin that allows us to stream logs in various format to remote destination.
## Why should I use it?
Inside docker environment, it is best to ship your logs to a remote location because Docker does not do a good job managing its own log files.
If you use supervisord to run your process inside a Docker container, you may find this plugin handy.
## Installation
```
cd /path/to/supervisor-remote-logging
pip install -e .
```
Add the plugin as an event listener:
```
[eventlistener:logging]
command = supervisor_remote_logging
events = PROCESS_LOG
```
## Configurations
* `SUPERVISOR_LOG_TYPE` There can only be 3 options: syslog, syslog_json, tcp_json.
* `DOCKER_CID` Pass Docker container id explicitly.
* `SUPERVISOR_PROCESS_NAME` Pass processname explicitly.
## Log Formats
**1. Syslog** `SUPERVISOR_LOG_TYPE=syslog`
Syslog remote endpoint is configured with the following environment variables:
* `SYSLOG_SERVER`
* `SYSLOG_PORT`
* `SYSLOG_PROTO`
**2. Syslog JSON** `SUPERVISOR_LOG_TYPE=syslog_json`
Syslog JSON remote endpoint is configured similarly to Syslog endpoint.
**3. TCP JSON** `SUPERVISOR_LOG_TYPE=tcp_json`
TCP JSON remote endpoint is configured with the following environment variables:
* `JSON_SERVER`
* `JSON_PORT`
Example JSON payload:
```
{
"hostname":"localhost",
"time": "2014-12-11T03:02:45.2112+00:00",
"log":"ERROR: unable to connect to localhost:3306",
"pid": 123,
"container_id": "6b7ec98af6d7",
"stream": "stdout",
"image_tag": "heka/latest",
"service_env": "staging",
"service_name": "be_site",
}
```
## Contribution Guidelines
You are welcome to send pull requests to us - however, by doing so you agree that you are granting New Relic a non-exclusive, non-revokable, no-cost license to use the code, algorithms, patents, and ideas in that code in our products if we so choose. You also agree the code is provided as-is and you provide no warranties as to its fitness or correctness for any purpose.
## Running Tests for Contributors
```
# Install nose module.
pip install nose
# Run tests.
nosetests
```
|
newrelic/supervisor-remote-logging
|
README.md
|
Markdown
|
bsd-2-clause
| 2,586 |
class JsonC < Formula
desc "JSON parser for C"
homepage "https://github.com/json-c/json-c/wiki"
url "https://github.com/json-c/json-c/archive/json-c-0.15-20200726.tar.gz"
version "0.15"
sha256 "4ba9a090a42cf1e12b84c64e4464bb6fb893666841d5843cc5bef90774028882"
license "MIT"
head "https://github.com/json-c/json-c.git"
bottle do
cellar :any
sha256 "60d15ece3fb1fdc8722785de8243c2261222f674e998509375522a1de75497ea" => :catalina
sha256 "6ab7f776315184769ed74115f614996401eae4577c36144ba4cdd1d41427d0cf" => :mojave
sha256 "a211a34a52b452386cf6e23f8f27cc9d088e64d2793bae7a4b3a7a069d31a88a" => :high_sierra
sha256 "a758d616079a3ef989fccb1f595a930b9fb849f0fcc6a6d235f951233487d637" => :x86_64_linux
end
depends_on "cmake" => :build
def install
mkdir "build" do
system "cmake", "..", *std_cmake_args
system "make", "install"
end
end
test do
(testpath/"test.c").write <<~'EOS'
#include <stdio.h>
#include <json-c/json.h>
int main() {
json_object *obj = json_object_new_object();
json_object *value = json_object_new_string("value");
json_object_object_add(obj, "key", value);
printf("%s\n", json_object_to_json_string(obj));
return 0;
}
EOS
if OS.mac?
system ENV.cc, "-I#{include}", "-L#{lib}", "-ljson-c", "test.c", "-o", "test"
else
system ENV.cc, "-I#{include}", "test.c", "-L#{lib}", "-ljson-c", "-o", "test"
end
assert_equal '{ "key": "value" }', shell_output("./test").chomp
end
end
|
rwhogg/homebrew-core
|
Formula/json-c.rb
|
Ruby
|
bsd-2-clause
| 1,554 |
class Dcm2niix < Formula
desc "DICOM to NIfTI converter"
homepage "https://www.nitrc.org/plugins/mwiki/index.php/dcm2nii:MainPage"
url "https://github.com/rordenlab/dcm2niix/archive/v1.0.20200331.tar.gz"
sha256 "d057f3dbfb0ec9474695075725bc09e28f1d1e021f5fe71c22903ed8cc18f7cb"
license "BSD-3-Clause"
head "https://github.com/rordenlab/dcm2niix.git"
bottle do
cellar :any_skip_relocation
sha256 "d6087edcd6fc5bd534295bbb5d909764b0f83ecc50812e58923a8200a22f3b65" => :catalina
sha256 "bd5449e4418187c4882e2b32afa857632dd8119f2583f5741272f74d65d82603" => :mojave
sha256 "072d6b24939de3dd5202142398083a4e9759c7adfc2c34d323b4b76fcecb542f" => :high_sierra
sha256 "e49a56f40cba1ec1fd94180224d97c81402b64723d871901944c405f152c9608" => :x86_64_linux
end
depends_on "cmake" => :build
resource "sample.dcm" do
url "https://raw.githubusercontent.com/dangom/sample-dicom/master/MR000000.dcm"
sha256 "4efd3edd2f5eeec2f655865c7aed9bc552308eb2bc681f5dd311b480f26f3567"
end
def install
system "cmake", ".", *std_cmake_args
system "make", "install"
end
test do
resource("sample.dcm").stage testpath
system "#{bin}/dcm2niix", "-f", "%d_%e", "-z", "n", "-b", "y", testpath
assert_predicate testpath/"localizer_1.nii", :exist?
assert_predicate testpath/"localizer_1.json", :exist?
end
end
|
rwhogg/homebrew-core
|
Formula/dcm2niix.rb
|
Ruby
|
bsd-2-clause
| 1,355 |
var searchData=
[
['diag2dturb',['Diag2DTurb',['../structDiag2DTurb.html',1,'']]],
['diagdrasla',['DiagDRASLA',['../structDiagDRASLA.html',1,'']]],
['drasla',['DRASLA',['../structDRASLA.html',1,'']]]
];
|
dgroselj/DRASLA
|
doc/html/search/classes_0.js
|
JavaScript
|
bsd-2-clause
| 209 |
/*
* Copyright (c) 2011 Alex Hornung <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <sys/types.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <time.h>
#include "tcplay.h"
#ifndef SIGINFO
#define SIGINFO SIGUSR1
#endif
#define FLAG_LONG_FDE 0xff01
#define FLAG_LONG_USE_BACKUP 0xff02
#define FLAG_LONG_MOD 0xff04
#define FLAG_LONG_MOD_KF 0xff08
#define FLAG_LONG_MOD_PRF 0xff10
#define FLAG_LONG_MOD_NONE 0xff20
#define FLAG_LONG_MOD_TO_FILE 0xff40
#define FLAG_LONG_USE_HDR_FILE 0xfe01
#define FLAG_LONG_USE_HHDR_FILE 0xfe02
#define FLAG_LONG_NO_RETRIES 0xfabc
static
void
sig_handler(int sig)
{
if ((sig == SIGUSR1 || sig == SIGINFO) && (summary_fn != NULL))
summary_fn();
}
static
void
usage(void)
{
fprintf(stderr,
"usage: tcplay -c -d device [-g] [-z] [-w] [-a pbkdf_hash] [-b cipher]\n"
" [-f keyfile_hidden] [-k keyfile] [-x pbkdf_hash] [-y cipher]\n"
" tcplay -i -d device [-e] [-f keyfile_hidden] [-k keyfile]\n"
" [-s system_device] [--fde] [--use-backup]\n"
" [--use-hdr-file=hdr_file] [--use-hidden-hdr-file=hdr_file]\n"
" tcplay -m mapping -d device [-e] [-f keyfile_hidden] [-k keyfile]\n"
" [-s system_device] [--fde] [--use-backup] [--allow-trim]\n"
" [--use-hdr-file=hdr_file] [--use-hidden-hdr-file=hdr_file]\n"
" tcplay --modify -d device [-k keyfile] [--new-keyfile=keyfile]\n"
" [--new-pbkdf-prf=pbkdf_hash] [-s system_device] [--fde]\n"
" [--use-backup] [--save-hdr-to-file=hdr_file] [-w]\n"
" [--use-hdr-file=hdr_file] [--use-hidden-hdr-file=hdr_file]\n"
" tcplay --modify -d device [-k keyfile] --restore-from-backup-hdr [-w]\n"
" tcplay -j mapping\n"
" tcplay -u mapping\n"
" tcplay -h | -v\n"
"\n"
"Valid commands are:\n"
" -c, --create\n"
"\t Creates a new TC volume on the device specified by -d or --device.\n"
" -h, --help\n"
"\t Print help message and exit.\n"
" -i, --info\n"
"\t Gives information about the TC volume specified by -d or --device.\n"
" -j <mapping name>, --info-mapped=<mapping name>\n"
"\t Gives information about the mapped TC volume under the given mapping.\n"
" -m <mapping name>, --map=<mapping name>\n"
"\t Creates a dm-crypt mapping with the given name for the device\n"
"\t specified by -d or --device.\n"
" -u <mapping name>, --unmap=<mapping name>\n"
"\t Removes a dm-crypt mapping with the given name.\n"
" --modify\n"
"\t Changes the volume's passphrase, keyfile and optionally the hashing\n"
"\t function used for the PBKDF password derivation.\n"
" -v, --version\n"
"\t Print version message and exit.\n"
"\n"
"Valid options for --create are:\n"
" -a <pbkdf prf algorithm>, --pbkdf-prf=<pbkdf prf algorithm>\n"
"\t Specifies which hashing function to use for the PBKDF password\n"
"\t derivation when creating a new volume.\n"
"\t To see valid options, specify '-a help'.\n"
" -b <cipher>, --cipher=<cipher>\n"
"\t Specifies which cipher to use when creating a new TC volume.\n"
"\t To see valid options, specify '-b help'.\n"
" -g, --hidden\n"
"\t Specifies that the newly created volume will contain a hidden volume.\n"
" -x <pbkdf prf algorithm>, --pbkdf-prf=<pbkdf prf algorithm>\n"
"\t Specifies which hashing function to use for the PBKDF password\n"
"\t derivation when creating a new hidden volume. By default, the\n"
"\t same as for the outer volume will be used.\n"
"\t To see valid options, specify '-x help'.\n"
" -y <cipher>, --cipher=<cipher>\n"
"\t Specifies which cipher to use when creating a new hidden volume.\n"
"\t By default, the same as for the outer volume will be used.\n"
"\t To see valid options, specify '-y help'.\n"
" -z, --insecure-erase\n"
"\t Skips the erase of the disk. Possible security hazard.\n"
" -w, --weak-keys\n"
"\t Uses a weak source of entropy (urandom) for key material.\n"
"\t WARNING: This is a REALLY REALLY bad idea for anything but\n"
"\t testing.\n"
"\n"
"Valid options for --modify are:\n"
" --new-keyfile=<key file>\n"
"\t Specifies a key file to use for the password derivation, when\n"
"\t re-encrypting the header, can appear multiple times.\n"
" --new-pbkdf-prf=<pbkdf prf algorithm>\n"
"\t Specifies which hashing function to use for the PBKDF password\n"
"\t derivation when re-encrypting the header.\n"
"\t To see valid options, specify '-a help'.\n"
" -s <disk path>, --system-encryption=<disk path>\n"
"\t Specifies that the disk (e.g. /dev/da0) is using system encryption.\n"
" --fde\n"
"\t Specifies that the disk (e.g. /dev/da0) is using full disk encryption.\n"
" --use-backup\n"
"\t Uses the backup headers (at the end of the volume) instead of the\n"
"\t primary headers. Both normal and backup headers will be modified!\n"
"\t This is useful when your primary headers have been corrupted.\n"
" --use-hdr-file=<header file>\n"
"\t Use the header in the specified file instead of the main header on the\n"
"\t disk as source for the modify operation.\n"
" --use-hidden-hdr-file=<header file>\n"
"\t Use the header in the specified file instead of the hidden header on the\n"
"\t disk as source for the modify operation.\n"
" --restore-from-backup-hdr\n"
"\t Implies --use-backup, no new PBKDF hashing function, no new keyfiles\n"
"\t and no new passphrase.\n"
"\t In other words, this will simply restore both headers from the backup\n"
"\t header. This option cannot be used to restore from a backup header file.\n"
" -w, --weak-keys\n"
"\t Uses a weak source of entropy (urandom) for salt material. The\n"
"\t key material is not affected, as the master keys are kept intact.\n"
"\t WARNING: This is a bad idea for anything but testing.\n"
" --save-hdr-backup=<header file>\n"
"\t Saves the modified header in the specified file instead of updating\n"
"\t the header files on disk.\n"
"\n"
"Valid options for --info and --map are:\n"
" -e, --protect-hidden\n"
"\t Protect a hidden volume when mounting the outer volume.\n"
" -s <disk path>, --system-encryption=<disk path>\n"
"\t Specifies that the disk (e.g. /dev/da0) is using system encryption.\n"
" -t, --allow-trim\n"
"\t Allow discards (TRIM command) on mapped volume.\n"
" --fde\n"
"\t Specifies that the disk (e.g. /dev/da0) is using full disk encryption.\n"
" --use-backup\n"
"\t Uses the backup headers (at the end of the volume) instead of the\n"
"\t primary headers.\n"
"\t This is useful when your primary headers have been corrupted.\n"
" --use-hdr-file=<header file>\n"
"\t Use the header in the specified file instead of the main header on the\n"
"\t disk.\n"
" --use-hidden-hdr-file=<header file>\n"
"\t Use the header in the specified file instead of the hidden header on the\n"
"\t disk.\n"
"\n"
"Valid options common to all commands are:\n"
" -d <device path>, --device=<device path>\n"
"\t Specifies the path to the volume to operate on (e.g. /dev/da0s1).\n"
" -f <key file>, --keyfile-hidden=<key file>\n"
"\t Specifies a key file to use for the hidden volume password derivation.\n"
"\t This option is only valid in combination with -e, --protect-hidden\n"
"\t or -g, --hidden.\n"
" -k <key file>, --keyfile=<key file>\n"
"\t Specifies a key file to use for the password derivation, can appear\n"
"\t multiple times.\n"
);
exit(EXIT_FAILURE);
}
static struct option longopts[] = {
{ "create", no_argument, NULL, 'c' },
{ "cipher", required_argument, NULL, 'b' },
{ "cipher-hidden", required_argument, NULL, 'y' },
{ "hidden", no_argument, NULL, 'g' },
{ "pbkdf-prf", required_argument, NULL, 'a' },
{ "pbkdf-prf-hidden", required_argument, NULL, 'x' },
{ "info", no_argument, NULL, 'i' },
{ "info-mapped", required_argument, NULL, 'j' },
{ "map", required_argument, NULL, 'm' },
{ "keyfile", required_argument, NULL, 'k' },
{ "keyfile-hidden", required_argument, NULL, 'f' },
{ "protect-hidden", no_argument, NULL, 'e' },
{ "device", required_argument, NULL, 'd' },
{ "system-encryption", required_argument, NULL, 's' },
{ "allow-trim", no_argument, NULL, 't' },
{ "fde", no_argument, NULL, FLAG_LONG_FDE },
{ "use-backup", no_argument, NULL, FLAG_LONG_USE_BACKUP },
{ "use-hdr-file", required_argument, NULL, FLAG_LONG_USE_HDR_FILE },
{ "use-hidden-hdr-file",required_argument, NULL, FLAG_LONG_USE_HHDR_FILE },
{ "modify", no_argument, NULL, FLAG_LONG_MOD },
{ "new-keyfile", required_argument, NULL, FLAG_LONG_MOD_KF },
{ "new-pbkdf-prf", required_argument, NULL, FLAG_LONG_MOD_PRF },
{ "restore-from-backup-hdr", no_argument, NULL, FLAG_LONG_MOD_NONE },
{ "save-hdr-backup", required_argument, NULL, FLAG_LONG_MOD_TO_FILE },
{ "unmap", required_argument, NULL, 'u' },
{ "version", no_argument, NULL, 'v' },
{ "weak-keys", no_argument, NULL, 'w' },
{ "insecure-erase", no_argument, NULL, 'z' },
{ "help", no_argument, NULL, 'h' },
{ "no-retries", no_argument, NULL, FLAG_LONG_NO_RETRIES },
{ NULL, 0, NULL, 0 },
};
#define _set_str_opt(opt) \
do { \
if ((opts->opt = strdup_safe_mem(optarg)) == NULL) { \
fprintf(stderr, "Could not allocate safe mem.\n"); \
exit(EXIT_FAILURE); \
} \
} while(0)
int
main(int argc, char *argv[])
{
struct tcplay_opts *opts;
int ch, error;
int info_vol = 0, map_vol = 0,
unmap_vol = 0, info_map = 0,
create_vol = 0, modify_vol = 0;
if ((error = tc_play_init()) != 0) {
fprintf(stderr, "Initialization failed, exiting.");
exit(EXIT_FAILURE);
}
atexit(check_and_purge_safe_mem);
signal(SIGUSR1, sig_handler);
signal(SIGINFO, sig_handler);
if ((opts = opts_init()) == NULL) {
fprintf(stderr, "Initialization failed (opts), exiting.");
exit(EXIT_FAILURE);
}
opts->interactive = 1;
while ((ch = getopt_long(argc, argv, "a:b:cd:ef:ghij:k:m:s:tu:vwx:y:z",
longopts, NULL)) != -1) {
switch(ch) {
case 'a':
if (opts->prf_algo != NULL)
usage();
if ((opts->prf_algo = check_prf_algo(optarg, 0)) == NULL) {
if (strcmp(optarg, "help") == 0)
exit(EXIT_SUCCESS);
else
usage();
/* NOT REACHED */
}
break;
case 'b':
if (opts->cipher_chain != NULL)
usage();
if ((opts->cipher_chain = check_cipher_chain(optarg, 0)) == NULL) {
if (strcmp(optarg, "help") == 0)
exit(EXIT_SUCCESS);
else
usage();
/* NOT REACHED */
}
break;
case 'c':
create_vol = 1;
break;
case 'd':
_set_str_opt(dev);
break;
case 'e':
opts->protect_hidden = 1;
break;
case 'f':
if ((error = opts_add_keyfile_hidden(opts, optarg)) != 0) {
fprintf(stderr, "Could not add keyfile: %s\n", optarg);
exit(EXIT_FAILURE);
}
break;
case 'g':
opts->hidden = 1;
break;
case 'i':
info_vol = 1;
break;
case 'j':
info_map = 1;
_set_str_opt(map_name);
break;
case 'k':
if ((error = opts_add_keyfile(opts, optarg)) != 0) {
fprintf(stderr, "Could not add keyfile: %s\n", optarg);
exit(EXIT_FAILURE);
}
break;
case 'm':
map_vol = 1;
_set_str_opt(map_name);
break;
case 's':
opts->flags |= TC_FLAG_SYS;
_set_str_opt(sys_dev);
break;
case 't':
opts->flags |= TC_FLAG_ALLOW_TRIM;
break;
case 'u':
unmap_vol = 1;
_set_str_opt(map_name);
break;
case 'v':
printf("tcplay v%d.%d\n", MAJ_VER, MIN_VER);
exit(EXIT_SUCCESS);
/* NOT REACHED */
case 'w':
fprintf(stderr, "WARNING: Using urandom as source of "
"entropy for key material is a really bad idea.\n");
opts->weak_keys_and_salt = 1;
break;
case 'x':
if (opts->h_prf_algo != NULL)
usage();
if ((opts->h_prf_algo = check_prf_algo(optarg, 0)) == NULL) {
if (strcmp(optarg, "help") == 0)
exit(EXIT_SUCCESS);
else
usage();
/* NOT REACHED */
}
break;
case 'y':
if (opts->h_cipher_chain != NULL)
usage();
if ((opts->h_cipher_chain = check_cipher_chain(optarg, 0)) == NULL) {
if (strcmp(optarg, "help") == 0)
exit(EXIT_SUCCESS);
else
usage();
/* NOT REACHED */
}
break;
case 'z':
opts->secure_erase = 0;
break;
case FLAG_LONG_FDE:
opts->flags |= TC_FLAG_FDE;
break;
case FLAG_LONG_USE_BACKUP:
opts->flags |= TC_FLAG_BACKUP;
break;
case FLAG_LONG_USE_HDR_FILE:
opts->flags |= TC_FLAG_HDR_FROM_FILE;
_set_str_opt(hdr_file_in);
break;
case FLAG_LONG_USE_HHDR_FILE:
opts->flags |= TC_FLAG_H_HDR_FROM_FILE;
_set_str_opt(h_hdr_file_in);
break;
case FLAG_LONG_MOD:
modify_vol = 1;
break;
case FLAG_LONG_MOD_KF:
if ((error = opts_add_keyfile_new(opts, optarg)) != 0) {
fprintf(stderr, "Could not add keyfile: %s\n", optarg);
exit(EXIT_FAILURE);
}
break;
case FLAG_LONG_MOD_PRF:
if (opts->new_prf_algo != NULL)
usage();
if ((opts->new_prf_algo = check_prf_algo(optarg, 0)) == NULL) {
if (strcmp(optarg, "help") == 0)
exit(EXIT_SUCCESS);
else
usage();
/* NOT REACHED */
}
break;
case FLAG_LONG_MOD_NONE:
opts->new_prf_algo = NULL;
opts->flags |= TC_FLAG_ONLY_RESTORE;
opts->flags |= TC_FLAG_BACKUP;
break;
case FLAG_LONG_MOD_TO_FILE:
opts->flags |= TC_FLAG_SAVE_TO_FILE;
_set_str_opt(hdr_file_out);
break;
case FLAG_LONG_NO_RETRIES:
opts->retries = 1;
break;
case 'h':
case '?':
default:
usage();
/* NOT REACHED */
}
}
argc -= optind;
argv += optind;
/* Check arguments */
if (!(((map_vol || info_vol || create_vol || modify_vol) && opts->dev != NULL) ||
((unmap_vol || info_map) && opts->map_name != NULL)) ||
(TC_FLAG_SET(opts->flags, SYS) && TC_FLAG_SET(opts->flags, FDE)) ||
(map_vol + info_vol + create_vol + unmap_vol + info_map + modify_vol > 1) ||
(opts->hidden && !create_vol) ||
(TC_FLAG_SET(opts->flags, SYS) && (opts->sys_dev == NULL)) ||
(TC_FLAG_SET(opts->flags, ONLY_RESTORE) && (opts->n_newkeyfiles > 0 || opts->new_prf_algo != NULL)) ||
(TC_FLAG_SET(opts->flags, BACKUP) && (opts->sys_dev != NULL || TC_FLAG_SET(opts->flags, FDE))) ||
(map_vol && (opts->map_name == NULL)) ||
(unmap_vol && (opts->map_name == NULL)) ||
(!modify_vol && opts->n_newkeyfiles > 0) ||
(!modify_vol && opts->new_prf_algo != NULL) ||
(!modify_vol && TC_FLAG_SET(opts->flags, ONLY_RESTORE)) ||
(!modify_vol && TC_FLAG_SET(opts->flags, SAVE_TO_FILE)) ||
(!(opts->protect_hidden || create_vol) && opts->n_hkeyfiles > 0)) {
usage();
/* NOT REACHED */
}
/* Create a new volume */
if (create_vol) {
error = create_volume(opts);
if (error) {
tc_log(1, "could not create new volume on %s\n", opts->dev);
}
} else if (info_map) {
error = info_mapped_volume(opts);
} else if (info_vol) {
error = info_volume(opts);
} else if (map_vol) {
error = map_volume(opts);
} else if (unmap_vol) {
error = dm_teardown(opts->map_name, NULL);
} else if (modify_vol) {
error = modify_volume(opts);
}
return error;
}
#undef _set_str_opt
|
Nmishin/tc-play
|
main.c
|
C
|
bsd-2-clause
| 16,900 |
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2021 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PHYSICS_EXTENSIONS_TRIANGLE_MESH_H
#define PX_PHYSICS_EXTENSIONS_TRIANGLE_MESH_H
/** \addtogroup extensions
@{
*/
#include "PxPhysXConfig.h"
#include "common/PxPhysXCommonConfig.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxGeometry;
class PxTriangleMeshGeometry;
class PxHeightFieldGeometry;
/**
\brief Utility class to find mesh triangles touched by a specified geometry object.
This class is a helper calling PxMeshQuery::findOverlapTriangleMesh or PxMeshQuery::findOverlapHeightField under the hood,
while taking care of necessary memory management issues.
PxMeshQuery::findOverlapTriangleMesh and PxMeshQuery::findOverlapHeightField are the "raw" functions operating on user-provided fixed-size
buffers. These functions abort with an error code in case of buffer overflow. PxMeshOverlapUtil is a convenient helper function checking
this error code, and resizing buffers appropriately, until the desired call succeeds.
Returned triangle indices are stored within the class, and can be used with PxMeshQuery::getTriangle() to retrieve the triangle properties.
*/
class PxMeshOverlapUtil
{
public:
PxMeshOverlapUtil();
~PxMeshOverlapUtil();
/**
\brief Find the mesh triangles which touch the specified geometry object.
\param[in] geom The geometry object to test for mesh triangle overlaps. Supported geometries are #PxSphereGeometry, #PxCapsuleGeometry and #PxBoxGeometry
\param[in] geomPose Pose of the geometry object
\param[in] meshGeom The triangle mesh geometry to check overlap against
\param[in] meshPose Pose of the triangle mesh
\return Number of overlaps found. Triangle indices can then be accessed through the #getResults() function.
@see PxGeometry PxTransform PxTriangleMeshGeometry PxMeshQuery::findOverlapTriangleMesh
*/
PxU32 findOverlap(const PxGeometry& geom, const PxTransform& geomPose, const PxTriangleMeshGeometry& meshGeom, const PxTransform& meshPose);
/**
\brief Find the height field triangles which touch the specified geometry object.
\param[in] geom The geometry object to test for height field overlaps. Supported geometries are #PxSphereGeometry, #PxCapsuleGeometry and #PxBoxGeometry. The sphere and capsule queries are currently conservative estimates.
\param[in] geomPose Pose of the geometry object
\param[in] hfGeom The height field geometry to check overlap against
\param[in] hfPose Pose of the height field
\return Number of overlaps found. Triangle indices can then be accessed through the #getResults() function.
@see PxGeometry PxTransform PxHeightFieldGeometry PxMeshQuery::findOverlapHeightField
*/
PxU32 findOverlap(const PxGeometry& geom, const PxTransform& geomPose, const PxHeightFieldGeometry& hfGeom, const PxTransform& hfPose);
/**
\brief Retrieves array of triangle indices after a findOverlap call.
\return Indices of touched triangles
*/
PX_FORCE_INLINE const PxU32* getResults() const { return mResultsMemory; }
/**
\brief Retrieves number of triangle indices after a findOverlap call.
\return Number of touched triangles
*/
PX_FORCE_INLINE PxU32 getNbResults() const { return mNbResults; }
private:
PxU32* mResultsMemory;
PxU32 mResults[256];
PxU32 mNbResults;
PxU32 mMaxNbResults;
};
/**
\brief Computes an approximate minimum translational distance (MTD) between a geometry object and a mesh.
This iterative function computes an approximate vector that can be used to depenetrate a geom object
from a triangle mesh. Returned depenetration vector should be applied to 'geom', to get out of the mesh.
The function works best when the amount of overlap between the geom object and the mesh is small. If the
geom object's center goes inside the mesh, backface culling usually kicks in, no overlap is detected,
and the function does not compute an MTD vector.
The function early exits if no overlap is detected after a depenetration attempt. This means that if
maxIter = N, the code will attempt at most N iterations but it might exit earlier if depenetration has
been successful. Usually N = 4 gives good results.
\param[out] direction Computed MTD unit direction
\param[out] depth Penetration depth. Always positive or zero.
\param[in] geom The geometry object
\param[in] geomPose Pose for the geometry object
\param[in] meshGeom The mesh geometry
\param[in] meshPose Pose for the mesh
\param[in] maxIter Max number of iterations before returning.
\param[out] usedIter Number of depenetrations attempts performed during the call. Will not be returned if the pointer is NULL.
\return True if the MTD has successfully been computed, i.e. if objects do overlap.
@see PxGeometry PxTransform PxTriangleMeshGeometry
*/
bool PxComputeTriangleMeshPenetration(PxVec3& direction,
PxReal& depth,
const PxGeometry& geom,
const PxTransform& geomPose,
const PxTriangleMeshGeometry& meshGeom,
const PxTransform& meshPose,
PxU32 maxIter,
PxU32* usedIter = NULL);
/**
\brief Computes an approximate minimum translational distance (MTD) between a geometry object and a heightfield.
This iterative function computes an approximate vector that can be used to depenetrate a geom object
from a heightfield. Returned depenetration vector should be applied to 'geom', to get out of the heightfield.
The function works best when the amount of overlap between the geom object and the mesh is small. If the
geom object's center goes inside the heightfield, backface culling usually kicks in, no overlap is detected,
and the function does not compute an MTD vector.
The function early exits if no overlap is detected after a depenetration attempt. This means that if
maxIter = N, the code will attempt at most N iterations but it might exit earlier if depenetration has
been successful. Usually N = 4 gives good results.
\param[out] direction Computed MTD unit direction
\param[out] depth Penetration depth. Always positive or zero.
\param[in] geom The geometry object
\param[in] geomPose Pose for the geometry object
\param[in] heightFieldGeom The heightfield geometry
\param[in] heightFieldPose Pose for the heightfield
\param[in] maxIter Max number of iterations before returning.
\param[out] usedIter Number of depenetrations attempts performed during the call. Will not be returned if the pointer is NULL.
\return True if the MTD has successfully been computed, i.e. if objects do overlap.
@see PxGeometry PxTransform PxHeightFieldGeometry
*/
bool PxComputeHeightFieldPenetration(PxVec3& direction,
PxReal& depth,
const PxGeometry& geom,
const PxTransform& geomPose,
const PxHeightFieldGeometry& heightFieldGeom,
const PxTransform& heightFieldPose,
PxU32 maxIter,
PxU32* usedIter = NULL);
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
|
nyaki-HUN/DESIRE
|
DESIRE-Modules/Physics-PhysX/Externals/physx/include/extensions/PxTriangleMeshExt.h
|
C
|
bsd-2-clause
| 8,674 |
/*
* rsxgltest - feedback1
*/
#define GL3_PROTOTYPES
#include <GL3/gl3.h>
#include "rsxgltest.h"
#include "math3d.h"
#include "sine_wave.h"
#include <stddef.h>
#include "points_vert.h"
#include "feedback1_frag.h"
#include <io/pad.h>
#include <math.h>
#include <Eigen/Geometry>
const char * rsxgltest_name = "feedback1";
struct sine_wave_t rgb_waves[3] = {
{ 0.5f,
0.5f,
1.0f
},
{
0.5f,
0.5f,
1.5f
},
{
0.5f,
0.5f,
2.5f
}
};
struct sine_wave_t xyz_waves[3] = {
{ 0.5f,
0.5f,
1.0f / 4.0f
},
{
0.5f,
0.5f,
1.5f / 4.0f
},
{
0.5f,
0.5f,
2.5f / 4.0f
}
};
GLuint buffers[2] = { 0,0 };
GLuint shaders[2] = { 0,0 };
GLuint program = 0;
GLint ProjMatrix_location = -1, TransMatrix_location = -1;
const GLuint npoints = 100;
const GLuint batchsize = 256;
const GLuint nbatch = (npoints / batchsize) + ((npoints % batchsize) ? 1 : 0);
GLint batchfirst[nbatch];
GLsizei batchcount[nbatch];
GLvoid const * batchoffsets[nbatch];
GLuint * client_elements = 0;
GLvoid const * client_batchindices[nbatch];
GLuint elements = 0;
#define DTOR(X) ((X)*0.01745329f)
#define RTOD(d) ((d)*57.295788f)
Eigen::Projective3f ProjMatrix(perspective(DTOR(54.3),1920.0 / 1080.0,0.1,1000.0));
Eigen::Affine3f ViewMatrixInv =
Eigen::Affine3f(Eigen::Affine3f::Identity() *
(
Eigen::Translation3f(1.779,2.221,4.034) *
(
Eigen::AngleAxisf(DTOR(0),Eigen::Vector3f::UnitZ()) *
Eigen::AngleAxisf(DTOR(23.8),Eigen::Vector3f::UnitY()) *
Eigen::AngleAxisf(DTOR(-26.738),Eigen::Vector3f::UnitX())
)
)
).inverse();
extern "C"
void
rsxgltest_pad(unsigned int,const padData * paddata)
{
if(paddata -> BTN_UP) {
tcp_printf("up\n");
}
else if(paddata -> BTN_DOWN) {
tcp_printf("down\n");
}
}
extern "C"
void
rsxgltest_init(int argc,const char ** argv)
{
tcp_printf("%s\n",__PRETTY_FUNCTION__);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
// Set up us the program:
shaders[0] = glCreateShader(GL_VERTEX_SHADER);
shaders[1] = glCreateShader(GL_FRAGMENT_SHADER);
program = glCreateProgram();
glAttachShader(program,shaders[0]);
glAttachShader(program,shaders[1]);
// Supply shader binaries:
//glShaderBinary(1,shaders,0,points_vpo,points_vpo_size);
//glShaderBinary(1,shaders + 1,0,points_fpo,points_fpo_size);
// Supply shader SOURCES!
char szInfo[2048];
const GLchar * shader_srcs[] = { (const GLchar *)points_vert, (const GLchar *)feedback1_frag };
GLint shader_srcs_lengths[] = { points_vert_len, feedback1_frag_len };
GLint compiled = 0;
glShaderSource(shaders[0],1,shader_srcs,shader_srcs_lengths);
glCompileShader(shaders[0]);
glGetShaderiv(shaders[0],GL_COMPILE_STATUS,&compiled);
tcp_printf("shader compile status: %i\n",compiled);
glGetShaderInfoLog(shaders[0],2048,0,szInfo);
tcp_printf("%s\n",szInfo);
glShaderSource(shaders[1],1,shader_srcs + 1,shader_srcs_lengths + 1);
glCompileShader(shaders[1]);
glGetShaderiv(shaders[1],GL_COMPILE_STATUS,&compiled);
tcp_printf("shader compile status: %i\n",compiled);
glGetShaderInfoLog(shaders[1],2048,0,szInfo);
tcp_printf("%s\n",szInfo);
const char * varyings[] = {
"gl_Position"
};
glTransformFeedbackVaryings(program,1,varyings,GL_SEPARATE_ATTRIBS);
// Link the program for real:
glLinkProgram(program);
glValidateProgram(program);
summarize_program("draw",program);
GLint
vertex_location = glGetAttribLocation(program,"position");
ProjMatrix_location = glGetUniformLocation(program,"ProjMatrix");
TransMatrix_location = glGetUniformLocation(program,"TransMatrix");
tcp_printf("vertex_location: %i\n",vertex_location);
tcp_printf("ProjMatrix_location: %i TransMatrix_location: %i\n",
ProjMatrix_location,TransMatrix_location);
glUseProgram(program);
glUniformMatrix4fv(ProjMatrix_location,1,GL_FALSE,ProjMatrix.data());
// Set up us the vertex data:
glGenBuffers(2,buffers);
glBindBuffer(GL_ARRAY_BUFFER,buffers[0]);
glBufferData(GL_ARRAY_BUFFER,sizeof(float) * 3 * 2 * npoints,0,GL_STATIC_DRAW);
float * geometry = (float *)glMapBuffer(GL_ARRAY_BUFFER,GL_WRITE_ONLY);
for(size_t i = 0;i < npoints;++i,geometry += 6) {
geometry[0] = drand48() * 5.0 - 2.5;
geometry[1] = drand48() * 5.0 - 2.5;
geometry[2] = drand48() * 5.0 - 2.5;
geometry[3] = 1.0;
geometry[4] = 1.0;
geometry[5] = 1.0;
}
glUnmapBuffer(GL_ARRAY_BUFFER);
client_elements = (GLuint *)malloc(sizeof(GLuint) * npoints);
for(size_t i = 0;i < npoints;++i) {
client_elements[i] = i;
}
GLint first = 0;
for(size_t i = 0;i < nbatch;++i) {
batchfirst[i] = first;
batchcount[i] = (i == (nbatch - 1)) ? (npoints % batchsize) : (batchsize);
batchoffsets[i] = (GLvoid const*)((uint64_t)first * sizeof(GLuint));
client_batchindices[i] = client_elements + first;
first += batchsize;
}
glGenBuffers(1,&elements);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,elements);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(GLuint) * npoints,0,GL_STATIC_DRAW);
GLuint * pelements = (GLuint *)glMapBuffer(GL_ELEMENT_ARRAY_BUFFER,GL_WRITE_ONLY);
for(size_t i = 0;i < npoints;++i) {
pelements[i] = i;
}
glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
glEnableVertexAttribArray(vertex_location);
glVertexAttribPointer(vertex_location,3,GL_FLOAT,GL_FALSE,sizeof(float) * 3 * 2,0);
glPointSize(1);
glBindBuffer(GL_ARRAY_BUFFER,0);
glBindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER,buffers[1]);
const size_t nfeedback = sizeof(float) * 4 * npoints;
GLfloat * pfeedback = (GLfloat *)malloc(nfeedback);
GLfloat * ppfeedback = pfeedback;
for(size_t i = 0;i < npoints;++i,ppfeedback += 4) {
ppfeedback[0] = 3.0;
ppfeedback[1] = 5.0;
ppfeedback[2] = 7.0;
ppfeedback[3] = (float)i;
}
glBufferData(GL_TRANSFORM_FEEDBACK_BUFFER,nfeedback,pfeedback,GL_STATIC_DRAW);
free(pfeedback);
glBindBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER,0,buffers[1],0,nfeedback);
}
extern "C"
int
rsxgltest_draw()
{
static int frame = 0;
float rgb[3] = {
compute_sine_wave(rgb_waves,rsxgltest_elapsed_time),
compute_sine_wave(rgb_waves + 1,rsxgltest_elapsed_time),
compute_sine_wave(rgb_waves + 2,rsxgltest_elapsed_time)
};
glClearColor(0,0,0,1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
float xyz[3] = {
compute_sine_wave(xyz_waves,rsxgltest_elapsed_time),
compute_sine_wave(xyz_waves + 1,rsxgltest_elapsed_time),
compute_sine_wave(xyz_waves + 2,rsxgltest_elapsed_time)
};
Eigen::Affine3f rotmat =
Eigen::Affine3f::Identity() *
Eigen::AngleAxisf(DTOR(xyz[2]) * 360.0f,Eigen::Vector3f::UnitZ()) *
Eigen::AngleAxisf(DTOR(xyz[1]) * 360.0f,Eigen::Vector3f::UnitY()) *
Eigen::AngleAxisf(DTOR(xyz[0]) * 360.0f,Eigen::Vector3f::UnitX());
glPointSize(4.0);
{
Eigen::Affine3f modelview = ViewMatrixInv * (Eigen::Affine3f::Identity() * Eigen::Translation3f(0,0,0) * rotmat);
glUniformMatrix4fv(TransMatrix_location,1,GL_FALSE,modelview.data());
//int which = frame % 6;
int which = 0;
if(which == 0) {
report_glerror("Before transform feedback");
glBeginTransformFeedback(GL_POINTS);
report_glerror("glBeginTransformFeedback");
glDrawArrays(GL_POINTS,0,npoints);
report_glerror("glDrawArrays");
glEndTransformFeedback();
report_glerror("glEndTransformFeedback");
// Dump the alleged feedback buffer:
GLfloat * pfeedback = (GLfloat *)glMapBuffer(GL_TRANSFORM_FEEDBACK_BUFFER,GL_READ_ONLY);
if(pfeedback) {
for(size_t i = 0;i < npoints;++i,pfeedback += 4) {
tcp_printf("%04i: %.3f, %.3f, %.3f, %.3f\n",i,pfeedback[0],pfeedback[1],pfeedback[2],pfeedback[3]);
}
}
glUnmapBuffer(GL_TRANSFORM_FEEDBACK_BUFFER);
}
else if(which == 1) {
glMultiDrawArrays(GL_POINTS,batchfirst,batchcount,nbatch);
}
else if(which == 2) {
glDrawElements(GL_POINTS,npoints,GL_UNSIGNED_INT,client_elements);
}
else if(which == 3) {
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,elements);
glDrawElements(GL_POINTS,npoints,GL_UNSIGNED_INT,0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
}
else if(which == 4) {
glMultiDrawElements(GL_POINTS,batchcount,GL_UNSIGNED_INT,client_batchindices,nbatch);
}
else if(which == 5) {
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,elements);
glMultiDrawElements(GL_POINTS,batchcount,GL_UNSIGNED_INT,batchoffsets,nbatch);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
}
}
++frame;
return 1;
}
extern "C"
void
rsxgltest_exit()
{
glDeleteShader(shaders[0]);
glDeleteProgram(program);
glDeleteShader(shaders[1]);
}
|
gzorin/RSXGL
|
src/samples/rsxgltest/feedback1.cc
|
C++
|
bsd-2-clause
| 8,773 |
package Zonemaster::Exception v0.0.1;
use 5.14.2;
use Moose;
use overload '""' => \&string;
has 'message' => ( is => 'ro', isa => 'Str', required => 1 );
sub string {
my ( $self ) = @_;
return $self->message;
}
no Moose;
__PACKAGE__->meta->make_immutable;
1;
=head1 NAME
Zonemaster::Exception -- base class for Zonemaster exceptions
=head1 SYNOPSIS
die Zonemaster::Exception->new({ message => "This is an exception" });
=head1 ATTRIBUTES
=over
=item message
A string attribute holding a message for possible human consumption.
=back
=head1 METHODS
=over
=item string()
Method that stringifies the object by returning the C<message> attribute.
Stringification is overloaded to this.
=back
=cut
|
mtoma/zonemaster
|
Zonemaster/lib/Zonemaster/Exception.pm
|
Perl
|
bsd-2-clause
| 726 |
// Copyright 2010-2014 UT-Battelle, LLC. See LICENSE.txt for more information.
#ifndef EAVL_COLOR_BAR_ANNOTATION_H
#define EAVL_COLOR_BAR_ANNOTATION_H
#include "eavlView.h"
#include "eavlColor.h"
// ****************************************************************************
// Class: eavlColorLegendAnnotation
//
// Purpose:
/// Annotation which renders a set of discrete colors and values.
//
// Programmer: Jeremy Meredith
// Creation: May 1, 2014
//
// Modifications:
// ****************************************************************************
class eavlColorLegendAnnotation : public eavlAnnotation
{
protected:
vector<string> labels;
vector<eavlColor> colors;
vector<eavlScreenTextAnnotation*> annot;
public:
eavlColorLegendAnnotation(eavlWindow *win) : eavlAnnotation(win)
{
}
virtual ~eavlColorLegendAnnotation()
{
}
void Clear()
{
labels.clear();
colors.clear();
}
void AddItem(const string &label, eavlColor color)
{
labels.push_back(label);
colors.push_back(color);
}
virtual void Render(eavlView &view)
{
win->SetupForScreenSpace();
float l = -0.95, r = -0.90;
float b = +0.90, t = +0.95;
float spacing = 0.07;
for (unsigned int i=0; i<colors.size(); ++i)
{
win->surface->AddRectangle(l,
t - spacing*float(i),
r-l,
b-t,
colors[i]);
}
// reset positions
l = -0.95; r = -0.90;
b = +0.90; t = +0.95;
const float fontscale = 0.05;
while (annot.size() < labels.size())
{
annot.push_back(new eavlScreenTextAnnotation(win, "text",
eavlColor::black,
fontscale,
0,0,
0));
}
for (unsigned int i=0; i<labels.size(); ++i)
{
eavlScreenTextAnnotation *txt = annot[i];
txt->SetText(labels[i]);
txt->SetPosition(r + .02, (b+t)/2. - spacing*float(i));
txt->SetAlignment(eavlTextAnnotation::Left,
eavlTextAnnotation::VCenter);
txt->Render(view);
}
}
};
#endif
|
jsmeredith/EAVL
|
src/rendering/eavlColorLegendAnnotation.h
|
C
|
bsd-2-clause
| 2,521 |
/*
* Compression Factory
* (C) 2014,2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/compression.h>
#include <botan/mem_ops.h>
#include <botan/exceptn.h>
#include <cstdlib>
#if defined(BOTAN_HAS_ZLIB)
#include <botan/zlib.h>
#endif
#if defined(BOTAN_HAS_BZIP2)
#include <botan/bzip2.h>
#endif
#if defined(BOTAN_HAS_LZMA)
#include <botan/lzma.h>
#endif
namespace Botan {
//static
std::unique_ptr<Compression_Algorithm>
Compression_Algorithm::create(const std::string& name)
{
#if defined(BOTAN_HAS_ZLIB)
if(name == "Zlib" || name == "zlib")
return std::make_unique<Zlib_Compression>();
if(name == "Gzip" || name == "gzip" || name == "gz")
return std::make_unique<Gzip_Compression>();
if(name == "Deflate" || name == "deflate")
return std::make_unique<Deflate_Compression>();
#endif
#if defined(BOTAN_HAS_BZIP2)
if(name == "bzip2" || name == "bz2" || name == "Bzip2")
return std::make_unique<Bzip2_Compression>();
#endif
#if defined(BOTAN_HAS_LZMA)
if(name == "lzma" || name == "xz" || name == "LZMA")
return std::make_unique<LZMA_Compression>();
#endif
BOTAN_UNUSED(name);
return nullptr;
}
//static
std::unique_ptr<Compression_Algorithm>
Compression_Algorithm::create_or_throw(const std::string& algo)
{
if(auto compressor = Compression_Algorithm::create(algo))
{
return compressor;
}
throw Lookup_Error("Compression", algo, "");
}
//static
std::unique_ptr<Decompression_Algorithm>
Decompression_Algorithm::create(const std::string& name)
{
#if defined(BOTAN_HAS_ZLIB)
if(name == "Zlib" || name == "zlib")
return std::make_unique<Zlib_Decompression>();
if(name == "Gzip" || name == "gzip" || name == "gz")
return std::make_unique<Gzip_Decompression>();
if(name == "Deflate" || name == "deflate")
return std::make_unique<Deflate_Decompression>();
#endif
#if defined(BOTAN_HAS_BZIP2)
if(name == "bzip2" || name == "bz2" || name == "Bzip2")
return std::make_unique<Bzip2_Decompression>();
#endif
#if defined(BOTAN_HAS_LZMA)
if(name == "lzma" || name == "xz" || name == "LZMA")
return std::make_unique<LZMA_Decompression>();
#endif
BOTAN_UNUSED(name);
return nullptr;
}
//static
std::unique_ptr<Decompression_Algorithm>
Decompression_Algorithm::create_or_throw(const std::string& algo)
{
if(auto decompressor = Decompression_Algorithm::create(algo))
{
return decompressor;
}
throw Lookup_Error("Decompression", algo, "");
}
}
|
randombit/botan
|
src/lib/compression/compression.cpp
|
C++
|
bsd-2-clause
| 2,578 |
wallaby
=======
Dummy package for easy installation of all dependencies.
For more information on wallaby visit http://wlby.freshx.de
|
FreshXOpenSource/wallaby
|
README.md
|
Markdown
|
bsd-2-clause
| 135 |
class Sonar4 < Formula
desc "Manage code quality"
homepage "http://www.sonarqube.org/"
url "http://dist.sonar.codehaus.org/sonarqube-4.5.4.zip"
sha256 "c72f833d290da237e967a34d6ed03d7f33c97ec90f4c0b77209dfd8a3100ae44"
bottle do
sha256 "c3a82451cb70a5411fc7c617d468637286ba21920de10ebe8a72e1ecdee329dd" => :yosemite
sha256 "48d0c098e215a2ef51c66ac3dcaad608edde67d83ee4d625b49f96112e42fb85" => :mavericks
sha256 "3263ac8ab0dbaa64f42bf9638cbae51b5bc30ecfb724111f8351498b951f9b68" => :mountain_lion
end
def install
# Delete native bin directories for other systems
rm_rf Dir["bin/{aix,hpux,linux,solaris,windows}-*"]
if MacOS.prefer_64_bit?
rm_rf "bin/macosx-universal-32"
else
rm_rf "bin/macosx-universal-64"
end
# Delete Windows files
rm_f Dir["war/*.bat"]
libexec.install Dir["*"]
if MacOS.prefer_64_bit?
bin.install_symlink "#{libexec}/bin/macosx-universal-64/sonar.sh" => "sonar"
else
bin.install_symlink "#{libexec}/bin/macosx-universal-32/sonar.sh" => "sonar"
end
end
plist_options manual: "sonar console"
def plist; <<-EOS.undent
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>#{plist_name}</string>
<key>ProgramArguments</key>
<array>
<string>#{opt_bin}/sonar</string>
<string>start</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
EOS
end
test do
assert_match "SonarQube", pipe_output("#{bin}/sonar status")
end
end
|
DomT4/homebrew-versions
|
sonar4.rb
|
Ruby
|
bsd-2-clause
| 1,704 |
<?php
/**********************************************************
* LunaBB - The Bulletin Board that is out of this world! *
* Project by Jordan Gomm (http://gomm.me) *
* Licensed under BSD 2-clause, see "LICENSE" file *
* Filename: Default.info.php *
**********************************************************/
$TEMPLATE['NAME'] = "LunaBB Default";
$TEMPLATE['AUTHOR'] = "Jordan Gomm";
$TEMPLATE['WEBSITE'] = "http://gomm.me";
$TEMPLATE['EMAIL'] = "[email protected]";
$TEMPLATE['VERSION'] = "0001";
$TEMPLATE['FRIENDLYVERSION'] = "0.0.0.1a";
$TEMPLATE['SUPPORTEDVERSION'] = "0001";
$TEMPLATE['UUID'] = "F7D30D74-5882-42DD-8001-B406BBBA6A19";
|
jordangomm/LunaBB
|
templates/Default/Default.info.php
|
PHP
|
bsd-2-clause
| 700 |
package de.lessvoid.nifty.slick2d.render.font.loader;
import de.lessvoid.nifty.slick2d.render.font.DefaultSlickRenderFont;
import de.lessvoid.nifty.slick2d.render.font.SlickLoadFontException;
import de.lessvoid.nifty.slick2d.render.font.SlickRenderFont;
import org.newdawn.slick.Graphics;
/**
* The loader is able to load the default render font
*
* @author Martin Karing <[email protected]>
*/
public final class DefaultSlickRenderFontLoader implements SlickRenderFontLoader {
/**
* Load the requested font.
*/
@Override
public SlickRenderFont loadFont(final Graphics g, final String filename) throws SlickLoadFontException {
try {
g.resetFont();
return new DefaultSlickRenderFont(g.getFont());
} catch (final SlickLoadFontException e) {
throw new SlickLoadFontException("Loading font failed.", e);
}
}
}
|
xranby/nifty-gui
|
nifty-renderer-slick/src/main/java/de/lessvoid/nifty/slick2d/render/font/loader/DefaultSlickRenderFontLoader.java
|
Java
|
bsd-2-clause
| 865 |
/*============================================================================
CMake - Cross Platform Makefile Generator
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef cmProjectCommand_h
#define cmProjectCommand_h
#include "cmCommand.h"
/** \class cmProjectCommand
* \brief Specify the name for this build project.
*
* cmProjectCommand is used to specify a name for this build project.
* It is defined once per set of CMakeList.txt files (including
* all subdirectories). Currently it just sets the name of the workspace
* file for Microsoft Visual C++
*/
class cmProjectCommand : public cmCommand
{
public:
/**
* This is a virtual constructor for the command.
*/
virtual cmCommand* Clone()
{
return new cmProjectCommand;
}
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
virtual bool InitialPass(std::vector<std::string> const& args,
cmExecutionStatus &status);
/**
* The name of the command as specified in CMakeList.txt.
*/
virtual const char* GetName() const {return "project";}
cmTypeMacro(cmProjectCommand, cmCommand);
};
#endif
|
unix1986/universe
|
tool/cmake-3.0.2/Source/cmProjectCommand.h
|
C
|
bsd-2-clause
| 1,579 |
/**
* Copyright (c) 2013-2014. Francisco Contreras, Holland Salazar.
* Copyright (c) 2015. Tobias Strebitzer, Francisco Contreras, Holland Salazar.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* Neither the name of the Baker Framework nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written
* permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
package com.bakerframework.baker.activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
import com.bakerframework.baker.BakerApplication;
import com.bakerframework.baker.R;
import com.bakerframework.baker.model.BookJson;
import com.bakerframework.baker.settings.Configuration;
import com.bakerframework.baker.view.CustomWebView;
import com.bakerframework.baker.view.CustomWebViewPager;
import com.bakerframework.baker.view.WebViewFragment;
import com.bakerframework.baker.view.WebViewFragmentPagerAdapter;
import com.viewpagerindicator.LinePageIndicator;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class IssueActivity extends FragmentActivity {
private boolean doubleTap = false;
private boolean enableDoubleTap = true;
private boolean enableBackNextButton = false;
private GestureDetectorCompat gestureDetector;
private WebViewFragmentPagerAdapter webViewPagerAdapter;
private CustomWebViewPager pager;
private BookJson jsonBook;
public final static String MODAL_URL = "com.giniem.gindpubs.MODAL_URL";
public final static String ORIENTATION = "com.giniem.gindpubs.ORIENTATION";
private Resources resources;
private int previousIndex = -1;
private Long startedTime = 0L;
private boolean hasElapsedTime = false;
private String metaBakerPageName = "";
private String metaBakerPageCategory = "";
private String orientation;
private boolean STANDALONE_MODE = false;
private boolean RETURN_TO_SHELF = false;
private boolean ENABLE_BACK_NEXT_BUTTONS = false;
private boolean ENABLE_DOUBLE_TAP = true;
private boolean ENABLE_TUTORIAL = false;
public BookJson getJsonBook() {
return this.jsonBook;
}
public CustomWebViewPager getPager() {
return this.pager;
}
@Override
protected void onDestroy() {
Log.d(this.getClass().getName(), "Called onDestroy method.");
WebViewFragment fragment = (WebViewFragment) webViewPagerAdapter.instantiateItem(pager, pager.getCurrentItem());
fragment.getWebView().destroy();
super.onDestroy();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// We would like to keep the screen on while reading the magazine
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.html_pager);
Intent intent = getIntent();
try {
STANDALONE_MODE = intent.getBooleanExtra(Configuration.ISSUE_STANDALONE, false);
RETURN_TO_SHELF = intent.getBooleanExtra(Configuration.ISSUE_RETURN_TO_SHELF, true);
ENABLE_DOUBLE_TAP = intent.getBooleanExtra(Configuration.ISSUE_ENABLE_DOUBLE_TAP, true);
ENABLE_BACK_NEXT_BUTTONS = intent.getBooleanExtra(Configuration.ISSUE_ENABLE_BACK_NEXT_BUTTONS, false);
ENABLE_TUTORIAL = intent.getBooleanExtra(Configuration.ISSUE_ENABLE_TUTORIAL, false);
Log.d(this.getClass().getName(), "Will run in standalone mode: " + STANDALONE_MODE);
if (!RETURN_TO_SHELF) {
setResult(ShelfActivity.STANDALONE_MAGAZINE_ACTIVITY_FINISH);
} else {
setResult(0);
}
jsonBook = new BookJson();
jsonBook.setIssueName(intent.getStringExtra(Configuration.ISSUE_NAME));
Log.d(this.getClass().toString(), "THE RAW BOOK.JSON IS: " + intent.getStringExtra(Configuration.BOOK_JSON_KEY));
jsonBook.fromJsonString(intent.getStringExtra(Configuration.BOOK_JSON_KEY));
this.setOrientation(jsonBook.getOrientation());
this.setPagerView(jsonBook);
this.setEnableDoubleTap(ENABLE_DOUBLE_TAP);
this.setEnableBackNextButton(ENABLE_BACK_NEXT_BUTTONS);
detectFirstOrLastPage();
gestureDetector = new GestureDetectorCompat(this,
new MyGestureListener());
} catch (Exception ex) {
ex.printStackTrace();
Toast.makeText(this, "Not valid book.json found!",
Toast.LENGTH_LONG).show();
}
resources = getResources();
}
private void detectFirstOrLastPage() {
if (!isEnableBackNextButton()) {
return;
}
int allItems = this.getJsonBook().getContents().size();
int currentItem = this.pager.getCurrentItem();
if (currentItem == (allItems - 1)) {
Log.d(this.getClass().getName(), "Last page detected.");
((Button)findViewById(R.id.buttonNext)).setText(getString(R.string.lbl_finish));
if (allItems > 1) {
findViewById(R.id.buttonBack).setVisibility(View.VISIBLE);
}
} else if (currentItem == 0) {
Log.d(this.getClass().getName(), "First page detected.");
findViewById(R.id.buttonBack).setVisibility(View.GONE);
((Button)findViewById(R.id.buttonNext)).setText(getString(R.string.lbl_next));
} else {
findViewById(R.id.buttonBack).setVisibility(View.VISIBLE);
((Button)findViewById(R.id.buttonNext)).setText(getString(R.string.lbl_next));
}
}
private void goNext() {
int currentItem = this.pager.getCurrentItem();
int nextItem = currentItem + 1;
int allItems = this.getJsonBook().getContents().size();
Log.d(this.getClass().getName(), "All items: " + allItems + ", current item: " + currentItem + ", next item: " + nextItem);
if (nextItem < allItems) {
this.pager.setCurrentItem(nextItem);
this.detectFirstOrLastPage();
} else if (nextItem == allItems) {
this.finish();
}
}
private void goBack() {
int currentItem = this.pager.getCurrentItem();
int nextItem = currentItem - 1;
int allItems = this.getJsonBook().getContents().size();
Log.d(this.getClass().getName(), "All items: " + allItems + ", current item: " + currentItem + ", next item: " + nextItem);
if (nextItem >= 0) {
this.pager.setCurrentItem(nextItem);
this.detectFirstOrLastPage();
}
}
private void setOrientation(String _orientation) {
_orientation = _orientation.toUpperCase();
this.orientation = _orientation;
final String PORTRAIT = "PORTRAIT";
final String LANDSCAPE = "LANDSCAPE";
switch (_orientation) {
case PORTRAIT:
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
case LANDSCAPE:
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
default:
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
break;
}
}
public void resetOrientation() {
this.setOrientation(this.orientation);
}
public boolean isEnableDoubleTap() {
return enableDoubleTap;
}
public void setEnableDoubleTap(boolean enableDoubleTap) {
this.enableDoubleTap = enableDoubleTap;
}
public boolean isEnableBackNextButton() {
return enableBackNextButton;
}
public void setEnableBackNextButton(boolean enableBackNextButton) {
this.enableBackNextButton = enableBackNextButton;
if (enableBackNextButton) {
findViewById(R.id.buttonNext).setVisibility(View.VISIBLE);
// Click on the next button
findViewById(R.id.buttonNext).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goNext();
}
});
// No need for a "Back" button when there's only one page.
if (this.getJsonBook().getContents().size() > 1) {
findViewById(R.id.buttonBack).setVisibility(View.VISIBLE);
// Click on the back button
findViewById(R.id.buttonBack).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goBack();
}
});
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.magazine, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
private Map<String, String> getBakerMetaTags(final String htmlPath) {
Map<String, String> values = new HashMap<>();
Log.d(this.getClass().getName(), "Trying to parse: " + htmlPath);
try {
URL url = new URL(htmlPath);
File file = new File(url.getPath());
Document document = Jsoup.parse(file, null);
Elements metas = document.select("meta");
for (Element meta : metas) {
if (meta.hasAttr("name") && meta.attr("name").equals("baker-page-name")) {
if (meta.hasAttr("content")) {
values.put("baker-page-name", meta.attr("content"));
} else {
values.put("baker-page-name", "");
}
} else if (meta.hasAttr("name") && meta.attr("name").equals("baker-page-category")) {
if (meta.hasAttr("content")) {
values.put("baker-page-category", meta.attr("content"));
} else {
values.put("baker-page-category", "");
}
}
}
} catch (IOException e) {
Log.e(this.getClass().getName(), "Error parsing the document", e);
}
return values;
}
private void setPagerView(final BookJson book) {
String path = "file://" + Configuration.getMagazinesDirectory() + File.separator;
if (STANDALONE_MODE) {
path = "file:///android_asset".concat(File.separator)
.concat(getString(R.string.path_standalone_books_directory)).concat(File.separator);
} else if (ENABLE_TUTORIAL) {
path = "file:///android_asset".concat(File.separator);
}
if (book.getLiveUrl() != null) {
path = book.getLiveUrl();
}
final String finalPath = path;
Log.d(this.getClass().toString(), "THE PATH FOR LOADING THE PAGES WILL BE: " + finalPath);
// ViewPager and its adapters use support library
// fragments, so use getSupportFragmentManager.
webViewPagerAdapter = new WebViewFragmentPagerAdapter(
getSupportFragmentManager(), book, finalPath, this);
pager = (CustomWebViewPager) findViewById(R.id.pager);
pager.setAdapter(webViewPagerAdapter);
//Bind the title indicator to the adapter
LinePageIndicator indicator = (LinePageIndicator)findViewById(R.id.indicator);
if (!ENABLE_TUTORIAL) {
indicator.setVisibility(View.GONE);
}
indicator.setViewPager(pager);
indicator.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
if (hasElapsedTime) {
Long timeElapsed = System.currentTimeMillis() - startedTime;
if (timeElapsed > resources.getInteger(R.integer.ga_page_view_time_elapsed))
((BakerApplication) IssueActivity.this.getApplication()).sendTimingEvent(
metaBakerPageCategory,
timeElapsed,
getString(R.string.ga_issue_page_view),
metaBakerPageName);
((BakerApplication) IssueActivity.this.getApplication()).sendEvent(
metaBakerPageCategory,
getString(R.string.ga_issue_page_view),
metaBakerPageName);
startedTime = 0L;
hasElapsedTime = false;
previousIndex = -1;
metaBakerPageName = "";
metaBakerPageCategory = "";
}
Log.d(this.getClass().getName(), "Loading page at index: " + position);
detectFirstOrLastPage();
if (resources.getBoolean(R.bool.ga_enable) && resources.getBoolean(R.bool.ga_register_page_view_event)) {
String page = finalPath + book.getMagazineName() + File.separator + book.getContents().get(position);
Map<String, String> tags = getBakerMetaTags(page);
if (tags.containsKey("baker-page-name")) {
String name = tags.get("baker-page-name");
String category = tags.containsKey("baker-page-category") ? tags.get("baker-page-category") : getString(R.string.ga_issues_category);
name = (name.isEmpty()) ? book.getContents().get(position) : name;
category = (category.isEmpty()) ? getString(R.string.ga_issues_category) : category;
if (resources.getBoolean(R.bool.ga_register_page_view_time_elapsed_event)) {
startedTime = System.currentTimeMillis();
hasElapsedTime = true;
previousIndex = position;
metaBakerPageName = name;
metaBakerPageCategory = category;
} else {
((BakerApplication) IssueActivity.this.getApplication()).sendEvent(
category,
getString(R.string.ga_issue_page_view),
name);
}
}
}
}
});
CustomWebView viewIndex = (CustomWebView) findViewById(R.id.webViewIndex);
viewIndex.getSettings().setJavaScriptEnabled(true);
viewIndex.getSettings().setUseWideViewPort(true);
viewIndex.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String stringUrl) {
// mailto links will be handled by the OS.
if (stringUrl.startsWith("mailto:")) {
Uri uri = Uri.parse(stringUrl);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
} else {
try {
URL url = new URL(stringUrl);
// We try to remove the referrer string to avoid passing it to the server in case the URL is an external link.
String referrer = "";
if (url.getQuery() != null) {
Map<String, String> variables = Configuration.splitUrlQueryString(url);
String finalQueryString = "";
for (Map.Entry<String, String> entry : variables.entrySet()) {
if (entry.getKey().equals("referrer")) {
referrer = entry.getValue();
} else {
finalQueryString += entry.getKey() + "=" + entry.getValue() + "&";
}
}
if (!finalQueryString.isEmpty()) {
finalQueryString = "?" + finalQueryString.substring(0, finalQueryString.length() - 1);
}
stringUrl = stringUrl.replace("?" + url.getQuery(), finalQueryString);
}
// Aaaaand that was the process of removing the referrer from the query string.
if (!url.getProtocol().equals("file")) {
Log.d("REFERRER>>>", "THE REFERRER IS: " + referrer);
if (referrer.equals(IssueActivity.this.getString(R.string.url_external_referrer))) {
Uri uri = Uri.parse(stringUrl);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
} else if (referrer.equals(IssueActivity.this.getString(R.string.url_baker_referrer))) {
IssueActivity.this.openLinkInModal(stringUrl);
return true;
} else {
// We return false to tell the webview that we are not going to handle the URL override.
return false;
}
} else {
stringUrl = url.getPath().substring(url.getPath().lastIndexOf("/") + 1);
Log.d(">>>URL_DATA", "FINAL INTERNAL HTML FILENAME = " + stringUrl);
int index = IssueActivity.this.getJsonBook().getContents().indexOf(stringUrl);
if (index != -1) {
Log.d(this.getClass().toString(), "Index to load: " + index
+ ", page: " + stringUrl);
IssueActivity.this.getPager().setCurrentItem(index);
view.setVisibility(View.GONE);
} else {
// If the file DOES NOT exist, we won't load it.
File htmlFile = new File(url.getPath());
if (htmlFile.exists()) {
return false;
}
}
}
} catch (MalformedURLException ex) {
Log.d(">>>URL_DATA", ex.getMessage());
} catch (UnsupportedEncodingException ignored) {
}
}
return true;
}
});
viewIndex.loadUrl(path + book.getMagazineName() + File.separator
+ "index.html");
viewIndex.setBackgroundColor(0x00000000);
viewIndex.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
WebViewFragment fragment = (WebViewFragment) this.webViewPagerAdapter
.instantiateItem(pager, pager.getCurrentItem());
if (fragment.inCustomView()) {
fragment.hideCustomView();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean dispatchTouchEvent(@NonNull MotionEvent event) {
// Intercept the touch events.
this.gestureDetector.onTouchEvent(event);
if (doubleTap) {
//No need to pass double tap to children
doubleTap = false;
} else {
// We call the superclass implementation for the touch
// events to continue along children.
return super.dispatchTouchEvent(event);
}
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
this.gestureDetector.onTouchEvent(event);
if (doubleTap) {
//No need to pass double tap to children
doubleTap = false;
} else {
// We call the superclass implementation.
return super.onTouchEvent(event);
}
return true;
}
public void openLinkInModal(final String url) {
Intent intent = new Intent(this, ModalActivity.class);
intent.putExtra(MODAL_URL, url);
intent.putExtra(ORIENTATION, this.getRequestedOrientation());
startActivity(intent);
}
/**
* Used to handle the gestures, but we will only need the onDoubleTap. The
* other events will be passed to children views.
*
* @author Holland
*
*/
class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDoubleTap(MotionEvent event) {
if (isEnableDoubleTap()) {
doubleTap = true;
CustomWebView viewIndex = (CustomWebView) findViewById(R.id.webViewIndex);
//Disable Index Zoom
viewIndex.getSettings().setSupportZoom(false);
if (viewIndex.isShown()) {
viewIndex.setVisibility(View.GONE);
} else {
WebViewFragment fragment = (WebViewFragment) IssueActivity.this.webViewPagerAdapter
.instantiateItem(pager, pager.getCurrentItem());
if (!fragment.inCustomView()) {
viewIndex.setVisibility(View.VISIBLE);
}
}
}
return true;
}
}
}
|
MowebJobs/baker-android-refactor
|
Baker/src/main/java/com/bakerframework/baker/activity/IssueActivity.java
|
Java
|
bsd-2-clause
| 24,436 |
var EIDSS = {
BvMessages: {
'bntHideSearch': 'แซแแแแแก แแแแแแแ',
'bntShowSearch': 'แซแแแแแก แฉแแแแแแ',
'btnClear': 'แแแแจแ แฉแแฌแแ แแแ แขแแฅแกแขแแก แแแกแฃแคแแแแแแ',
'btnHideErrDetail': 'แแแขแแแแแแก แแแแแแแ',
'btnSelect': 'แแ แฉแแแ',
'btnShowErrDetail': 'แแแขแแแแแแก แฉแแแแแแ',
'btnView': 'แแแฎแแ',
'strSave_Id': 'แแแแแฎแกแแแ แแแ',
'tooltipSave_Id': 'แแแแแฎแกแแแ แแแ',
'strClose_Id': 'แแแฎแฃแ แแ',
'strRefresh_Id': 'แแแแแฎแแแแ',
'tooltipRefresh_Id': 'แแแแแฎแแแแ',
'strCreate_Id': 'แแฎแแแ',
'tooltipCreate_Id': 'แจแแฅแแแ',
'strEdit_Id': 'แ แแแแฅแขแแ แแแ',
'tooltipEdit_Id': 'แ แแแแฅแขแแ แแแ',
'Confirmation': 'แแแแแกแขแฃแ แแแ',
'Delete Record': 'แฉแแแแฌแแ แแก แฌแแจแแ',
'ErrAuthentication': 'แแแแฎแแแแแก แจแแกแแกแ แฃแแแแแแ แกแแญแแ แแ แแแแฎแแแ แแแแแก แแแขแแ แแแแชแแ.',
'ErrDatabase': 'แจแแชแแแแ แแแแแชแแแแ แแแแแกแแแ แแฃแจแแแแแก แแ แแก.',
'errDatabaseNotFound': 'แจแแฃแซแแแแแแแ \'{0}\' แแแแแชแแแแ แแแแแก แแแฎแกแแ \'{1}\' แกแแ แแแ แแ. แจแแแแแฌแแแ แแแแแชแแแแ แแแแแก แแแกแแฎแแแแแแก แกแแกแฌแแ แ.',
'ErrDataValidation': 'แแแแแแ แ แฃแฏแ แแจแ แแ แแกแฌแแ แ แแแแแชแแแแแแ',
'ErrEmptyUserLogin': 'แแแแฎแแแ แแแแแก แกแแฎแแแ แฃแแแ แจแแแแกแแก',
'ErrFieldSampleIDNotFound': 'แแแแฃแจแแก แกแแแแแ ID แแ แแแแซแแแแ แชแฎแ แแแจแ.',
'ErrFillDataset': 'แจแแชแแแแ แแแแแชแแแแ แแแแแแแ แแแแแชแแแแ แแแแฆแแแแกแแก',
'ErrFilterValidatioError': 'แคแแแขแ แแก แแ แแขแแ แแฃแแแแแก แแแแจแแแแแแแ [{0}] แแแแแกแแแแก แแ แจแแแซแแแแ แแงแแก แจแแฃแแกแแแแแ.',
'errGeneralNetworkError': 'แจแแฃแซแแแแแแแ SQLแกแแ แแแ แแแ แแแแแแจแแ แแแ. แแแฎแแแ, แจแแแแแฌแแแ, แ แแ แฅแกแแแแแ แแแแจแแ แ แฉแแ แแฃแแแ แแ แแแแแ แกแชแแแแ แแ แคแแ แแแก แแแฎแกแแ.',
'ErrIncorrectDatabaseVersion': 'แแแแแชแแแแ แแแแ แแ แแ แกแแแแแก แแ แแ แแแแ แแฅแขแฃแแแ. แแแฎแแแ แแแแแแฎแแแ แแแแแชแแแแ แแแแ',
'errInvailidSiteID': 'แแแแแฅแขแแก แแ แแกแฌแแ แ ID แแแแ แแ แกแแ แแฃแแ แแแแแ แ',
'errInvailidSiteType': 'แแแแแฅแขแแก แแ แแกแฌแแ แ แขแแแ แแ แกแแ แแฃแแ แแแแแ แ',
'ErrInvalidFieldFormat': '\'{0}\' แแแแแกแแแแก แแแแแชแแแแแแก แคแแ แแแขแ แแ แแกแฌแแ แแ .',
'ErrInvalidLogin': 'แแ แแกแฌแแ แ แกแแกแขแแแแจแ แจแแกแแแแก แกแแฎแแแ/แแแ แแแ',
'ErrInvalidParameter': 'sql แแแแ แแขแแ แก แแ แแกแฌแแ แ แแแฉแแแแแแแแ แแแแแแแแแ',
'errInvalidSearchCriteria': 'แซแแแแแก แแ แแกแฌแแ แ แแ แแขแแ แแฃแแแแ.',
'ErrLocalFieldSampleIDNotFound': 'แแแแแแแแ แแแ/แกแแแแแ ID แชแฎแ แแแจแ แแ แแแแซแแแแ.',
'ErrLoginIsLocked': 'แกแแกแขแแแแจแ แจแแกแแแ แแแแแแแแ. แกแชแแแแ แฎแแแแฎแแ แแแ แแแแฃแแ แแ แแแก แจแแแแแ.',
'ErrLowClientVersion': 'แแ แแแ แแแแก แแแ แกแแ แแ แแแแแฎแแแแ แแแแแชแแแแ แแแแแก แแ แกแแแก.แแแฎแแแ แแแแแแฎแแแ แแ แแแ แแแ.',
'ErrLowDatabaseVersion': 'แแ แแแ แแแ แแแฎแแแก แฃแแฎแแแก แแแแแชแแแแ แแแแแก. แแแฎแแแ แแแแแแฎแแแ.',
'ErrMandatoryFieldRequired': '\'{0}\' แแแแแก แจแแแกแแแ แกแแแแแแแแฃแแแ. แแ แแแแจแ แแแแแชแแแแแ แฃแแแ แจแแแงแแแแแ แคแแ แแแก แแแแแฎแกแแแ แแแแแแ.',
'errNoFreeLocation': 'แแ แกแแชแแแจแ แแ แแ แแก แแแแแกแฃแคแแแ แแแแแแ',
'ErrOldPassword': 'แแแแฎแแแ แแแแแก แซแแแแ (แแแแแแแแ แ) แแแ แแแ แแ แแกแฌแแ แแ. แแแ แแแ แแ แจแแฃแชแแแแแ.',
'Error': 'แจแแชแแแแ',
'ErrPasswordExpired': 'แแฅแแแแ แแแ แแแแก แแแฅแแแแแแแก แแแแ แแแแแฌแฃแ แ. แแแฎแแแ, แจแแชแแแแแ แแแ แแแ.',
'ErrPasswordPolicy': 'แจแแฃแซแแแแแแแ แแแ แแแแก แแแแแฎแแแแ. แแฎแแแ แแแ แแแแก แแแแจแแแแแแแแแ แแ แแแแแงแแคแแแแแก แกแแแ แซแแก, แกแแ แแฃแแแก แแ แแกแขแแ แแแก แแแแฎแแแแแก.',
'ErrPost': 'แจแแชแแแแ แแแแแชแแแแ แแแแแจแ แแแแแชแแแแ แแแแแฎแกแแแ แแแแกแแก',
'errSampleInTransfer': 'แแแแฃแจแ "{0}" แฃแแแ แจแแขแแแแแแ แแแแแขแแแแก แกแแแจแ "{1}"',
'errSQLLoginError': 'แจแแฃแซแแแแแแแ SQL แกแแ แแแ แแแ แแแแแแจแแ แแแ. แจแแแแแฌแแแ SQL แกแแ แแแ แแแ แแแแแแจแแ แแแแก แแแ แแแแขแ แแแแก แกแแกแฌแแ แ SQL แกแแ แแแ แแก แฉแแแแ แแแ แแ SQL แกแแ แแแ แแก แแแกแแฌแแแแแแแ.',
'ErrSqlQuery': 'แจแแชแแแแ sql แแแแฎแแแแแก แจแแกแ แฃแแแแแกแแก.',
'errSqlServerDoesntExist': 'แจแแฃแซแแแแแแแ SQLแกแแ แแแ แแแ แแแแแแจแแ แแแ. แแแฎแแแ. แจแแแแแฌแแแ, แ แแ แฅแกแแแแแ แแแแจแแ แ แฉแแ แแฃแแแ, SQL แกแแ แแแ แ แแ แแ แแก แแแแแจแฃแแ แแ แแแแแ แกแชแแแแ แแ แคแแ แแแก แแแฎแกแแ.',
'errSqlServerNotFound': 'แจแแฃแซแแแแแแแ \'{0}\' SQL แกแแ แแแ แแแ แแแแแแจแแ แแแ. แจแแแแแฌแแแ SQL แกแแ แแแ แแก แแแกแแฎแแแแแแก แกแแกแฌแแ แ แแ SQL แกแแ แแแ แแก แแแกแแฌแแแแแแแ.',
'ErrStoredProcedure': 'แแแแแชแแแแ แแแแแจแ แจแแแแฎแแแก แแ แแชแแแฃแ แแก แจแแกแ แฃแแแแแก แแ แแก แแแคแแฅแกแแ แแ แจแแชแแแแ',
'ErrUndefinedStdError': 'แแ แแแ แแแแจแ แจแแชแแแแแ. แแแฎแแแ แแแฃแแแแแแแ แแ แจแแชแแแแแแก แจแแกแแฎแแ แแแคแแ แแแชแแ แแ แแแ แแแแก แแแขแแ แแ แฏแแฃแคแก',
'errUnknownError': 'แแ แแแ แแแแจแ แจแแชแแแแแ',
'ErrUnprocessedError': 'แแ แแแ แแแแจแ แจแแชแแแแแ. แแแฎแแแ แแแฃแแแแแแแ แแ แจแแชแแแแแก แจแแกแแฎแแ แแแคแแ แแแชแแ แแ แแแ แแแแก แแแขแแ แแ แฏแแฃแคแก',
'ErrUserNotFound': 'แแแแฎแแแ แแแแแก แกแแฎแแแ แแ แแแแซแแแแ.',
'ErrWebTemporarilyUnavailableFunction': 'ErrWebTemporarilyUnavailableFunction',
'Message': 'แจแแขแงแแแแแแแ',
'msgCancel': 'แงแแแแ แจแแงแแแแแแ แแแแแชแแแ แแแแแแ แแแแ. แแแแแ แซแแแแแ?',
'msgCantDeleteRecord': 'แฉแแแแฌแแ แแก แฌแแจแแ แจแแฃแซแแแแแแแ.',
'msgClearControl': 'แแแแจแแแแแแแแก แฌแแกแแจแแแแแ แแแแฌแแฅแแ Ctrl-Del แแแแแแจแก.',
'msgConfimation': 'แแแแแกแขแฃแ แแแ',
'msgConfirmClearFlexForm': 'แแแแแกแฃแคแแแแ แแแแแแแก แจแแแแแแกแ?',
'msgConfirmClearLookup': 'แแแแแกแฃแคแแแแ แจแแแแแแกแ?',
'msgDeletePrompt': 'แแแแแฅแขแ แแฅแแแแ แแแแฆแแแฃแแ. แแแแฆแแแฃแ แแฅแแแก แแแแแฅแขแ?',
'msgDeleteRecordPrompt': 'แฉแแแแฌแแ แ แแฅแแแแ แแแแฆแแแฃแแ. แแกแฃแ แ แฉแแแแฌแแ แแก แแแแฆแแแ?',
'msgCancelPrompt': 'แแกแฃแ แ แงแแแแ แชแแแแแแแแก แแแฃแฅแแแแ แแ แคแแ แแแก แแแฎแฃแ แแ?',
'msgSavePrompt': 'แแกแฃแ แ แแแแแชแแแแแแก แจแแแแฎแแ?',
'msgOKPrompt': 'แแกแฃแ แ แแแแแชแแแแแแก แจแแแแฎแแ แแ แคแแ แแแก แแแฎแฃแ แแ?',
'msgEIDSSCopyright': 'แกแแแแขแแ แ แฃแคแแแแ ยฉ 2005-2011 Black && Veatch Special Projects Corp',
'msgEIDSSRunning': 'แแแแแก-แแก แแ แแแ แแฃแแแ แ แแแแแแแแแฏแแ แแแจแแแแ แจแแฃแซแแแแแแแ. แแแแแก แแ แแฎแแ แฃแแแ แแ แแก แแแจแแแแฃแแ.',
'msgEmptyLogin': 'แกแแกแขแแแแจแ แจแแกแแแ แแ แแ แแก แแแแกแแแฆแแ แฃแแ',
'msgMessage': 'แจแแขแงแแแแแแแ',
'msgNoDeletePermission': 'แแฅแแแ แแ แ แแแฅแแ แแ แแแแแฅแขแแก แฌแแจแแแก แฃแคแแแแ',
'msgNoFreeSpace': 'แแ แแแแแแแแแแแ แแแแแแ แแแแแกแฃแคแแแ แแแแแแ แแฆแแ แแ แแก',
'msgNoInsertPermission': 'แแฅแแแ แแ แแแฅแแ แแ แแแแแฅแขแแก แจแแฅแแแแก แฃแคแแแแ',
'msgNoRecordsFound': 'แซแแแแแก แแแชแแแฃแแ แแ แแขแแ แแฃแแแแแก แแแฎแแแแแ แฉแแแแฌแแ แ แแ แแแแแแแแแ.',
'msgNoSelectPermission': 'แแ แคแแ แแแก แแแฎแแแก แฃแคแแแแ แแ แแแฅแแ',
'msgParameterAlreadyExists': 'แแแแ แฃแแแ แแ แกแแแแแก',
'msgPasswordChanged': 'แแฅแแแแ แแแ แแแ แฌแแ แแแขแแแแ แจแแแชแแแแ.',
'msgPasswordNotTheSame': 'แแแ แแแแก แแแแแกแขแฃแ แแแ แแ แแกแฌแแ แแ.',
'msgReasonEmpty': 'แจแแแงแแแแแ แชแแแแแแแแก แจแแขแแแแก แแแแแแ',
'msgReplicationPrompt': 'แแแแฌแงแแก แ แแแแแแแชแแ แกแฎแแ แแแแแฅแขแแแแก แแแแแกแแฎแแ แแแแแชแแแแแแ?',
'msgREplicationPromptCaption': 'แแแแแแกแขแฃแ แแ แ แแแแแแแชแแ',
'msgWaitFormCaption': 'แแแฎแแแ แแแแแแแแแ',
'msgWaitFormLoading': 'แคแแ แแ แแขแแแ แแแแ',
'msgWrongDiagnosis': 'แจแแชแแแแแ แแแแแแแแ แฃแแแ แแแแกแฎแแแแแแแแแแก แกแแฌแงแแกแ แแแแแแแแแกแแแ.',
'Save data?': 'แแกแฃแ แ แแแแแชแแแแแแก แจแแแแฎแแ?',
'Warning': 'แแแคแ แแฎแแแแแ',
'SecurityLog_EIDSS_finished_successfully': 'แแแแแก-แ แแแแฎแฃแ แ แฌแแ แแแขแแแแ',
'SecurityLog_EIDSS_started_abnormaly': 'แแแแแก-แ แแแแจแแ แแ แแกแฌแแ แแ',
'SecurityLog_EIDSS_started_successfully': 'แแแแแก-แ แแแแจแแ แฌแแ แแแขแแแแ',
'strCancel_Id': 'แแแฃแฅแแแแ',
'strChangeDiagnosisReason_msgId': 'แแแแแแ แแ แแก แกแแแแแแแแฃแแ แแแแ.',
'strDelete_Id': 'แฌแแจแแ',
'strOK_Id': 'แแแแฎ',
'tooltipCancel_Id': 'แแแฃแฅแแแแ',
'tooltipClose_Id': 'แแแฎแฃแ แแ',
'tooltipDelete_Id': 'แฌแแจแแ',
'tooltipOK_Id': 'แแแแฎ',
'titleAccessionDetails': 'แแแขแแแฃแ แ แแแคแแ แแแชแแ แแแแฃแจแแแแก แแแฆแแแแก แจแแกแแฎแแ',
'titleAntibiotic': 'แแ แแแแ แแขแ',
'titleContactInformation': 'แแแคแแ แแแชแแ แแแแขแแฅแขแแก แจแแกแแฎแแ',
'titleDiagnosisChange': 'แแแแแแแแแก แจแแชแแแ',
'titleDuplicates': 'แแฃแแแแแแขแแแ',
'titleEmployeeDetails': 'แแแคแแ แแแชแแ แแแแแแจแ แแแแแก แจแแกแแฎแแ',
'titleEmployeeList': 'แแแแแแจแ แแแแแแ แฉแแแแแแแแแแ',
'titleGeoLocation': 'แแแแแ แแคแแฃแแ แแแแแแแแแแแ แแแแ',
'titleHumanCaseList': 'แแแแแแแแแ แแแแแแแแแแก แจแแแแฎแแแแแแ แฉแแแแแแแแแแ',
'titleOrganizationList': 'แแ แแแแแแแชแแแแแก แฉแแแแแแแแแแ',
'titlePersonsList': 'แแแ แแแแก แฉแแแแแแแแแแ',
'titleTestResultChange': 'แขแแกแขแแก แจแแแแแแก แจแแชแแแ',
'titleSampleDetails': 'แแแแฃแจแแก แแแขแแแฃแ แ แแแแแชแแแแแ',
'errLoginMandatoryFields': 'แงแแแแ แแแแแจแแแกแแแ แกแแแแแแแแฃแแแ.',
'msgAddToPreferencesPrompt': 'แแ แฉแแฃแแ แฉแแแแฌแแ แ แแแแแแขแแแ แจแแ แฉแแฃแ แฉแแแแฌแแ แแแก.',
'msgRemoveFromPreferencesPrompt': 'แแ แฉแแฃแแ แฉแแแแฌแแ แ แแแแฆแแแฃแแ แแฅแแแแ แจแแ แฉแแฃแแ แฉแแแแฌแแ แแแแแแ.',
'strAdd_Id': 'แแแแแขแแแ',
'strRemove_Id': 'แแแแฆแแแ',
'titleResultSummary': 'แจแแแแแแแแก แจแแฏแแแแแ แแ แแแขแแ แแ แแขแแชแแ',
'titleVeterinaryCaseList': 'แแแข แจแแแแฎแแแแแแ แฉแแแแแแแแแแ',
'titlePensideTest': 'แแฅแกแแ แแก แขแแกแขแ',
'titleTestDetails': 'แแแขแแแแแ',
'titleASSessionList': 'แแฅแขแแฃแ แ แแแแแแฎแแแแแแแแแก แกแแกแแแแแก แฉแแแแแแแแแแ',
'titleTestResultDetails': 'แขแแกแขแแก แจแแแแแแแแก แแแขแแแแแ',
'ErrObjectCantBeDeleted': 'แแแแแฅแขแแก แฌแแจแแ แจแแฃแซแแแแแแแ.',
'titleVaccination': 'แแแฅแชแแแแแชแแ',
'msgAsSessionNoCaseCreated': 'แแ แแ แแก แแแแแแแแ แจแแแแแแก แแฅแแแ แแแแฃแจแ.',
'strYes_Id': 'แแแแฎ',
'strNo_Id': 'แแ แ',
'titleClinicalSigns': 'แกแแฎแแแแแแแก แแแแแแแแแแแแแฃแ แ แแ แแแแแแแฃแ แ แแแแแแ',
'LastName': 'แแแแ แ',
'FirstName': 'แกแแฎแแแ',
'MiddleName': 'แแแแแก แกแแฎแแแ',
'AsCampaign_GetSessionRemovalConfirmation': 'แแฅแแแ แแแแแแแแแ แแกแฃแ แ แแแแจแแ แแก แแแแฆแแแ แจแแ แฉแแฃแแ แกแแกแแแแแ?',
'titleSelectFarm': 'แจแแแ แฉแแแ แคแแ แแ',
'ErrAllMandatoryFieldsRequired': 'You must enter data in all mandatory fields.'
}
}
|
EIDSS/EIDSS-Legacy
|
EIDSS v5/eidss.webclient/Scripts/Messages/EIDSS.BvMessages.ka-GE.js
|
JavaScript
|
bsd-2-clause
| 16,730 |
<!DOCTYPE html>
<html>
<head>
<title>Check Austrian Projection</title>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" type="text/css">
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
<script>
function read() {
if (map.getView().getZoom() > 12) {
document.getElementById('status').style.color = 'orange';
document.getElementById('status').innerHTML = "STATUS: Kein passender EPSG-Code gefunden. Verschieben Sie den Kartenausschnitt oder kontrollieren Sie die Eingabefelder der unbekannten Koordinate.";
var lon = document.getElementById('lon').value;
var lon_modulo = lon - (lon % 0.25);
var lon_string = "" + lon_modulo;
lon_string = lon_string.replace(".", "dot");
if (lon_string.indexOf("dot") == -1) {
lon_string = lon_string + "dot0";
}
lat = document.getElementById('lat').value;
var lat_modulo = lat - (lat % 0.25);
var lat_string = "" + lat_modulo;
lat_string = lat_string.replace(".", "dot");
if (lat_string.indexOf("dot") == -1) {
lat_string = lat_string + "dot0";
}
var path = lon_string + "_" + lat_string + ".txt";
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "https://raw.githubusercontent.com/maegger/CheckAustrianProjectionDatabase/master/" + path, true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) {
// Makes sure the document is ready to parse.
if (txtFile.status === 200) {
// Makes sure it's found the file.
inhalt = txtFile.responseText;
liste = inhalt.split("\n");
var arrayLength = liste.length;
for (var i = 0; i < arrayLength; i++) {
var epsg = liste[i].split(";")[0];
var wkt = liste[i].split(";")[1];
var x = document.getElementById('x').value;
var y = document.getElementById('y').value;
//var point_geom = new ol.geom.Point([x, y]);
var format = new ol.format.WKT();
var feature = format.readFeature(wkt);
if (ol.extent.containsXY(feature.getGeometry().getExtent(), x, y) == true) {
document.getElementById('status').style.color = 'green';
document.getElementById('status').innerHTML = "STATUS: Die Koordinate hat wahrscheinlich den EPSG-Code: " + epsg;
}
}
}
}
}
txtFile.send(null);
} else {
document.getElementById('status').style.color = 'red';
document.getElementById('status').innerHTML = "STATUS: Bitte navigieren Sie mit Zoom ('+') und Pan zu dem Ort, wo sich die unbekannte Koordinate befindet, bis die Farbe und der Inhalt dieses Text wechselt.";
}
}
</script>
<style>
.map {
background: white;
height: 75%;
width: 100%;
}
body, html {
height: 100%;
width: 100%;
}
* {
font-family: Arial, Helvetica, sans-serif;
padding-left: 3px;
padding-right: 3px;
font-weight: 600;
}
</style>
</head>
<body >
<div style="height: 85%;width: 100%">
<h1 style="font-weight: bold">Check Austrian Projection by Manfred Egger</h1>
Koordinate mit unbekannten EPSG-CODE eingeben :
X:
<input id="x" value="">
Y:
<input id="y" value="">
<br />
ACHTUNG: Dieser Prototyp testet die unbekannte Koordinate nur auf folgende EPSG-Codes:
4326;
31254;
31255;
31256;
31257;
31258;
31259;
31284;
31285;
31286;
31287;
25833;
25832
</br><br>
<div id="status" style="font-weight: bold"></div>
<br />
Mittelpunkt Karte: LAT:
<input id="lat" value="">
LON:
<input id="lon" value="">
<div id="map" class="map" style="width: 100%" ></div>
<br><br>
<div >Datenquelle: <a href="https://www.basemap.at/">basemap.at</a><br><a align="right" href="https://egger-gis.at"><img src="logo.png"></a></div>
</div>
<script>
var capabilitiesUrl = 'https://maps.wien.gv.at/basemap/1.0.0/WMTSCapabilities.xml';
// HiDPI support:
// * Use 'bmaphidpi' layer (pixel ratio 2) for device pixel ratio > 1
// * Use 'geolandbasemap' layer (pixel ratio 1) for device pixel ratio == 1
var hiDPI = ol.has.DEVICE_PIXEL_RATIO > 1;
var layer = hiDPI ? 'bmaphidpi' : 'geolandbasemap';
var tilePixelRatio = hiDPI ? 2 : 1;
var map = new ol.Map({
target: 'map',
view: new ol.View({
center: [1537897, 6039579],
zoom: 7
})
});
$.ajax(capabilitiesUrl).then(function(response) {
var result = new ol.format.WMTSCapabilities().read(response);
var options = ol.source.WMTS.optionsFromCapabilities(result, {
layer: layer,
matrixSet: 'google3857',
requestEncoding: 'REST',
style: 'normal'
});
options.tilePixelRatio = tilePixelRatio;
map.addLayer(new ol.layer.Tile({
source: new ol.source.WMTS(options)
}));
});
function display(id, value) {
document.getElementById(id).value = value.toFixed(3);
}
function wrapLon(value) {
var worlds = Math.floor((value + 180) / 360);
return value - (worlds * 360);
}
function onMoveEnd(evt) {
var map = evt.map;
var extent = map.getView().calculateExtent(map.getSize());
var center = ol.proj.transform(ol.extent.getCenter(extent), 'EPSG:3857', 'EPSG:4326');
display('lon', wrapLon(center[0]));
display('lat', wrapLon(center[1]));
read();
}
map.on('moveend', onMoveEnd);
</script>
</body>
</html>
|
maegger/maegger.github.io
|
map_austria.html
|
HTML
|
bsd-2-clause
| 7,224 |
#ifndef __H_UNET_OPEN_DEVICE__
#define __H_UNET_OPEN_DEVICE__
#include <unet/OpenCLDevice.hpp>
#include <vector>
namespace unet {
class OpenCLDeviceManager {
public:
static void Initialize();
static OpenCLDevice *GetDevice();
};
}
#endif
|
Sentimentron/unet
|
include/unet/OpenCLDeviceManager.hpp
|
C++
|
bsd-2-clause
| 294 |
//
// BasicWithTexture.cpp
// ShaderPlayground
//
// Created by Zhu Wen on 14-5-13.
// Copyright (c) 2014ๅนด K-Res. All rights reserved.
//
#include "BasicWithTexture.h"
#include "../Helpers.h"
#include "../Resources/banana.h"
BasicWithTexture::BasicWithTexture():
_tex(0),
_vertexArray(0),
_vertexBuffer(0),
_shader(NULL),
_rotation(0.f)
{
demoName = "BasicWithTexture";
}
void BasicWithTexture::SetupGL()
{
_shader = ShaderManager::Instance()->GetShader("BasicWithTexture");
glEnable(GL_DEPTH_TEST);
glGenVertexArraysOES(1, &_vertexArray);
glBindVertexArrayOES(_vertexArray);
glGenBuffers(1, &_vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(bananaVertexData), bananaVertexData, GL_STATIC_DRAW);
glEnableVertexAttribArray(VA_POSITION);
glVertexAttribPointer(VA_POSITION, 3, GL_FLOAT, GL_TRUE, 32, BUFFER_OFFSET(0));
glEnableVertexAttribArray(VA_NORMAL);
glVertexAttribPointer(VA_NORMAL, 3, GL_FLOAT, GL_TRUE, 32, BUFFER_OFFSET(12));
glEnableVertexAttribArray(VA_TEXCOORD);
glVertexAttribPointer(VA_TEXCOORD, 2, GL_FLOAT, GL_TRUE, 32, BUFFER_OFFSET(24));
glBindVertexArrayOES(0);
_tex = LoadGLTexture("banana.jpg");
DemoBase::SetupGL();
}
void BasicWithTexture::TearDownGL()
{
if (isLoaded)
{
glDeleteBuffers(1, &_vertexBuffer);
glDeleteVertexArraysOES(1, &_vertexArray);
glDeleteTextures(1, &_tex);
//ShaderManager::Instance()->DelShader(_shader);
}
DemoBase::TearDownGL();
}
void BasicWithTexture::Update(const float viewWidth, const float viewHeight, const float time)
{
// LOGI("BasicWithTexture update: %f rot: %f", time, _rotation);
float aspect = fabsf(viewWidth / viewHeight);
Matrix4f _matProj = perspective<float>(65.f, aspect, 0.1f, 100.f);
Affine3f _transBase;
_transBase = Translation3f(0.f, 0.f, -4.f)*AngleAxis<float>(_rotation, Vector3f(0.f, 1.f, 0.f));
Affine3f _transView;
Vector3f axis(1.f, 1.f, 1.f);
axis.normalize();
_transView = Translation3f(0.f, 0.f, -1.5f)*AngleAxis<float>(_rotation, axis)*Scaling(2.f);
_transView = _transBase*_transView;
_matNormal1 = _transView.matrix().inverse().transpose().topLeftCorner<3, 3>();
_matMVP1 = _matProj*_transView.matrix();
_transView = Translation3f(0.f, 0.f, 1.5f)*AngleAxis<float>(_rotation, axis)*Scaling(2.f);
_transView = _transBase*_transView;
_matNormal2 = _transView.matrix().inverse().transpose().topLeftCorner<3, 3>();
_matMVP2 = _matProj*_transView.matrix();
_rotation += time;
}
void BasicWithTexture::Render()
{
glClearColor(0.65f, 0.65f, 0.65f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Render the object again with ES2
glUseProgram(_shader->program);
glBindVertexArrayOES(_vertexArray);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, _tex);
glUniform1i(_shader->uniforms[UNIFORM_TEX], 0);
glUniformMatrix4fv(_shader->uniforms[UNIFORM_MVP], 1, 0, _matMVP1.data());
glUniformMatrix3fv(_shader->uniforms[UNIFORM_NORMAL], 1, 0, _matNormal1.data());
glDrawArrays(GL_TRIANGLES, 0, bananaNumVerts);
glUniformMatrix4fv(_shader->uniforms[UNIFORM_MVP], 1, 0, _matMVP2.data());
glUniformMatrix3fv(_shader->uniforms[UNIFORM_NORMAL], 1, 0, _matNormal2.data());
glDrawArrays(GL_TRIANGLES, 0, bananaNumVerts);
}
|
K-Res/ShaderPlayground-iOS
|
ShaderPlayground/Demos/BasicWithTexture.cpp
|
C++
|
bsd-2-clause
| 3,477 |
DROP VIEW IF EXISTS view_daftar_pengeluaran_distamben;
CREATE VIEW view_daftar_pengeluaran_distamben AS
SELECT
*
FROM
view_daftar_pengeluaran_kabupaten
WHERE
1 = 1 AND
id_skpd = 17;
GRANT ALL PRIVILEGES ON view_daftar_pengeluaran_distamben TO lap_distamben;
REVOKE INSERT, UPDATE, DELETE ON view_daftar_pengeluaran_distamben FROM lap_distamben;
|
muntaza/Open_Persediaan
|
sql1_persediaan/daftar_pengeluaran_barang_sql/daftar_pengeluaran_distamben.sql
|
SQL
|
bsd-2-clause
| 351 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.