text stringlengths 2 1.04M | meta dict |
|---|---|
'''Shortcode arbitrary integer base alphabet conversion'''
# http://stackoverflow.com/a/1119769/1524507
def int_to_str(num, alphabet):
'''Convert integer to string.'''
if (num == 0):
return alphabet[0]
arr = []
base = len(alphabet)
while num:
rem = num % base
num = num // base
arr.append(alphabet[rem])
arr.reverse()
return ''.join(arr)
def str_to_int(string, alphabet):
'''Convert string to integer.'''
base = len(alphabet)
strlen = len(string)
num = 0
idx = 0
for char in string:
power = (strlen - (idx + 1))
num += alphabet.rindex(char) * (base ** power)
idx += 1
return num
| {
"content_hash": "a0fb5ecee94384ad9a9b04284a6ba3e0",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 58,
"avg_line_length": 22.483870967741936,
"alnum_prop": 0.5652797704447633,
"repo_name": "hugovk/terroroftinytown",
"id": "739f2e55283558fc93a79cba61b05954b5a854b0",
"size": "714",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "terroroftinytown/client/alphabet.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2558"
},
{
"name": "HTML",
"bytes": "27247"
},
{
"name": "JavaScript",
"bytes": "4211"
},
{
"name": "Python",
"bytes": "234754"
}
],
"symlink_target": ""
} |
Tests
-----
If you are testing the current release of this plugin via bundler
```
bundle exec vagrant up default
```
## Expect
### Box `default`
- The box `default` is a docker container that will be a reverse
proxy. It should provision itself and work without errors.
- You can check that the proxy is working by
`tail -f /var/log/tinyproxy/tinyproxy.log` inside the container
- **NOTE**: You'll need to use `docker exec <hash> -it bash` to get into the container
### Box `apt_host`
- Vagrant should automatically instally docker-ce.
- The box should come up and provision itself with the proxy settings
configured in your Vagrantfile.
- **NOTE**: You can use `ssh` to connect to this container.
| {
"content_hash": "ce9fb9e45ce041a0a8e217c071216f69",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 88,
"avg_line_length": 23.677419354838708,
"alnum_prop": 0.7029972752043597,
"repo_name": "tmatilai/vagrant-proxyconf",
"id": "669d17f493ac2c84190d52665810afcfd5fc0d23",
"size": "734",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/issues/199/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Awk",
"bytes": "1268"
},
{
"name": "Dockerfile",
"bytes": "8595"
},
{
"name": "Ruby",
"bytes": "209668"
},
{
"name": "Shell",
"bytes": "8465"
}
],
"symlink_target": ""
} |
from pyramid_mailer.interfaces import IMailer
from pyramid_mailer.mailer import DummyMailer
def includeme(config):
mailer = DummyMailer()
config.registry.registerUtility(mailer, IMailer)
| {
"content_hash": "7036287a85724527a87312b5f02c7772",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 52,
"avg_line_length": 32.666666666666664,
"alnum_prop": 0.8010204081632653,
"repo_name": "dakra/pyramid_mailer",
"id": "7b11043a84f48606267d17ae9b6cbdc986a71017",
"size": "196",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pyramid_mailer/testing.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "86315"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Thu Mar 08 14:17:43 MST 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.wildfly.swarm.config.messaging.activemq.server.PooledConnectionFactory (BOM: * : All 2018.3.3 API)</title>
<meta name="date" content="2018-03-08">
<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.wildfly.swarm.config.messaging.activemq.server.PooledConnectionFactory (BOM: * : All 2018.3.3 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactory.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2018.3.3</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../index.html?org/wildfly/swarm/config/messaging/activemq/server/class-use/PooledConnectionFactory.html" target="_top">Frames</a></li>
<li><a href="PooledConnectionFactory.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>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.wildfly.swarm.config.messaging.activemq.server.PooledConnectionFactory" class="title">Uses of Class<br>org.wildfly.swarm.config.messaging.activemq.server.PooledConnectionFactory</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactory.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">PooledConnectionFactory</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.messaging.activemq">org.wildfly.swarm.config.messaging.activemq</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.messaging.activemq.server">org.wildfly.swarm.config.messaging.activemq.server</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.config.messaging.activemq">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactory.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">PooledConnectionFactory</a> in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/package-summary.html">org.wildfly.swarm.config.messaging.activemq</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/package-summary.html">org.wildfly.swarm.config.messaging.activemq</a> that return <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactory.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">PooledConnectionFactory</a></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>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactory.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">PooledConnectionFactory</a></code></td>
<td class="colLast"><span class="typeNameLabel">Server.ServerResources.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/Server.ServerResources.html#pooledConnectionFactory-java.lang.String-">pooledConnectionFactory</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> key)</code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/package-summary.html">org.wildfly.swarm.config.messaging.activemq</a> that return types with arguments of type <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactory.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">PooledConnectionFactory</a></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>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="http://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a><<a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactory.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">PooledConnectionFactory</a>></code></td>
<td class="colLast"><span class="typeNameLabel">Server.ServerResources.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/Server.ServerResources.html#pooledConnectionFactories--">pooledConnectionFactories</a></span>()</code>
<div class="block">Get the list of PooledConnectionFactory resources</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/package-summary.html">org.wildfly.swarm.config.messaging.activemq</a> with parameters of type <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactory.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">PooledConnectionFactory</a></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>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/Server.html" title="type parameter in Server">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">Server.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/Server.html#pooledConnectionFactory-org.wildfly.swarm.config.messaging.activemq.server.PooledConnectionFactory-">pooledConnectionFactory</a></span>(<a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactory.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">PooledConnectionFactory</a> value)</code>
<div class="block">Add the PooledConnectionFactory object to the list of subresources</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Method parameters in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/package-summary.html">org.wildfly.swarm.config.messaging.activemq</a> with type arguments of type <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactory.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">PooledConnectionFactory</a></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>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/Server.html" title="type parameter in Server">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">Server.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/Server.html#pooledConnectionFactories-java.util.List-">pooledConnectionFactories</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a><<a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactory.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">PooledConnectionFactory</a>> value)</code>
<div class="block">Add all PooledConnectionFactory objects to this subresource</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.wildfly.swarm.config.messaging.activemq.server">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactory.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">PooledConnectionFactory</a> in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/package-summary.html">org.wildfly.swarm.config.messaging.activemq.server</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/package-summary.html">org.wildfly.swarm.config.messaging.activemq.server</a> with type parameters of type <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactory.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">PooledConnectionFactory</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactory.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">PooledConnectionFactory</a><T extends <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactory.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">PooledConnectionFactory</a><T>></span></code>
<div class="block">Defines a managed connection factory.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>interface </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactoryConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server">PooledConnectionFactoryConsumer</a><T extends <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactory.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">PooledConnectionFactory</a><T>></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>interface </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactorySupplier.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server">PooledConnectionFactorySupplier</a><T extends <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactory.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">PooledConnectionFactory</a>></span></code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/package-summary.html">org.wildfly.swarm.config.messaging.activemq.server</a> that return <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactory.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">PooledConnectionFactory</a></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>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactory.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">PooledConnectionFactory</a></code></td>
<td class="colLast"><span class="typeNameLabel">PooledConnectionFactorySupplier.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactorySupplier.html#get--">get</a></span>()</code>
<div class="block">Constructed instance of PooledConnectionFactory resource</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/PooledConnectionFactory.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2018.3.3</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../index.html?org/wildfly/swarm/config/messaging/activemq/server/class-use/PooledConnectionFactory.html" target="_top">Frames</a></li>
<li><a href="PooledConnectionFactory.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>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2018 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "a93a05719e1d0bcf8809c551464402df",
"timestamp": "",
"source": "github",
"line_count": 260,
"max_line_length": 638,
"avg_line_length": 67.78076923076924,
"alnum_prop": 0.6877943596436475,
"repo_name": "wildfly-swarm/wildfly-swarm-javadocs",
"id": "f52e6e442f03add527e5ff5c8ba6fbbe9ba36fb4",
"size": "17623",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "2018.3.3/apidocs/org/wildfly/swarm/config/messaging/activemq/server/class-use/PooledConnectionFactory.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
\section{Evaluation}
All in all we are quite happy with \SPLC. Our added syntactic sugar and the
higher order functions make our implementation of \SPL{} quite comfortable to
program in. Due to the UNIX style interface it is quite easy to combine
usage of the compiler with \SSM.
There are however of course a lot of things to can be improved. We discuss a few
of the most interesting and most pressing issues. First of all error handling
in \SPLC{} can be greatly improved. Currently a lot of error happen at position
(0,0), most notably all type errors happen at this position. It would be a
great improvement in usability if errors would always be reported at the
correct position. A second issue is that in \SPLC{} it is not possible to
spread a program over multiple modules, when developing larger programs this
would be an absolute requirement. Thirdly \SPLC{} currently does not allow for
multiple recursion, and all functions need to be declared before they are
called. It would be nice to have multiple recursion and to not be forced to
structure your program in the order in which functions are called.
\subsection{Known Bugs}
For higher order functions there is a small bug that when an assignment is done
to a variable with a higher order function type where the number of arguments
is bigger than one and one of the, not-last, arguments is a higher order
functien itself the behaviour is unspecified. The bug happens because the
function is placed on the heap but the heap is distorted because one of the
arguments also modifies the heap. We are certain that with some time we can fix
this problem since it is an assembly issue.
\subsection{Work division}
\begin{description}
\item [Lexing \& parsing]:
\begin{description}
\item [\Yard] Pim
\item [Lexing] Mart \& Pim
\item [Parsing] Mostly Mart, some Pim
\item [Sugar] literal string: Mart, literal lists: Pim, Variable
arguments printing: Mart, Let-expansion: Pim, Lambdas: Pim
\end{description}
\item [Semantical analysis]:
\begin{description}
\item [Sanity checks] Mart
\item [Type inference] Mostly Pim, some Mart
\item [Lambda lifting] Pim
\end{description}
\item [Code generation]:
\begin{description}
\item [RWST monad] Mart
\item [Basic Generation] Mart \& Pim
\item [Higher order functions] Mart
\end{description}
\end{description}
\subsection{Metrics}
Between the February the seventh and June the sixth, $18.283$ lines of code
been written of which $12.497$ have been removed later on. Detailed records
can be found on the open git repository available on
\url{https://github.com/dopefishh/cc1516}. Most of the code is written with
pair programming.
The source code of \SPLC{} contains $2051$ lines of code, the rest of the lines
of code committed can be attributed to the presentations, test programs and
grammar specification.
| {
"content_hash": "d4aefd9842eda9e6d7bd9e4ef087fcc8",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 80,
"avg_line_length": 46.721311475409834,
"alnum_prop": 0.7729824561403509,
"repo_name": "dopefishh/cc1516",
"id": "70bbb9de9724b27ffb0ec039d6e1ad4f504ec689",
"size": "2850",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "deliverables/report/eval.tex",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Clean",
"bytes": "70636"
},
{
"name": "Makefile",
"bytes": "1923"
},
{
"name": "TeX",
"bytes": "78299"
}
],
"symlink_target": ""
} |
package org.killbill.billing.payment.core.janitor;
import java.util.UUID;
import org.killbill.notificationq.DefaultUUIDNotificationKey;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class JanitorNotificationKey extends DefaultUUIDNotificationKey {
private final String taskName;
// Could be NULL (backward compatibility)
private final Boolean isApiPayment;
private final Integer attemptNumber;
@JsonCreator
public JanitorNotificationKey(@JsonProperty("uuidKey") final UUID uuidKey,
@JsonProperty("taskName") final String taskName,
@JsonProperty("apiPayment") final Boolean isApiPayment,
@JsonProperty("attemptNumber") final Integer attemptNumber) {
super(uuidKey);
this.taskName = taskName;
this.isApiPayment = isApiPayment;
this.attemptNumber = attemptNumber;
}
public String getTaskName() {
return taskName;
}
public Boolean getApiPayment() {
return isApiPayment;
}
public Integer getAttemptNumber() {
return attemptNumber;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("JanitorNotificationKey{");
sb.append("taskName='").append(taskName).append('\'');
sb.append(", isApiPayment=").append(isApiPayment);
sb.append(", attemptNumber=").append(attemptNumber);
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
final JanitorNotificationKey that = (JanitorNotificationKey) o;
if (taskName != null ? !taskName.equals(that.taskName) : that.taskName != null) {
return false;
}
if (isApiPayment != null ? !isApiPayment.equals(that.isApiPayment) : that.isApiPayment != null) {
return false;
}
return attemptNumber != null ? attemptNumber.equals(that.attemptNumber) : that.attemptNumber == null;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (taskName != null ? taskName.hashCode() : 0);
result = 31 * result + (isApiPayment != null ? isApiPayment.hashCode() : 0);
result = 31 * result + (attemptNumber != null ? attemptNumber.hashCode() : 0);
return result;
}
}
| {
"content_hash": "e767c5cb8773fcfb5a1deaa1ff194d4c",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 109,
"avg_line_length": 32.30120481927711,
"alnum_prop": 0.6165609847071988,
"repo_name": "killbill/killbill",
"id": "fe614e92d7b197eec37b8df398acd3c1d68a9506",
"size": "3368",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "payment/src/main/java/org/killbill/billing/payment/core/janitor/JanitorNotificationKey.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "105855"
},
{
"name": "HTML",
"bytes": "16358"
},
{
"name": "Java",
"bytes": "13037928"
},
{
"name": "JavaScript",
"bytes": "136386"
},
{
"name": "Mustache",
"bytes": "4593"
},
{
"name": "PLpgSQL",
"bytes": "14609"
},
{
"name": "Ruby",
"bytes": "9048"
},
{
"name": "Shell",
"bytes": "22894"
}
],
"symlink_target": ""
} |
package nam.workspaceService;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.List;
import nam.NamRepository;
import nam.model.Workspace;
import nam.model.util.ModelFixture;
import nam.model.util.ModelHelper;
import org.aries.jaxb.JAXBSessionCache;
import org.aries.runtime.BeanContext;
import org.aries.tx.AbstractHandlerUnitTest;
import org.aries.tx.Transactional;
import org.aries.validate.util.CheckpointManager;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class WorkspaceServiceHandlerUnitTest extends AbstractHandlerUnitTest {
private WorkspaceServiceHandlerImpl fixture;
private NamRepository mockNamRepository;
public String getName() {
return "WorkspaceService";
}
public String getDomain() {
return "nam-service";
}
public Transactional getFixture() {
return fixture;
}
@Before
public void setUp() throws Exception {
mockNamRepository = mock(NamRepository.class);
CheckpointManager.addConfiguration("nam-service-checks.xml");
JAXBSessionCache jaxbSessionCache = new JAXBSessionCache(getDomain());
CheckpointManager.setJAXBSessionCache(jaxbSessionCache);
super.setUp();
}
@After
public void tearDown() throws Exception {
BeanContext.clear();
mockNamRepository = null;
fixture = null;
super.tearDown();
}
protected WorkspaceServiceHandlerImpl createFixture() throws Exception {
fixture = new WorkspaceServiceHandlerImpl();
fixture.namRepository = mockNamRepository;
initialize(fixture);
return fixture;
}
@Test
public void test_getWorkspaceList_Success() throws Exception {
List<Workspace> expectedWorkspaceRecords = ModelFixture.createWorkspace_List();
when(mockNamRepository.getAllWorkspaceRecords()).thenReturn(expectedWorkspaceRecords);
try {
fixture = createFixture();
List<Workspace> actualWorkspaceRecords = fixture.getWorkspaceList();
//TODO ModelHelper.assertWorkspaceRecordListEquals(expectedWorkspaceRecords, actualWorkspaceRecords);
} catch (Throwable e) {
validateAfterException(e);
} finally {
validateAfterExecution();
}
}
}
| {
"content_hash": "13b2fbe8f1d07be543e2ea0115d54215",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 104,
"avg_line_length": 26,
"alnum_prop": 0.7838196286472149,
"repo_name": "tfisher1226/ARIES",
"id": "24300a9d9de2e4b67ae7912729b5bd23b476b617",
"size": "2262",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "nam/nam-service/src/test/java/nam/workspaceService/WorkspaceServiceHandlerUnitTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1606"
},
{
"name": "CSS",
"bytes": "660469"
},
{
"name": "Common Lisp",
"bytes": "91717"
},
{
"name": "Emacs Lisp",
"bytes": "12403"
},
{
"name": "GAP",
"bytes": "86009"
},
{
"name": "HTML",
"bytes": "9381408"
},
{
"name": "Java",
"bytes": "25671734"
},
{
"name": "JavaScript",
"bytes": "304513"
},
{
"name": "Shell",
"bytes": "51942"
}
],
"symlink_target": ""
} |
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Copyright 2009 Google Inc. All Rights Reserved
/**
* @fileoverview Defines a Long class for representing a 64-bit two's-complement
* integer value, which faithfully simulates the behavior of a Java "long". This
* implementation is derived from LongLib in GWT.
*
*/
goog.info.Long='Long ... loaded ';
goog.provide('goog.math.Long')
/**
* Constructs a 64-bit two's-complement integer, given its low and high 32-bit
* values as *signed* integers. See the from* functions below for more
* convenient ways of constructing Longs.
*
* The internal representation of a long is the two given signed, 32-bit values.
* We use 32-bit pieces because these are the size of integers on which
* Javascript performs bit-operations. For operations like addition and
* multiplication, we split each number into 16-bit pieces, which can easily be
* multiplied within Javascript's floating-point representation without overflow
* or change in sign.
*
* In the algorithms below, we frequently reduce the negative case to the
* positive case by negating the input(s) and then post-processing the result.
* Note that we must ALWAYS check specially whether those values are MIN_VALUE
* (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
* a positive number, it overflows back into a negative). Not handling this
* case would often result in infinite recursion.
*
* @param {number} low The low (signed) 32 bits of the long.
* @param {number} high The high (signed) 32 bits of the long.
* @constructor
*/
goog.math.Long = function(low, high) {
/**
* @type {number}
* @private
*/
this.low_ = low | 0; // force into 32 signed bits.
/**
* @type {number}
* @private
*/
this.high_ = high | 0; // force into 32 signed bits.
};
// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the
// from* methods on which they depend.
/**
* A cache of the Long representations of small integer values.
* @type {Object}
* @private
*/
goog.math.Long.INT_CACHE_ = {};
/**
* Returns a Long representing the given (32-bit) integer value.
* @param {number} value The 32-bit integer in question.
* @return {goog.math.Long} The corresponding Long value.
*/
goog.math.Long.fromInt = function(value) {
if (-128 <= value && value < 128) {
var cachedObj = goog.math.Long.INT_CACHE_[value];
if (cachedObj) {
return cachedObj;
}
}
var obj = new goog.math.Long(value | 0, value < 0 ? -1 : 0);
if (-128 <= value && value < 128) {
goog.math.Long.INT_CACHE_[value] = obj;
}
return obj;
};
/**
* Returns a Long representing the given value, provided that it is a finite
* number. Otherwise, zero is returned.
* @param {number} value The number in question.
* @return {goog.math.Long} The corresponding Long value.
*/
goog.math.Long.fromNumber = function(value) {
if (isNaN(value) || !isFinite(value)) {
return goog.math.Long.ZERO;
} else if (value <= -goog.math.Long.TWO_PWR_63_DBL_) {
return goog.math.Long.MIN_VALUE;
} else if (value + 1 >= goog.math.Long.TWO_PWR_63_DBL_) {
return goog.math.Long.MAX_VALUE;
} else if (value < 0) {
return goog.math.Long.fromNumber(-value).negate();
} else {
return new goog.math.Long(
(value % goog.math.Long.TWO_PWR_32_DBL_) | 0,
(value / goog.math.Long.TWO_PWR_32_DBL_) | 0);
}
};
/**
* Returns a Long representing the 64-bit integer that comes by concatenating
* the given high and low bits. Each is assumed to use 32 bits.
* @param {number} lowBits The low 32-bits.
* @param {number} highBits The high 32-bits.
* @return {goog.math.Long} The corresponding Long value.
*/
goog.math.Long.fromBits = function(lowBits, highBits) {
return new goog.math.Long(lowBits, highBits);
};
/**
* Returns a Long representation of the given string, written using the given
* radix.
* @param {string} str The textual representation of the Long.
* @param {number} opt_radix The radix in which the text is written.
* @return {goog.math.Long} The corresponding Long value.
*/
goog.math.Long.fromString = function(str, opt_radix) {
if (str.length == 0) {
throw Error('number format error: empty string');
}
var radix = opt_radix || 10;
if (radix < 2 || 36 < radix) {
throw Error('radix out of range: ' + radix);
}
if (str.charAt(0) == '-') {
return goog.math.Long.fromString(str.substring(1), radix).negate();
} else if (str.indexOf('-') >= 0) {
throw Error('number format error: interior "-" character: ' + str);
}
// Do several (8) digits each time through the loop, so as to
// minimize the calls to the very expensive emulated div.
var radixToPower = goog.math.Long.fromNumber(Math.pow(radix, 8));
var result = goog.math.Long.ZERO;
for (var i = 0; i < str.length; i += 8) {
var size = Math.min(8, str.length - i);
var value = parseInt(str.substring(i, i + size), radix);
if (size < 8) {
var power = goog.math.Long.fromNumber(Math.pow(radix, size));
result = result.multiply(power).add(goog.math.Long.fromNumber(value));
} else {
result = result.multiply(radixToPower);
result = result.add(goog.math.Long.fromNumber(value));
}
}
return result;
};
// NOTE: the compiler should inline these constant values below and then remove
// these variables, so there should be no runtime penalty for these.
/**
* Number used repeated below in calculations. This must appear before the
* first call to any from* function below.
* @type {number}
* @private
*/
goog.math.Long.TWO_PWR_16_DBL_ = 1 << 16;
/**
* @type {number}
* @private
*/
goog.math.Long.TWO_PWR_24_DBL_ = 1 << 24;
/**
* @type {number}
* @private
*/
goog.math.Long.TWO_PWR_32_DBL_ =
goog.math.Long.TWO_PWR_16_DBL_ * goog.math.Long.TWO_PWR_16_DBL_;
/**
* @type {number}
* @private
*/
goog.math.Long.TWO_PWR_31_DBL_ =
goog.math.Long.TWO_PWR_32_DBL_ / 2;
/**
* @type {number}
* @private
*/
goog.math.Long.TWO_PWR_48_DBL_ =
goog.math.Long.TWO_PWR_32_DBL_ * goog.math.Long.TWO_PWR_16_DBL_;
/**
* @type {number}
* @private
*/
goog.math.Long.TWO_PWR_64_DBL_ =
goog.math.Long.TWO_PWR_32_DBL_ * goog.math.Long.TWO_PWR_32_DBL_;
/**
* @type {number}
* @private
*/
goog.math.Long.TWO_PWR_63_DBL_ =
goog.math.Long.TWO_PWR_64_DBL_ / 2;
/** @type {goog.math.Long} */
goog.math.Long.ZERO = goog.math.Long.fromInt(0);
/** @type {goog.math.Long} */
goog.math.Long.ONE = goog.math.Long.fromInt(1);
/** @type {goog.math.Long} */
goog.math.Long.NEG_ONE = goog.math.Long.fromInt(-1);
/** @type {goog.math.Long} */
goog.math.Long.MAX_VALUE =
goog.math.Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0);
/** @type {goog.math.Long} */
goog.math.Long.MIN_VALUE = goog.math.Long.fromBits(0, 0x80000000 | 0);
/**
* @type {goog.math.Long}
* @private
*/
goog.math.Long.TWO_PWR_24_ = goog.math.Long.fromInt(1 << 24);
/** @return {number} The value, assuming it is a 32-bit integer. */
goog.math.Long.prototype.toInt = function() {
return this.low_;
};
/** @return {number} The closest floating-point representation to this value. */
goog.math.Long.prototype.toNumber = function() {
return this.high_ * goog.math.Long.TWO_PWR_32_DBL_ +
this.getLowBitsUnsigned();
};
/**
* @param {number} opt_radix The radix in which the text should be written.
* @return {string} The textual representation of this value.
*/
goog.math.Long.prototype.toString = function(opt_radix) {
var radix = opt_radix || 10;
if (radix < 2 || 36 < radix) {
throw Error('radix out of range: ' + radix);
}
if (this.isZero()) {
return '0';
}
if (this.isNegative()) {
if (this.equals(goog.math.Long.MIN_VALUE)) {
// We need to change the Long value before it can be negated, so we remove
// the bottom-most digit in this base and then recurse to do the rest.
var radixLong = goog.math.Long.fromNumber(radix);
var div = this.div(radixLong);
var rem = div.multiply(radixLong).subtract(this);
return div.toString(radix) + rem.toInt().toString(radix);
} else {
return '-' + this.negate().toString(radix);
}
}
// Do several (6) digits each time through the loop, so as to
// minimize the calls to the very expensive emulated div.
var radixToPower = goog.math.Long.fromNumber(Math.pow(radix, 6));
var rem = this;
var result = '';
while (true) {
var remDiv = rem.div(radixToPower);
var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt();
var digits = intval.toString(radix);
rem = remDiv;
if (rem.isZero()) {
return digits + result;
} else {
while (digits.length < 6) {
digits = '0' + digits;
}
result = '' + digits + result;
}
}
};
/** @return {number} The high 32-bits as a signed value. */
goog.math.Long.prototype.getHighBits = function() {
return this.high_;
};
/** @return {number} The low 32-bits as a signed value. */
goog.math.Long.prototype.getLowBits = function() {
return this.low_;
};
/** @return {number} The low 32-bits as an unsigned value. */
goog.math.Long.prototype.getLowBitsUnsigned = function() {
return (this.low_ >= 0) ?
this.low_ : goog.math.Long.TWO_PWR_32_DBL_ + this.low_;
};
/**
* @return {number} Returns the number of bits needed to represent the absolute
* value of this Long.
*/
goog.math.Long.prototype.getNumBitsAbs = function() {
if (this.isNegative()) {
if (this.equals(goog.math.Long.MIN_VALUE)) {
return 64;
} else {
return this.negate().getNumBitsAbs();
}
} else {
var val = this.high_ != 0 ? this.high_ : this.low_;
for (var bit = 31; bit > 0; bit--) {
if ((val & (1 << bit)) != 0) {
break;
}
}
return this.high_ != 0 ? bit + 33 : bit + 1;
}
};
/** @return {boolean} Whether this value is zero. */
goog.math.Long.prototype.isZero = function() {
return this.high_ == 0 && this.low_ == 0;
};
/** @return {boolean} Whether this value is negative. */
goog.math.Long.prototype.isNegative = function() {
return this.high_ < 0;
};
/** @return {boolean} Whether this value is odd. */
goog.math.Long.prototype.isOdd = function() {
return (this.low_ & 1) == 1;
};
/**
* @param {goog.math.Long} other Long to compare against.
* @return {boolean} Whether this Long equals the other.
*/
goog.math.Long.prototype.equals = function(other) {
return (this.high_ == other.high_) && (this.low_ == other.low_);
};
/**
* @param {goog.math.Long} other Long to compare against.
* @return {boolean} Whether this Long does not equal the other.
*/
goog.math.Long.prototype.notEquals = function(other) {
return (this.high_ != other.high_) || (this.low_ != other.low_);
};
/**
* @param {goog.math.Long} other Long to compare against.
* @return {boolean} Whether this Long is less than the other.
*/
goog.math.Long.prototype.lessThan = function(other) {
return this.compare(other) < 0;
};
/**
* @param {goog.math.Long} other Long to compare against.
* @return {boolean} Whether this Long is less than or equal to the other.
*/
goog.math.Long.prototype.lessThanOrEqual = function(other) {
return this.compare(other) <= 0;
};
/**
* @param {goog.math.Long} other Long to compare against.
* @return {boolean} Whether this Long is greater than the other.
*/
goog.math.Long.prototype.greaterThan = function(other) {
return this.compare(other) > 0;
};
/**
* @param {goog.math.Long} other Long to compare against.
* @return {boolean} Whether this Long is greater than or equal to the other.
*/
goog.math.Long.prototype.greaterThanOrEqual = function(other) {
return this.compare(other) >= 0;
};
/**
* Compares this Long with the given one.
* @param {goog.math.Long} other Long to compare against.
* @return {number} 0 if they are the same, 1 if the this is greater, and -1
* if the given one is greater.
*/
goog.math.Long.prototype.compare = function(other) {
if (this.equals(other)) {
return 0;
}
var thisNeg = this.isNegative();
var otherNeg = other.isNegative();
if (thisNeg && !otherNeg) {
return -1;
}
if (!thisNeg && otherNeg) {
return 1;
}
// at this point, the signs are the same, so subtraction will not overflow
if (this.subtract(other).isNegative()) {
return -1;
} else {
return 1;
}
};
/** @return {goog.math.Long} The negation of this value. */
goog.math.Long.prototype.negate = function() {
if (this.equals(goog.math.Long.MIN_VALUE)) {
return goog.math.Long.MIN_VALUE;
} else {
return this.not().add(goog.math.Long.ONE);
}
};
/**
* Returns the sum of this and the given Long.
* @param {goog.math.Long} other Long to add to this one.
* @return {goog.math.Long} The sum of this and the given Long.
*/
goog.math.Long.prototype.add = function(other) {
// Divide each number into 4 chunks of 16 bits, and then sum the chunks.
var a48 = this.high_ >>> 16;
var a32 = this.high_ & 0xFFFF;
var a16 = this.low_ >>> 16;
var a00 = this.low_ & 0xFFFF;
var b48 = other.high_ >>> 16;
var b32 = other.high_ & 0xFFFF;
var b16 = other.low_ >>> 16;
var b00 = other.low_ & 0xFFFF;
var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
c00 += a00 + b00;
c16 += c00 >>> 16;
c00 &= 0xFFFF;
c16 += a16 + b16;
c32 += c16 >>> 16;
c16 &= 0xFFFF;
c32 += a32 + b32;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c48 += a48 + b48;
c48 &= 0xFFFF;
return goog.math.Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
};
/**
* Returns the difference of this and the given Long.
* @param {goog.math.Long} other Long to subtract from this.
* @return {goog.math.Long} The difference of this and the given Long.
*/
goog.math.Long.prototype.subtract = function(other) {
return this.add(other.negate());
};
/**
* Returns the product of this and the given long.
* @param {goog.math.Long} other Long to multiply with this.
* @return {goog.math.Long} The product of this and the other.
*/
goog.math.Long.prototype.multiply = function(other) {
if (this.isZero()) {
return goog.math.Long.ZERO;
} else if (other.isZero()) {
return goog.math.Long.ZERO;
}
if (this.equals(goog.math.Long.MIN_VALUE)) {
return other.isOdd() ? goog.math.Long.MIN_VALUE : goog.math.Long.ZERO;
} else if (other.equals(goog.math.Long.MIN_VALUE)) {
return this.isOdd() ? goog.math.Long.MIN_VALUE : goog.math.Long.ZERO;
}
if (this.isNegative()) {
if (other.isNegative()) {
return this.negate().multiply(other.negate());
} else {
return this.negate().multiply(other).negate();
}
} else if (other.isNegative()) {
return this.multiply(other.negate()).negate();
}
// If both longs are small, use float multiplication
if (this.lessThan(goog.math.Long.TWO_PWR_24_) &&
other.lessThan(goog.math.Long.TWO_PWR_24_)) {
return goog.math.Long.fromNumber(this.toNumber() * other.toNumber());
}
// Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
// We can skip products that would overflow.
var a48 = this.high_ >>> 16;
var a32 = this.high_ & 0xFFFF;
var a16 = this.low_ >>> 16;
var a00 = this.low_ & 0xFFFF;
var b48 = other.high_ >>> 16;
var b32 = other.high_ & 0xFFFF;
var b16 = other.low_ >>> 16;
var b00 = other.low_ & 0xFFFF;
var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
c00 += a00 * b00;
c16 += c00 >>> 16;
c00 &= 0xFFFF;
c16 += a16 * b00;
c32 += c16 >>> 16;
c16 &= 0xFFFF;
c16 += a00 * b16;
c32 += c16 >>> 16;
c16 &= 0xFFFF;
c32 += a32 * b00;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c32 += a16 * b16;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c32 += a00 * b32;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
c48 &= 0xFFFF;
return goog.math.Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
};
/**
* Returns this Long divided by the given one.
* @param {goog.math.Long} other Long by which to divide.
* @return {goog.math.Long} This Long divided by the given one.
*/
goog.math.Long.prototype.div = function(other) {
if (other.isZero()) {
throw Error('division by zero');
} else if (this.isZero()) {
return goog.math.Long.ZERO;
}
if (this.equals(goog.math.Long.MIN_VALUE)) {
if (other.equals(goog.math.Long.ONE) ||
other.equals(goog.math.Long.NEG_ONE)) {
return goog.math.Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
} else if (other.equals(goog.math.Long.MIN_VALUE)) {
return goog.math.Long.ONE;
} else {
// At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
var halfThis = this.shiftRight(1);
var approx = halfThis.div(other).shiftLeft(1);
if (approx.equals(goog.math.Long.ZERO)) {
return other.isNegative() ? goog.math.Long.ONE : goog.math.Long.NEG_ONE;
} else {
var rem = this.subtract(other.multiply(approx));
var result = approx.add(rem.div(other));
return result;
}
}
} else if (other.equals(goog.math.Long.MIN_VALUE)) {
return goog.math.Long.ZERO;
}
if (this.isNegative()) {
if (other.isNegative()) {
return this.negate().div(other.negate());
} else {
return this.negate().div(other).negate();
}
} else if (other.isNegative()) {
return this.div(other.negate()).negate();
}
// Repeat the following until the remainder is less than other: find a
// floating-point that approximates remainder / other *from below*, add this
// into the result, and subtract it from the remainder. It is critical that
// the approximate value is less than or equal to the real value so that the
// remainder never becomes negative.
var res = goog.math.Long.ZERO;
var rem = this;
while (rem.greaterThanOrEqual(other)) {
// Approximate the result of division. This may be a little greater or
// smaller than the actual value.
var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber()));
// We will tweak the approximate result by changing it in the 48-th digit or
// the smallest non-fractional digit, whichever is larger.
var log2 = Math.ceil(Math.log(approx) / Math.LN2);
var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48);
// Decrease the approximation until it is smaller than the remainder. Note
// that if it is too large, the product overflows and is negative.
var approxRes = goog.math.Long.fromNumber(approx);
var approxRem = approxRes.multiply(other);
while (approxRem.isNegative() || approxRem.greaterThan(rem)) {
approx -= delta;
approxRes = goog.math.Long.fromNumber(approx);
approxRem = approxRes.multiply(other);
}
// We know the answer can't be zero... and actually, zero would cause
// infinite recursion since we would make no progress.
if (approxRes.isZero()) {
approxRes = goog.math.Long.ONE;
}
res = res.add(approxRes);
rem = rem.subtract(approxRem);
}
return res;
};
/**
* Returns this Long modulo the given one.
* @param {goog.math.Long} other Long by which to mod.
* @return {goog.math.Long} This Long modulo the given one.
*/
goog.math.Long.prototype.modulo = function(other) {
return this.subtract(this.div(other).multiply(other));
};
/** @return {goog.math.Long} The bitwise-NOT of this value. */
goog.math.Long.prototype.not = function() {
return goog.math.Long.fromBits(~this.low_, ~this.high_);
};
/**
* Returns the bitwise-AND of this Long and the given one.
* @param {goog.math.Long} other The Long with which to AND.
* @return {goog.math.Long} The bitwise-AND of this and the other.
*/
goog.math.Long.prototype.and = function(other) {
return goog.math.Long.fromBits(this.low_ & other.low_,
this.high_ & other.high_);
};
/**
* Returns the bitwise-OR of this Long and the given one.
* @param {goog.math.Long} other The Long with which to OR.
* @return {goog.math.Long} The bitwise-OR of this and the other.
*/
goog.math.Long.prototype.or = function(other) {
return goog.math.Long.fromBits(this.low_ | other.low_,
this.high_ | other.high_);
};
/**
* Returns the bitwise-XOR of this Long and the given one.
* @param {goog.math.Long} other The Long with which to XOR.
* @return {goog.math.Long} The bitwise-XOR of this and the other.
*/
goog.math.Long.prototype.xor = function(other) {
return goog.math.Long.fromBits(this.low_ ^ other.low_,
this.high_ ^ other.high_);
};
/**
* Returns this Long with bits shifted to the left by the given amount.
* @param {number} numBits The number of bits by which to shift.
* @return {goog.math.Long} This shifted to the left by the given amount.
*/
goog.math.Long.prototype.shiftLeft = function(numBits) {
numBits &= 63;
if (numBits == 0) {
return this;
} else {
var low = this.low_;
if (numBits < 32) {
var high = this.high_;
return goog.math.Long.fromBits(
low << numBits,
(high << numBits) | (low >>> (32 - numBits)));
} else {
return goog.math.Long.fromBits(0, low << (numBits - 32));
}
}
};
/**
* Returns this Long with bits shifted to the right by the given amount.
* @param {number} numBits The number of bits by which to shift.
* @return {goog.math.Long} This shifted to the right by the given amount.
*/
goog.math.Long.prototype.shiftRight = function(numBits) {
numBits &= 63;
if (numBits == 0) {
return this;
} else {
var high = this.high_;
if (numBits < 32) {
var low = this.low_;
return goog.math.Long.fromBits(
(low >>> numBits) | (high << (32 - numBits)),
high >> numBits);
} else {
return goog.math.Long.fromBits(
high >> (numBits - 32),
high >= 0 ? 0 : -1);
}
}
};
/**
* Returns this Long with bits shifted to the right by the given amount, with
* the new top bits matching the current sign bit.
* @param {number} numBits The number of bits by which to shift.
* @return {goog.math.Long} This shifted to the right by the given amount, with
* zeros placed into the new leading bits.
*/
goog.math.Long.prototype.shiftRightUnsigned = function(numBits) {
numBits &= 63;
if (numBits == 0) {
return this;
} else {
var high = this.high_;
if (numBits < 32) {
var low = this.low_;
return goog.math.Long.fromBits(
(low >>> numBits) | (high << (32 - numBits)),
high >>> numBits);
} else if (numBits == 32) {
return goog.math.Long.fromBits(high, 0);
} else {
return goog.math.Long.fromBits(high >>> (numBits - 32), 0);
}
}
};
| {
"content_hash": "950f369ccc3b784f496e2b798e2e14b7",
"timestamp": "",
"source": "github",
"line_count": 790,
"max_line_length": 80,
"avg_line_length": 29.430379746835442,
"alnum_prop": 0.6387096774193548,
"repo_name": "dapangchi/stampcircles",
"id": "3337bdb580e8aac4d71aa455ddc6f0e4fe1195da",
"size": "23250",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/goog/math/long.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ABAP",
"bytes": "1924"
},
{
"name": "ActionScript",
"bytes": "18248"
},
{
"name": "ApacheConf",
"bytes": "1458"
},
{
"name": "Assembly",
"bytes": "1012"
},
{
"name": "AutoHotkey",
"bytes": "1440"
},
{
"name": "Batchfile",
"bytes": "520"
},
{
"name": "C#",
"bytes": "166"
},
{
"name": "C++",
"bytes": "1522"
},
{
"name": "CSS",
"bytes": "789836"
},
{
"name": "Clojure",
"bytes": "1588"
},
{
"name": "CoffeeScript",
"bytes": "806"
},
{
"name": "ColdFusion",
"bytes": "172"
},
{
"name": "Common Lisp",
"bytes": "1264"
},
{
"name": "Dart",
"bytes": "1968"
},
{
"name": "Erlang",
"bytes": "2756"
},
{
"name": "Forth",
"bytes": "1958"
},
{
"name": "FreeMarker",
"bytes": "2034"
},
{
"name": "GLSL",
"bytes": "1024"
},
{
"name": "Go",
"bytes": "1282"
},
{
"name": "Groovy",
"bytes": "2160"
},
{
"name": "HTML",
"bytes": "7118863"
},
{
"name": "Haskell",
"bytes": "1024"
},
{
"name": "Haxe",
"bytes": "894"
},
{
"name": "Java",
"bytes": "3100"
},
{
"name": "JavaScript",
"bytes": "97295928"
},
{
"name": "Julia",
"bytes": "404"
},
{
"name": "LSL",
"bytes": "4248"
},
{
"name": "Liquid",
"bytes": "3766"
},
{
"name": "LiveScript",
"bytes": "11494"
},
{
"name": "Lua",
"bytes": "1962"
},
{
"name": "Makefile",
"bytes": "9893"
},
{
"name": "OCaml",
"bytes": "1078"
},
{
"name": "Objective-C",
"bytes": "5344"
},
{
"name": "OpenSCAD",
"bytes": "666"
},
{
"name": "PHP",
"bytes": "3800480"
},
{
"name": "Pascal",
"bytes": "2824"
},
{
"name": "Perl",
"bytes": "1356"
},
{
"name": "PowerShell",
"bytes": "836"
},
{
"name": "Python",
"bytes": "23303"
},
{
"name": "R",
"bytes": "4890"
},
{
"name": "Ruby",
"bytes": "10601"
},
{
"name": "Rust",
"bytes": "990"
},
{
"name": "Scala",
"bytes": "3082"
},
{
"name": "Scheme",
"bytes": "1118"
},
{
"name": "Shell",
"bytes": "2401"
},
{
"name": "Tcl",
"bytes": "1798"
},
{
"name": "TeX",
"bytes": "135485"
},
{
"name": "TypeScript",
"bytes": "3214"
},
{
"name": "Visual Basic",
"bytes": "1832"
},
{
"name": "XQuery",
"bytes": "228"
},
{
"name": "XSLT",
"bytes": "1175"
}
],
"symlink_target": ""
} |
namespace bitbots_ros_control {
class LedsHardwareInterface : public bitbots_ros_control::HardwareInterface{
public:
LedsHardwareInterface(rclcpp::Node::SharedPtr nh,
std::shared_ptr<DynamixelDriver> &driver,
uint8_t id,
uint8_t num_leds,
uint8_t start_number);
bool init();
void read(const rclcpp::Time &t, const rclcpp::Duration &dt);
void write(const rclcpp::Time &t, const rclcpp::Duration &dt);
private:
rclcpp::Node::SharedPtr nh_;
std::shared_ptr<DynamixelDriver> driver_;
uint8_t id_;
uint8_t start_number_;
bool write_leds_ = false;
std::vector<std_msgs::msg::ColorRGBA> leds_;
rclcpp::Service<bitbots_msgs::srv::Leds>::SharedPtr leds_service_;
void setLeds(const std::shared_ptr<bitbots_msgs::srv::Leds::Request> req, std::shared_ptr<bitbots_msgs::srv::Leds::Response> resp);
void ledCb0(std_msgs::msg::ColorRGBA msg);
void ledCb1(std_msgs::msg::ColorRGBA msg);
void ledCb2(std_msgs::msg::ColorRGBA msg);
rclcpp::Subscription<std_msgs::msg::ColorRGBA>::SharedPtr sub0_;
rclcpp::Subscription<std_msgs::msg::ColorRGBA>::SharedPtr sub1_;
rclcpp::Subscription<std_msgs::msg::ColorRGBA>::SharedPtr sub2_;
};
}
#endif | {
"content_hash": "283e17b4a075ec5a85621e7631e988b4",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 133,
"avg_line_length": 36.02857142857143,
"alnum_prop": 0.6708961141950832,
"repo_name": "bit-bots/bitbots_lowlevel",
"id": "7bb05bc9b7b8663bb11c7f5fce11bfedc61241e6",
"size": "1596",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bitbots_ros_control/include/bitbots_ros_control/leds_hardware_interface.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "132796"
},
{
"name": "CMake",
"bytes": "5100"
},
{
"name": "Python",
"bytes": "32411"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<!--
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_ImportExport:etc/export.xsd">
<entityType entity="catalog_product" name="bundle" model="Magento\BundleImportExport\Model\Export\Product\Type\Bundle" />
</config>
| {
"content_hash": "b06078e1374560ce0671578b07e42d5a",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 149,
"avg_line_length": 45.42857142857143,
"alnum_prop": 0.7484276729559748,
"repo_name": "j-froehlich/magento2_wk",
"id": "c7fd951bfab53b4b48b3550a859273ec0995d708",
"size": "426",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vendor/magento/module-bundle-import-export/etc/export.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "13636"
},
{
"name": "CSS",
"bytes": "2076720"
},
{
"name": "HTML",
"bytes": "6151072"
},
{
"name": "JavaScript",
"bytes": "2488727"
},
{
"name": "PHP",
"bytes": "12466046"
},
{
"name": "Shell",
"bytes": "6088"
},
{
"name": "XSLT",
"bytes": "19979"
}
],
"symlink_target": ""
} |
using System;
using Serilog;
namespace Nimbus.Logger.Serilog
{
public class SerilogStaticLogger : ILogger
{
public void Debug(string format, params object[] args)
{
Log.Debug(format, args);
}
public void Info(string format, params object[] args)
{
Log.Information(format, args);
}
public void Warn(string format, params object[] args)
{
Log.Warning(format, args);
}
public void Warn(Exception exc, string format, params object[] args)
{
Log.Warning(exc, format, args);
}
public void Error(string format, params object[] args)
{
Log.Error(format, args);
}
public void Error(Exception exc, string format, params object[] args)
{
Log.Error(exc, format, args);
}
}
} | {
"content_hash": "27e82aae20e1026e29a2733da0b5d28e",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 77,
"avg_line_length": 23.605263157894736,
"alnum_prop": 0.5473801560758083,
"repo_name": "KodrAus/Nimbus",
"id": "ea670ad1e43240d70dabf50779ff6be8e05c031c",
"size": "899",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Extensions/Nimbus.Logger.Serilog/Logger/Serilog/SerilogStaticLogger.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "106"
},
{
"name": "C#",
"bytes": "948023"
},
{
"name": "CSS",
"bytes": "685"
},
{
"name": "HTML",
"bytes": "5125"
},
{
"name": "JavaScript",
"bytes": "21032"
},
{
"name": "PowerShell",
"bytes": "20908"
}
],
"symlink_target": ""
} |
package org.dozer.functional_tests;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.dozer.CustomFieldMapper;
import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;
import org.dozer.functional_tests.support.SampleDefaultBeanFactory;
import org.dozer.functional_tests.support.TestCustomFieldMapper;
import org.dozer.util.CollectionUtils;
import org.dozer.vo.AnotherTestObject;
import org.dozer.vo.AnotherTestObjectPrime;
import org.dozer.vo.FieldValue;
import org.dozer.vo.Fruit;
import org.dozer.vo.InsideTestObject;
import org.dozer.vo.MethodFieldTestObject;
import org.dozer.vo.MethodFieldTestObject2;
import org.dozer.vo.NoReadMethod;
import org.dozer.vo.NoReadMethodPrime;
import org.dozer.vo.NoVoidSetters;
import org.dozer.vo.NoWriteMethod;
import org.dozer.vo.NoWriteMethodPrime;
import org.dozer.vo.PrimitiveArrayObj;
import org.dozer.vo.PrimitiveArrayObjPrime;
import org.dozer.vo.SimpleObj;
import org.dozer.vo.SimpleObjPrime;
import org.dozer.vo.TestObject;
import org.dozer.vo.TestObjectPrime;
import org.dozer.vo.TestObjectPrime2;
import org.dozer.vo.allowedexceptions.ThrowException;
import org.dozer.vo.allowedexceptions.ThrowExceptionPrime;
import org.dozer.vo.context.ContextMapping;
import org.dozer.vo.context.ContextMappingNested;
import org.dozer.vo.context.ContextMappingNestedPrime;
import org.dozer.vo.context.ContextMappingPrime;
import org.dozer.vo.iface.ApplicationUser;
import org.dozer.vo.iface.UpdateMember;
import org.dozer.vo.index.Mccoy;
import org.dozer.vo.index.MccoyPrime;
import org.dozer.vo.isaccessible.Foo;
import org.dozer.vo.isaccessible.FooPrime;
import org.dozer.vo.isaccessible.PrivateConstructorBean;
import org.dozer.vo.isaccessible.PrivateConstructorBeanPrime;
import org.dozer.vo.orphan.Child;
import org.dozer.vo.orphan.ChildPrime;
import org.dozer.vo.orphan.Parent;
import org.dozer.vo.orphan.ParentPrime;
import org.dozer.vo.perf.MyClassA;
import org.dozer.vo.perf.MyClassB;
import org.dozer.vo.set.NamesArray;
import org.dozer.vo.set.NamesCollection;
import org.dozer.vo.set.NamesSet;
import org.dozer.vo.set.NamesSortedSet;
import org.dozer.vo.set.SomeDTO;
import org.dozer.vo.set.SomeOtherDTO;
import org.dozer.vo.set.SomeVO;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author garsombke.franz
*/
public class GranularDozerBeanMapperTest extends AbstractFunctionalTest {
@Test
public void testFieldAccessible() throws Exception {
Mapper mapper = getMapper("fieldAttributeMapping.xml");
TestObject to = newInstance(TestObject.class);
to.setFieldAccessible("fieldAccessible");
to.setFieldAccessiblePrimInt(2);
InsideTestObject ito = newInstance(InsideTestObject.class);
ito.setLabel("label");
to.setFieldAccessibleComplexType(ito);
String[] stringArray = new String[] { "one", "two" };
to.setFieldAccessibleArrayToList(stringArray);
TestObjectPrime top = mapper.map(to, TestObjectPrime.class);
assertEquals("fieldAccessible", top.fieldAccessible);
assertEquals("label", top.fieldAccessibleComplexType.getLabelPrime());
assertEquals(2, top.fieldAccessiblePrimInt);
assertEquals("one", top.fieldAccessibleArrayToList.get(0));
assertEquals("two", top.fieldAccessibleArrayToList.get(1));
// Map Back
TestObject toDest = mapper.map(top, TestObject.class);
assertEquals("fieldAccessible", toDest.getFieldAccessible());
assertEquals("label", toDest.getFieldAccessibleComplexType().getLabel());
assertEquals(2, toDest.getFieldAccessiblePrimInt());
assertEquals("one", toDest.getFieldAccessibleArrayToList()[0]);
assertEquals("two", toDest.getFieldAccessibleArrayToList()[1]);
}
@Test
public void testOverloadGetSetMethods() throws Exception {
Mapper mapper = getMapper("fieldAttributeMapping.xml");
TestObject to = newInstance(TestObject.class);
Date date = new Date();
to.setOverloadGetField(new Date());
TestObjectPrime top = mapper.map(to, TestObjectPrime.class);
assertEquals(date, top.getOverloadSetField());
// Map Back
TestObject toDest = (TestObject) mapper.map(top, TestObject.class);
assertEquals(date, toDest.getOverloadGetField());
}
@Test
public void testFieldCreateMethod() throws Exception {
Mapper mapper = getMapper("fieldAttributeMapping.xml");
TestObject to = newInstance(TestObject.class);
InsideTestObject ito = newInstance(InsideTestObject.class);
// we did not set any values. this will be set in the 'createMethod'
to.setCreateMethodType(ito);
TestObjectPrime top = mapper.map(to, TestObjectPrime.class);
assertEquals("myField", top.getCreateMethodType().getMyField());
// Map Back
TestObject toDest = mapper.map(top, TestObject.class);
assertEquals("testCreateMethod", toDest.getCreateMethodType().getTestCreateMethod());
}
@Test
public void testIntegerToString() throws Exception {
Mapper mapper = getMapper("fieldAttributeMapping.xml");
TestObject to = newInstance(TestObject.class);
Integer[] array = new Integer[] { new Integer(1), new Integer(2) };
to.setArrayForLists(array);
TestObjectPrime top = mapper.map(to, TestObjectPrime.class);
assertEquals("1", top.getListForArray().get(0));
}
@Test
public void testMapNull_MappingLevel() throws Exception {
Mapper mapper = getMapper("nullFieldMapping.xml");
// check that null does not override an existing value when map-null="false"
AnotherTestObject src = newInstance(AnotherTestObject.class);
src.setField3(null);
src.setField4(null);
AnotherTestObjectPrime dest = newInstance(AnotherTestObjectPrime.class);
dest.setTo(newInstance(TestObject.class));
dest.setField3("555");
dest.getTo().setOne("4641");
// dest field should remain unchanged
mapper.map(src, dest);
assertEquals("invalid dest field value", "555", dest.getField3());
assertEquals("invalid dest field value2", "4641", dest.getTo().getOne());
}
@Test
public void testMapNull_MappingLevel2() throws Exception {
Mapper mapper = getMapper("nullFieldMapping.xml");
// Reverse mapping
AnotherTestObjectPrime src = newInstance(AnotherTestObjectPrime.class);
src.setTo(newInstance(TestObject.class));
src.setField3(null);
src.getTo().setOne(null);
AnotherTestObject dest = newInstance(AnotherTestObject.class);
dest.setField3("555");
dest.setField4("4641");
// dest field should remain unchanged
mapper.map(src, dest);
assertEquals("invalid dest field value", "555", dest.getField3());
assertEquals("invalid dest field value2", "4641", dest.getField4());
}
@Test
public void testMapEmptyString_MappingLevel() throws Exception {
Mapper mapper = getMapper("nullFieldMapping.xml");
// check that "" does not override an existing value when
// map-empty-string="false"
AnotherTestObject src = newInstance(AnotherTestObject.class);
src.setField3("");
src.setField4("");
AnotherTestObjectPrime dest = newInstance(AnotherTestObjectPrime.class);
dest.setTo(newInstance(TestObject.class));
dest.setField3("555");
dest.getTo().setOne("4641");
// dest field should remain unchanged
mapper.map(src, dest);
assertEquals("invalid dest field value", "555", dest.getField3());
assertEquals("invalid dest field value2", "4641", dest.getTo().getOne());
}
@Test
public void testMapEmptyString_MappingLevel2() throws Exception {
Mapper mapper = getMapper("nullFieldMapping.xml");
// reverse mapping
AnotherTestObjectPrime src = newInstance(AnotherTestObjectPrime.class);
src.setTo(newInstance(TestObject.class));
src.setField3("");
src.getTo().setOne("");
AnotherTestObject dest = newInstance(AnotherTestObject.class);
dest.setField3("555");
dest.setField4("4641");
// dest field should remain unchanged
mapper.map(src, dest);
assertEquals("invalid dest field value", "555", dest.getField3());
assertEquals("invalid dest field value2", "4641", dest.getField4());
}
@Test
public void testMapNull_ClassLevel() throws Exception {
Mapper mapper = getMapper("nullFieldMapping.xml");
// check that null does not override an existing value when map-null="false"
TestObject src = newInstance(TestObject.class);
src.setOne(null);
TestObjectPrime2 dest = newInstance(TestObjectPrime2.class);
dest.setOne("555");
// dest field should remain unchanged
mapper.map(src, dest);
assertNotNull("dest should not be null", dest.getOne());
assertEquals("invalid dest field value", "555", dest.getOne());
// reverse mapping
TestObjectPrime2 src2 = newInstance(TestObjectPrime2.class);
src2.setOne(null);
TestObject dest2 = newInstance(TestObject.class);
dest2.setOne("555");
// dest field should NOT remain unchanged
mapper.map(src2, dest2);
assertNull("dest should be null", dest2.getOne());
}
@Test
public void testMapEmptyString_ClassLevel() throws Exception {
Mapper mapper = getMapper("nullFieldMapping.xml");
// check that "" does not override an existing value when
// map-empty-string="false"
TestObject src = newInstance(TestObject.class);
src.setOne("");
TestObjectPrime2 dest = newInstance(TestObjectPrime2.class);
dest.setOne("555");
// dest field should remain unchanged
mapper.map(src, dest);
assertNotNull("dest should not be null", dest.getOne());
assertEquals("invalid dest field value", "555", dest.getOne());
// reverse mapping
TestObjectPrime2 src2 = newInstance(TestObjectPrime2.class);
src2.setOne("");
TestObject dest2 = newInstance(TestObject.class);
dest2.setOne("555");
// dest field should NOT remain unchanged
mapper.map(src2, dest2);
assertNotNull("dest should not be null", dest2.getOne());
assertEquals("dest should be an empty string", "", dest2.getOne());
}
@Test
public void testContextMappingWithNestedContext() throws Exception {
Mapper mapper = getMapper("contextMapping.xml");
ContextMappingNested cmn = newInstance(ContextMappingNested.class);
cmn.setLoanNo("loanNoNested");
List<ContextMappingNested> list = newInstance(ArrayList.class);
list.add(cmn);
ContextMapping cm = newInstance(ContextMapping.class);
cm.setLoanNo("loanNo");
cm.setContextList(list);
ContextMappingPrime cmpA = mapper.map(cm, ContextMappingPrime.class, "caseA");
assertNull(cmpA.getLoanNo());
assertNull(((ContextMappingNestedPrime) cmpA.getContextList().get(0)).getLoanNo());
ContextMappingPrime cmpB = mapper.map(cm, ContextMappingPrime.class, "caseB");
assertEquals("loanNo", cmpB.getLoanNo());
assertEquals("loanNoNested", ((ContextMappingNested) cmpB.getContextList().get(0)).getLoanNo());
ContextMappingNestedPrime cmn2 = newInstance(ContextMappingNestedPrime.class);
cmn2.setLoanNo("loanNoNested");
List<ContextMappingNestedPrime> list2 = newInstance(ArrayList.class);
list2.add(cmn2);
ContextMappingPrime prime = newInstance(ContextMappingPrime.class);
prime.setLoanNo("loanNo");
prime.setContextList(list2);
ContextMapping cmDest = mapper.map(prime, ContextMapping.class, "caseA");
assertNull(cmDest.getLoanNo());
assertNull(((ContextMappingNested) cmDest.getContextList().get(0)).getLoanNo());
ContextMapping cmpBDest = mapper.map(prime, ContextMapping.class, "caseB");
assertEquals("loanNo", cmpBDest.getLoanNo());
assertEquals("loanNoNested", ((ContextMappingNestedPrime) cmpBDest.getContextList().get(0)).getLoanNo());
}
@Test
public void testArrayToSortedSet() {
NamesArray from = newInstance(NamesArray.class);
String[] names = { "John", "Bill", "Tony", "Fred", "Bruce" };
from.setNames(names);
NamesSortedSet to = mapper.map(from, NamesSortedSet.class);
assertNotNull(to);
assertEquals(names.length, to.getNames().size());
}
@Test
public void testSortedSetToArray() {
NamesSortedSet from = newInstance(NamesSortedSet.class);
NamesArray to = null;
SortedSet<String> names = newInstance(TreeSet.class);
names.add("Jen");
names.add("Sue");
names.add("Sally");
names.add("Jill");
from.setNames(names);
to = mapper.map(from, NamesArray.class);
assertNotNull(to);
assertEquals(names.size(), to.getNames().length);
}
@Test
public void testSetToSortedSet() {
NamesSet from = newInstance(NamesSet.class);
NamesSortedSet to = null;
Set<String> names = newInstance(HashSet.class);
names.add("Red");
names.add("Blue");
names.add("Green");
from.setNames(names);
to = mapper.map(from, NamesSortedSet.class);
assertNotNull(to);
assertEquals(names.size(), to.getNames().size());
}
/**
* When the source type is a Set and the destination is a Collection we expect that the
* mapper narrows to the Set type instead of using a List by default.
*
* issue https://github.com/DozerMapper/dozer/issues/287
*/
@Test
public void testSetToCollection() {
NamesSet from = newInstance(NamesSet.class);
NamesCollection to;
Set<String> names = newInstance(HashSet.class);
names.add("Red");
names.add("Blue");
names.add("Green");
names.add("Green");
from.setNames(names);
to = mapper.map(from, NamesCollection.class);
assertNotNull(to);
assertTrue(to.getNames() instanceof Set);
assertThat(to.getNames().size(), is(3));
assertEquals(names.size(), to.getNames().size());
}
@Test
public void testSortedSetToSet() {
NamesSortedSet from = newInstance(NamesSortedSet.class);
NamesSet to = null;
SortedSet<String> names = newInstance(TreeSet.class);
names.add("Bone");
names.add("White");
names.add("Beige");
names.add("Ivory");
names.add("Cream");
names.add("Off white");
from.setNames(names);
to = mapper.map(from, NamesSet.class);
assertNotNull(to);
assertEquals(names.size(), to.getNames().size());
}
@Test
public void testSetPrivateField() {
mapper = getMapper("isaccessiblemapping.xml");
Foo src = newInstance(Foo.class);
List<String> list = (ArrayList<String>) newInstance(ArrayList.class);
list.add("test1");
list.add("test2");
src.setCategories(list);
FooPrime dest = mapper.map(src, FooPrime.class);
assertNotNull(dest);
}
@Test
public void testStringToIndexedSet_UsingHint() {
mapper = getMapper("indexMapping.xml");
Mccoy src = newInstance(Mccoy.class);
src.setStringProperty(String.valueOf(System.currentTimeMillis()));
src.setField2("someValue");
MccoyPrime dest = mapper.map(src, MccoyPrime.class, "usingDestHint");
Set<?> destSet = dest.getFieldValueObjects();
assertNotNull("dest set should not be null", destSet);
assertEquals("dest set should contain 1 entry", 1, destSet.size());
Object entry = destSet.iterator().next();
assertTrue("dest set entry should be instance of FieldValue", entry instanceof FieldValue);
assertEquals("invalid value for dest object", src.getStringProperty(), ((FieldValue) entry).getValue("theKey"));
}
public void testAllowedExceptionsDoNotThrowException() throws Exception {
Mapper mapper = getMapper("allowedExceptionsMapping.xml");
TestObject to2 = newInstance(TestObject.class);
to2.setThrowNonAllowedExceptionOnMap("do not throw me");
try {
mapper.map(to2, TestObjectPrime.class);
} catch (RuntimeException e) {
fail("This should not have been thrown");
}
}
public void testAllowedExceptions_ImplicitDoNotThrow() throws Exception {
ThrowException to2 = newInstance(ThrowException.class);
to2.setThrowNotAllowedException("do not throw me");
try {
mapper.map(to2, ThrowExceptionPrime.class);
} catch (RuntimeException e) {
fail("This should not have been thrown");
}
}
@Test
public void testPrimitiveArrayToList() throws Exception {
mapper = getMapper("primitiveArrayToListMapping.xml");
int[] i = new int[] { 1, 2, 3 };
PrimitiveArrayObj src = newInstance(PrimitiveArrayObj.class);
src.setField1(i);
PrimitiveArrayObjPrime dest = mapper.map(src, PrimitiveArrayObjPrime.class);
assertNotNull("dest list field should not be null", dest.getField1());
assertEquals("invalid dest field size", i.length, dest.getField1().size());
List<?> srcObjectList = CollectionUtils.convertPrimitiveArrayToList(i);
assertEquals("invalid dest field value", srcObjectList, dest.getField1());
}
@Test
public void testPrimitiveArrayToList_UsingHint() throws Exception {
mapper = getMapper("primitiveArrayToListMapping.xml");
int[] srcArray = new int[] { 1, 2, 3 };
PrimitiveArrayObj src = newInstance(PrimitiveArrayObj.class);
src.setField1(srcArray);
PrimitiveArrayObjPrime dest = mapper.map(src, PrimitiveArrayObjPrime.class, "primitiveToArrayUsingHint");
assertNotNull("dest list field should not be null", dest.getField1());
assertEquals("invalid dest field size", srcArray.length, dest.getField1().size());
for (int i = 0; i < srcArray.length; i++) {
String srcValue = String.valueOf(srcArray[i]);
String resultValue = (String) dest.getField1().get(i);
assertEquals("invalid result entry value", srcValue, resultValue);
}
}
@Test
public void testInterface() throws Exception {
mapper = getMapper("interfaceMapping.xml");
ApplicationUser user = newInstance(ApplicationUser.class);
user.setSubscriberNumber("123");
// Mapping works
UpdateMember destObject = mapper.map(user, UpdateMember.class);
assertEquals("invalid value for subsriber #", user.getSubscriberNumber(), destObject.getSubscriberKey().getSubscriberNumber());
// Clear value
destObject = new UpdateMember();
// Mapping doesn't work
mapper.map(user, destObject);
assertNotNull("dest field should not be null", destObject.getSubscriberKey());
assertEquals("invalid value for subsriber #", user.getSubscriberNumber(), destObject.getSubscriberKey().getSubscriberNumber());
}
@Test
public void testCustomFieldMapper() throws Exception {
CustomFieldMapper customFieldMapper = new TestCustomFieldMapper();
((DozerBeanMapper) mapper).setCustomFieldMapper(customFieldMapper);
String currentTime = String.valueOf(System.currentTimeMillis());
SimpleObj src = newInstance(SimpleObj.class);
src.setField1(currentTime);
src.setField6("field6Value" + currentTime);
SimpleObjPrime dest = mapper.map(src, SimpleObjPrime.class);
assertNotNull("dest field1 should not be null", dest.getField1());
assertNotNull("dest field6 should not be null", dest.getField6());
assertEquals("dest field1 should have been set by custom field mapper", TestCustomFieldMapper.fieldValue, dest.getField1());
assertEquals("dest field6 should NOT have been set by custom field mapper", src.getField6(), dest.getField6());
}
@Test
public void testPrivateConstructor() throws Exception {
PrivateConstructorBean src = PrivateConstructorBean.newInstance();
src.setField1("someValue");
PrivateConstructorBeanPrime dest = mapper.map(src, PrivateConstructorBeanPrime.class);
assertNotNull("dest bean should not be null", dest);
assertEquals("field1 not mapped correctly", src.getField1(), dest.getField1());
}
/*
* Bug #1549738
*/
@Test
public void testSetMapping_UppercaseFieldNameInXML() throws Exception {
// For some reason the resulting SomeVO contains a Set with 4 objects. 2 SomeOtherDTO's and 2 SomeOtherVO's. I
// believe it
// should only contain 2 SomeOtherVO's. It has something to do with specifying the field name starting with cap in
// the mapping file. If
// you change the field mapping to start with lower case it seems to map correctly.
Mapper mapper = getMapper("setMappingWithUpperCaseFieldName.xml");
SomeDTO someDto = newInstance(SomeDTO.class);
someDto.setField1(new Integer("1"));
SomeOtherDTO someOtherDto = newInstance(SomeOtherDTO.class);
someOtherDto.setOtherField2(someDto);
someOtherDto.setOtherField3("value1");
SomeDTO someDto2 = newInstance(SomeDTO.class);
someDto2.setField1(new Integer("2"));
SomeOtherDTO someOtherDto2 = newInstance(SomeOtherDTO.class);
someOtherDto2.setOtherField2(someDto2);
someOtherDto2.setOtherField3("value2");
SomeDTO src = newInstance(SomeDTO.class);
src.setField2(new SomeOtherDTO[] { someOtherDto2, someOtherDto });
SomeVO dest = mapper.map(src, SomeVO.class);
assertEquals("incorrect resulting set size", src.getField2().length, dest.getField2().size());
// TODO: add more asserts
}
@Test
public void testGlobalBeanFactoryAppliedToDefaultMappings() throws Exception {
mapper = getMapper("global-configuration.xml");
TestObjectPrime dest = mapper.map(newInstance(TestObject.class), TestObjectPrime.class);
assertNotNull("created by factory name should not be null", dest.getCreatedByFactoryName());
assertEquals(SampleDefaultBeanFactory.class.getName(), dest.getCreatedByFactoryName());
}
@Test
public void testStringToDateMapping() throws Exception {
mapper = getMapper("dozerBeanMapping.xml");
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss:SS");
String dateStr = "01/29/1975 10:45:13:25";
TestObject sourceObj = newInstance(TestObject.class);
sourceObj.setDateStr(dateStr);
TestObjectPrime result = mapper.map(sourceObj, TestObjectPrime.class);
assertEquals(df.parse(dateStr), result.getDateFromStr());
assertEquals(dateStr, df.format(result.getDateFromStr()));
TestObject result2 = mapper.map(result, TestObject.class);
assertEquals(df.format(result.getDateFromStr()), result2.getDateStr());
assertEquals(result.getDateFromStr(), df.parse(result2.getDateStr()));
}
@Test
public void testMethodMapping() throws Exception {
mapper = getMapper("dozerBeanMapping.xml");
MethodFieldTestObject sourceObj = newInstance(MethodFieldTestObject.class);
sourceObj.setIntegerStr("1500");
sourceObj.setPriceItem("3500");
sourceObj.setFieldOne("fieldOne");
MethodFieldTestObject2 result = mapper.map(sourceObj, MethodFieldTestObject2.class);
assertEquals("invalid result object size", 1, result.getIntegerList().size());
assertEquals("invalid result object value", 3500, result.getTotalPrice());
assertEquals("invalid result object value", "fieldOne", result.getFieldOne());
// map back
MethodFieldTestObject result2 = mapper.map(result, MethodFieldTestObject.class);
// if no exceptions we thrown we are good. stopOnErrors = true. both values will be null
// since this is a one-way mapping we shouldn't have a value
assertNull(result2.getFieldOne());
}
@Test
public void testNoReadMethod() throws Exception {
// If the field doesnt have a getter/setter, dont add it is a default field to be mapped.
mapper = getMapper("dozerBeanMapping.xml");
NoReadMethod src = newInstance(NoReadMethod.class);
src.setNoReadMethod("somevalue");
NoReadMethodPrime dest = mapper.map(src, NoReadMethodPrime.class);
assertNull("field should be null because no read method exists for field", dest.getXXXXX());
}
@Test
public void testNoReadMethodSameClassTypes() throws Exception {
// If the field doesnt have a getter/setter, dont add it is a default field to be mapped.
mapper = getMapper("dozerBeanMapping.xml");
NoReadMethod src = newInstance(NoReadMethod.class);
src.setNoReadMethod("somevalue");
NoReadMethod dest = mapper.map(src, NoReadMethod.class);
assertNull("field should be null because no read method exists for field", dest.getXXXXX());
}
@Test
public void testNoReadMethod_GetterOnlyWithParams() throws Exception {
// Dont use getter methods that have a param when discovering default fields to be mapped.
mapper = getMapper("dozerBeanMapping.xml");
NoReadMethod src = newInstance(NoReadMethod.class);
src.setOtherNoReadMethod("someValue");
NoReadMethod dest = mapper.map(src, NoReadMethod.class);
assertNull("field should be null because no read method exists for field", dest.getOtherNoReadMethod(-1));
}
@Test
public void testNoWriteMethod() throws Exception {
mapper = getMapper("dozerBeanMapping.xml");
NoWriteMethod src = newInstance(NoWriteMethod.class);
src.setXXXXXX("someValue");
NoWriteMethodPrime dest = mapper.map(src, NoWriteMethodPrime.class);
assertNull("field should be null because no write method exists for field", dest.getNoWriteMethod());
}
@Test
public void testNoWriteMethodSameClassTypes() throws Exception {
// When mapping between identical types, if the field doesnt have a getter/setter, dont
// add it is a default field to be mapped.
mapper = getMapper("dozerBeanMapping.xml");
NoWriteMethod src = newInstance(NoWriteMethod.class);
src.setXXXXXX("someValue");
mapper.map(newInstance(NoReadMethod.class), NoReadMethod.class);
NoWriteMethod dest = mapper.map(src, NoWriteMethod.class);
assertNull("field should be null because no write method exists for field", dest.getNoWriteMethod());
}
@Test
public void testNoVoidSetters() throws Exception {
mapper = getMapper("dozerBeanMapping.xml");
NoVoidSetters src = newInstance(NoVoidSetters.class);
src.setDescription("someValue");
src.setI(1);
NoVoidSetters dest = mapper.map(src, NoVoidSetters.class);
assertEquals("invalid dest field value", src.getDescription(), dest.getDescription());
assertEquals("invalid dest field value", src.getI(), dest.getI());
}
@Test
public void testNullField() throws Exception {
mapper = getMapper("dozerBeanMapping.xml");
AnotherTestObject src = newInstance(AnotherTestObject.class);
src.setField2(null);
AnotherTestObjectPrime dest = newInstance(AnotherTestObjectPrime.class);
dest.setField2(Integer.valueOf("555"));
// check that null overrides an existing value
mapper.map(src, dest);
assertNull("dest field should be null", dest.getField2());
}
@Test
public void testNullField2() throws Exception {
mapper = getMapper("dozerBeanMapping.xml");
// Test that String --> String with an empty String input value results
// in the destination field being an empty String and not null.
String input = "";
TestObject src = newInstance(TestObject.class);
src.setOne(input);
TestObjectPrime dest = mapper.map(src, TestObjectPrime.class);
assertNotNull("dest field should not be null", dest.getOnePrime());
assertEquals("invalid dest field value", input, dest.getOnePrime());
}
@Test
public void testNullToPrimitive() throws Exception {
mapper = getMapper("dozerBeanMapping.xml");
AnotherTestObject src = newInstance(AnotherTestObject.class);
AnotherTestObjectPrime prime = newInstance(AnotherTestObjectPrime.class);
TestObject to = newInstance(TestObject.class);
to.setThePrimitive(AnotherTestObjectPrime.DEFAULT_FIELD1);
prime.setTo(to);
mapper.map(src, prime);
// check primitive on deep field
// primitive should still be default
assertEquals("invalid field value", AnotherTestObjectPrime.DEFAULT_FIELD1, prime.getField1());
assertEquals("invalid field value", AnotherTestObjectPrime.DEFAULT_FIELD1, prime.getTo().getThePrimitive());
}
@Test
public void testGlobalRelationshipType() throws Exception {
mapper = getMapper("relationship-type-global-configuration.xml");
TestObject src = new TestObject();
src.setHintList(new ArrayList<String>(Arrays.asList(new String[] { "a" })));
TestObjectPrime dest = new TestObjectPrime();
dest.setHintList(new ArrayList<String>(Arrays.asList(new String[] { "a", "b" })));
mapper.map(src, dest);
assertEquals("wrong # of elements in dest list for non-cumulative mapping", 2, dest.getHintList().size());
}
@Test
public void testClassMapRelationshipType() throws Exception {
mapper = getMapper("relationshipTypeMapping.xml");
TestObject src = new TestObject();
src.setHintList(new ArrayList<String>(Arrays.asList(new String[] { "a" })));
TestObjectPrime dest = new TestObjectPrime();
dest.setHintList(new ArrayList<String>(Arrays.asList(new String[] { "a", "b" })));
mapper.map(src, dest);
assertEquals("wrong # of elements in dest list for non-cumulative mapping", 2, dest.getHintList().size());
}
@Test
public void testRemoveOrphans() {
mapper = getMapper("removeOrphansMapping.xml");
MyClassA myClassA = new MyClassA();
MyClassB myClassB = new MyClassB();
Fruit apple = new Fruit();
apple.setName("Apple");
Fruit banana = new Fruit();
banana.setName("Banana");
Fruit grape = new Fruit();
grape.setName("Grape");
Fruit orange = new Fruit();
orange.setName("Orange");
Fruit kiwiFruit = new Fruit();
kiwiFruit.setName("Kiwi Fruit");
List<Fruit> srcFruits = new ArrayList<Fruit>();
srcFruits.add(apple);
srcFruits.add(banana);
srcFruits.add(kiwiFruit);
List<Fruit> destFruits = new ArrayList<Fruit>();
destFruits.add(grape); // not in src
destFruits.add(banana); // shared with src fruits
destFruits.add(orange); // not in src
myClassA.setAStringList(srcFruits);
myClassB.setAStringList(destFruits);
mapper.map(myClassA, myClassB, "testRemoveOrphansOnList");
assertEquals(3, myClassB.getAStringList().size());
assertTrue(myClassB.getAStringList().contains(apple));
assertTrue(myClassB.getAStringList().contains(banana));
assertTrue(myClassB.getAStringList().contains(kiwiFruit));
assertFalse(myClassB.getAStringList().contains(grape));
assertFalse(myClassB.getAStringList().contains(orange));
}
@Test
public void testOrphanRemovalSet() {
mapper = getMapper("removeOrphansMapping.xml");
Parent parent = new Parent(new Long(1), "parent");
Child child1 = new Child(new Long(1), "child1");
Set<Child> childrenSet = new HashSet<Child>();
childrenSet.add(child1);
parent.setChildrenSet(childrenSet);
ParentPrime parentPrime = mapper.map(parent, ParentPrime.class);
// Make sure the first one was mapped ok.
assertEquals(parent.getChildrenSet().size(), parentPrime.getChildrenSet().size());
ChildPrime child2 = new ChildPrime(new Long(2L), "child2");
parentPrime.getChildrenSet().add(child2);
mapper.map(parentPrime, parent);
// Make sure adding one works ok.
assertEquals(parentPrime.getChildrenSet().size(), parent.getChildrenSet().size());
parentPrime.getChildrenSet().clear();
mapper.map(parentPrime, parent);
// Make sure REMOVING them (the orphan children) works ok.
assertEquals(parentPrime.getChildrenSet().size(), parent.getChildrenSet().size());
}
@Test
public void testOrphanRemovalList() {
mapper = getMapper("removeOrphansMapping.xml");
Parent parent = new Parent(new Long(1), "parent");
Child child1 = new Child(new Long(1), "child1");
List<Child> childrenList = new ArrayList<Child>();
childrenList.add(child1);
parent.setChildrenList(childrenList);
ParentPrime parentPrime = mapper.map(parent, ParentPrime.class);
// Make sure the first one was mapped ok.
assertEquals(parent.getChildrenList().size(), parentPrime.getChildrenList().size());
ChildPrime child2 = new ChildPrime(new Long(2L), "child2");
parentPrime.getChildrenList().add(child2);
mapper.map(parentPrime, parent);
// Make sure adding one works ok.
assertEquals(parentPrime.getChildrenList().size(), parent.getChildrenList().size());
parentPrime.getChildrenList().clear();
mapper.map(parentPrime, parent);
// Make sure REMOVING them (the orphan children) works ok.
assertEquals(parentPrime.getChildrenList().size(), parent.getChildrenList().size());
}
}
| {
"content_hash": "df22dbe3fa7260fae6c5c5745c98f588",
"timestamp": "",
"source": "github",
"line_count": 847,
"max_line_length": 131,
"avg_line_length": 39.3482880755608,
"alnum_prop": 0.7071531445031205,
"repo_name": "STRiDGE/dozer",
"id": "2bb81241046e79dc6bc342ea10d0b91d0b3c13c8",
"size": "33944",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/test/java/org/dozer/functional_tests/GranularDozerBeanMapperTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1967284"
},
{
"name": "Protocol Buffer",
"bytes": "747"
},
{
"name": "Shell",
"bytes": "492"
}
],
"symlink_target": ""
} |
package org.apiviewer.test;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
/**
* @author hitesh.bargujar
*
*/
@RunWith(value = Cucumber.class)
@CucumberOptions(format = {"pretty", "json:build/testReports"},
features = {"src/test/resources"})
public class ApiViewerCucumberRunner {
}
| {
"content_hash": "d16dc1f9223f6801915034d660b53e1c",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 63,
"avg_line_length": 21,
"alnum_prop": 0.7338935574229691,
"repo_name": "APIVIEWER/api-viewer-service",
"id": "ca64c335fbf0bc9acf541b24e7be797417f45803",
"size": "357",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "api-viewer-system-tests/src/test/java/org/apiviewer/test/ApiViewerCucumberRunner.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Cucumber",
"bytes": "331"
},
{
"name": "Java",
"bytes": "37408"
}
],
"symlink_target": ""
} |
using System.Windows;
namespace CrystalKeeper.Gui
{
/// <summary>
/// Interaction logic for DlgImgDisplayGui.xaml
/// </summary>
public partial class DlgImgDisplayGui : Window
{
public DlgImgDisplayGui()
{
InitializeComponent();
}
}
}
| {
"content_hash": "a275018b5af9a37c8d71cbbbf26dab92",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 51,
"avg_line_length": 19.8,
"alnum_prop": 0.5959595959595959,
"repo_name": "JoshuaLamusga/Crystal-Keeper",
"id": "3166a5dc2873b6cdedc90133db65fda1e945c756",
"size": "299",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CrystalKeeper/Gui/DlgImgDisplayGui.xaml.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "489185"
}
],
"symlink_target": ""
} |
package com.cisco.oss.foundation.directory.client;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import com.cisco.oss.foundation.directory.exception.ServiceException;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.cisco.oss.foundation.directory.entity.InstanceChange;
import com.cisco.oss.foundation.directory.entity.ModelServiceInstance;
import com.cisco.oss.foundation.directory.entity.OperationalStatus;
import com.cisco.oss.foundation.directory.utils.HttpResponse;
import com.cisco.oss.foundation.directory.utils.HttpUtils;
import static org.junit.Assert.assertEquals;
import static com.cisco.oss.foundation.directory.utils.JsonSerializer.serialize;
/**
* Test for lookup changes by using restful client
*/
public class LookupChangesTestByRestfulClient {
private final static Logger LOG = LoggerFactory.getLogger(LookupChangesTestByRestfulClient.class);
private final DirectoryServiceRestfulClient restfulClient = new DirectoryServiceRestfulClient();
private final ModelServiceInstance instance;
public LookupChangesTestByRestfulClient(){
final Date date = new Date();
final Map<String, String> metadata = new HashMap<>();
metadata.put("datacenter", "dc01");
metadata.put("solution", "core");
this.instance = new ModelServiceInstance("odrm", "192.168.2.3", "192.168.2.3", "http://cisco.com/vbo/odrm/setupsession",
OperationalStatus.UP, null, date,
date, metadata);
this.instance.setHeartbeatTime(date);
}
@Before
public void setUp(){
restfulClient.setInvoker(new DirectoryServiceRestfulClient.DirectoryHttpInvoker() {
@Override
public HttpResponse invoke(String uri, String payload, HttpUtils.HttpMethod method, Map<String, String> headers) {
LOG.debug("invoke url:{} method:{} ", uri, method);
List<InstanceChange<ModelServiceInstance>> list = new ArrayList<>();
list.add(new InstanceChange<>(0L, "test", InstanceChange.ChangeType.ADD,
null, instance));
String json = "";
try {
json = new String(serialize(list));
} catch (IOException e) {
e.printStackTrace();
}
return new HttpResponse(200, json);
}
});
}
@Test
public void testLookupChangesSince() throws InterruptedException {
final long now = System.currentTimeMillis();
TimeUnit.MILLISECONDS.sleep(10L);
List<InstanceChange<ModelServiceInstance>> result = restfulClient.lookupChangesSince("test", now);
assertEquals(1, result.size());
LOG.debug("{}", result.get(0));
}
@Test
public void testLookupInError() throws InterruptedException{
final long now = System.currentTimeMillis();
TimeUnit.MILLISECONDS.sleep(10L);
DirectoryServiceRestfulClient client = new DirectoryServiceRestfulClient();
client.setInvoker(new DirectoryServiceRestfulClient.DirectoryHttpInvoker() {
@Override
public HttpResponse invoke(String uri, String payload, HttpUtils.HttpMethod method, Map<String, String> headers) {
LOG.debug("invoke url:{} method:{} ", uri, method);
List<InstanceChange<ModelServiceInstance>> list = new ArrayList<>();
list.add(new InstanceChange<>(0L, "test", InstanceChange.ChangeType.ADD,
null, instance));
String json = "";
try {
json = new String(serialize(list));
} catch (IOException e) {
e.printStackTrace();
}
return new HttpResponse(199, json);
}
});;
try {
List<InstanceChange<ModelServiceInstance>> result = client.lookupChangesSince("test", now);
}catch (ServiceException se){
assertEquals("Unknown HTTP Code, code=199", se.getMessage());
}
}
}
| {
"content_hash": "baf61f1863a2a76c4a4fea8916a93e8e",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 128,
"avg_line_length": 40.339622641509436,
"alnum_prop": 0.6508419083255379,
"repo_name": "foundation-runtime/service-directory",
"id": "4efeed200ac09e2fd29ad931754828b2eb44b87f",
"size": "4276",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "1.2/sd-api/src/test/java/com/cisco/oss/foundation/directory/client/LookupChangesTestByRestfulClient.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1635530"
},
{
"name": "Shell",
"bytes": "1341"
}
],
"symlink_target": ""
} |
// create the module and name it trans
var trans = angular.module('trans', ['ngRoute','ui.bootstrap']);
// configure our routes
trans.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'pages/home.html'
})
// route for the about page
.when('/about', {
templateUrl : 'pages/about.html',
controller : 'aboutController'
})
// route for the contact page
.when('/contact', {
templateUrl : 'pages/contact.html',
controller : 'contactController'
});
});
// create the controller and inject Angular's $scope
trans.controller('mainController',function($scope,$http){
var store = this;
store.products = [];
$http.get('js/product.json.js').success(function(data){
$scope.products=data;
});
});
trans.controller('aboutController', function($scope) {
$scope.message = 'Look! I am an about page.';
});
trans.controller('contactController', function($scope) {
$scope.message = 'Contact us! JK. This is just a demo.';
});
trans.controller('CarouselDemoCtrl', function ($scope) {
$scope.myInterval = 5000;
var slides = $scope.slides = [];
$scope.addSlide = function() {
var newWidth = 2000 + slides.length + 1;
slides.push({
image: 'http://placekitten.com/' + newWidth + '/300',
text: ['More','Extra','Lots of','Surplus'][slides.length % 4] + ' ' +
['Cats', 'Kittys', 'Felines', 'Cutes'][slides.length % 4]
});
};
for (var i=0; i<4; i++) {
$scope.addSlide();
}
});
| {
"content_hash": "0577e5b0db30a6a75c7d042cf55518a8",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 75,
"avg_line_length": 27.545454545454547,
"alnum_prop": 0.6138613861386139,
"repo_name": "aditi121/demo-angular-project",
"id": "1a1361d102ecd6c59bbd59160a34a61b5250b26e",
"size": "1538",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/main.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "120397"
},
{
"name": "HTML",
"bytes": "3908"
},
{
"name": "JavaScript",
"bytes": "167766"
}
],
"symlink_target": ""
} |
package net.katsuster.strview.media.ps;
import net.katsuster.strview.util.bit.*;
import net.katsuster.strview.media.bit.*;
/**
* <p>
* MPEG2-PS (Program Stream) pack header
* </p>
*
* <p>
* 参考規格
* </p>
* <ul>
* <li>ITU-T H.222, ISO/IEC 13818-1:
* Information technology – Generic coding of moving pictures and
* associated audio information: Systems</li>
* </ul>
*/
public class PSHeaderPack
extends PSHeader
implements Cloneable {
public UInt reserved1; //must be '0010 (MPEG1)' or '01 (MPEG2)'
public UInt system_clock_reference_base_high;
public UInt marker_bit1;
public UInt system_clock_reference_base_mid;
public UInt marker_bit2;
public UInt system_clock_reference_base_low;
public UInt marker_bit3;
public UInt system_clock_reference_extension;
public UInt marker_bit4;
public UInt program_mux_rate;
public UInt marker_bit5;
public UInt marker_bit6;
public UInt reserved2;
public UInt pack_stuffing_length;
public LargeBitList stuffing_byte;
public PSHeaderPack() {
reserved1 = new UInt("reserved1" );
system_clock_reference_base_high = new UInt("system_clock_reference_base_high");
marker_bit1 = new UInt("marker_bit1" );
system_clock_reference_base_mid = new UInt("system_clock_reference_base_mid" );
marker_bit2 = new UInt("marker_bit2" );
system_clock_reference_base_low = new UInt("system_clock_reference_base_low" );
marker_bit3 = new UInt("marker_bit3" );
system_clock_reference_extension = new UInt("system_clock_reference_extension");
marker_bit4 = new UInt("marker_bit4" );
program_mux_rate = new UInt("program_mux_rate" );
marker_bit5 = new UInt("marker_bit5" );
marker_bit6 = new UInt("marker_bit6" );
reserved2 = new UInt("reserved2" );
pack_stuffing_length = new UInt("pack_stuffing_length" );
stuffing_byte = new SubLargeBitList("stuffing_byte");
}
@Override
public PSHeaderPack clone()
throws CloneNotSupportedException {
PSHeaderPack obj = (PSHeaderPack)super.clone();
obj.reserved1 = (UInt)reserved1.clone();
obj.system_clock_reference_base_high = (UInt)system_clock_reference_base_high.clone();
obj.marker_bit1 = (UInt)marker_bit1.clone();
obj.system_clock_reference_base_mid = (UInt)system_clock_reference_base_mid.clone();
obj.marker_bit2 = (UInt)marker_bit2.clone();
obj.system_clock_reference_base_low = (UInt)system_clock_reference_base_low.clone();
obj.marker_bit3 = (UInt)marker_bit3.clone();
obj.system_clock_reference_extension = (UInt)system_clock_reference_extension.clone();
obj.marker_bit4 = (UInt)marker_bit4.clone();
obj.program_mux_rate = (UInt)program_mux_rate.clone();
obj.marker_bit5 = (UInt)marker_bit5.clone();
obj.marker_bit6 = (UInt)marker_bit6.clone();
obj.reserved2 = (UInt)reserved2.clone();
obj.pack_stuffing_length = (UInt)pack_stuffing_length.clone();
obj.stuffing_byte = (LargeBitList)stuffing_byte.clone();
return obj;
}
@Override
public String getTypeName() {
return "PS pack header";
}
@Override
protected void readBits(BitStreamReader c) {
readBits(c, this);
}
public static void readBits(BitStreamReader c,
PSHeaderPack d) {
c.enterBlock(d);
PSHeader.readBits(c, d);
if (c.peekLong(2) == 0) {
readMPEG1(c, d);
} else {
readMPEG2(c, d);
}
c.leaveBlock();
}
public static void readMPEG1(BitStreamReader c,
PSHeaderPack d) {
d.reserved1 = c.readUInt( 4, d.reserved1 );
d.system_clock_reference_base_high = c.readUInt( 3, d.system_clock_reference_base_high);
d.marker_bit1 = c.readUInt( 1, d.marker_bit1 );
d.system_clock_reference_base_mid = c.readUInt(15, d.system_clock_reference_base_mid );
d.marker_bit2 = c.readUInt( 1, d.marker_bit2 );
d.system_clock_reference_base_low = c.readUInt(15, d.system_clock_reference_base_low );
d.marker_bit3 = c.readUInt( 1, d.marker_bit3 );
d.marker_bit4 = c.readUInt( 1, d.marker_bit4 );
d.program_mux_rate = c.readUInt(22, d.program_mux_rate );
d.marker_bit5 = c.readUInt( 1, d.marker_bit5 );
}
public static void readMPEG2(BitStreamReader c,
PSHeaderPack d) {
int size_st;
d.reserved1 = c.readUInt( 2, d.reserved1 );
d.system_clock_reference_base_high = c.readUInt( 3, d.system_clock_reference_base_high);
d.marker_bit1 = c.readUInt( 1, d.marker_bit1 );
d.system_clock_reference_base_mid = c.readUInt(15, d.system_clock_reference_base_mid );
d.marker_bit2 = c.readUInt( 1, d.marker_bit2 );
d.system_clock_reference_base_low = c.readUInt(15, d.system_clock_reference_base_low );
d.marker_bit3 = c.readUInt( 1, d.marker_bit3 );
d.system_clock_reference_extension = c.readUInt( 9, d.system_clock_reference_extension);
d.marker_bit4 = c.readUInt( 1, d.marker_bit4 );
d.program_mux_rate = c.readUInt(22, d.program_mux_rate );
d.marker_bit5 = c.readUInt( 1, d.marker_bit5 );
d.marker_bit6 = c.readUInt( 1, d.marker_bit6 );
d.reserved2 = c.readUInt( 5, d.reserved2 );
d.pack_stuffing_length = c.readUInt( 3, d.pack_stuffing_length );
//残りを埋めているバイト列を読む
size_st = d.pack_stuffing_length.intValue();
if (size_st < 0) {
throw new IllegalStateException("stuffing bytes have negative size"
+ "(size: " + size_st + ")");
}
d.stuffing_byte = c.readBitList(size_st, d.stuffing_byte);
}
@Override
protected void writeBits(BitStreamWriter c) {
writeBits(c, this);
}
public static void writeBits(BitStreamWriter c,
PSHeaderPack d) {
c.enterBlock(d);
PSHeader.writeBits(c, d);
if (d.reserved1.intValue() == 2) {
writeMPEG1(c, d);
} else {
writeMPEG2(c, d);
}
c.leaveBlock();
}
public static void writeMPEG1(BitStreamWriter c,
PSHeaderPack d) {
c.writeUInt( 4, d.reserved1 );
c.writeUInt( 3, d.system_clock_reference_base_high);
c.writeUInt( 1, d.marker_bit1 );
c.writeUInt(15, d.system_clock_reference_base_mid );
c.writeUInt( 1, d.marker_bit2 );
c.writeUInt(15, d.system_clock_reference_base_low );
c.writeUInt( 1, d.marker_bit3 );
c.mark("scr", d.getSCRBase());
c.writeUInt( 1, d.marker_bit4 );
c.writeUInt(22, d.program_mux_rate );
c.writeUInt( 1, d.marker_bit5 );
}
public static void writeMPEG2(BitStreamWriter c,
PSHeaderPack d) {
c.writeUInt( 2, d.reserved1 );
c.writeUInt( 3, d.system_clock_reference_base_high);
c.writeUInt( 1, d.marker_bit1 );
c.writeUInt(15, d.system_clock_reference_base_mid );
c.writeUInt( 1, d.marker_bit2 );
c.writeUInt(15, d.system_clock_reference_base_low );
c.writeUInt( 1, d.marker_bit3 );
c.mark("scr", d.getSCRBase());
c.writeUInt( 9, d.system_clock_reference_extension);
c.writeUInt( 1, d.marker_bit4 );
c.writeUInt(22, d.program_mux_rate );
c.writeUInt( 1, d.marker_bit5 );
c.writeUInt( 1, d.marker_bit6 );
c.writeUInt( 5, d.reserved2 );
c.writeUInt( 3, d.pack_stuffing_length );
//残りを埋める
c.writeBitList(d.pack_stuffing_length.intValue() << 3, d.stuffing_byte);
}
public long getSCRBase() {
return getSCRValue(
system_clock_reference_base_high.longValue(),
system_clock_reference_base_mid.longValue(),
system_clock_reference_base_low.longValue());
}
public static long getSCRValue(long high, long mid, long low) {
return ((high << 30) | (mid << 15) | (low << 0));
}
}
| {
"content_hash": "976b71b0e0c2d3da03a117aeb839b375",
"timestamp": "",
"source": "github",
"line_count": 215,
"max_line_length": 96,
"avg_line_length": 44.70232558139535,
"alnum_prop": 0.515659140568099,
"repo_name": "katsuster/strview",
"id": "a15f0e53ebaf5b48e71dc12e008c37068e9e7f2b",
"size": "9663",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "view/src/net/katsuster/strview/media/ps/PSHeaderPack.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1338231"
}
],
"symlink_target": ""
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu()]
public class TerrainData : UpdatableData {
public float uniformScale = 2f;
public bool useFalloff;
public bool useFlatShading;
public float meshHeightMultiplier;
public AnimationCurve meshHeightCurve;
public float minHeight
{
get
{
return uniformScale * meshHeightMultiplier * meshHeightCurve.Evaluate(0);
}
}
public float maxHeight
{
get
{
return uniformScale * meshHeightMultiplier * meshHeightCurve.Evaluate(1);
}
}
}
| {
"content_hash": "429cb6961f83f5f628b2935d2663d041",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 76,
"avg_line_length": 17.40625,
"alnum_prop": 0.7576301615798923,
"repo_name": "Batora07/ProceduralLandmassGeneration",
"id": "8af9f47f3bb37bee68ebe51e74f6669228f1d570",
"size": "559",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Assets/Scripts/Data/TerrainData.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "42623"
},
{
"name": "GLSL",
"bytes": "2305"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Meadow.Logging.Log4Net")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Meadow.Logging.Log4Net")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b4ce83d7-ceac-46e7-8872-64c887693f4f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "76c3a676cbaa00402a91c0675e6133df",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 39.22222222222222,
"alnum_prop": 0.7485835694050992,
"repo_name": "Shirasho/Meadow",
"id": "383cb6a6c133ffe10ba99e41589676c039f9af0e",
"size": "1415",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Meadow.Logging.Log4Net/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "751108"
},
{
"name": "PowerShell",
"bytes": "3737"
}
],
"symlink_target": ""
} |
<?php
namespace WoohooLabs\SpecGenerator\Swagger2\Parameters;
class BodyParameter extends AbstractSchemaParameterFactory
{
/**
* @param string $name
* @return $this
*/
public static function create($name = null)
{
return new self($name);
}
/**
* @param string $name
*/
public function __construct($name = null)
{
parent::__construct($name, "body");
}
}
| {
"content_hash": "85460767c41f0d2f5dde1ed3920721d9",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 58,
"avg_line_length": 19.454545454545453,
"alnum_prop": 0.5911214953271028,
"repo_name": "woohoolabs/spec-generator",
"id": "b2aa69255de714649389c454bc17764e90897068",
"size": "428",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Swagger2/Parameters/BodyParameter.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "138130"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using Octopus.Client;
using Octopus.Client.Model;
using Serilog;
namespace Octoposh.TestDataGenerator.Fixtures
{
/// <summary>
/// This fixture is in charge of creating/setting up most of the things that can be found in the "Library" section of the Octopus portal, such as External feeds, Script modules, Library Variable Sets,etc
/// </summary>
class LibraryFixture
{
private static IOctopusAsyncRepository _repository;
private static readonly string[] FeedNames = { "Local Folder", "FeedTests_Feed1", "FeedTests_Feed2", "unmodified_TestFeed" };
private static readonly string[] ScriptModuleNames = { "ScriptModuleTests_Module1" };
private static readonly string[] LibraryVariableSetNames = { "VariableSetTests_Library1", "VariableSetTests_Library2", "unmodified_TestLibraryVariableSet" };
/// <summary>
/// Run the fixture
/// </summary>
public static void Run()
{
_repository = OctopusRepository.GetRepository().Result;
Log.Logger.Information("**Running Library Fixture**");
CreateLibraryStuff();
}
#region Library Stuff
private static void CreateLibraryStuff()
{
CreateFeeds();
CreateScriptModules();
CreateLibraryVariableSets();
}
private static void CreateFeeds()
{
foreach (var feedName in FeedNames)
{
var feed = _repository.Feeds.FindByName(feedName).Result ?? new NuGetFeedResource();
feed.Name = feedName;
feed.FeedUri = "C:\\packages";
try
{
Log.Information($"Creating/Modifying Feed [{feed.Name}]");
if (feed.Id != null)
_repository.Feeds.Modify(feed).Wait();
else
_repository.Feeds.Create(feed).Wait();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
private static void CreateScriptModules()
{
foreach (var scriptModuleName in ScriptModuleNames)
{
var scriptModule = _repository.LibraryVariableSets.FindByName(scriptModuleName).Result ??
new LibraryVariableSetResource();
scriptModule.Name = scriptModuleName;
scriptModule.Description = GeneralResourceProperty.ResourceDescription;
scriptModule.ContentType = VariableSetContentType.ScriptModule;
try
{
Log.Information($"Creating/Modifying Script Module [{scriptModule.Name}]");
if (scriptModule.Id != null)
_repository.LibraryVariableSets.Modify(scriptModule).Wait();
else
_repository.LibraryVariableSets.Create(scriptModule).Wait();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
private static void CreateLibraryVariableSets()
{
foreach (var libraryVariableSetName in LibraryVariableSetNames)
{
var libraryVariableSet = _repository.LibraryVariableSets.FindByName(libraryVariableSetName).Result ??
new LibraryVariableSetResource();
libraryVariableSet.Name = libraryVariableSetName;
libraryVariableSet.Description = GeneralResourceProperty.ResourceDescription;
libraryVariableSet.ContentType = VariableSetContentType.Variables;
try
{
Log.Information($"Creating/Modifying Library Variable Set [{libraryVariableSet.Name}]");
libraryVariableSet = libraryVariableSet.Id != null ? _repository.LibraryVariableSets.Modify(libraryVariableSet).Result : _repository.LibraryVariableSets.Create(libraryVariableSet).Result;
Log.Information($"Adding variables to Library Variable Set [{libraryVariableSet.Name}]");
var variableSet = _repository.VariableSets.Get(libraryVariableSet.VariableSetId).Result;
variableSet.Variables.Clear();
variableSet.AddOrUpdateVariableValue("foo", "bar");
_repository.VariableSets.Modify(variableSet);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
#endregion
}
}
| {
"content_hash": "66de9001286e9b314e614007253dc687",
"timestamp": "",
"source": "github",
"line_count": 133,
"max_line_length": 207,
"avg_line_length": 37.05263157894737,
"alnum_prop": 0.5631087662337663,
"repo_name": "Dalmirog/OctoPosh",
"id": "c0b55f8dee042ed12e47c95463f70b4ff6d4910f",
"size": "4930",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Octoposh.TestDataGenerator/Fixtures/LibraryFixture.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "492504"
},
{
"name": "CSS",
"bytes": "852"
},
{
"name": "JavaScript",
"bytes": "212"
},
{
"name": "PowerShell",
"bytes": "84943"
}
],
"symlink_target": ""
} |
@implementation UIView (Util)
- (UIImage *)createImage
{
UIGraphicsBeginImageContextWithOptions(self.bounds.size, YES, [UIScreen mainScreen].scale);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
@end
| {
"content_hash": "d0864059e77fba73b6e647e427ba5322",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 95,
"avg_line_length": 34.1,
"alnum_prop": 0.7712609970674487,
"repo_name": "imjerrybao/CMUtils",
"id": "38c41338ef1c7659516d50a12881e8302c335e8a",
"size": "492",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CMUtils/Categories/UIView+Util.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "98644"
},
{
"name": "Ruby",
"bytes": "1845"
}
],
"symlink_target": ""
} |
require('../../test-env');
describe('dig.data.priorityQueue', function() {
var pq;
beforeEach(function() {
pq = new dig.data.PriorityQueue();
});
describe("constructor", function() {
it("PriorityQueue() returns an empty queue", function() {
assert.equal(0, pq.size());
});
it("should throw an error if new was not used", function() {
assert.throws(function() { dig.data.PriorityQueue(); });
});
});
describe("keys()", function() {
it("returns all of the keys in the queue", function() {
pq.add("a", 1);
pq.add(1, 2);
pq.add(false, 3);
pq.add(undefined, 4);
pq.add(null, 5);
assert.isTrue(pq.has("a"));
assert.isTrue(pq.has(1));
assert.isTrue(pq.has(false));
assert.isTrue(pq.has(undefined));
assert.isTrue(pq.has(null));
});
});
describe("has(key)", function() {
it("returns true if the key is in the queue", function() {
pq.add("a", 1);
assert.isTrue(pq.has("a"));
});
it("returns false if the key is not in the queue", function() {
assert.isFalse(pq.has("a"));
});
});
describe("priority(key)", function() {
it("returns the current priority for the key", function() {
pq.add("a", 1);
pq.add("b", 2);
assert.equal(1, pq.priority("a"));
assert.equal(2, pq.priority("b"));
});
});
describe("add(key, pri)", function() {
it("adds the key to the queue", function() {
pq.add("a", 1);
assert.deepEqual(["a"], pq.keys());
});
it("returns true if the key was added", function() {
assert.isTrue(pq.add("a", 1));
});
it("returns false if the key already exists in the queue", function() {
pq.add("a", 1);
assert.isFalse(pq.add("a", 1));
});
});
describe("min()", function() {
it("returns undefined when the queue is empty", function() {
assert.isUndefined(pq.min());
});
it("returns the smallest element", function() {
pq.add("b", 2);
pq.add("a", 1);
assert.equal("a", pq.min());
});
it("does not remove the minimum element from the queue", function() {
pq.add("b", 2);
pq.add("a", 1);
pq.min();
assert.equal(2, pq.size());
});
});
describe("removeMin()", function() {
it("removes the minimum element from the queue", function() {
pq.add("b", 2);
pq.add("a", 1);
pq.add("c", 3);
pq.add("e", 5);
pq.add("d", 4);
assert.equal("a", pq.removeMin());
assert.equal("b", pq.removeMin());
assert.equal("c", pq.removeMin());
assert.equal("d", pq.removeMin());
assert.equal("e", pq.removeMin());
});
it("throws an error if there is no element in the queue", function() {
assert.throws(function() { pq.removeMin(); });
});
});
describe("decrease(key, pri)", function() {
it("decreases the priority of a key", function() {
pq.add("a", 1);
pq.decrease("a", -1);
assert.equal(-1, pq.priority("a"));
});
it("raises an error if the key is not in the queue", function() {
assert.throws(function() { pq.decrease("a", -1); });
});
it("raises an error if the new priority is greater than current", function() {
pq.add("a", 1);
assert.throws(function() { pq.decrease("a", 2); });
});
});
});
| {
"content_hash": "4a6b0410f8b83864134a2b19d6aa1ea7",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 82,
"avg_line_length": 26.832,
"alnum_prop": 0.5405485986881335,
"repo_name": "cpettitt/dig.js",
"id": "cd343dd38bb3d1c36ee45be790ded2ad8cb332ce",
"size": "3354",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/dig/data/priority-queue-test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "DOT",
"bytes": "1749"
},
{
"name": "JavaScript",
"bytes": "123620"
}
],
"symlink_target": ""
} |
import { Directive, OnInit, ElementRef, Renderer, Input } from '@angular/core';
import { TranslateService, LangChangeEvent } from '@ngx-translate/core';
@Directive({
selector: '[jhiActiveMenu]'
})
export class ActiveMenuDirective implements OnInit {
@Input() jhiActiveMenu: string;
constructor(private el: ElementRef, private renderer: Renderer, private translateService: TranslateService) {}
ngOnInit() {
this.translateService.onLangChange.subscribe((event: LangChangeEvent) => {
this.updateActiveFlag(event.lang);
});
this.updateActiveFlag(this.translateService.currentLang);
}
updateActiveFlag(selectedLanguage) {
if (this.jhiActiveMenu === selectedLanguage) {
this.renderer.setElementClass(this.el.nativeElement, 'active', true);
} else {
this.renderer.setElementClass(this.el.nativeElement, 'active', false);
}
}
}
| {
"content_hash": "ad62e10c9df8f49baf8a1773c75135d6",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 114,
"avg_line_length": 36,
"alnum_prop": 0.6848290598290598,
"repo_name": "alexandrofs/gfp",
"id": "edbdeb94fd98c2bf7b2e8525aa50a45a84c697bc",
"size": "936",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "src/main/webapp/app/layouts/navbar/active-menu.directive.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12471"
},
{
"name": "Dockerfile",
"bytes": "431"
},
{
"name": "HTML",
"bytes": "276935"
},
{
"name": "Java",
"bytes": "746273"
},
{
"name": "JavaScript",
"bytes": "18518"
},
{
"name": "Shell",
"bytes": "429"
},
{
"name": "TSQL",
"bytes": "569"
},
{
"name": "TypeScript",
"bytes": "711193"
}
],
"symlink_target": ""
} |
using System;
using System.Windows;
using System.Windows.Input;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using AppStudio.Data;
using AppStudio.Services;
namespace AppStudio.ViewModels
{
public class ContactUsViewModel : ViewModelBase<MenuSchema>
{
private RelayCommandEx<MenuSchema> itemClickCommand;
public RelayCommandEx<MenuSchema> ItemClickCommand
{
get
{
if (itemClickCommand == null)
{
itemClickCommand = new RelayCommandEx<MenuSchema>(
(item) =>
{
if (item.GetValue("Type").EqualNoCase("Section"))
{
NavigationServices.NavigateToPage(item.GetValue("Target"));
}
else
{
var targetUri = TryCreateUri(item.GetValue("Target"));
if (targetUri != null)
{
NavigationServices.NavigateTo(targetUri);
}
}
});
}
return itemClickCommand;
}
}
private RelayCommandEx<string> changeFontSizeCommand;
public RelayCommandEx<string> ChangeFontSizeCommand
{
get
{
if (changeFontSizeCommand == null)
{
changeFontSizeCommand = new RelayCommandEx<string>((s) =>
{
FontSizes fontSize;
Enum.TryParse<FontSizes>(s, out fontSize);
DisplayFontSize = fontSize;
});
}
return changeFontSizeCommand;
}
}
public FontSizes DisplayFontSize
{
get
{
if (ApplicationData.Current.LocalSettings.Values.ContainsKey(LocalSettingNames.TextViewerFontSizeSetting))
{
FontSizes fontSizes;
Enum.TryParse<FontSizes>(ApplicationData.Current.LocalSettings.Values[LocalSettingNames.TextViewerFontSizeSetting].ToString(), out fontSizes);
return fontSizes;
}
return FontSizes.Normal;
}
set
{
ApplicationData.Current.LocalSettings.Values[LocalSettingNames.TextViewerFontSizeSetting] = value.ToString();
this.OnPropertyChanged("DisplayFontSize");
}
}
override protected DataSourceBase<MenuSchema> CreateDataSource()
{
return new ContactUsDataSource(); // MenuDataSource
}
override public bool HasMoreItems
{
get { return false; }
}
override protected void NavigateToSelectedItem()
{
var currentItem = GetCurrentItem();
if (currentItem != null)
{
if (currentItem.GetValue("Type").EqualNoCase("Section"))
{
NavigationServices.NavigateToPage(currentItem.GetValue("Target"));
}
else
{
NavigationServices.NavigateTo(new Uri(currentItem.GetValue("Target"), UriKind.Absolute));
}
}
}
}
}
| {
"content_hash": "42f98e0e940c03bb20c86bbce2f100d2",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 162,
"avg_line_length": 32.486486486486484,
"alnum_prop": 0.4789240155296728,
"repo_name": "SangramChavan/IEEE-Connected-Learning-Win-8.1",
"id": "d1a2587c4567acd61fef412cee0ddce2f130f05b",
"size": "3606",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AppStudio.Shared/ViewModels/ContactUsViewModel.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "281298"
},
{
"name": "HTML",
"bytes": "7449"
}
],
"symlink_target": ""
} |
from logging import WARNING, DEBUG
import yaml
import os.path
def load():
u"""サーバーとアプリの環境設定を読み込む
"""
env = 'development' if not os.environ.get('APP_NAME') else \
os.environ.get('APP_NAME')
base_path = os.path.dirname(os.path.dirname(__file__))
conf_path = '%s/%s' % (base_path, "conf/server.yml")
with open(conf_path) as f:
server_conf = yaml.load(f)
server_conf['common'].update(server_conf[env])
logging_level = DEBUG if server_conf['common']['debug'] \
else WARNING
server_conf['common'].update({'logging_level': logging_level})
server_conf['common'].update({'env': env})
return server_conf['common']
| {
"content_hash": "8558ef38ce7b75b09225ad879261a82a",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 70,
"avg_line_length": 34.9,
"alnum_prop": 0.6117478510028653,
"repo_name": "JFK/python-tornado-site-template",
"id": "582ba3a2c5a37224a30ddefc831b365b1635ff53",
"size": "826",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "www/mylib/conf.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3728"
},
{
"name": "HTML",
"bytes": "20018"
},
{
"name": "JavaScript",
"bytes": "55520"
},
{
"name": "Python",
"bytes": "22539"
}
],
"symlink_target": ""
} |
//
// DO NOT EDIT THIS FILE, IT HAS BEEN GENERATED USING AndroidAnnotations 3.0.1.
//
package com.prom.by.views;
import android.content.Context;
import android.widget.TextView;
import com.android.volley.toolbox.NetworkImageView;
import com.prom.by.R.id;
import com.prom.by.R.layout;
import org.androidannotations.api.view.HasViews;
import org.androidannotations.api.view.OnViewChangedListener;
import org.androidannotations.api.view.OnViewChangedNotifier;
/**
* We use @SuppressWarning here because our java code
* generator doesn't know that there is no need
* to import OnXXXListeners from View as we already
* are in a View.
*
*/
@SuppressWarnings("unused")
public final class ItemView_
extends ItemView
implements HasViews, OnViewChangedListener
{
private boolean alreadyInflated_ = false;
private final OnViewChangedNotifier onViewChangedNotifier_ = new OnViewChangedNotifier();
public ItemView_(Context context) {
super(context);
init_();
}
public static ItemView build(Context context) {
ItemView_ instance = new ItemView_(context);
instance.onFinishInflate();
return instance;
}
/**
* The mAlreadyInflated_ hack is needed because of an Android bug
* which leads to infinite calls of onFinishInflate()
* when inflating a layout with a parent and using
* the <merge /> tag.
*
*/
@Override
public void onFinishInflate() {
if (!alreadyInflated_) {
alreadyInflated_ = true;
inflate(getContext(), layout.view_item, this);
onViewChangedNotifier_.notifyViewChanged(this);
}
super.onFinishInflate();
}
private void init_() {
OnViewChangedNotifier previousNotifier = OnViewChangedNotifier.replaceNotifier(onViewChangedNotifier_);
OnViewChangedNotifier.registerOnViewChangedListener(this);
OnViewChangedNotifier.replaceNotifier(previousNotifier);
}
@Override
public void onViewChanged(HasViews hasViews) {
itemName = ((TextView) hasViews.findViewById(id.item_name));
itemCost = ((TextView) hasViews.findViewById(id.item_cost));
photo = ((NetworkImageView) hasViews.findViewById(id.item_photo));
itemPrice = ((TextView) hasViews.findViewById(id.item_price));
}
}
| {
"content_hash": "39f6b393874b14ffc0b04f3288bdda2e",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 111,
"avg_line_length": 30.69736842105263,
"alnum_prop": 0.6995285040720103,
"repo_name": "cliffroot/prom.by",
"id": "32cfb39f27f240144d8b2b1c82bf4aada824ddd5",
"size": "2333",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "project/apt_generated/com/prom/by/views/ItemView_.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "772"
},
{
"name": "Java",
"bytes": "341223"
}
],
"symlink_target": ""
} |
This feature is language-specific.
It occurs with 1 different values: `Anim`.
This is a <a href="../../u/overview/feat-layers.html">layered feature</a> with the following layers: [Animacy](), [Animacy[gram]]().
9 tokens (0%) have a non-empty value of `Animacy[gram]`.
7 types (0%) occur at least once with a non-empty value of `Animacy[gram]`.
7 lemmas (0%) occur at least once with a non-empty value of `Animacy[gram]`.
The feature is used with 1 part-of-speech tags: [uk-pos/NOUN]() (9; 0% instances).
### `NOUN`
9 [uk-pos/NOUN]() tokens (0% of all `NOUN` tokens) have a non-empty value of `Animacy[gram]`.
The most frequent other feature values with which `NOUN` and `Animacy[gram]` co-occurred: <tt><a href="Number.html">Number</a>=EMPTY</tt> (9; 100%), <tt><a href="Case.html">Case</a>=Acc</tt> (9; 100%), <tt><a href="Animacy.html">Animacy</a>=Inan</tt> (9; 100%), <tt><a href="Gender.html">Gender</a>=Masc</tt> (9; 100%).
`NOUN` tokens may have the following values of `Animacy[gram]`:
## Relations with Agreement in `Animacy[gram]`
The 10 most frequent relations where parent and child node agree in `Animacy[gram]`:
<tt>NOUN --[<a href="../dep/appos.html">appos</a>]--> NOUN</tt> (1; 100%).
| {
"content_hash": "7da671d27c2b7a1b1c1571245f6e8b0b",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 319,
"avg_line_length": 50.416666666666664,
"alnum_prop": 0.6743801652892562,
"repo_name": "PhyloStar/UDTelugu",
"id": "1bb2c564a110cb3aad2165090bd8c644aac0ebc6",
"size": "1333",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_includes/stats/uk/feat/Animacy-gram.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "62487"
},
{
"name": "HTML",
"bytes": "800587"
},
{
"name": "JavaScript",
"bytes": "181266"
},
{
"name": "Perl 6",
"bytes": "3953"
},
{
"name": "Python",
"bytes": "53707"
},
{
"name": "Ruby",
"bytes": "578"
},
{
"name": "Shell",
"bytes": "9597"
}
],
"symlink_target": ""
} |
insert into t_users (email) values('jack@itcrowd.pl');
| {
"content_hash": "98187845a6bad4b6c121f671b5698eda",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 54,
"avg_line_length": 55,
"alnum_prop": 0.7272727272727273,
"repo_name": "ftomassetti/JavaIncrementalParser",
"id": "27794a384963aad7de46344722da720997976fda",
"size": "55",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/resources/javaee7-samples/jms/jms-xa/src/main/resources/META-INF/load.sql",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "45351"
},
{
"name": "Groovy",
"bytes": "4889"
},
{
"name": "Java",
"bytes": "2084352"
},
{
"name": "JavaScript",
"bytes": "103909"
},
{
"name": "Scala",
"bytes": "75554"
},
{
"name": "TypeScript",
"bytes": "583"
}
],
"symlink_target": ""
} |
import numpy as np
import matplotlib.pyplot as plt
from sklearn import ensemble, svm,datasets
import brica1
# Randomforest Component Definition
class RandomForestClassifierComponent(brica1.Component):
def __init__(self, n_in):
super(RandomForestClassifierComponent, self).__init__()
self.classifier = ensemble.RandomForestClassifier()
self.make_in_port("in0", n_in)
self.make_out_port("out0", 1)
def fire(self):
x = self.inputs["in0"]
z = self.classifier.predict([x])
self.results["out0"] = z
def fit(self, X, y):
self.classifier.fit(X, y)
# SVM Component Definition
class SVMComponent(brica1.Component):
def __init__(self, n_in):
super(SVMComponent, self).__init__()
self.classifier = svm.LinearSVC(C=1.0)
self.make_in_port("in0", n_in)
self.make_out_port("out0", 1)
def fire(self):
x = self.inputs["in0"]
z = self.classifier.predict([x])
self.results["out0"] = z
def fit(self, X, y):
self.classifier.fit(X, y)
# SVM vs RFC Component Definition
class SVMvsRFC_Component(brica1.Component):
def __init__(self, n_in):
super(SVMvsRFC_Component, self).__init__()
self.make_in_port("in0",n_in)
self.make_in_port("in1",n_in)
self.make_out_port("out0", 1)
def fire(self):
x = self.inputs["in0"]
y = self.inputs["in1"]
self.results["out0"] = (x==y)
# Load iris dataset
iris = datasets.load_iris()
X = iris.data[:, :2]
y = iris.target
# Setup data feeder component
feeder = brica1.ConstantComponent()
feeder.make_out_port("out0", 2)
# Setup components
svm = SVMComponent(2)
svm.fit(X, y)
RFC = RandomForestClassifierComponent(2)
RFC.fit(X,y)
SR =SVMvsRFC_Component(1)
# Connect the components
brica1.connect((feeder, "out0"), (svm, "in0"))
brica1.connect((feeder, "out0"), (RFC, "in0"))
brica1.connect((svm, "out0"), (SR, "in0"))
brica1.connect((RFC, "out0"), (SR, "in1"))
# Add components to module
mod = brica1.Module()
mod.add_component("feeder", feeder)
mod.add_component("svm", svm)
mod.add_component("RFC",RFC)
mod.add_component("SR", SR)
# Setup scheduler and agent
a = brica1.Agent()
a.add_submodule("mod", mod)
s = brica1.VirtualTimeSyncScheduler(a)
# Test the classifier
svm_result=[]
RFC_result=[]
svm_vs_RFC=[]
for i in xrange(len(X)):
feeder.set_state("out0", X[i]) # Set data feeder to training data i
s.step() # Execute prediction
svm_result.append(svm.get_out_port("out0").buffer[0])
RFC_result.append(RFC.get_out_port("out0").buffer[0])
s.step()
svm_vs_RFC.append(SR.get_out_port("out0").buffer[0])
for i in xrange(len(X)):
print "SVM: {}\tRFC: {}\tRESULT: {}".format(svm_result[i], RFC_result[i], svm_vs_RFC[i])
| {
"content_hash": "441743ba05c76e663641adf34a8eea3b",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 92,
"avg_line_length": 25.89908256880734,
"alnum_prop": 0.6301806588735388,
"repo_name": "wbap/BriCA1",
"id": "e573d4735afaa9764540d4885740bd8e0e169ca2",
"size": "2840",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/sklearn/svc_vs_rfc.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "264"
},
{
"name": "Python",
"bytes": "56007"
}
],
"symlink_target": ""
} |
import allergy_intolerance from 'ember-fhir-adapter/models/allergy-intolerance';
export default allergy_intolerance; | {
"content_hash": "95a145591d935355c7bd730c9ee2f743",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 80,
"avg_line_length": 58,
"alnum_prop": 0.853448275862069,
"repo_name": "intervention-engine/ember-fhir-adapter",
"id": "ccfdc07a82afc79194d0e299c43978aac1bc9269",
"size": "154",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/allergy-intolerance.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1626"
},
{
"name": "JavaScript",
"bytes": "766477"
}
],
"symlink_target": ""
} |
require_dependency "subscriptions/application_controller"
module Subscriptions
class InvoicesController < ApplicationController
before_filter :set_invoice, only: [:show, :edit, :update, :destroy]
# GET /invoices
def index
@invoices = Invoice.all
end
# GET /invoices/1
def show
end
# GET /invoices/new
def new
@invoice = Invoice.new
end
# GET /invoices/1/edit
def edit
end
# POST /invoices
def create
@invoice = Invoice.new(invoice_params)
if @invoice.save
redirect_to @invoice, notice: 'Invoice was successfully created.'
else
render action: 'new'
end
end
# PATCH/PUT /invoices/1
def update
if @invoice.update(invoice_params)
redirect_to @invoice, notice: 'Invoice was successfully updated.'
else
render action: 'edit'
end
end
# DELETE /invoices/1
def destroy
@invoice.destroy
redirect_to invoices_url, notice: 'Invoice was successfully destroyed.'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_invoice
@invoice = Invoice.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def invoice_params
params.require(:invoice).permit(:invoice_start_date, :invoice_end_date, :customer_id)
end
end
end
| {
"content_hash": "4cfa3b79e50bdd2f7904d565091bdd57",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 93,
"avg_line_length": 22.85483870967742,
"alnum_prop": 0.6358503881439661,
"repo_name": "camperoo/subscriptions",
"id": "685fab6a9213e87fbb42bed09901673f65892a02",
"size": "1417",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/controllers/subscriptions/invoices_controller.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "122989"
},
{
"name": "JavaScript",
"bytes": "61489"
},
{
"name": "Ruby",
"bytes": "85433"
}
],
"symlink_target": ""
} |
SHA := $(shell git rev-parse --short HEAD)
VERSION := $(shell cat VERSION)
BUILDPATH := "build/"
LD_FLAGS := -s -w
GOVERSION := $(shell go version | sed -e 's/ /-/g')
BDATE := $(shell date -u +%Y-%m-%d.%H:%M:%S)
test:
go test $(shell go list ./... | grep -v /vendor/)
build:
mkdir -p $(BUILDPATH)
go build -i -v --ldflags "$(LD_FLAGS)" -o build/ring github.com/getcfs/megacfs/ring
go build -i -v -o build/cfs --ldflags " $(LD_FLAGS) \
-X main.commitVersion=$(SHA) \
-X main.cfsVersion=$(VERSION) \
-X main.goVersion=$(GOVERSION) \
-X main.buildDate=$(BDATE)" github.com/getcfs/megacfs/cfs
go build -i -v -o build/cfsd --ldflags " $(LD_FLAGS) \
-X main.commitVersion=$(SHA) \
-X main.cfsdVersion=$(VERSION) \
-X main.goVersion=$(GOVERSION) \
-X main.buildDate=$(BDATE)" github.com/getcfs/megacfs/cfsd
go build -i -v -o build/cfsadm --ldflags " $(LD_FLAGS) \
-X main.commitVersion=$(SHA) \
-X main.cfsadmVersion=$(VERSION) \
-X main.goVersion=$(GOVERSION) \
-X main.buildDate=$(BDATE)" github.com/getcfs/megacfs/cfsadm
clean:
rm -rf $(BUILDPATH)
install:
go install -v $(shell go list ./... | grep -v /vendor/)
vendor-unlock:
find vendor/ -name vendored.git -execdir mv -i vendored.git .git \; -prune
vendor-lock:
find vendor/ -name .git -execdir mv -i .git vendored.git \; -prune
| {
"content_hash": "965614185b1b7ec8a7084355d19c8b82",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 84,
"avg_line_length": 33.275,
"alnum_prop": 0.6393688955672426,
"repo_name": "letterj/megacfs",
"id": "2955c20704ce74303fb20ccc38f710e7273adbd1",
"size": "1331",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Makefile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "454873"
},
{
"name": "Makefile",
"bytes": "2011"
},
{
"name": "Protocol Buffer",
"bytes": "14064"
},
{
"name": "Shell",
"bytes": "9205"
},
{
"name": "Vim script",
"bytes": "1044"
}
],
"symlink_target": ""
} |
<!-- Footer Start -->
<footer id="footer">
<!-- Footer Bottom Start -->
<div class="footer-bottom">
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-xs-12 col-sm-12 ">
<h3>
<p class="copyright text-center" >© 2016 你知道吗?</p>
</h3>
</div>
</div>
</div>
</div>
<!-- Footer Bottom End -->
</footer>
<!-- Scroll To Top -->
<a href="#" class="scrollup"><i class="icon-angle-up"></i></a>
</div>
<!-- Wrap End -->
<!-- The Scripts -->
<script src="<?php echo site_url()?>assets/js/lib/jquery.min.js"></script>
<script src="<?php echo site_url()?>assets/js/lib/bootstrap.min.js"></script>
<script src="<?php echo site_url()?>assets/js/jquery.parallax.js"></script>
<script src="<?php echo site_url()?>assets/js/modernizr-2.6.2.min.js"></script>
<script src="<?php echo site_url()?>assets/js/jquery.nivo.slider.pack.js"></script>
<script src="<?php echo site_url()?>assets/js/jquery.prettyPhoto.js"></script>
<script src="<?php echo site_url()?>assets/js/superfish.js"></script>
<!--
<script src="<?php echo site_url()?>assets/js/tweetMachine.js"></script>
-->
<script src="<?php echo site_url()?>assets/js/tytabs.js"></script>
<script src="<?php echo site_url()?>assets/js/jquery.gmap.min.js"></script>
<script src="<?php echo site_url()?>assets/js/circularnav.js"></script>
<script src="<?php echo site_url()?>assets/js/jquery.sticky.js"></script>
<!--
<script src="<?php echo site_url()?>assets/js/jflickrfeed.js"></script>
-->
<script src="<?php echo site_url()?>assets/js/imagesloaded.pkgd.min.js"></script>
<script src="<?php echo site_url()?>assets/js/waypoints.min.js"></script>
<script src="<?php echo site_url()?>assets/js/spectrum.js"></script>
<!--
<script src="<?php echo site_url()?>assets/js/switcher.js"></script>
-->
<script src="<?php echo site_url()?>assets/js/custom.js"></script>
<script src="<?php echo site_url()?>assets/js/revolution-slider/js/jquery.themepunch.revolution.min.js"></script>
<!-- jquery-ui-1.11.4.custom -->
<script src="<?php echo site_url(); ?>assets/css/jquery-ui-1.11.4.custom/jquery-ui.min.js"></script>
<!-- mp3 -->
<script src="<?php echo site_url(); ?>assets/js/lib/audioplayer.js"></script>
<?php echo Assets::js(); ?>
</body>
</html> | {
"content_hash": "ead9a64ce2da67917b68089872f2de3f",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 125,
"avg_line_length": 45.278688524590166,
"alnum_prop": 0.5224475018102824,
"repo_name": "shenzhen-tq/nzdm",
"id": "a0cff0fa1e16439aba4d2a389cf973435f4793b2",
"size": "2772",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/themes/default/general/footer.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "356"
},
{
"name": "CSS",
"bytes": "152574"
},
{
"name": "HTML",
"bytes": "36952"
},
{
"name": "JavaScript",
"bytes": "432192"
},
{
"name": "PHP",
"bytes": "1905434"
}
],
"symlink_target": ""
} |
package io.fd.vpp.jvpp.core.test;
import io.fd.vpp.jvpp.JVppRegistry;
import io.fd.vpp.jvpp.JVppRegistryImpl;
import io.fd.vpp.jvpp.core.JVppCoreImpl;
import io.fd.vpp.jvpp.core.dto.BridgeDomainDetailsReplyDump;
import io.fd.vpp.jvpp.core.dto.BridgeDomainDump;
import io.fd.vpp.jvpp.core.dto.GetNodeIndex;
import io.fd.vpp.jvpp.core.dto.GetNodeIndexReply;
import io.fd.vpp.jvpp.core.dto.ShowVersion;
import io.fd.vpp.jvpp.core.dto.ShowVersionReply;
import io.fd.vpp.jvpp.core.dto.SwInterfaceDetails;
import io.fd.vpp.jvpp.core.dto.SwInterfaceDetailsReplyDump;
import io.fd.vpp.jvpp.core.dto.SwInterfaceDump;
import io.fd.vpp.jvpp.core.future.FutureJVppCoreFacade;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
public class FutureApiTest {
private static final Logger LOG = Logger.getLogger(FutureApiTest.class.getName());
private static void testShowVersion(final FutureJVppCoreFacade jvpp) throws Exception {
LOG.info("Sending ShowVersion request...");
final Future<ShowVersionReply> replyFuture = jvpp.showVersion(new ShowVersion()).toCompletableFuture();
final ShowVersionReply reply = replyFuture.get();
LOG.info(
String.format(
"Received ShowVersionReply: context=%d, program=%s, version=%s, buildDate=%s, buildDirectory=%s%n",
reply.context, new String(reply.program), new String(reply.version), new String(reply.buildDate),
new String(reply.buildDirectory)));
}
private static void testEmptyBridgeDomainDump(final FutureJVppCoreFacade jvpp) throws Exception {
LOG.info("Sending ShowVersion request...");
final BridgeDomainDump request = new BridgeDomainDump();
request.bdId = -1; // dump call
final CompletableFuture<BridgeDomainDetailsReplyDump>
replyFuture = jvpp.bridgeDomainDump(request).toCompletableFuture();
final BridgeDomainDetailsReplyDump reply = replyFuture.get();
if (reply == null || reply.bridgeDomainDetails == null) {
LOG.severe("Received null response for empty dump: " + reply);
} else {
LOG.info(
String.format(
"Received empty bridge-domain dump reply with list of bridge-domains: %s, %s",
reply.bridgeDomainDetails, reply.bridgeDomainSwIfDetails));
}
}
private static void testGetNodeIndex(final FutureJVppCoreFacade jvpp) {
LOG.info("Sending GetNodeIndex request...");
final GetNodeIndex request = new GetNodeIndex();
request.nodeName = "non-existing-node".getBytes();
final Future<GetNodeIndexReply> replyFuture = jvpp.getNodeIndex(request).toCompletableFuture();
try {
final GetNodeIndexReply reply = replyFuture.get();
LOG.info(
String.format(
"Received GetNodeIndexReply: context=%d, nodeIndex=%d%n", reply.context, reply.nodeIndex));
} catch (Exception e) {
LOG.log(Level.SEVERE, "GetNodeIndex request failed", e);
}
}
private static void testSwInterfaceDump(final FutureJVppCoreFacade jvpp) throws Exception {
LOG.info("Sending SwInterfaceDump request...");
final SwInterfaceDump request = new SwInterfaceDump();
request.nameFilterValid = 0;
request.nameFilter = "".getBytes();
final Future<SwInterfaceDetailsReplyDump> replyFuture = jvpp.swInterfaceDump(request).toCompletableFuture();
final SwInterfaceDetailsReplyDump reply = replyFuture.get();
for (SwInterfaceDetails details : reply.swInterfaceDetails) {
Objects.requireNonNull(details, "reply.swInterfaceDetails contains null element!");
LOG.info(
String.format("Received SwInterfaceDetails: interfaceName=%s, l2AddressLength=%d, adminUpDown=%d, "
+ "linkUpDown=%d, linkSpeed=%d, linkMtu=%d%n",
new String(details.interfaceName), details.l2AddressLength, details.adminUpDown,
details.linkUpDown, details.linkSpeed, (int) details.linkMtu));
}
}
private static void testFutureApi() throws Exception {
LOG.info("Testing Java future API");
try (final JVppRegistry registry = new JVppRegistryImpl("FutureApiTest");
final FutureJVppCoreFacade jvppFacade = new FutureJVppCoreFacade(registry, new JVppCoreImpl())) {
LOG.info("Successfully connected to VPP");
testEmptyBridgeDomainDump(jvppFacade);
testShowVersion(jvppFacade);
testGetNodeIndex(jvppFacade);
testSwInterfaceDump(jvppFacade);
LOG.info("Disconnecting...");
}
}
public static void main(String[] args) throws Exception {
testFutureApi();
}
}
| {
"content_hash": "7b070b6b89ca6f33441e35dd9cf2cfc6",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 116,
"avg_line_length": 45.357798165137616,
"alnum_prop": 0.6814320388349514,
"repo_name": "GabrielGanne/vpp-flowtable",
"id": "f478bab442f05b1ace81aaf70b1d5fdc3fee055b",
"size": "5560",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/vpp-api/java/jvpp-core/io/fd/vpp/jvpp/core/test/FutureApiTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "14862"
},
{
"name": "C",
"bytes": "11501817"
},
{
"name": "C++",
"bytes": "537711"
},
{
"name": "CSS",
"bytes": "794"
},
{
"name": "Emacs Lisp",
"bytes": "99891"
},
{
"name": "Java",
"bytes": "120676"
},
{
"name": "Lua",
"bytes": "80051"
},
{
"name": "M4",
"bytes": "57750"
},
{
"name": "Makefile",
"bytes": "205336"
},
{
"name": "Objective-C",
"bytes": "22802"
},
{
"name": "Python",
"bytes": "585538"
},
{
"name": "Ruby",
"bytes": "3461"
},
{
"name": "Shell",
"bytes": "37208"
},
{
"name": "Yacc",
"bytes": "3034"
}
],
"symlink_target": ""
} |
#region License
// Copyright(c) Workshell Ltd
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Workshell.PE.Annotations;
using Workshell.PE.Content;
using Workshell.PE.Extensions;
using Workshell.PE.Native;
namespace Workshell.PE.Resources
{
public sealed class ResourceDirectory : DataContent, IEnumerable<ResourceDirectoryEntry>
{
private ResourceDirectoryEntry[] _entries;
internal ResourceDirectory(PortableExecutableImage image, DataDirectory dataDirectory, Location location, ResourceDirectoryEntry directoryEntry) : base(image, dataDirectory, location)
{
_entries = new ResourceDirectoryEntry[0];
DirectoryEntry = directoryEntry;
}
#region Static Methods
public static ResourceDirectory Get(PortableExecutableImage image)
{
return GetAsync(image).GetAwaiter().GetResult();
}
public static async Task<ResourceDirectory> GetAsync(PortableExecutableImage image)
{
if (!image.NTHeaders.DataDirectories.Exists(DataDirectoryType.ResourceTable))
return null;
var dataDirectory = image.NTHeaders.DataDirectories[DataDirectoryType.ResourceTable];
if (DataDirectory.IsNullOrEmpty(dataDirectory))
return null;
var calc = image.GetCalculator();
var rva = dataDirectory.VirtualAddress;
var va = image.NTHeaders.OptionalHeader.ImageBase + rva;
var offset = calc.RVAToOffset(rva);
var size = Utils.SizeOf<IMAGE_RESOURCE_DIRECTORY>().ToUInt32();
var section = calc.RVAToSection(rva);
var location = new Location(image, offset, rva, va, size, size, section);
var directory = new ResourceDirectory(image, dataDirectory, location, null);
await directory.LoadAsync().ConfigureAwait(false);
return directory;
}
#endregion
#region Methods
public IEnumerator<ResourceDirectoryEntry> GetEnumerator()
{
foreach (var entry in _entries)
yield return entry;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public DateTime GetTimeDateStamp()
{
return Utils.ConvertTimeDateStamp(TimeDateStamp);
}
public Version GetVersion()
{
return new Version(MajorVersion, MinorVersion);
}
internal async Task LoadAsync()
{
var calc = Image.GetCalculator();
var stream = Image.GetStream();
stream.Seek(Location.FileOffset.ToInt64(),SeekOrigin.Begin);
var directorySize = Utils.SizeOf<IMAGE_RESOURCE_DIRECTORY>();
IMAGE_RESOURCE_DIRECTORY directory;
try
{
directory = await stream.ReadStructAsync<IMAGE_RESOURCE_DIRECTORY>(directorySize).ConfigureAwait(false);
}
catch (Exception ex)
{
throw new PortableExecutableImageException(Image, "Could not read resource directory from stream.", ex);
}
var count = directory.NumberOfNamedEntries + directory.NumberOfIdEntries;
var entries = new List<ResourceDirectoryEntry>(count);
var offset = Location.FileOffset + directorySize.ToUInt32();
var entrySize = Utils.SizeOf<IMAGE_RESOURCE_DIRECTORY_ENTRY>();
for (int i = 0; i < count; i++)
{
stream.Seek(offset.ToInt64(),SeekOrigin.Begin);
var entry = await stream.ReadStructAsync<IMAGE_RESOURCE_DIRECTORY_ENTRY>(entrySize).ConfigureAwait(false);
var rva = calc.OffsetToRVA(offset);
var va = Image.NTHeaders.OptionalHeader.ImageBase + rva;
var section = calc.RVAToSection(rva);
var location = new Location(Image, offset, rva, va, entrySize.ToUInt32(), entrySize.ToUInt32(), section);
var directoryEntry = new ResourceDirectoryEntry(Image, DataDirectory, location, this, entry);
entries.Add(directoryEntry);
offset += entrySize.ToUInt32();
}
_entries = entries.ToArray();
Characteristics = directory.Characteristics;
TimeDateStamp = directory.TimeDateStamp;
MajorVersion = directory.MajorVersion;
MinorVersion = directory.MinorVersion;
NumberOfNamedEntries = directory.NumberOfNamedEntries;
NumberOfIdEntries = directory.NumberOfIdEntries;
}
#endregion
#region Properties
public ResourceDirectoryEntry DirectoryEntry { get; }
public int Count => _entries.Length;
public ResourceDirectoryEntry this[int index] => _entries[index];
[FieldAnnotation("Characteristics", Order = 1)]
public uint Characteristics { get; private set; }
[FieldAnnotation("Date/Time Stamp", Order = 2)]
public uint TimeDateStamp { get; private set; }
[FieldAnnotation("Major Version", Order = 3)]
public ushort MajorVersion { get; private set; }
[FieldAnnotation("Minor Version", Order = 4)]
public ushort MinorVersion { get; private set; }
[FieldAnnotation("Number of Named Entries", Order = 5)]
public ushort NumberOfNamedEntries { get; private set; }
[FieldAnnotation("Number of ID Entries", Order = 6)]
public ushort NumberOfIdEntries { get; private set; }
#endregion
}
}
| {
"content_hash": "0301098f60bf005d56ef60324af7dc9a",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 191,
"avg_line_length": 37.806451612903224,
"alnum_prop": 0.6355233219567691,
"repo_name": "Workshell/pe",
"id": "75a2596c0714ab62c652fa141b5e017dedc1ff42",
"size": "7034",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Workshell.PE/Content/Resources/ResourceDirectory.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "755869"
}
],
"symlink_target": ""
} |
package contacts;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.testng.*;
import org.testng.annotations.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import com.saucelabs.testng.SauceOnDemandTestListener;
import com.saucelabs.common.SauceOnDemandAuthentication;
import com.saucelabs.common.SauceOnDemandSessionIdProvider;
import com.saucelabs.testng.SauceOnDemandAuthenticationProvider;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.testng.Assert.assertEquals;
@Listeners({SauceOnDemandTestListener.class})
public class Only_email extends magento.pages.TestBase {
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
public WebDriver createDriver(String browser, String version, String os) throws MalformedURLException {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.BROWSER_NAME, browser);
if (version != null) {
capabilities.setCapability(CapabilityType.VERSION, version);
}
capabilities.setCapability(CapabilityType.PLATFORM, os);
capabilities.setCapability("name", "Only_email");
capabilities.setCapability("passed", "true");
webDriver.set(new RemoteWebDriver(
new URL("http://qatestingtestqa:7d7d449c-27c0-45c7-9339-3aad563a5cc0@ondemand.saucelabs.com:80/wd/hub"),
capabilities));
sessionId.set(((RemoteWebDriver) getWebDriver()).getSessionId().toString());
return webDriver.get();
}
@Test(dataProvider = "hardCodedBrowsers")
public void testUntitled2(String browser, String version, String os) throws Exception {
WebDriver driver = createDriver(browser, version, os);
driver.get(baseUrl + "contacts");
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("email")).sendKeys("test@test.com");
driver.findElement(By.xpath("(//button[@type='submit'])[2]")).click();
assertEquals("This is a required field.", driver.findElement(By.id("advice-required-entry-name")).getText());
assertEquals("This is a required field.", driver.findElement(By.id("advice-required-entry-lastname")).getText());
assertEquals("This is a required field.", driver.findElement(By.id("advice-required-entry-comment")).getText());
driver.quit();
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| {
"content_hash": "4d5548c8b0598987037107b22ff6a0f2",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 119,
"avg_line_length": 36.34375,
"alnum_prop": 0.7357408999713385,
"repo_name": "LanaVoit/pgs-tests",
"id": "badf6346ea5e262813495e83adce2c07bdfff894",
"size": "3489",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/contacts/Only_email.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "10674"
},
{
"name": "Java",
"bytes": "193554"
},
{
"name": "JavaScript",
"bytes": "7110"
}
],
"symlink_target": ""
} |
.PHONY: deploy
deploy:
git checkout gh-pages
git merge master
git push
git checkout master | {
"content_hash": "e95580790e7c1b5636620b7d36414af0",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 22,
"avg_line_length": 13.571428571428571,
"alnum_prop": 0.7684210526315789,
"repo_name": "primozcigler/check-my-pipipi",
"id": "8ca9eaf8d7e92bc03296413d0c96fd9bc6cc9de9",
"size": "95",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Makefile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1517"
},
{
"name": "JavaScript",
"bytes": "3710"
},
{
"name": "Makefile",
"bytes": "95"
}
],
"symlink_target": ""
} |
/*
* Author: atotic
* Created on Mar 23, 2004
* License: Common Public License v1.0
*/
package vgrechka.phizdetsidea.phizdets.debugger.pydev;
import com.google.common.collect.Maps;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.xdebugger.breakpoints.SuspendPolicy;
import com.intellij.xdebugger.frame.XValueChildrenList;
import vgrechka.phizdetsidea.phizdets.console.pydev.PydevCompletionVariant;
import vgrechka.phizdetsidea.phizdets.debugger.*;
import vgrechka.phizdetsidea.phizdets.debugger.pydev.transport.ClientModeDebuggerTransport;
import vgrechka.phizdetsidea.phizdets.debugger.pydev.transport.DebuggerTransport;
import vgrechka.phizdetsidea.phizdets.debugger.pydev.transport.ServerModeDebuggerTransport;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.net.ServerSocket;
import java.security.SecureRandom;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static vgrechka.phizdetsidea.phizdets.debugger.pydev.transport.BaseDebuggerTransport.logFrame;
public class RemoteDebugger implements ProcessDebugger {
private static final int RESPONSE_TIMEOUT = 60000;
private static final Logger LOG = Logger.getInstance("#vgrechka.phizdetsidea.phizdets.pydev.remote.RemoteDebugger");
private static final String LOCAL_VERSION = "0.1";
public static final String TEMP_VAR_PREFIX = "__py_debug_temp_var_";
private static final SecureRandom ourRandom = new SecureRandom();
private final IPyDebugProcess myDebugProcess;
private int mySequence = -1;
private final Object mySequenceObject = new Object(); // for synchronization on mySequence
private final Map<String, PyThreadInfo> myThreads = new ConcurrentHashMap<>();
private final Map<Integer, ProtocolFrame> myResponseQueue = new HashMap<>();
private final TempVarsHolder myTempVars = new TempVarsHolder();
private Map<Pair<String, Integer>, String> myTempBreakpoints = Maps.newHashMap();
private final List<RemoteDebuggerCloseListener> myCloseListeners = ContainerUtil.createLockFreeCopyOnWriteList();
@NotNull private final DebuggerTransport myDebuggerTransport;
public RemoteDebugger(@NotNull IPyDebugProcess debugProcess, @NotNull String host, int port) {
myDebugProcess = debugProcess;
myDebuggerTransport = new ClientModeDebuggerTransport(this, host, port);
}
public RemoteDebugger(@NotNull IPyDebugProcess debugProcess, @NotNull ServerSocket socket, int timeout) {
myDebugProcess = debugProcess;
myDebuggerTransport = new ServerModeDebuggerTransport(this, socket, timeout);
}
protected RemoteDebugger(@NotNull IPyDebugProcess debugProcess, @NotNull DebuggerTransport debuggerTransport) {
myDebugProcess = debugProcess;
myDebuggerTransport = debuggerTransport;
}
public IPyDebugProcess getDebugProcess() {
return myDebugProcess;
}
@Override
public boolean isConnected() {
return myDebuggerTransport.isConnected();
}
@Override
public void waitForConnect() throws Exception {
myDebuggerTransport.waitForConnect();
}
private void writeToConsole(PyIo io) {
ConsoleViewContentType contentType;
if (io.getCtx() == 2) {
contentType = ConsoleViewContentType.ERROR_OUTPUT;
}
else {
contentType = ConsoleViewContentType.NORMAL_OUTPUT;
}
myDebugProcess.printToConsole(io.getText(), contentType);
}
@Override
public String handshake() throws PyDebuggerException {
final VersionCommand command = new VersionCommand(this, LOCAL_VERSION, SystemInfo.isUnix ? "UNIX" : "WIN");
command.execute();
String version = command.getRemoteVersion();
if (version != null) {
version = version.trim();
}
return version;
}
@Override
public PyDebugValue evaluate(final String threadId,
final String frameId,
final String expression, final boolean execute) throws PyDebuggerException {
return evaluate(threadId, frameId, expression, execute, true);
}
@Override
public PyDebugValue evaluate(final String threadId,
final String frameId,
final String expression,
final boolean execute,
boolean trimResult)
throws PyDebuggerException {
final EvaluateCommand command = new EvaluateCommand(this, threadId, frameId, expression, execute, trimResult);
command.execute();
return command.getValue();
}
@Override
public void consoleExec(String threadId, String frameId, String expression, PyDebugCallback<String> callback) {
final ConsoleExecCommand command = new ConsoleExecCommand(this, threadId, frameId, expression);
command.execute(callback);
}
@Override
public XValueChildrenList loadFrame(final String threadId, final String frameId) throws PyDebuggerException {
final GetFrameCommand command = new GetFrameCommand(this, threadId, frameId);
command.execute();
return command.getVariables();
}
// todo: don't generate temp variables for qualified expressions - just split 'em
@Override
public XValueChildrenList loadVariable(final String threadId, final String frameId, final PyDebugValue var) throws PyDebuggerException {
setTempVariable(threadId, frameId, var);
final GetVariableCommand command = new GetVariableCommand(this, threadId, frameId, var);
command.execute();
return command.getVariables();
}
@Override
public ArrayChunk loadArrayItems(String threadId,
String frameId,
PyDebugValue var,
int rowOffset,
int colOffset,
int rows,
int cols,
String format) throws PyDebuggerException {
final GetArrayCommand command = new GetArrayCommand(this, threadId, frameId, var, rowOffset, colOffset, rows, cols, format);
command.execute();
return command.getArray();
}
@Override
public void loadReferrers(final String threadId,
final String frameId,
final PyReferringObjectsValue var,
final PyDebugCallback<XValueChildrenList> callback) {
RunCustomOperationCommand cmd = new GetReferrersCommand(this, threadId, frameId, var);
cmd.execute(new PyDebugCallback<List<PyDebugValue>>() {
@Override
public void ok(List<PyDebugValue> value) {
XValueChildrenList list = new XValueChildrenList();
for (PyDebugValue v : value) {
list.add(v);
}
callback.ok(list);
}
@Override
public void error(PyDebuggerException exception) {
callback.error(exception);
}
});
}
@Override
public PyDebugValue changeVariable(final String threadId, final String frameId, final PyDebugValue var, final String value)
throws PyDebuggerException {
setTempVariable(threadId, frameId, var);
return doChangeVariable(threadId, frameId, var.getEvaluationExpression(), value);
}
private PyDebugValue doChangeVariable(final String threadId, final String frameId, final String varName, final String value)
throws PyDebuggerException {
final ChangeVariableCommand command = new ChangeVariableCommand(this, threadId, frameId, varName, value);
command.execute();
return command.getNewValue();
}
@Override
@Nullable
public String loadSource(String path) {
LoadSourceCommand command = new LoadSourceCommand(this, path);
try {
command.execute();
return command.getContent();
}
catch (PyDebuggerException e) {
return "#Couldn't load source of file " + path;
}
}
private void cleanUp() {
myThreads.clear();
myResponseQueue.clear();
synchronized (mySequenceObject) {
mySequence = -1;
}
myTempVars.clear();
}
// todo: change variable in lists doesn't work - either fix in pydevd or format var name appropriately
private void setTempVariable(final String threadId, final String frameId, final PyDebugValue var) {
final PyDebugValue topVar = var.getTopParent();
if (!myDebugProcess.canSaveToTemp(topVar.getName())) {
return;
}
if (myTempVars.contains(threadId, frameId, topVar.getTempName())) {
return;
}
topVar.setTempName(generateTempName());
try {
doChangeVariable(threadId, frameId, topVar.getTempName(), topVar.getName());
myTempVars.put(threadId, frameId, topVar.getTempName());
}
catch (PyDebuggerException e) {
LOG.error(e);
topVar.setTempName(null);
}
}
public String generateSaveTempName(final String threadId, final String frameId) {
final String tempName = generateTempName();
myTempVars.put(threadId, frameId, tempName);
return tempName;
}
private void clearTempVariables(final String threadId) {
final Map<String, Set<String>> threadVars = myTempVars.get(threadId);
if (threadVars == null || threadVars.size() == 0) return;
for (Map.Entry<String, Set<String>> entry : threadVars.entrySet()) {
final Set<String> frameVars = entry.getValue();
if (frameVars == null || frameVars.size() == 0) continue;
final String expression = "del " + StringUtil.join(frameVars, ",");
try {
evaluate(threadId, entry.getKey(), expression, true);
}
catch (PyDebuggerException e) {
LOG.error(e);
}
}
myTempVars.clear(threadId);
}
private static String generateTempName() {
return TEMP_VAR_PREFIX + ourRandom.nextInt(Integer.MAX_VALUE);
}
@Override
public Collection<PyThreadInfo> getThreads() {
return Collections.unmodifiableCollection(new ArrayList<>(myThreads.values()));
}
int getNextSequence() {
synchronized (mySequenceObject) {
mySequence += 2;
return mySequence;
}
}
void placeResponse(final int sequence, final ProtocolFrame response) {
synchronized (myResponseQueue) {
if (response == null || myResponseQueue.containsKey(sequence)) {
myResponseQueue.put(sequence, response);
}
if (response != null) {
myResponseQueue.notifyAll();
}
}
}
@Nullable
ProtocolFrame waitForResponse(final int sequence) {
ProtocolFrame response;
long until = System.currentTimeMillis() + RESPONSE_TIMEOUT;
synchronized (myResponseQueue) {
do {
try {
myResponseQueue.wait(1000);
}
catch (InterruptedException ignore) {
}
response = myResponseQueue.get(sequence);
}
while (response == null && isConnected() && System.currentTimeMillis() < until);
myResponseQueue.remove(sequence);
}
return response;
}
@Override
public void execute(@NotNull final AbstractCommand command) {
if (command instanceof ResumeOrStepCommand) {
final String threadId = ((ResumeOrStepCommand)command).getThreadId();
clearTempVariables(threadId);
}
try {
command.execute();
}
catch (PyDebuggerException e) {
LOG.error(e);
}
}
boolean sendFrame(final ProtocolFrame frame) {
return myDebuggerTransport.sendFrame(frame);
}
@Override
public void suspendAllThreads() {
for (PyThreadInfo thread : getThreads()) {
suspendThread(thread.getId());
}
}
@Override
public void suspendThread(String threadId) {
final SuspendCommand command = new SuspendCommand(this, threadId);
execute(command);
}
@Override
public void close() {
myDebuggerTransport.close();
fireCloseEvent();
}
@Override
public void disconnect() {
myDebuggerTransport.disconnect();
cleanUp();
}
@Override
public void run() throws PyDebuggerException {
new RunCommand(this).execute();
}
@Override
public void smartStepInto(String threadId, String functionName) {
final SmartStepIntoCommand command = new SmartStepIntoCommand(this, threadId, functionName);
execute(command);
}
@Override
public void resumeOrStep(String threadId, ResumeOrStepCommand.Mode mode) {
final ResumeOrStepCommand command = new ResumeOrStepCommand(this, threadId, mode);
execute(command);
}
@Override
public void setTempBreakpoint(@NotNull String type, @NotNull String file, int line) {
final SetBreakpointCommand command =
new SetBreakpointCommand(this, type, file, line);
execute(command); // set temp. breakpoint
myTempBreakpoints.put(Pair.create(file, line), type);
}
@Override
public void removeTempBreakpoint(@NotNull String file, int line) {
String type = myTempBreakpoints.get(Pair.create(file, line));
if (type != null) {
final RemoveBreakpointCommand command = new RemoveBreakpointCommand(this, type, file, line);
execute(command); // remove temp. breakpoint
}
else {
LOG.error("Temp breakpoint not found for " + file + ":" + line);
}
}
@Override
public void setBreakpoint(@NotNull String typeId,
@NotNull String file,
int line,
@Nullable String condition,
@Nullable String logExpression,
@Nullable String funcName,
@NotNull SuspendPolicy policy) {
final SetBreakpointCommand command =
new SetBreakpointCommand(this, typeId, file, line,
condition,
logExpression,
funcName,
policy);
execute(command);
}
@Override
public void removeBreakpoint(@NotNull String typeId, @NotNull String file, int line) {
final RemoveBreakpointCommand command =
new RemoveBreakpointCommand(this, typeId, file, line);
execute(command);
}
@Override
public void setShowReturnValues(boolean isShowReturnValues) {
final ShowReturnValuesCommand command = new ShowReturnValuesCommand(this, isShowReturnValues);
execute(command);
}
// for DebuggerReader only
public void processResponse(@NotNull final String line) {
try {
final ProtocolFrame frame = new ProtocolFrame(line);
logFrame(frame, false);
if (AbstractThreadCommand.isThreadCommand(frame.getCommand())) {
processThreadEvent(frame);
}
else if (AbstractCommand.isWriteToConsole(frame.getCommand())) {
writeToConsole(ProtocolParser.parseIo(frame.getPayload()));
}
else if (AbstractCommand.isExitEvent(frame.getCommand())) {
fireCommunicationError();
}
else if (AbstractCommand.isCallSignatureTrace(frame.getCommand())) {
recordCallSignature(ProtocolParser.parseCallSignature(frame.getPayload()));
}
else if (AbstractCommand.isConcurrencyEvent(frame.getCommand())) {
recordConcurrencyEvent(ProtocolParser.parseConcurrencyEvent(frame.getPayload(), myDebugProcess.getPositionConverter()));
}
else if (AbstractCommand.isInputRequested(frame.getCommand())) {
myDebugProcess.consoleInputRequested(ProtocolParser.parseInputCommand(frame.getPayload()));
}
else if (ProcessCreatedCommand.isProcessCreatedCommand(frame.getCommand())) {
onProcessCreatedEvent();
}
else {
placeResponse(frame.getSequence(), frame);
}
}
catch (Throwable t) {
// shouldn't interrupt reader thread
LOG.error(t);
}
}
private void recordCallSignature(PySignature signature) {
myDebugProcess.recordSignature(signature);
}
private void recordConcurrencyEvent(PyConcurrencyEvent event) {
myDebugProcess.recordLogEvent(event);
}
// todo: extract response processing
private void processThreadEvent(ProtocolFrame frame) throws PyDebuggerException {
switch (frame.getCommand()) {
case AbstractCommand.CREATE_THREAD: {
final PyThreadInfo thread = parseThreadEvent(frame);
if (!thread.isPydevThread()) { // ignore pydevd threads
myThreads.put(thread.getId(), thread);
if (myDebugProcess.getSession().isSuspended() && myDebugProcess.isSuspendedOnAllThreadsPolicy()) {
// Sometimes the notification about new threads may come slow from the Phizdets side. We should check if
// the current session is suspended in the "Suspend all threads" mode and suspend new thread, which hasn't been suspended
suspendThread(thread.getId());
}
}
break;
}
case AbstractCommand.SUSPEND_THREAD: {
final PyThreadInfo event = parseThreadEvent(frame);
PyThreadInfo thread = myThreads.get(event.getId());
if (thread == null) {
LOG.error("Trying to stop on non-existent thread: " + event.getId() + ", " + event.getStopReason() + ", " + event.getMessage());
myThreads.put(event.getId(), event);
thread = event;
}
thread.updateState(PyThreadInfo.State.SUSPENDED, event.getFrames());
thread.setStopReason(event.getStopReason());
thread.setMessage(event.getMessage());
boolean updateSourcePosition = true;
if (event.getStopReason() == AbstractCommand.SUSPEND_THREAD) {
// That means that the thread was stopped manually from the Java side either while suspending all threads
// or after the "Pause" command. In both cases we shouldn't change debugger focus if session is already suspended.
updateSourcePosition = !myDebugProcess.getSession().isSuspended();
}
myDebugProcess.threadSuspended(thread, updateSourcePosition);
break;
}
case AbstractCommand.RESUME_THREAD: {
final String id = ProtocolParser.getThreadId(frame.getPayload());
final PyThreadInfo thread = myThreads.get(id);
if (thread != null) {
thread.updateState(PyThreadInfo.State.RUNNING, null);
myDebugProcess.threadResumed(thread);
}
break;
}
case AbstractCommand.KILL_THREAD: {
final String id = frame.getPayload();
final PyThreadInfo thread = myThreads.get(id);
if (thread != null) {
thread.updateState(PyThreadInfo.State.KILLED, null);
myThreads.remove(id);
}
if (myDebugProcess.getSession().getCurrentPosition() == null) {
for (PyThreadInfo threadInfo : myThreads.values()) {
// notify UI of suspended threads left in debugger if one thread finished its work
if ((threadInfo != null) && (threadInfo.getState() == PyThreadInfo.State.SUSPENDED)) {
myDebugProcess.threadResumed(threadInfo);
myDebugProcess.threadSuspended(threadInfo, true);
}
}
}
break;
}
case AbstractCommand.SHOW_CONSOLE: {
final PyThreadInfo event = parseThreadEvent(frame);
PyThreadInfo thread = myThreads.get(event.getId());
if (thread == null) {
myThreads.put(event.getId(), event);
thread = event;
}
thread.updateState(PyThreadInfo.State.SUSPENDED, event.getFrames());
thread.setStopReason(event.getStopReason());
thread.setMessage(event.getMessage());
myDebugProcess.showConsole(thread);
break;
}
}
}
private PyThreadInfo parseThreadEvent(ProtocolFrame frame) throws PyDebuggerException {
return ProtocolParser.parseThread(frame.getPayload(), myDebugProcess.getPositionConverter());
}
private static class TempVarsHolder {
private final Map<String, Map<String, Set<String>>> myData = new HashMap<>();
public boolean contains(final String threadId, final String frameId, final String name) {
final Map<String, Set<String>> threadVars = myData.get(threadId);
if (threadVars == null) return false;
final Set<String> frameVars = threadVars.get(frameId);
if (frameVars == null) return false;
return frameVars.contains(name);
}
protected void put(final String threadId, final String frameId, final String name) {
Map<String, Set<String>> threadVars = myData.get(threadId);
if (threadVars == null) myData.put(threadId, (threadVars = new HashMap<>()));
Set<String> frameVars = threadVars.get(frameId);
if (frameVars == null) threadVars.put(frameId, (frameVars = new HashSet<>()));
frameVars.add(name);
}
protected Map<String, Set<String>> get(final String threadId) {
return myData.get(threadId);
}
protected void clear() {
myData.clear();
}
protected void clear(final String threadId) {
final Map<String, Set<String>> threadVars = myData.get(threadId);
if (threadVars != null) {
threadVars.clear();
}
}
}
public void addCloseListener(RemoteDebuggerCloseListener listener) {
myCloseListeners.add(listener);
}
public void removeCloseListener(RemoteDebuggerCloseListener listener) {
myCloseListeners.remove(listener);
}
@Override
public List<PydevCompletionVariant> getCompletions(String threadId, String frameId, String prefix) {
final GetCompletionsCommand command = new GetCompletionsCommand(this, threadId, frameId, prefix);
execute(command);
return command.getCompletions();
}
@Override
public String getDescription(String threadId, String frameId, String cmd) {
final GetDescriptionCommand command = new GetDescriptionCommand(this, threadId, frameId, cmd);
execute(command);
return command.getResult();
}
@Override
public void addExceptionBreakpoint(ExceptionBreakpointCommandFactory factory) {
execute(factory.createAddCommand(this));
}
@Override
public void removeExceptionBreakpoint(ExceptionBreakpointCommandFactory factory) {
execute(factory.createRemoveCommand(this));
}
@Override
public void suspendOtherThreads(PyThreadInfo thread) {
if (!myThreads.containsKey(thread.getId())) {
// It means that breakpoint with "Suspend all" policy was reached in another process
// and we should suspend all threads in the current process on Java side
for (PyThreadInfo otherThread : getThreads()) {
if (!otherThread.getId().equals(thread.getId())) {
suspendThread(otherThread.getId());
}
}
}
}
protected void onProcessCreatedEvent() throws PyDebuggerException {
}
protected void fireCloseEvent() {
for (RemoteDebuggerCloseListener listener : myCloseListeners) {
listener.closed();
}
}
public void fireCommunicationError() {
for (RemoteDebuggerCloseListener listener : myCloseListeners) {
listener.communicationError();
}
}
// for DebuggerReader only
public void fireExitEvent() {
for (RemoteDebuggerCloseListener listener : myCloseListeners) {
listener.detached();
}
}
}
| {
"content_hash": "bc3889996ce3b4ad5b58fe2e5c279009",
"timestamp": "",
"source": "github",
"line_count": 667,
"max_line_length": 138,
"avg_line_length": 34.79460269865068,
"alnum_prop": 0.6826525336091003,
"repo_name": "vovagrechka/fucking-everything",
"id": "19ba6ef3848afb4ee29501bc545045ae98c781c6",
"size": "23208",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "phizdets/phizdets-idea/src/vgrechka/phizdetsidea/phizdets/debugger/pydev/RemoteDebugger.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "14137"
},
{
"name": "AutoHotkey",
"bytes": "2929"
},
{
"name": "Batchfile",
"bytes": "51982"
},
{
"name": "C#",
"bytes": "1805"
},
{
"name": "CSS",
"bytes": "85999"
},
{
"name": "F#",
"bytes": "8016"
},
{
"name": "HTML",
"bytes": "46668"
},
{
"name": "Java",
"bytes": "32832511"
},
{
"name": "JavaScript",
"bytes": "3518439"
},
{
"name": "Kotlin",
"bytes": "7227789"
},
{
"name": "Lex",
"bytes": "15020"
},
{
"name": "PHP",
"bytes": "7642921"
},
{
"name": "PLSQL",
"bytes": "5226"
},
{
"name": "Python",
"bytes": "1111"
},
{
"name": "Racket",
"bytes": "6512"
},
{
"name": "Scala",
"bytes": "40445"
},
{
"name": "Shell",
"bytes": "28714"
},
{
"name": "TypeScript",
"bytes": "2368260"
},
{
"name": "Vim script",
"bytes": "703"
}
],
"symlink_target": ""
} |
from .SipAddress import SipAddress
from .SipRoute import SipRoute
from .UaStateGeneric import UaStateGeneric
from .CCEvents import CCEventRing, CCEventConnect, CCEventFail, CCEventRedirect, CCEventDisconnect
class UacStateRinging(UaStateGeneric):
sname = 'Ringing(UAC)'
triedauth = False
def recvResponse(self, resp):
body = resp.getBody()
code, reason = resp.getSCode()
scode = (code, reason, body)
if code < 200:
if self.ua.p1xx_ts == None:
self.ua.p1xx_ts = resp.rtime
self.ua.last_scode = code
event = CCEventRing(scode, rtime = resp.rtime, origin = self.ua.origin)
for ring_cb in self.ua.ring_cbs:
ring_cb(self.ua, resp.rtime, self.ua.origin, code)
if body != None:
if self.ua.on_remote_sdp_change != None:
self.ua.on_remote_sdp_change(body, lambda x: self.ua.delayed_remote_sdp_update(event, x))
return None
else:
self.ua.rSDP = body.getCopy()
else:
self.ua.rSDP = None
self.ua.equeue.append(event)
return None
if self.ua.expire_timer != None:
self.ua.expire_timer.cancel()
self.ua.expire_timer = None
if code >= 200 and code < 300:
if resp.countHFs('contact') > 0:
self.ua.rTarget = resp.getHFBody('contact').getUrl().getCopy()
self.ua.routes = [x.getCopy() for x in resp.getHFBodys('record-route')]
self.ua.routes.reverse()
if len(self.ua.routes) > 0:
if not self.ua.routes[0].getUrl().lr:
self.ua.routes.append(SipRoute(address = SipAddress(url = self.ua.rTarget.getCopy())))
self.ua.rTarget = self.ua.routes.pop(0).getUrl()
self.ua.rAddr = self.ua.rTarget.getAddr()
else:
self.ua.rAddr = self.ua.routes[0].getAddr()
else:
self.ua.rAddr = self.ua.rTarget.getAddr()
self.ua.rUri.setTag(resp.getHFBody('to').getTag())
event = CCEventConnect(scode, rtime = resp.rtime, origin = self.ua.origin)
self.ua.startCreditTimer(resp.rtime)
if body != None:
if self.ua.on_remote_sdp_change != None:
self.ua.on_remote_sdp_change(body, lambda x: self.ua.delayed_remote_sdp_update(event, x))
self.ua.connect_ts = resp.rtime
return (UaStateConnected, self.ua.conn_cbs, resp.rtime, self.ua.origin)
else:
self.ua.rSDP = body.getCopy()
else:
self.ua.rSDP = None
self.ua.equeue.append(event)
self.ua.connect_ts = resp.rtime
return (UaStateConnected, self.ua.conn_cbs, resp.rtime, self.ua.origin)
if code in (301, 302) and resp.countHFs('contact') > 0:
scode = (code, reason, body, resp.getHFBody('contact').getUrl().getCopy())
self.ua.equeue.append(CCEventRedirect(scode, rtime = resp.rtime, origin = self.ua.origin))
else:
event = CCEventFail(scode, rtime = resp.rtime, origin = self.ua.origin)
try:
event.reason = resp.getHFBody('reason')
except:
pass
self.ua.equeue.append(event)
self.ua.disconnect_ts = resp.rtime
return (UaStateFailed, self.ua.fail_cbs, resp.rtime, self.ua.origin, code)
def recvEvent(self, event):
if isinstance(event, CCEventFail) or isinstance(event, CCEventRedirect) or isinstance(event, CCEventDisconnect):
self.ua.global_config['_sip_tm'].cancelTransaction(self.ua.tr, reason = event.reason)
if self.ua.expire_timer != None:
self.ua.expire_timer.cancel()
self.ua.expire_timer = None
self.ua.disconnect_ts = event.rtime
return (UacStateCancelling, self.ua.disc_cbs, event.rtime, event.origin, self.ua.last_scode)
#print 'wrong event %s in the Ringing state' % event
return None
if 'UaStateFailed' not in globals():
from .UaStateFailed import UaStateFailed
if 'UaStateConnected' not in globals():
from .UaStateConnected import UaStateConnected
if 'UacStateCancelling' not in globals():
from .UacStateCancelling import UacStateCancelling
| {
"content_hash": "a51d787cdf15c3ab7eca8662d753e205",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 120,
"avg_line_length": 48.46739130434783,
"alnum_prop": 0.5826418479479704,
"repo_name": "hgascon/pulsar",
"id": "dd73a722ea7914deedb782cfc4760f5608803366",
"size": "5584",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pulsar/core/sippy/UacStateRinging.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "550357"
},
{
"name": "R",
"bytes": "1007"
},
{
"name": "Shell",
"bytes": "4616"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tlcn</groupId>
<artifactId>TLCN</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>TLCN</name>
<description>Website Quan ly dieu xe</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/jasperreports/jasperreports -->
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.2.0</version>
</dependency>
<dependency>
<groupId>org.passay</groupId>
<artifactId>passay</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.5.0-b01</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.jasperreports/jasperreports-fonts -->
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-fonts</artifactId>
<version>6.0.0</version>
</dependency>
<dependency>
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio</artifactId>
<version>7.13.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>com.heroku.sdk</groupId>
<artifactId>heroku-maven-plugin</artifactId>
<configuration>
<processTypes>
<web>java $JAVA_OPTS -cp target/classes:target/dependency/* Main</web>
</processTypes>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>test</id>
<build>
<plugins>
<plugin>
<groupId>com.heroku.sdk</groupId>
<artifactId>heroku-maven-plugin</artifactId>
<configuration>
<appName>myapp-test</appName>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>prod</id>
<build>
<plugins>
<plugin>
<groupId>com.heroku.sdk</groupId>
<artifactId>heroku-maven-plugin</artifactId>
<configuration>
<appName>myapp-prod</appName>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<packaging>war</packaging>
</project>
| {
"content_hash": "e54dfbf99e40b04dc3b0346129b8009b",
"timestamp": "",
"source": "github",
"line_count": 158,
"max_line_length": 104,
"avg_line_length": 29.044303797468356,
"alnum_prop": 0.6792329483547613,
"repo_name": "akiyamayami/TLCN",
"id": "69fc9a2370a0de6c2378c799655eb911d6b6c5c4",
"size": "4589",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "target/heroku/app/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4994"
},
{
"name": "CSS",
"bytes": "206151"
},
{
"name": "HTML",
"bytes": "425588"
},
{
"name": "Java",
"bytes": "422153"
},
{
"name": "JavaScript",
"bytes": "50835"
},
{
"name": "PHP",
"bytes": "4464"
},
{
"name": "Shell",
"bytes": "6468"
}
],
"symlink_target": ""
} |
musicmaster.js: components/*
cat components/* > musicmaster.js
| {
"content_hash": "8cbf88f00964e58700bb59f7440fb62b",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 34,
"avg_line_length": 32,
"alnum_prop": 0.765625,
"repo_name": "debolk/musicmaster-js",
"id": "3d3854fa48700b534aed111944fd7219b21011a4",
"size": "64",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Makefile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "38964"
},
{
"name": "Makefile",
"bytes": "64"
}
],
"symlink_target": ""
} |
#import <Foundation/NSInputSourceSet.h>
@class NSSelectSet;
@interface NSSelectInputSourceSet : NSInputSourceSet {
NSMutableSet *_outputSources;
NSSelectSet *_outputSet;
}
@end
| {
"content_hash": "e9b530e500b8c333aa789754d8dd1fe1",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 54,
"avg_line_length": 15.75,
"alnum_prop": 0.7619047619047619,
"repo_name": "wenq1/cocotron",
"id": "962dac8505b6617391ea5da7a49e0eba1cc0891b",
"size": "1261",
"binary": false,
"copies": "2",
"ref": "refs/heads/upstream",
"path": "Foundation/NSStream/NSSelectInputSourceSet.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "4525390"
},
{
"name": "Shell",
"bytes": "301"
}
],
"symlink_target": ""
} |
using System.Threading.Tasks;
using Common;
using Core;
namespace AzureRepositories
{
public class AzureQueueReader : IQueueReader
{
private readonly IQueueExt _queueExt;
public AzureQueueReader(IQueueExt queueExt)
{
_queueExt = queueExt;
_queueExt.RegisterTypes(
QueueType.Create("GenerateNewWallet", typeof(TaskToDoGenerateNewWallet)),
QueueType.Create("CashIn", typeof(TaskToDoCashIn)),
QueueType.Create("OrdinaryCashIn", typeof(TaskToDoOrdinaryCashIn)),
QueueType.Create("CashOut", typeof(TaskToDoCashOut)),
QueueType.Create("Uncolor", typeof(TaskToDoUncolor)),
QueueType.Create("CashOutSeparateSignatures", typeof(TaskToDoCashOutSeparateSignatures)),
QueueType.Create("OrdinaryCashOut", typeof(TaskToDoOrdinaryCashOut)),
QueueType.Create("GetCurrentBalance", typeof(TaskToDoGetCurrentBalance)),
QueueType.Create("Swap", typeof(TaskToDoSwap)),
QueueType.Create("GetBalance", typeof(TaskToDoGetBalance)),
QueueType.Create("DepositWithdraw", typeof(TaskToDoDepositWithdraw)),
QueueType.Create("Exchange", typeof(TaskToDoSendAsset)),
QueueType.Create("GenerateFeeOutputs", typeof(TaskToDoGenerateFeeOutputs)),
QueueType.Create("GenerateIssuerOutputs", typeof(TaskToDoGenerateIssuerOutputs)),
QueueType.Create("Transfer", typeof(TaskToDoTransfer)),
QueueType.Create("TransferAllAssetsToAddress", typeof(TaskToDoTransferAllAssetsToAddress)),
QueueType.Create("GetIssuersOutputStatus", typeof(TaskToDoGetIssuersOutputStatus)),
QueueType.Create("GetFeeOutputsStatus", typeof(TaskToDoGetFeeOutputsStatus)),
QueueType.Create("GenerateRefundingTransaction", typeof(TaskToDoGenerateRefundingTransaction)),
QueueType.Create("GetInputWalletAddresses", typeof(TaskToDoGetInputWalletAddresses)),
QueueType.Create("UpdateAssets", typeof(TaskToDoUpdateAssets)),
QueueType.Create("GetExpiredUnclaimedRefundingTransactions", typeof(TaskToDoGetExpiredUnclaimedRefundingTransactions))
);
}
public async Task<TransactionToDoBase> GetTaskToDo()
{
// ToDo - improve - make sure that we shold Delete it only after we put it to our Local Storage. For first stage is good
var message = await _queueExt.GetMessageAsync();
return message as TransactionToDoBase;
}
}
}
| {
"content_hash": "053dd2883e89b43b9e4c8cf183b90f7e",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 134,
"avg_line_length": 53.97959183673469,
"alnum_prop": 0.675992438563327,
"repo_name": "LykkeCity/WalletBackEnd",
"id": "613d9793bfca14108225b1f9dcc07965790433a6",
"size": "2647",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AzureRepositories/AzureQueueReader.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "86"
},
{
"name": "C#",
"bytes": "1154148"
},
{
"name": "JavaScript",
"bytes": "213"
},
{
"name": "PowerShell",
"bytes": "183"
}
],
"symlink_target": ""
} |
<?php echo $this->load->view('content/admin/field_types_subnav'); ?>
<div class="box">
<div class="heading">
<h1><img alt="" src="<?php echo theme_url('assets/images/layout.png'); ?>">Content Type Edit
- <?php echo $Content_type->title; ?> (<?php echo $Content_type->short_name; ?>)</h1>
<div class="buttons">
<a class="button" href="#" id="save"><span>Save</span></a>
<a class="button" href="#" id="save_exit"><span>Save & Exit</span></a>
<a class="button" href="<?php echo site_url(ADMIN_PATH . '/content/types'); ?>"><span>Cancel</span></a>
</div>
</div>
<div class="content">
<?php echo form_open('', 'id="layout_edit"'); ?>
<div>
<table class="list">
<thead>
<tr>
<th width="220">Fields</th>
<th>Short Tag (click on tags below to copy)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Entry Title</td>
<td>
<div style="position:relative;"><a class="copy_text" href="javascript:void(0);">{{ title }}</a>
or
<a class="copy_text" href="javascript:void(0);">{{ title_editable }}</a></div>
</td>
</tr>
<?php foreach ($Fields as $Field): ?>
<tr>
<td><?php echo $Field->label; ?></td>
<td>
<div style="position:relative;"><a class="copy_text"
href="javascript:void(0);">{{ <?php echo $Field->short_tag; ?>
}}</a></div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div id="tabs">
<ul class="htabs">
<li><a href="#html-tab">HTML</a></li>
<li><a href="#page-head-tab">Page <head></a></li>
<li><a href="#revisions-tab">Revisions</a></li>
<li><a href="#settings-tab">Settings</a></li>
</ul>
<div id="html-tab">
<?php echo form_textarea(array('name' => 'layout', 'id' => 'layout', 'value' => set_value('layout', !empty($Content_type->layout) ? $Content_type->layout : ''))); ?>
</div>
<div id="page-head-tab">
<p class="info">Include custom JavaScript, CSS, and/or meta information in the <strong>
<head></strong> block of this content type's pages.</p>
<?php echo form_textarea(array('name' => 'page_head', 'id' => 'page_head', 'value' => set_value('page_head', !empty($Content_type->page_head) ? $Content_type->page_head : ''))); ?>
</div>
<div id="revisions-tab">
<?php $Revisions = $Content_type->get_revisions();
$r = $Revisions->result_count(); ?>
<table class="list">
<thead>
<tr>
<th>Revision</th>
<th>Author</th>
<th>Date</th>
<th class="right">Action</th>
</tr>
</thead>
<tbody>
<?php if ($Revisions->exists()): ?>
<?php foreach ($Revisions as $Revision): ?>
<tr>
<td>Revision <?php echo $r; ?></td>
<td><?php echo $Revision->author_name; ?></td>
<td><?php echo date('m/d/Y h:i a', strtotime($Revision->revision_date)); ?></td>
<td class="right">
<?php if (($revision_id == '' && $r == $Revisions->result_count())
|| $Revision->id == $revision_id): ?>
<strong>Currently Loaded</strong>
<?php else: ?>
[ <a
href="<?php echo site_url(ADMIN_PATH . '/content/types/edit/' . $Revision->resource_id . '/' . $Revision->id); ?> ">Load
Revision</a> ]
</td>
<?php endif; ?>
</tr>
<?php $r--; ?>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td class="center" colspan="4">No revisions have been saved.</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
<div id="settings-tab">
<div class="form">
<div>
<label for="title"><span class="required">*</span> Title:</label>
<?php echo form_input(array('name' => 'title', 'id' => 'title', 'value' => set_value('title', !empty($Content_type->title) ? $Content_type->title : ''))); ?>
</div>
<div>
<label for="short_name"><span class="required">*</span> Short Name:</label>
<?php echo form_input(array('name' => 'short_name', 'id' => 'short_name', 'value' => set_value('short_name', !empty($Content_type->short_name) ? $Content_type->short_name : ''))); ?>
</div>
<div class="field_spacing">
<label for="theme_layout"><span class="required">*</span> Theme Layout:</label>
<?php echo form_dropdown('theme_layout', $theme_layouts, set_value('theme_layout', !empty($Content_type->theme_layout) ? $Content_type->theme_layout : '')); ?>
</div>
<div>
<?php echo form_label('Enable Dynamic Routing:', 'enable_dynamic_routing'); ?>
<?php echo form_checkbox(array('name' => 'enable_dynamic_routing', 'id' => 'enable_dynamic_routing', 'value' => '1', 'checked' => set_checkbox('enable_dynamic_routing', '1', !empty($Content_type->dynamic_route) ? TRUE : FALSE))); ?>
</div>
<div style="display: none;" id="dynamic_route_div">
<label for="dynamic_route"><span class="required">*</span> Dynamic Route:<span class="help">Path and identifieer of the content type. When rendered, any additional url segments appended are considered parameters.</span></label>
<?php echo site_url(); ?><?php echo form_input(array('name' => 'dynamic_route', 'id' => 'dynamic_route', 'value' => set_value('dynamic_route', !empty($Content_type->dynamic_route) ? $Content_type->dynamic_route : ''))); ?>
</div>
<div>
<?php echo form_label('<span class="required">*</span> Enable Versioning:', 'enable_versioning'); ?>
<span>
<label><?php echo form_radio(array('name' => 'enable_versioning', 'value' => '1', 'checked' => set_radio('enable_versioning', '1', !empty($Content_type->enable_versioning) ? TRUE : FALSE))); ?>
Yes</label>
<label><?php echo form_radio(array('name' => 'enable_versioning', 'value' => '0', 'checked' => set_radio('enable_versioning', '0', empty($Content_type->enable_versioning) ? TRUE : FALSE))); ?>
No</label>
</span>
</div>
<div style="display: none;" id="max_revisions_div">
<?php echo form_label('<span class="required">*</span> Max Revisions:<span class="help">The maximum number of revisions to keep for each entry.</span>', 'max_revisions'); ?>
<?php echo form_input(array('name' => 'max_revisions', 'id' => 'max_revisions', 'value' => set_value('max_revisions', !empty($Content_type->max_revisions) ? $Content_type->max_revisions : '5'), 'style' => 'width: 50px;')); ?>
<span class="ex">25 Max</span>
</div>
<div>
<?php echo form_label('Number of Entries Allowed:<span class="help">Number of entries allowed to be created with this content type</span>', 'entries_allowed'); ?>
<?php echo form_input(array('name' => 'entries_allowed', 'id' => 'entries_allowed', 'value' => set_value('entries_allowed', isset($Content_type->entries_allowed) ? $Content_type->entries_allowed : ''), 'class' => 'short')); ?>
<span class="ex">Leave blank for unlimited</span>
</div>
<div>
<?php echo form_label('Category Group:<span class="help">Assign a set of categories to this content type so that authors can specify categories for entries.</span>', 'category_group_id'); ?>
<?php echo form_dropdown('category_group_id', $category_groups, set_value('category_gorup_id', !empty($Content_type->category_group_id) ? $Content_type->category_group_id : ''), 'id="category_group_id"'); ?>
</div>
<div>
<?php echo form_label('<span class="required">*</span> Restrict Admin Access:<span class="help">Only make this content type\'s entries visible to specified groups.</span>', 'restrict_admin_access'); ?>
<div class="multi_fields">
<span>
<label><?php echo form_radio(array('name' => 'restrict_admin_access', 'value' => '1', 'checked' => set_radio('restrict_admin_access', '1', !empty($Content_type->restrict_admin_access) ? TRUE : FALSE))); ?>
Yes</label>
<label><?php echo form_radio(array('name' => 'restrict_admin_access', 'value' => '0', 'checked' => set_radio('restrict_admin_access', '0', empty($Content_type->restrict_admin_access) ? TRUE : FALSE))); ?>
No</label>
</span>
<div id="admin_access_field">
<div class="fields_wrapper">
<div class="scrollbox">
<?php $i = 0; ?>
<?php foreach ($Admin_groups as $Group): ?>
<div class="<?php echo ($i % 2 == 0) ? 'even' : 'odd' ?>">
<label>
<input type="checkbox" value="<?php echo $Group->id; ?>"
name="selected_admin_groups[]" <?php echo set_checkbox('selected_admin_groups[]', $Group->id, in_array($Group->id, $current_admin_groups) ? TRUE : FALSE); ?>>
<?php echo $Group->name; ?>
</label>
</div>
<?php $i++; ?>
<?php endforeach; ?>
</div>
<a onclick="$(this).parent().find(':checkbox').attr('checked', true);">Select
All</a>
/
<a onclick="$(this).parent().find(':checkbox').attr('checked', false);">Unselect
All</a>
</div>
</div>
</div>
</div>
<div>
<?php echo form_label('<span class="required">*</span> Access:<span class="help">Make this content type and its entries accessible to:<br /><br />NOTE: Permission checks are only applied when accessing pages and dynamic routes directly via URL.</span>', 'access'); ?>
<div class="multi_fields">
<span>
<label><?php echo form_radio(array('name' => 'access', 'value' => '0', 'checked' => set_radio('access', '0', empty($Content_type->access) ? TRUE : FALSE))); ?>
Everyone</label><br/>
<label><?php echo form_radio(array('name' => 'access', 'value' => '1', 'checked' => set_radio('access', '1', ($Content_type->access == 1) ? TRUE : FALSE))); ?>
Any Logged In User</label><br/>
<label><?php echo form_radio(array('name' => 'access', 'value' => '2', 'checked' => set_radio('access', '2', ($Content_type->access == 2) ? TRUE : FALSE))); ?>
Specified Groups</label>
</span>
<div id="access_field">
<div class="fields_wrapper">
<div class="scrollbox">
<?php $i = 0; ?>
<?php foreach ($Groups as $Group): ?>
<div class="<?php echo ($i % 2 == 0) ? 'even' : 'odd' ?>">
<label>
<input type="checkbox" value="<?php echo $Group->id; ?>"
name="restrict_to[]" <?php echo set_checkbox('restrict_to[]', $Group->id, in_array($Group->id, $restrict_to) ? TRUE : FALSE); ?>>
<?php echo $Group->name; ?>
</label>
</div>
<?php $i++; ?>
<?php endforeach; ?>
</div>
<a onclick="$(this).parent().find(':checkbox').attr('checked', true);">Select
All</a>
/
<a onclick="$(this).parent().find(':checkbox').attr('checked', false);">Unselect
All</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<?php echo form_close(); ?>
</div>
</div>
<?php js_start(); ?>
<script type="text/javascript">
$(document).ready(function () {
var editor = CodeMirror.fromTextArea(document.getElementById("layout"), {
lineNumbers: true,
matchBrackets: true,
mode: "application/x-httpd-php",
indentUnit: 4,
indentWithTabs: true,
enterMode: "keep",
tabMode: "shift"
});
var editor = CodeMirror.fromTextArea(document.getElementById("page_head"), {
lineNumbers: true,
matchBrackets: true,
mode: "application/x-httpd-php",
indentUnit: 4,
indentWithTabs: true,
enterMode: "keep",
tabMode: "shift"
});
$("#tabs").tabs();
// Save Content
$("#save, #save_exit").click(function () {
if ($('#category_group_id').val() != '<?php echo $Content_type->category_group_id; ?>') {
if (!confirm('Changing category groups will delete current category entry relations of this content type.\n\n Are you sure you want to continue?')) {
return false;
}
}
if ($(this).attr('id') == 'save_exit') {
$('<input>').attr({
type: 'hidden',
name: 'save_exit',
value: '1'
}).appendTo('#layout_edit');
$('#layout_edit').submit();
}
else {
$('#layout_edit').submit();
}
});
$('a.copy_text').zclip({
path: '<?php echo theme_url('assets/js/zclip/ZeroClipboard.swf'); ?>',
copy: function () {
return $(this).text();
},
afterCopy: function () {
}
});
// Hide / Show Admin Acess
$('input[name="restrict_admin_access"]').change(function (e) {
if ($('input[name="restrict_admin_access"]:checked').val() == 1) {
$('#admin_access_field').show();
}
else {
$('#admin_access_field').hide();
}
});
$('input[name="restrict_admin_access"]').trigger('change');
// Hide / Show Acess
$('input[name="access"]').change(function (e) {
if ($('input[name="access"]:checked').val() == 2) {
$('#access_field').show();
}
else {
$('#access_field').hide();
}
});
$('input[name="access"]').trigger('change');
// Hide / Show Max Revisions
$('input[name="enable_versioning"]').change(function (e) {
if ($('input[name="enable_versioning"]:checked').val() == 1) {
$('#max_revisions_div').show();
}
else {
$('#max_revisions_div').hide();
}
});
$('input[name="enable_versioning"]').trigger('change');
// Hide / Show Dynamic Routing
$('#enable_dynamic_routing').change(function (e) {
if ($('#enable_dynamic_routing').is(':checked')) {
$('#dynamic_route_div').show();
}
else {
$('#dynamic_route_div').hide();
}
});
$('#enable_dynamic_routing').trigger('change');
});
</script>
<?php js_end(); ?>
| {
"content_hash": "11c920ea8e430b421d9200d943344be3",
"timestamp": "",
"source": "github",
"line_count": 328,
"max_line_length": 295,
"avg_line_length": 58.58536585365854,
"alnum_prop": 0.3982098251457119,
"repo_name": "chintan21191/vlb",
"id": "b4750fbe399384d2c7a2a474f98db69b8a5ab66e",
"size": "19216",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/modules/content/views/admin/types/edit.php",
"mode": "33261",
"license": "mit",
"language": [],
"symlink_target": ""
} |
Adventure for fun and profit
---
Features:
* traversing the dungeon
* fighting with monsters
* fleeing from battle
* grabbing new items
* save/load game
* deterministic battle system with A/D/H
* permadeath
---
Fun is in creating something to play with.
Profit is in learning.
| {
"content_hash": "434ed0ea64de22d9693ec7f713ca9dc4",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 42,
"avg_line_length": 18.6,
"alnum_prop": 0.7562724014336918,
"repo_name": "tr00per/adventure",
"id": "159b81d78e7590ba71d7e670e2c48da741d10176",
"size": "279",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Haskell",
"bytes": "16872"
}
],
"symlink_target": ""
} |
Mutant::Meta::Example.add do
source 'if condition; true; else false; end'
singleton_mutations
# mutation of condition
mutation 'if !condition; true; else false; end'
mutation 'if nil; true; else false; end'
mutation 'if true; true; else false; end'
mutation 'if false; true; else false; end'
# Deleted else branch
mutation 'if condition; true end'
# Promote if branch
mutation 'true'
# Promote else branch
mutation 'false'
# Deleted if branch resulting in unless rendering
mutation 'unless condition; false; end'
# Deleted if branch with promoting else branch to if branch
mutation 'if condition; false end'
# mutation of if body
mutation 'if condition; false; else false; end'
mutation 'if condition; nil; else false; end'
# mutation of else body
mutation 'if condition; true; else true; end'
mutation 'if condition; true; else nil; end'
end
Mutant::Meta::Example.add do
source 'if condition; true; end'
singleton_mutations
mutation 'if !condition; true; end'
mutation 'if condition; false; end'
mutation 'if condition; nil; end'
mutation 'if true; true; end'
mutation 'if false; true; end'
mutation 'if nil; true; end'
mutation 'true'
end
Mutant::Meta::Example.add do
source 'unless condition; true; end'
singleton_mutations
mutation 'unless !condition; true; end'
mutation 'unless nil; true; end'
mutation 'unless true; true; end'
mutation 'unless false; true; end'
mutation 'unless condition; false; end'
mutation 'unless condition; nil; end'
mutation 'if condition; true; end'
mutation 'true'
end
| {
"content_hash": "352a9a2412371c4347237d20365dcb43",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 61,
"avg_line_length": 27.57377049180328,
"alnum_prop": 0.6730083234244947,
"repo_name": "nepalez/mutant",
"id": "610c8ccb39a67dd577027776771ddc668e0ce6ba",
"size": "1682",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "meta/if.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groff",
"bytes": "466"
},
{
"name": "Ruby",
"bytes": "405923"
}
],
"symlink_target": ""
} |
<?php
/*
* GENERATED CODE WARNING
* This file was automatically generated - do not edit!
*/
namespace Google\Cloud\AppEngine\Tests\Unit\V1;
use Google\ApiCore\ApiException;
use Google\ApiCore\CredentialsWrapper;
use Google\ApiCore\Testing\GeneratedTest;
use Google\ApiCore\Testing\MockTransport;
use Google\Cloud\AppEngine\V1\BatchUpdateIngressRulesResponse;
use Google\Cloud\AppEngine\V1\FirewallClient;
use Google\Cloud\AppEngine\V1\FirewallRule;
use Google\Cloud\AppEngine\V1\ListIngressRulesResponse;
use Google\Protobuf\GPBEmpty;
use Google\Rpc\Code;
use stdClass;
/**
* @group appengine
*
* @group gapic
*/
class FirewallClientTest extends GeneratedTest
{
/**
* @return TransportInterface
*/
private function createTransport($deserialize = null)
{
return new MockTransport($deserialize);
}
/**
* @return CredentialsWrapper
*/
private function createCredentials()
{
return $this->getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock();
}
/**
* @return FirewallClient
*/
private function createClient(array $options = [])
{
$options += [
'credentials' => $this->createCredentials(),
];
return new FirewallClient($options);
}
/**
* @test
*/
public function batchUpdateIngressRulesTest()
{
$transport = $this->createTransport();
$gapicClient = $this->createClient([
'transport' => $transport,
]);
$this->assertTrue($transport->isExhausted());
// Mock response
$expectedResponse = new BatchUpdateIngressRulesResponse();
$transport->addResponse($expectedResponse);
$response = $gapicClient->batchUpdateIngressRules();
$this->assertEquals($expectedResponse, $response);
$actualRequests = $transport->popReceivedCalls();
$this->assertSame(1, count($actualRequests));
$actualFuncCall = $actualRequests[0]->getFuncCall();
$actualRequestObject = $actualRequests[0]->getRequestObject();
$this->assertSame('/google.appengine.v1.Firewall/BatchUpdateIngressRules', $actualFuncCall);
$this->assertTrue($transport->isExhausted());
}
/**
* @test
*/
public function batchUpdateIngressRulesExceptionTest()
{
$transport = $this->createTransport();
$gapicClient = $this->createClient([
'transport' => $transport,
]);
$this->assertTrue($transport->isExhausted());
$status = new stdClass();
$status->code = Code::DATA_LOSS;
$status->details = 'internal error';
$expectedExceptionMessage = json_encode([
'message' => 'internal error',
'code' => Code::DATA_LOSS,
'status' => 'DATA_LOSS',
'details' => [],
], JSON_PRETTY_PRINT);
$transport->addResponse(null, $status);
try {
$gapicClient->batchUpdateIngressRules();
// If the $gapicClient method call did not throw, fail the test
$this->fail('Expected an ApiException, but no exception was thrown.');
} catch (ApiException $ex) {
$this->assertEquals($status->code, $ex->getCode());
$this->assertEquals($expectedExceptionMessage, $ex->getMessage());
}
// Call popReceivedCalls to ensure the stub is exhausted
$transport->popReceivedCalls();
$this->assertTrue($transport->isExhausted());
}
/**
* @test
*/
public function createIngressRuleTest()
{
$transport = $this->createTransport();
$gapicClient = $this->createClient([
'transport' => $transport,
]);
$this->assertTrue($transport->isExhausted());
// Mock response
$priority = 1165461084;
$sourceRange = 'sourceRange1669022745';
$description = 'description-1724546052';
$expectedResponse = new FirewallRule();
$expectedResponse->setPriority($priority);
$expectedResponse->setSourceRange($sourceRange);
$expectedResponse->setDescription($description);
$transport->addResponse($expectedResponse);
$response = $gapicClient->createIngressRule();
$this->assertEquals($expectedResponse, $response);
$actualRequests = $transport->popReceivedCalls();
$this->assertSame(1, count($actualRequests));
$actualFuncCall = $actualRequests[0]->getFuncCall();
$actualRequestObject = $actualRequests[0]->getRequestObject();
$this->assertSame('/google.appengine.v1.Firewall/CreateIngressRule', $actualFuncCall);
$this->assertTrue($transport->isExhausted());
}
/**
* @test
*/
public function createIngressRuleExceptionTest()
{
$transport = $this->createTransport();
$gapicClient = $this->createClient([
'transport' => $transport,
]);
$this->assertTrue($transport->isExhausted());
$status = new stdClass();
$status->code = Code::DATA_LOSS;
$status->details = 'internal error';
$expectedExceptionMessage = json_encode([
'message' => 'internal error',
'code' => Code::DATA_LOSS,
'status' => 'DATA_LOSS',
'details' => [],
], JSON_PRETTY_PRINT);
$transport->addResponse(null, $status);
try {
$gapicClient->createIngressRule();
// If the $gapicClient method call did not throw, fail the test
$this->fail('Expected an ApiException, but no exception was thrown.');
} catch (ApiException $ex) {
$this->assertEquals($status->code, $ex->getCode());
$this->assertEquals($expectedExceptionMessage, $ex->getMessage());
}
// Call popReceivedCalls to ensure the stub is exhausted
$transport->popReceivedCalls();
$this->assertTrue($transport->isExhausted());
}
/**
* @test
*/
public function deleteIngressRuleTest()
{
$transport = $this->createTransport();
$gapicClient = $this->createClient([
'transport' => $transport,
]);
$this->assertTrue($transport->isExhausted());
// Mock response
$expectedResponse = new GPBEmpty();
$transport->addResponse($expectedResponse);
$gapicClient->deleteIngressRule();
$actualRequests = $transport->popReceivedCalls();
$this->assertSame(1, count($actualRequests));
$actualFuncCall = $actualRequests[0]->getFuncCall();
$actualRequestObject = $actualRequests[0]->getRequestObject();
$this->assertSame('/google.appengine.v1.Firewall/DeleteIngressRule', $actualFuncCall);
$this->assertTrue($transport->isExhausted());
}
/**
* @test
*/
public function deleteIngressRuleExceptionTest()
{
$transport = $this->createTransport();
$gapicClient = $this->createClient([
'transport' => $transport,
]);
$this->assertTrue($transport->isExhausted());
$status = new stdClass();
$status->code = Code::DATA_LOSS;
$status->details = 'internal error';
$expectedExceptionMessage = json_encode([
'message' => 'internal error',
'code' => Code::DATA_LOSS,
'status' => 'DATA_LOSS',
'details' => [],
], JSON_PRETTY_PRINT);
$transport->addResponse(null, $status);
try {
$gapicClient->deleteIngressRule();
// If the $gapicClient method call did not throw, fail the test
$this->fail('Expected an ApiException, but no exception was thrown.');
} catch (ApiException $ex) {
$this->assertEquals($status->code, $ex->getCode());
$this->assertEquals($expectedExceptionMessage, $ex->getMessage());
}
// Call popReceivedCalls to ensure the stub is exhausted
$transport->popReceivedCalls();
$this->assertTrue($transport->isExhausted());
}
/**
* @test
*/
public function getIngressRuleTest()
{
$transport = $this->createTransport();
$gapicClient = $this->createClient([
'transport' => $transport,
]);
$this->assertTrue($transport->isExhausted());
// Mock response
$priority = 1165461084;
$sourceRange = 'sourceRange1669022745';
$description = 'description-1724546052';
$expectedResponse = new FirewallRule();
$expectedResponse->setPriority($priority);
$expectedResponse->setSourceRange($sourceRange);
$expectedResponse->setDescription($description);
$transport->addResponse($expectedResponse);
$response = $gapicClient->getIngressRule();
$this->assertEquals($expectedResponse, $response);
$actualRequests = $transport->popReceivedCalls();
$this->assertSame(1, count($actualRequests));
$actualFuncCall = $actualRequests[0]->getFuncCall();
$actualRequestObject = $actualRequests[0]->getRequestObject();
$this->assertSame('/google.appengine.v1.Firewall/GetIngressRule', $actualFuncCall);
$this->assertTrue($transport->isExhausted());
}
/**
* @test
*/
public function getIngressRuleExceptionTest()
{
$transport = $this->createTransport();
$gapicClient = $this->createClient([
'transport' => $transport,
]);
$this->assertTrue($transport->isExhausted());
$status = new stdClass();
$status->code = Code::DATA_LOSS;
$status->details = 'internal error';
$expectedExceptionMessage = json_encode([
'message' => 'internal error',
'code' => Code::DATA_LOSS,
'status' => 'DATA_LOSS',
'details' => [],
], JSON_PRETTY_PRINT);
$transport->addResponse(null, $status);
try {
$gapicClient->getIngressRule();
// If the $gapicClient method call did not throw, fail the test
$this->fail('Expected an ApiException, but no exception was thrown.');
} catch (ApiException $ex) {
$this->assertEquals($status->code, $ex->getCode());
$this->assertEquals($expectedExceptionMessage, $ex->getMessage());
}
// Call popReceivedCalls to ensure the stub is exhausted
$transport->popReceivedCalls();
$this->assertTrue($transport->isExhausted());
}
/**
* @test
*/
public function listIngressRulesTest()
{
$transport = $this->createTransport();
$gapicClient = $this->createClient([
'transport' => $transport,
]);
$this->assertTrue($transport->isExhausted());
// Mock response
$nextPageToken = '';
$ingressRulesElement = new FirewallRule();
$ingressRules = [
$ingressRulesElement,
];
$expectedResponse = new ListIngressRulesResponse();
$expectedResponse->setNextPageToken($nextPageToken);
$expectedResponse->setIngressRules($ingressRules);
$transport->addResponse($expectedResponse);
$response = $gapicClient->listIngressRules();
$this->assertEquals($expectedResponse, $response->getPage()->getResponseObject());
$resources = iterator_to_array($response->iterateAllElements());
$this->assertSame(1, count($resources));
$this->assertEquals($expectedResponse->getIngressRules()[0], $resources[0]);
$actualRequests = $transport->popReceivedCalls();
$this->assertSame(1, count($actualRequests));
$actualFuncCall = $actualRequests[0]->getFuncCall();
$actualRequestObject = $actualRequests[0]->getRequestObject();
$this->assertSame('/google.appengine.v1.Firewall/ListIngressRules', $actualFuncCall);
$this->assertTrue($transport->isExhausted());
}
/**
* @test
*/
public function listIngressRulesExceptionTest()
{
$transport = $this->createTransport();
$gapicClient = $this->createClient([
'transport' => $transport,
]);
$this->assertTrue($transport->isExhausted());
$status = new stdClass();
$status->code = Code::DATA_LOSS;
$status->details = 'internal error';
$expectedExceptionMessage = json_encode([
'message' => 'internal error',
'code' => Code::DATA_LOSS,
'status' => 'DATA_LOSS',
'details' => [],
], JSON_PRETTY_PRINT);
$transport->addResponse(null, $status);
try {
$gapicClient->listIngressRules();
// If the $gapicClient method call did not throw, fail the test
$this->fail('Expected an ApiException, but no exception was thrown.');
} catch (ApiException $ex) {
$this->assertEquals($status->code, $ex->getCode());
$this->assertEquals($expectedExceptionMessage, $ex->getMessage());
}
// Call popReceivedCalls to ensure the stub is exhausted
$transport->popReceivedCalls();
$this->assertTrue($transport->isExhausted());
}
/**
* @test
*/
public function updateIngressRuleTest()
{
$transport = $this->createTransport();
$gapicClient = $this->createClient([
'transport' => $transport,
]);
$this->assertTrue($transport->isExhausted());
// Mock response
$priority = 1165461084;
$sourceRange = 'sourceRange1669022745';
$description = 'description-1724546052';
$expectedResponse = new FirewallRule();
$expectedResponse->setPriority($priority);
$expectedResponse->setSourceRange($sourceRange);
$expectedResponse->setDescription($description);
$transport->addResponse($expectedResponse);
$response = $gapicClient->updateIngressRule();
$this->assertEquals($expectedResponse, $response);
$actualRequests = $transport->popReceivedCalls();
$this->assertSame(1, count($actualRequests));
$actualFuncCall = $actualRequests[0]->getFuncCall();
$actualRequestObject = $actualRequests[0]->getRequestObject();
$this->assertSame('/google.appengine.v1.Firewall/UpdateIngressRule', $actualFuncCall);
$this->assertTrue($transport->isExhausted());
}
/**
* @test
*/
public function updateIngressRuleExceptionTest()
{
$transport = $this->createTransport();
$gapicClient = $this->createClient([
'transport' => $transport,
]);
$this->assertTrue($transport->isExhausted());
$status = new stdClass();
$status->code = Code::DATA_LOSS;
$status->details = 'internal error';
$expectedExceptionMessage = json_encode([
'message' => 'internal error',
'code' => Code::DATA_LOSS,
'status' => 'DATA_LOSS',
'details' => [],
], JSON_PRETTY_PRINT);
$transport->addResponse(null, $status);
try {
$gapicClient->updateIngressRule();
// If the $gapicClient method call did not throw, fail the test
$this->fail('Expected an ApiException, but no exception was thrown.');
} catch (ApiException $ex) {
$this->assertEquals($status->code, $ex->getCode());
$this->assertEquals($expectedExceptionMessage, $ex->getMessage());
}
// Call popReceivedCalls to ensure the stub is exhausted
$transport->popReceivedCalls();
$this->assertTrue($transport->isExhausted());
}
}
| {
"content_hash": "2831cf2e5393d22a9c89d1d2a0834447",
"timestamp": "",
"source": "github",
"line_count": 421,
"max_line_length": 105,
"avg_line_length": 37.30878859857482,
"alnum_prop": 0.5997326032978927,
"repo_name": "googleapis/google-cloud-php",
"id": "9c57f9651437737a33f239a36738dd3a63fb8000",
"size": "16301",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "AppEngineAdmin/tests/Unit/V1/FirewallClientTest.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "3333"
},
{
"name": "PHP",
"bytes": "47981731"
},
{
"name": "Python",
"bytes": "413107"
},
{
"name": "Shell",
"bytes": "8171"
}
],
"symlink_target": ""
} |
When using JavaScript in the browser, we have access to global variables like `window` and `document`.
In Node.js, `window` becomes `global` and `document` becomes `process`.
| {
"content_hash": "2bd3516a1effcddb04ec9222631fe709",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 102,
"avg_line_length": 58.666666666666664,
"alnum_prop": 0.7556818181818182,
"repo_name": "charliegerard/til",
"id": "f44a545288b867812af1849e9c459e5b9067cc30",
"size": "207",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "javascript/node/commandLineCommands.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
module Aspose
module Cloud
module Tasks
class Assignments
def initialize(filename)
@filename = filename
raise 'filename not specified.' if filename.empty?
@base_uri = Aspose::Cloud::Common::Product.product_uri + '/tasks/' + @filename
end
=begin
Get all Assignments form Project
=end
def get_assignments(folder_name = '', storage_type = 'Aspose', storage_name = '')
str_uri = "#{@base_uri}/assignments"
str_uri = Aspose::Cloud::Common::Utils.append_storage(str_uri,folder_name,storage_name,storage_type)
signed_str_uri = Aspose::Cloud::Common::Utils.sign(str_uri)
JSON.parse(RestClient.get(signed_str_uri, {:accept=>'application/json'}))['Assignments']['AssignmentItem']
end
=begin
Get a Particular Assignment form Project
@param number assignment_id The id of the assignment.
=end
def get_assignment(assignment_id, folder_name = '', storage_type = 'Aspose', storage_name = '')
raise 'assignment_id not specified.' if assignment_id.nil?
str_uri = "#{@base_uri}/assignments/#{assignment_id}"
str_uri = Aspose::Cloud::Common::Utils.append_storage(str_uri,folder_name,storage_name,storage_type)
signed_str_uri = Aspose::Cloud::Common::Utils.sign(str_uri)
JSON.parse(RestClient.get(signed_str_uri, {:accept=>'application/json'}))['Assignment']
end
=begin
Add Assignment to Project
@param number task_id The unique id of the task to be assigned.
@param number resource_id The unique id of the resource to be assigned.
@param number units The units for the new assignment.
=end
def add_assignment(task_id, resource_id, units, folder_name = '', storage_type = 'Aspose', storage_name = '')
raise 'task_id not specified.' if task_id.nil?
raise 'resource_id not specified.' if resource_id.nil?
raise 'units not specified.' if units.nil?
str_uri = "#{@base_uri}/assignments"
qry = { :taskUid => task_id, :resourceUid => resource_id, :units => units }
str_uri = Aspose::Cloud::Common::Utils.build_uri(str_uri,qry)
str_uri = Aspose::Cloud::Common::Utils.append_storage(str_uri,folder_name,storage_name,storage_type)
signed_str_uri = Aspose::Cloud::Common::Utils.sign(str_uri)
JSON.parse(RestClient.post(signed_str_uri, '', {:accept=>'application/json'}))['AssignmentItem']
end
=begin
Delete an Assignment from a Project
@param number assignment_id The id of the assignment.
=end
def delete_assignment(assignment_id, folder_name = '', storage_type = 'Aspose', storage_name = '')
raise 'assignment_id not specified.' if assignment_id.nil?
str_uri = "#{@base_uri}/assignments/#{assignment_id}"
str_uri = Aspose::Cloud::Common::Utils.append_storage(str_uri,folder_name,storage_name,storage_type)
signed_str_uri = Aspose::Cloud::Common::Utils.sign(str_uri)
json = JSON.parse(RestClient.delete(signed_str_uri, {:accept=>'application/json'}))
json['Code'] == 200 ? true : false
end
end
end
end
end | {
"content_hash": "1aa74a9d4efbf21461699cc5d6784f14",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 117,
"avg_line_length": 44.66197183098591,
"alnum_prop": 0.6483759066540523,
"repo_name": "asposeforcloud/Aspose_Cloud_SDK_For_Ruby",
"id": "c2954bb5f2597301c74cbd0ca5b20eb957178335",
"size": "3171",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/tasks/assignments.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "480802"
}
],
"symlink_target": ""
} |
Ascent is a mobile first designed webapp that allows kids to track previously visited recreational parks and facilities and collect points through various channels such as visiting parks, scanning QR codes located at different facilities and so on.
##Install
These instructions assume that your environment has ruby installed (for the Compass gem).
1.) Install Node Version Manager
Visit https://github.com/creationix/nvm site for the latest instructions.
``` bash
curl https://raw.githubusercontent.com/creationix/nvm/v0.24.1/install.sh | bash
```
2.) Install node.
``` bash
nvm install stable
```
3.) Install the required node modules.
``` bash
npm install nodejs -g
npm install bower -g
npm install compass -g
npm install grunt -g
npm install grunt-cli -g
```
4.) Install compass ruby gem (Depending on how your ruby is installed, this may require root).
``` bash
gem install compass
```
5.) Clone the git repos
```bash
git clone https://github.com/myAmericaDevSummit2015/ascent
```
6.) Run these commands in ascent/www directory
``` bash
npm install
bower install
```
7.) Edit the /app/scripts/app.js file to include your RIDB Api Key, edit /app/scripts/controllers/map.js to include mapbox access_token, edit /app/scripts/controllers/park.js to include flicker access_token
8.) Start the grunt server. By default, the site will be hosted on http://0.0.0.0:9000/
``` bash
grunt serve
```
8.) Edit the /api/mongoid.yml file to include your database connection string (host,port,username/password)
10.) Run these commands in ascent/api directory to install ruby gems
``` bash
bundle install
```
11.) Run below command to start the api server
``` bash
rackup
```
## Helpful Tips
1.) If you are having problems running bower install, check to make sure the git protocol is not blocked by your firewall. To configure the default to use https instead of the git protocol, use the following commands:
To set https as default:
``` bash
git config --global url."https://".insteadOf git://
```
To undo global configs:
``` bash
git config --global --unset
```
2.) If you are experiencing errors, the following commands are helpful to resetting your environment.
* Delete the node modules directory in your project root
* Clean your npm cache with → sudo npm cache clean
* Reinstall with super user privileges → sudo npm install
##License
More information can be found on the license.md documentation
| {
"content_hash": "df5a7bd7d0806574eda3fac77b6fb6a1",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 249,
"avg_line_length": 27.82758620689655,
"alnum_prop": 0.7538207352333747,
"repo_name": "myAmericaDevSummit2015/Ascent",
"id": "fb38277869a2afbf8b531772a891a67ca517f21d",
"size": "2435",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "24139"
},
{
"name": "CSS",
"bytes": "46803"
},
{
"name": "HTML",
"bytes": "20247"
},
{
"name": "JavaScript",
"bytes": "1734645"
},
{
"name": "Ruby",
"bytes": "10316"
},
{
"name": "Shell",
"bytes": "3868"
}
],
"symlink_target": ""
} |
/*
* Antonin Bas (antonin@barefootnetworks.com)
*
*/
#include "error_codes.h"
#include "table_common.h"
#include "utils.h"
#include "PI/frontends/generic/pi.h"
#include "PI/pi.h"
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char table_add_hs[] =
"Add entry to a match table: "
"table_add <table name> <match fields> [priority] => "
"[<action name> <action parameters> | <indirect handle>]";
pi_cli_status_t do_table_add(char *subcmd) {
const char *args[1];
size_t num_args = sizeof(args) / sizeof(char *);
if (parse_fixed_args(subcmd, args, num_args) < num_args)
return PI_CLI_STATUS_TOO_FEW_ARGS;
const char *t_name = args[0];
pi_p4_id_t t_id = pi_p4info_table_id_from_name(p4info_curr, t_name);
if (t_id == PI_INVALID_ID) return PI_CLI_STATUS_INVALID_TABLE_NAME;
pi_cli_status_t status;
pi_match_key_t *mk;
pi_match_key_allocate(p4info_curr, t_id, &mk);
status = read_match_key_with_priority(NULL, t_id, mk, "=>");
if (status != PI_CLI_STATUS_SUCCESS) {
pi_match_key_destroy(mk);
return status;
}
pi_p4_id_t t_imp = pi_p4info_table_get_implementation(p4info_curr, t_id);
pi_table_entry_t t_entry;
if (t_imp == PI_INVALID_ID) {
status = get_entry_direct(&t_entry);
} else {
status = get_entry_indirect(&t_entry);
}
if (status != PI_CLI_STATUS_SUCCESS) {
pi_match_key_destroy(mk);
return status;
}
pi_entry_properties_t entry_properties;
pi_entry_properties_clear(&entry_properties);
t_entry.entry_properties = &entry_properties;
// direct resources
pi_direct_res_config_t direct_res_config;
direct_res_config.configs =
retrieve_direct_resource_configs(&direct_res_config.num_configs);
t_entry.direct_res_config = &direct_res_config;
pi_entry_handle_t handle = 0;
pi_status_t rc;
rc = pi_table_entry_add(sess, dev_tgt, t_id, mk, &t_entry, 0, &handle);
if (rc == PI_STATUS_SUCCESS)
printf("Entry was successfully added with handle %" PRIu64 ".\n", handle);
else
printf("Error when trying to add entry.\n");
pi_match_key_destroy(mk);
if (t_imp == PI_INVALID_ID)
cleanup_entry_direct(&t_entry);
else
cleanup_entry_indirect(&t_entry);
reset_direct_resource_configs();
return (rc == PI_STATUS_SUCCESS) ? PI_CLI_STATUS_SUCCESS
: PI_CLI_STATUS_TARGET_ERROR;
};
char *complete_table_add(const char *text, int state) {
return complete_table(text, state);
}
| {
"content_hash": "042d109edb62edf097fca8ce469f0331",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 78,
"avg_line_length": 28.125,
"alnum_prop": 0.6545454545454545,
"repo_name": "p4lang/PI",
"id": "5b4464026a6e6c845b0d38ad22deac64062200b1",
"size": "3084",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "CLI/table_add.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "669958"
},
{
"name": "C++",
"bytes": "1081539"
},
{
"name": "Dockerfile",
"bytes": "1709"
},
{
"name": "M4",
"bytes": "181467"
},
{
"name": "Makefile",
"bytes": "31887"
},
{
"name": "P4",
"bytes": "25371"
},
{
"name": "Python",
"bytes": "77805"
},
{
"name": "Shell",
"bytes": "7854"
},
{
"name": "Starlark",
"bytes": "14660"
}
],
"symlink_target": ""
} |
package timus;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
/**
* Created by sherxon on 12/8/16.
*/
public class Order1510 {
public static void main(String[] args) {
FastReader fastReader= new FastReader();
int n=fastReader.nextInt();
int[] a= new int[n];
for (int i = 0; i < n; i++) {
a[i]=fastReader.nextInt();
}
Arrays.sort(a);
System.out.println(a[n/2]);
}
private static class FastReader {
BufferedReader bf;
StringTokenizer st;
public FastReader() {
bf=new BufferedReader(new InputStreamReader(System.in));
}
String nextLine(){
String st="";
try {
st=bf.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return st;
}
String next(){
while (st==null || !st.hasMoreTokens()){
try {
st= new StringTokenizer(bf.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
}
}
| {
"content_hash": "50f1788cbfa9965d0c544c71dfe7bd81",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 68,
"avg_line_length": 24.403508771929825,
"alnum_prop": 0.4982027318475917,
"repo_name": "sherxon/AlgoDS",
"id": "53fab4b6892b568fe18583b479fb57231a089b66",
"size": "1391",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/timus/Order1510.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "819010"
}
],
"symlink_target": ""
} |
package pl.nn44.battleship.service;
import pl.nn44.battleship.model.Cell;
import pl.nn44.battleship.model.Coord;
import pl.nn44.battleship.model.Grid;
import pl.nn44.battleship.model.Ship;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public class FleetVerifierRules {
private final ShipFinder shipFinder;
public FleetVerifierRules(ShipFinder shipFinder) {
this.shipFinder = shipFinder;
}
public boolean hasAllowedValues(Grid grid) {
int[] cells = grid.getCells();
return Arrays.stream(cells).allMatch(val ->
val == Cell.Type.EMPTY.getCode() || val == Cell.Type.SHIP.getCode()
);
}
public boolean hasProperShipSizes(List<Ship> ships, List<Integer> availShipSizes) {
List<Integer> shipSizes = ships.stream()
.map(Ship::getSize)
.sorted(Comparator.reverseOrder())
.collect(Collectors.toUnmodifiableList());
return availShipSizes.equals(shipSizes);
}
public boolean hasSpaceAroundShips(List<Ship> ships) {
return hasSpaceAroundShipsHelper(ships, shipFinder::neighbours);
}
public boolean hasSpaceAroundShipsPlus(List<Ship> ships) {
return hasSpaceAroundShipsHelper(ships, shipFinder::neighboursPlus);
}
private boolean hasSpaceAroundShipsHelper(List<Ship> ships, Function<Ship, List<Coord>> neighboursSupplier) {
boolean collision = false;
outerLoop:
for (int i = 0; i < ships.size(); i++) {
Ship ship1 = ships.get(i);
List<Coord> neighbours = neighboursSupplier.apply(ship1);
for (int j = i + 1; j < ships.size(); j++) {
Ship ship2 = ships.get(j);
List<Coord> coords2 = ship2.getCoords();
if (!Collections.disjoint(coords2, neighbours)) {
collision = true;
break outerLoop;
}
}
}
return !collision;
}
public boolean allShipsStraight(List<Ship> ships) {
return ships.stream().allMatch(this::isShipStraight);
}
private boolean isShipStraight(Ship ship) {
return isOneRow(ship) || isOneCol(ship);
}
private boolean isOneRow(Ship ship) {
List<Coord> coords = ship.getCoords();
int rightRow = coords.get(0).getRow();
return coords.stream().map(Coord::getRow).allMatch(r -> r == rightRow);
}
private boolean isOneCol(Ship ship) {
List<Coord> coords = ship.getCoords();
int rightCol = coords.get(0).getCol();
return coords.stream().map(Coord::getCol).allMatch(r -> r == rightCol);
}
}
| {
"content_hash": "4dac748da3230e739ad6031c9eef0986",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 111,
"avg_line_length": 29.436781609195403,
"alnum_prop": 0.6884029675907849,
"repo_name": "180254/Battleship44",
"id": "7460379ddd27502c597c237e28ab97594627e810",
"size": "2561",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "battleship-back-end/src/main/java/pl/nn44/battleship/service/FleetVerifierRules.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6122"
},
{
"name": "HTML",
"bytes": "25985"
},
{
"name": "Java",
"bytes": "132031"
},
{
"name": "JavaScript",
"bytes": "8584"
},
{
"name": "Shell",
"bytes": "1630"
},
{
"name": "TypeScript",
"bytes": "91068"
}
],
"symlink_target": ""
} |
package com.demo.floatwindowdemo;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class FloatWindowBigView extends LinearLayout {
/**
* 记录大悬浮窗的宽度
*/
public static int viewWidth;
/**
* 记录大悬浮窗的高度
*/
public static int viewHeight;
public FloatWindowBigView(final Context context) {
super(context);
LayoutInflater.from(context).inflate(R.layout.float_window_big, this);
View view = findViewById(R.id.big_window_layout);
viewWidth = view.getLayoutParams().width;
viewHeight = view.getLayoutParams().height;
Button close = (Button) findViewById(R.id.close);
Button back = (Button) findViewById(R.id.back);
close.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 点击关闭悬浮窗的时候,移除所有悬浮窗,并停止Service
MyWindowManager.removeBigWindow(context);
MyWindowManager.removeSmallWindow(context);
Intent intent = new Intent(getContext(), FloatWindowService.class);
context.stopService(intent);
}
});
back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 点击返回的时候,移除大悬浮窗,创建小悬浮窗
MyWindowManager.removeBigWindow(context);
MyWindowManager.createSmallWindow(context);
}
});
}
}
| {
"content_hash": "204fb1756e304e977d1e1bd82c4c6405",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 72,
"avg_line_length": 27.755102040816325,
"alnum_prop": 0.7441176470588236,
"repo_name": "longwei243/viewlibrary",
"id": "331d9ed5bc807529408fe08b1929a6fd48913fac",
"size": "1482",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "android界面代码/悬浮窗小火箭发射效果/QQFloatWindowDemo/src/com/demo/floatwindowdemo/FloatWindowBigView.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "2935"
},
{
"name": "Java",
"bytes": "3049055"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace Gdbots\Bundle\PbjxBundle\Command;
use Gdbots\Pbj\Message;
use Gdbots\Pbj\Util\NumberUtil;
use Gdbots\Pbj\WellKnown\Microtime;
use Gdbots\Schemas\Pbjx\StreamId;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
final class ExportEventsCommand extends Command
{
use PbjxAwareCommandTrait;
protected static $defaultName = 'pbjx:export-events';
public function __construct(ContainerInterface $container)
{
$this->container = $container;
parent::__construct();
}
protected function configure()
{
$provider = $this->container->getParameter('gdbots_pbjx.event_store.provider');
$this
->setDescription("Pipes events from the EventStore ({$provider}) to STDOUT")
->setHelp(<<<EOF
The <info>%command.name%</info> command will pipe events from the EventStore ({$provider})
for the given StreamId if provided or all events and write the json value of the event on
one line (json newline delimited) to STDOUT.
<info>php %command.full_name% --tenant-id=client1 'stream-id'</info>
EOF
)
->addOption(
'batch-size',
null,
InputOption::VALUE_REQUIRED,
'Number of events to export at a time.',
100
)
->addOption(
'batch-delay',
null,
InputOption::VALUE_REQUIRED,
'Number of milliseconds (1000 = 1 second) to delay between batches.',
1000
)
->addOption(
'since',
null,
InputOption::VALUE_REQUIRED,
'Exports events where occurred_at is greater than this time ' .
'(unix timestamp or 16 digit microtime as int).'
)
->addOption(
'until',
null,
InputOption::VALUE_REQUIRED,
'Exports events where occurred_at is less than this time ' .
'(unix timestamp or 16 digit microtime as int).'
)
->addOption(
'context',
null,
InputOption::VALUE_REQUIRED,
'Context to provide to the EventStore (json).'
)
->addOption(
'tenant-id',
null,
InputOption::VALUE_REQUIRED,
'Tenant Id to use for this operation.'
)
->addArgument(
'stream-id',
InputArgument::OPTIONAL,
'The stream to export messages from. See Gdbots\Schemas\Pbjx\StreamId for details.'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$errOutput = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output;
$output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
$errOutput->setVerbosity(OutputInterface::VERBOSITY_NORMAL);
$batchSize = NumberUtil::bound((int)$input->getOption('batch-size'), 1, 1000);
$batchDelay = NumberUtil::bound((int)$input->getOption('batch-delay'), 100, 600000);
$since = $input->getOption('since');
$until = $input->getOption('until');
$context = $input->getOption('context') ?: '{}';
if (!str_contains($context, '{')) {
$context = base64_decode($context);
}
$context = json_decode($context, true);
$context['tenant_id'] = (string)$input->getOption('tenant-id');
$streamId = $input->getArgument('stream-id') ? StreamId::fromString($input->getArgument('stream-id')) : null;
if (!empty($since)) {
$since = Microtime::fromString(str_pad($since, 16, '0'));
}
if (!empty($until)) {
$until = Microtime::fromString(str_pad($until, 16, '0'));
}
$generator = $streamId
? $this->getPbjx()->getEventStore()->pipeEvents($streamId, $since, $until, $context)
: $this->getPbjx()->getEventStore()->pipeAllEvents($since, $until, $context);
$i = 0;
foreach ($generator as $result) {
++$i;
if ($result instanceof Message) {
$event = $result;
} else {
[$event] = $result;
}
try {
echo json_encode($event) . PHP_EOL;
} catch (\Throwable $e) {
$errOutput->writeln($e->getMessage());
}
if (0 === $i % $batchSize) {
if ($batchDelay > 0) {
usleep($batchDelay * 1000);
}
}
}
return self::SUCCESS;
}
}
| {
"content_hash": "5fb7a0b4436dd30a873b01f6ef2259e2",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 117,
"avg_line_length": 34.97260273972603,
"alnum_prop": 0.554445750097924,
"repo_name": "gdbots/pbjx-bundle-php",
"id": "419c742c757faddd9d19efe3509af59135ca61e2",
"size": "5106",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Command/ExportEventsCommand.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "179098"
}
],
"symlink_target": ""
} |
package com.example.stream.eb.detail;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatTextView;
import android.view.View;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.stream.core.delegates.StreamDelegate;
import com.example.stream.eb.R;
import com.example.stream.eb.R2;
import butterknife.BindView;
/**
* Created by StReaM on 9/11/2017.
*/
public class ProductInfoDelegate extends StreamDelegate {
@BindView(R2.id.tv_product_info_title)
AppCompatTextView mInfo = null;
@BindView(R2.id.tv_product_info_desc)
AppCompatTextView mDesc = null;
@BindView(R2.id.tv_product_info_price)
AppCompatTextView mPrice = null;
private static final String PRODUCT_INFO = "PRODUCT_INFO";
private JSONObject mData = null;
@Override
public Object setLayout() {
return R.layout.delegate_product_info;
}
public static ProductInfoDelegate create(String info) {
final Bundle args = new Bundle();
args.putString(PRODUCT_INFO, info);
ProductInfoDelegate delegate = new ProductInfoDelegate();
delegate.setArguments(args);
return delegate;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
String info = args.getString(PRODUCT_INFO);
mData = JSON.parseObject(info);
}
@Override
public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
String name = mData.getString("name");
String desc = mData.getString("description");
double price = mData.getDouble("price");
mInfo.setText(name);
mDesc.setText(desc);
mPrice.setText(String.valueOf(price));
}
}
| {
"content_hash": "dac38ef7a42eb63ac745006b389c9eaf",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 80,
"avg_line_length": 30.39344262295082,
"alnum_prop": 0.7022653721682848,
"repo_name": "streamj/JX",
"id": "db43b083b9db22b2a222670fe8a500fa6d054fde",
"size": "1854",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "stream-eb/src/main/java/com/example/stream/eb/detail/ProductInfoDelegate.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "3728"
},
{
"name": "Java",
"bytes": "315359"
},
{
"name": "JavaScript",
"bytes": "59268"
}
],
"symlink_target": ""
} |
require "test/unit"
class TC_NilClass_And_Instance < Test::Unit::TestCase
def setup
@x = nil
end
def test_basic
assert_respond_to(@x, :&)
assert_nothing_raised{ @x & "hello" }
assert_equal(false, @x & "hello")
assert_equal(false, @x & @x)
end
def test_edge_cases
assert_equal(false, @x & true)
assert_equal(false, @x & nil)
assert_equal(false, @x & 0)
assert_equal(false, @x & false)
end
end | {
"content_hash": "6409ee921781a2cbebfe5983111859b1",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 53,
"avg_line_length": 22.476190476190474,
"alnum_prop": 0.5741525423728814,
"repo_name": "google-code/android-scripting",
"id": "e84feb303c257c07830024a6f0f9fd3ce6299bdc",
"size": "671",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "jruby/src/test/externals/ruby_test/test/core/NilClass/instance/tc_and.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "145847"
},
{
"name": "Assembly",
"bytes": "310373"
},
{
"name": "Bison",
"bytes": "162176"
},
{
"name": "C",
"bytes": "14282640"
},
{
"name": "C++",
"bytes": "105675"
},
{
"name": "CSS",
"bytes": "24124"
},
{
"name": "Cucumber",
"bytes": "11401"
},
{
"name": "Diff",
"bytes": "13415"
},
{
"name": "Emacs Lisp",
"bytes": "146938"
},
{
"name": "GAP",
"bytes": "129009"
},
{
"name": "Groff",
"bytes": "26385"
},
{
"name": "HTML",
"bytes": "12203390"
},
{
"name": "Inno Setup",
"bytes": "18796"
},
{
"name": "Java",
"bytes": "9869454"
},
{
"name": "JavaScript",
"bytes": "148"
},
{
"name": "Lua",
"bytes": "178639"
},
{
"name": "Makefile",
"bytes": "228172"
},
{
"name": "Objective-C",
"bytes": "1384162"
},
{
"name": "OpenEdge ABL",
"bytes": "125979"
},
{
"name": "Perl",
"bytes": "3610"
},
{
"name": "Prolog",
"bytes": "66"
},
{
"name": "Python",
"bytes": "22184025"
},
{
"name": "R",
"bytes": "697"
},
{
"name": "Ruby",
"bytes": "12237045"
},
{
"name": "Shell",
"bytes": "152111"
},
{
"name": "Tcl",
"bytes": "1262"
},
{
"name": "VimL",
"bytes": "9547"
},
{
"name": "Visual Basic",
"bytes": "481"
},
{
"name": "XSLT",
"bytes": "14806"
}
],
"symlink_target": ""
} |
from django.db import models
from django.contrib.auth.models import User
from django.core.cache import cache
from helper.model import to_dict, get_deep_attr
# Create your models here.
class UserProfile(models.Model):
def __str__(self):
return self.user.username
user = models.OneToOneField(User, related_name="profile")
avatar = models.ImageField(upload_to="/userprofile/avatar/",default="/userprofile/avatar/default.jpg")
# user contains: username, first_name, last_name, email, groups, use_permissions, etc
phone_number = models.CharField(max_length=20, default="phone")
GENDER_CHOICES = [('M', 'Male'),('F', 'Female')]
gender = models.CharField(max_length=1, choices=GENDER_CHOICES,default='M')
date_of_birth = models.DateField(auto_now=True)
age = models.IntegerField(default=18)
language = models.CharField(max_length=10,default="Martian")
school = models.CharField(max_length=20,default="Community College") # todo: make list of choice
career = models.CharField(max_length=20,default="Malong") # todo: make list of choice
about_me = models.TextField(default="Something about myself...")
city = models.CharField(max_length=20,default="Single City") # todo: make list of choice
proximity = models.IntegerField(verbose_name="Proximity (km)", default=1) # unit in km
follower = models.ManyToManyField('self', null=True, blank=True, symmetrical=False) # one way relationship
blocked = models.ManyToManyField('self', related_name="blocked", null=True, blank=True) # two way relationship
recommendations = models.ManyToManyField('self', related_name='recommendation', null=True, blank=True) # two way relationship
stranger_fields=['user__username',
'about_me']
full_fields=['user__username',
'user__first_name',
'user__last_name',
'user__email',
'phone_number',
'gender',
'date_of_birth',
'age',
'language',
'school',
'career',
'about_me',
'city',
'proximity']
follower_fields=['user__username',
'gender',
'school',
'career',
'about_me']
blocked_fields=['user']
def get_userprofile_info(self, by_userprofile):
"""
get userprofile information by a userprofile, information provided will be based on relationship
and how user set information will be accessed
:param by_userprofile: userprofile requsted by
:return: dictionary package
"""
retVal=dict()
if by_userprofile==self:
# print "return full access"
for item in self.full_fields:
retVal[item]=get_deep_attr(self, item)
elif self in by_userprofile.follower.all(): # if target_profile is one of my follower
# print "return follower access"
for item in by_userprofile.follower_fields:
retVal[item]=get_deep_attr(self, item)
elif by_userprofile in self.blocked.all():
# print "return block access"
for item in self.blocked_fields:
retVal[item]=get_deep_attr(self, item)
else:
# print "stranger access"
for item in self.stranger_fields:
retVal[item]=get_deep_attr(self, item)
return retVal
def change_userprofile_info(self, field, new_value):
if field in ['username', 'first_name', 'last_name', 'email']:
setattr(self.user,field,new_value)
else:
setattr(self,field,new_value)
self.save()
def get_blocked(self):
"""
:return: UserProfile blocked as query set
"""
blocked_list = self.blocked.all().values_list('user__username', flat=True)
return blocked_list
def get_follower(self):
"""
:return: UserProfile followers as query set
"""
follower_list = self.follower.all().values_list('user__username', flat=True)
return follower_list
def rs_follow(self, target_userprofile):
"""
follow target userprofile
:param target_userprofile:
:return:
"""
try:
self.blocked.remove(target_userprofile)
except:
pass
target_userprofile.follower.add(self)
target_userprofile.save()
self.save()
def rs_block(self, target_userprofile):
"""
block target user profile
:param target_userprofile:
:return:
"""
self.blocked.add(target_userprofile)
try:
target_userprofile.follower.remove(self)
except:
pass
target_userprofile.save()
self.save()
def rs_reset(self, target_userprofile):
"""
reset relationship to stranger
:param target_userprofile:
:return:
"""
try:
target_userprofile.follower.remove(self)
except:
pass
try:
self.blocked.remove(target_userprofile)
except:
pass
target_userprofile.save()
self.save()
# algorithm should use these parameters to match other users
@staticmethod
def get_match_parameter(user):
match_parameter=dict()
match_parameter["gender"]=getattr(user,'gender')
match_parameter["DOB"]= getattr(user,'date_of_birth')
match_parameter["proximity"]=getattr(user,'proximity')
return match_parameter
| {
"content_hash": "4b1da70aa2eddd64f09feffc47983602",
"timestamp": "",
"source": "github",
"line_count": 183,
"max_line_length": 129,
"avg_line_length": 31.26775956284153,
"alnum_prop": 0.5896539671443551,
"repo_name": "FiniteElementries/barebone_server",
"id": "8393d0e8f21e5c34887d65cb92f3db2240f7a247",
"size": "5722",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "userprofile/models.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "41299"
}
],
"symlink_target": ""
} |
import '../app/shared/components/alert-message/alert-message.story.js'
import '../app/shared/components/full-button/full-button.story.js'
import '../app/shared/components/rounded-button/rounded-button.story.js'
import '../app/shared/components/search-bar/search-bar.story.js'
| {
"content_hash": "1fa29e1e8e87c5bd6116df65e492d185",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 72,
"avg_line_length": 69,
"alnum_prop": 0.782608695652174,
"repo_name": "ruddell/ignite-jhipster",
"id": "ab29c40e3497474a6ce9424ba90535b981c3f9e4",
"size": "276",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "boilerplate/storybook/stories.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "127594"
},
{
"name": "JavaScript",
"bytes": "162485"
},
{
"name": "Shell",
"bytes": "4110"
}
],
"symlink_target": ""
} |
package com.linkedin.pinot.transport.pool;
import com.linkedin.pinot.common.response.ServerInstance;
/**
*
* Interface to create/destroy and validate pooled resource
* The implementation is expected to be thread-safe as concurrent request to create connection for same/different servers
* is possible.
*
* @param <T>
*/
public interface PooledResourceManager<T> {
/**
* Create a new resource
* @param key to identify the pool which will host the resource
* @return future for the resource creation
*/
public T create(ServerInstance key);
/**
* Destroy the pooled resource
* @param key Key to identify the pool
* @param isBad Are we destroying because the connection is bad ?
* @param resource Resource to be destroyed
* @return true if successfully destroyed the resource, false otherwise
*/
public boolean destroy(ServerInstance key, boolean isBad, T resource);
/**
* Validate if the resource is good.
*
* @param key
* @param resource
* @return
*/
public boolean validate(ServerInstance key, T resource);
}
| {
"content_hash": "ac2187f9675ca4ab6f9f692d7fd9f54b",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 121,
"avg_line_length": 25.785714285714285,
"alnum_prop": 0.7137580794090489,
"repo_name": "apucher/pinot",
"id": "6163e52fec31a667eeb7bf391513d52fb1365cd6",
"size": "1720",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "pinot-transport/src/main/java/com/linkedin/pinot/transport/pool/PooledResourceManager.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "4620"
},
{
"name": "Batchfile",
"bytes": "7738"
},
{
"name": "CSS",
"bytes": "925082"
},
{
"name": "FreeMarker",
"bytes": "243834"
},
{
"name": "HTML",
"bytes": "274305"
},
{
"name": "Java",
"bytes": "14420303"
},
{
"name": "JavaScript",
"bytes": "5189610"
},
{
"name": "Makefile",
"bytes": "8076"
},
{
"name": "Python",
"bytes": "36574"
},
{
"name": "Shell",
"bytes": "51677"
},
{
"name": "Thrift",
"bytes": "5028"
}
],
"symlink_target": ""
} |
// Package requirematchinglabel implements the `require-matching-label` plugin.
// This is a configurable plugin that applies a label (and possibly comments)
// when an issue or PR does not have any labels matching a regexp. If a label
// is added that matches the regexp, the 'MissingLabel' is removed and the comment
// is deleted.
package requirematchinglabel
import (
"fmt"
"strings"
"time"
"k8s.io/test-infra/prow/config"
"k8s.io/test-infra/prow/github"
"k8s.io/test-infra/prow/pluginhelp"
"k8s.io/test-infra/prow/plugins"
"github.com/sirupsen/logrus"
)
var (
handlePRActions = map[github.PullRequestEventAction]bool{
github.PullRequestActionOpened: true,
github.PullRequestActionReopened: true,
github.PullRequestActionLabeled: true,
github.PullRequestActionUnlabeled: true,
}
handleIssueActions = map[github.IssueEventAction]bool{
github.IssueActionOpened: true,
github.IssueActionReopened: true,
github.IssueActionLabeled: true,
github.IssueActionUnlabeled: true,
}
)
const (
pluginName = "require-matching-label"
)
type githubClient interface {
AddLabel(org, repo string, number int, label string) error
RemoveLabel(org, repo string, number int, label string) error
CreateComment(org, repo string, number int, content string) error
GetIssueLabels(org, repo string, number int) ([]github.Label, error)
}
type commentPruner interface {
PruneComments(shouldPrune func(github.IssueComment) bool)
}
func init() {
plugins.RegisterIssueHandler(pluginName, handleIssue, helpProvider)
plugins.RegisterPullRequestHandler(pluginName, handlePullRequest, helpProvider)
}
func helpProvider(config *plugins.Configuration, _ []config.OrgRepo) (*pluginhelp.PluginHelp, error) {
descs := make([]string, 0, len(config.RequireMatchingLabel))
for _, cfg := range config.RequireMatchingLabel {
descs = append(descs, cfg.Describe())
}
// Only the 'Description' and 'Config' fields are necessary because this plugin does not react
// to any commands.
return &pluginhelp.PluginHelp{
Description: `The require-matching-label plugin is a configurable plugin that applies a label to issues and/or PRs that do not have any labels matching a regular expression. An example of this is applying a 'needs-sig' label to all issues that do not have a 'sig/*' label. This plugin can have multiple configurations to provide this kind of behavior for multiple different label sets. The configuration allows issue type, PR branch, and an optional explanation comment to be specified.`,
Config: map[string]string{
"": fmt.Sprintf("The plugin has the following configurations:\n<ul><li>%s</li></ul>", strings.Join(descs, "</li><li>")),
},
},
nil
}
type event struct {
org string
repo string
number int
author string
// The PR's base branch. If empty this is an Issue, not a PR.
branch string
// The label that was added or removed. If empty this is an open or reopen event.
label string
// The labels currently on the issue. For PRs this is not contained in the webhook payload and may be omitted.
currentLabels []github.Label
}
func handleIssue(pc plugins.Agent, ie github.IssueEvent) error {
if !handleIssueActions[ie.Action] {
return nil
}
e := &event{
org: ie.Repo.Owner.Login,
repo: ie.Repo.Name,
number: ie.Issue.Number,
author: ie.Issue.User.Login,
label: ie.Label.Name, // This will be empty for non-label events.
currentLabels: ie.Issue.Labels,
}
cp, err := pc.CommentPruner()
if err != nil {
return err
}
return handle(pc.Logger, pc.GitHubClient, cp, pc.PluginConfig.RequireMatchingLabel, e)
}
func handlePullRequest(pc plugins.Agent, pre github.PullRequestEvent) error {
if !handlePRActions[pre.Action] {
return nil
}
e := &event{
org: pre.Repo.Owner.Login,
repo: pre.Repo.Name,
number: pre.PullRequest.Number,
branch: pre.PullRequest.Base.Ref,
author: pre.PullRequest.User.Login,
label: pre.Label.Name, // This will be empty for non-label events.
}
cp, err := pc.CommentPruner()
if err != nil {
return err
}
return handle(pc.Logger, pc.GitHubClient, cp, pc.PluginConfig.RequireMatchingLabel, e)
}
// matchingConfigs filters irrelevant RequireMtchingLabel configs from
// the list of all configs.
// `branch` should be empty for Issues and non-empty for PRs.
// `label` should be omitted in the case of 'open' and 'reopen' actions.
func matchingConfigs(org, repo, branch, label string, allConfigs []plugins.RequireMatchingLabel) []plugins.RequireMatchingLabel {
var filtered []plugins.RequireMatchingLabel
for _, cfg := range allConfigs {
// Check if the config applies to this issue type.
if (branch == "" && !cfg.Issues) || (branch != "" && !cfg.PRs) {
continue
}
// Check if the config applies to this 'org[/repo][/branch]'.
if org != cfg.Org ||
(cfg.Repo != "" && cfg.Repo != repo) ||
(cfg.Branch != "" && branch != "" && cfg.Branch != branch) {
continue
}
// If we are reacting to a label event, see if it is relevant.
if label != "" && !cfg.Re.MatchString(label) {
continue
}
filtered = append(filtered, cfg)
}
return filtered
}
func handle(log *logrus.Entry, ghc githubClient, cp commentPruner, configs []plugins.RequireMatchingLabel, e *event) error {
// Find any configs that may be relevant to this event.
matchConfigs := matchingConfigs(e.org, e.repo, e.branch, e.label, configs)
if len(matchConfigs) == 0 {
return nil
}
if e.label == "" /* not a label event */ {
// If we are reacting to a PR or Issue being created or reopened, we should wait a
// few seconds to allow other automation to apply labels in order to minimize thrashing.
// We use the max grace period from applicable configs.
gracePeriod := time.Duration(0)
for _, cfg := range matchConfigs {
if cfg.GracePeriodDuration > gracePeriod {
gracePeriod = cfg.GracePeriodDuration
}
}
time.Sleep(gracePeriod)
// If currentLabels was populated it is now stale.
e.currentLabels = nil
}
if e.currentLabels == nil {
var err error
e.currentLabels, err = ghc.GetIssueLabels(e.org, e.repo, e.number)
if err != nil {
return fmt.Errorf("error getting the issue or pr's labels: %v", err)
}
}
// Handle the potentially relevant configs.
for _, cfg := range matchConfigs {
hasMissingLabel := false
hasMatchingLabel := false
for _, label := range e.currentLabels {
hasMissingLabel = hasMissingLabel || label.Name == cfg.MissingLabel
hasMatchingLabel = hasMatchingLabel || cfg.Re.MatchString(label.Name)
}
if hasMatchingLabel && hasMissingLabel {
if err := ghc.RemoveLabel(e.org, e.repo, e.number, cfg.MissingLabel); err != nil {
log.WithError(err).Errorf("Failed to remove %q label.", cfg.MissingLabel)
}
if cfg.MissingComment != "" {
cp.PruneComments(func(comment github.IssueComment) bool {
return strings.Contains(comment.Body, cfg.MissingComment)
})
}
} else if !hasMatchingLabel && !hasMissingLabel {
if err := ghc.AddLabel(e.org, e.repo, e.number, cfg.MissingLabel); err != nil {
log.WithError(err).Errorf("Failed to add %q label.", cfg.MissingLabel)
}
if cfg.MissingComment != "" {
msg := plugins.FormatSimpleResponse(e.author, cfg.MissingComment)
if err := ghc.CreateComment(e.org, e.repo, e.number, msg); err != nil {
log.WithError(err).Error("Failed to create comment.")
}
}
}
}
return nil
}
| {
"content_hash": "ce96f5b9ae8182f393e0436b972966d7",
"timestamp": "",
"source": "github",
"line_count": 213,
"max_line_length": 491,
"avg_line_length": 34.816901408450704,
"alnum_prop": 0.712378640776699,
"repo_name": "ixdy/kubernetes-test-infra",
"id": "254dce1bf890bfea5a69f1b34c403a93d7ecd7dd",
"size": "7985",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "prow/plugins/require-matching-label/require-matching-label.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "26680"
},
{
"name": "Go",
"bytes": "3591934"
},
{
"name": "HTML",
"bytes": "73212"
},
{
"name": "JavaScript",
"bytes": "207614"
},
{
"name": "Makefile",
"bytes": "62496"
},
{
"name": "Python",
"bytes": "977451"
},
{
"name": "Roff",
"bytes": "5462"
},
{
"name": "Shell",
"bytes": "99296"
},
{
"name": "Smarty",
"bytes": "516"
}
],
"symlink_target": ""
} |
//
// DP formulation based on https://figshare.com/articles/preprint/Notes_on_pairwise_alignment_with_dynamic_programming/5223973
//
#pragma once
#include "Compat.h"
#include "FixedSizeMap.h"
#include "BigAlloc.h"
#include "exit.h"
#include "Genome.h"
#include "Read.h"
#include "Tables.h"
#include "LandauVishkin.h"
#include "AffineGap.h"
const int VEC_SIZE = 8; // Number of 16-bit elements in vector
const int MAX_VEC_SEGMENTS = (MAX_READ_LENGTH + VEC_SIZE - 1) / (VEC_SIZE);
//
// These are global so there are only one for both senses of the template
//
extern double *lv_indelProbabilities; // Maps indels by length to probability of occurance.
extern double *lv_phredToProbability; // Maps ASCII phred character to probability of error, including
extern double *lv_perfectMatchProbability; // Probability that a read of this length has no mutations
// #define TRACE_AG
//
// Helper functions for operations on SSE registers
//
static inline int getMax(__m128i x) {
x = _mm_max_epi16(x, _mm_srli_si128((x), 8));
x = _mm_max_epi16(x, _mm_srli_si128((x), 4));
x = _mm_max_epi16(x, _mm_srli_si128((x), 2));
return _mm_extract_epi16(x, 0);
}
static inline int16_t getElem(int index, __m128i x) {
int16_t elem;
switch (index) {
case 0: elem = _mm_extract_epi16(x, 0); break;
case 1: elem = _mm_extract_epi16(x, 1); break;
case 2: elem = _mm_extract_epi16(x, 2); break;
case 3: elem = _mm_extract_epi16(x, 3); break;
case 4: elem = _mm_extract_epi16(x, 4); break;
case 5: elem = _mm_extract_epi16(x, 5); break;
case 6: elem = _mm_extract_epi16(x, 6); break;
case 7: elem = _mm_extract_epi16(x, 7); break;
default: elem = -1; break;
}
return elem;
}
static inline void printElem(__m128i x) {
printf("%hi,%hi,%hi,%hi,%hi,%hi,%hi,%hi,", _mm_extract_epi16(x, 0), _mm_extract_epi16(x, 1), _mm_extract_epi16(x, 2), _mm_extract_epi16(x, 3),
_mm_extract_epi16(x, 4), _mm_extract_epi16(x, 5), _mm_extract_epi16(x, 6), _mm_extract_epi16(x, 7));
}
// return (~mask)*v1 | (mask)*v2
static inline __m128i blend_sse(__m128i v1, __m128i v2, __m128i mask) {
v1 = _mm_andnot_si128(mask, v1);
v1 = _mm_or_si128(v1, _mm_and_si128(mask, v2));
return v1;
}
enum BacktraceActionType {
M = 0,
D = 1,
I = 2,
X = 3
};
//
// Computes the affine gap score between two strings based on Farrar's algorithm
//
template<int TEXT_DIRECTION = 1> class AffineGapVectorized {
public:
AffineGapVectorized()
{
init(1, 4, 6, 1, 10, 5);
}
AffineGapVectorized(
int i_matchReward,
int i_subPenalty,
int i_gapOpenPenalty,
int i_gapExtendPenalty,
int i_fivePrimeEndBonus,
int i_threePrimeEndBonus)
{
init(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty, i_fivePrimeEndBonus, i_threePrimeEndBonus);
}
static size_t getBigAllocatorReservation() { return sizeof(AffineGapVectorized<TEXT_DIRECTION>); }
~AffineGapVectorized()
{
}
void init(
int i_matchReward,
int i_subPenalty,
int i_gapOpenPenalty,
int i_gapExtendPenalty,
int i_fivePrimeEndBonus,
int i_threePrimeEndBonus)
{
matchReward = i_matchReward;
subPenalty = -i_subPenalty;
gapOpenPenalty = i_gapOpenPenalty + i_gapExtendPenalty; // First gap costs (gapOpen + gapExtend)
gapExtendPenalty = i_gapExtendPenalty;
fivePrimeEndBonus = i_fivePrimeEndBonus;
threePrimeEndBonus = i_threePrimeEndBonus;
//
// Initialize nucleotide <-> nucleotide transition matrix
//
int i, j, k = 0;
for (i = 0; i < (MAX_ALPHABET_SIZE - 1); i++) {
for (j = 0; j < (MAX_ALPHABET_SIZE - 1); j++) {
ntTransitionMatrix[k++] = (i == j) ? matchReward : subPenalty;
}
ntTransitionMatrix[k++] = -1; // FIXME: What penalty to use for N ?
}
for (i = 0; i < MAX_ALPHABET_SIZE; i++) {
ntTransitionMatrix[k++] = -1;
}
}
//
// Compute Hamming distance between text and pattern. Poorly matching sections of pattern are clipped out
// TODO: Make faster version
//
int computeGaplessScore(
const char* text,
int textLen,
const char* pattern,
const char* qualityString,
int patternLen,
int scoreInit,
int scoreLimit,
int* o_nEdits = NULL,
int* o_textOffset = NULL,
int* o_patternOffset = NULL,
double* matchProbability = NULL,
int* o_nEditsGapless = NULL)
{
_ASSERT(textLen <= MAX_READ_LENGTH + MAX_K);
_ASSERT(patternLen <= textLen);
int localTextOffset, localPatternOffset;
if (NULL == o_textOffset) {
//
// If the user doesn't want textOffset, just use a stack local to avoid
// having to check it all the time.
//
o_textOffset = &localTextOffset;
}
if (NULL == o_patternOffset) {
o_patternOffset = &localPatternOffset;
}
double localMatchProbability;
if (NULL == matchProbability) {
//
// If the user doesn't want matchProbability, just use a stack local to avoid
// having to check it all the time.
//
matchProbability = &localMatchProbability;
}
int localnEdits;
if (NULL == o_nEdits) {
//
// If the user doesn't want matchProbability, just use a stack local to avoid
// having to check it all the time.
//
o_nEdits = &localnEdits;
}
int localnEditsGapless;
if (NULL == o_nEditsGapless) {
//
// If the user doesn't want matchProbability, just use a stack local to avoid
// having to check it all the time.
//
o_nEditsGapless = &localnEditsGapless;
}
if (scoreLimit < 0 || NULL == text) {
*o_nEdits = ScoreAboveLimit;
*o_nEditsGapless = ScoreAboveLimit;
return ScoreAboveLimit;
}
//
// Start with perfect match probability and work our way down.
//
*matchProbability = 1.0;
if (TEXT_DIRECTION == -1) {
text--; // so now it points at the "first" character of t, not after it.
}
int gapLessScore = scoreInit;
int maxScore = scoreInit;
for (int i = 0; i < patternLen; i++) {
const char* p = pattern + i;
const char* t = text + i * TEXT_DIRECTION;
gapLessScore += (*p == *t) ? matchReward : subPenalty;
// Keep track of maximum score and corresponding length of pattern matched
if (gapLessScore > maxScore) {
maxScore = gapLessScore;
*o_patternOffset = i;
}
} // patternLen
// We were able to extend the seed. Now compute matchProbability for the portion that was extended
if (maxScore > scoreInit) {
*o_nEdits = 0;
int nMatches = 0;
for (int i = 0; i <= *o_patternOffset; i++) {
const char* p = pattern + i;
const char* t = text + i * TEXT_DIRECTION;
if (*p != *t) {
*o_nEdits += 1;
*matchProbability *= lv_phredToProbability[qualityString[i]];
} else {
nMatches++;
}
}
*matchProbability *= lv_perfectMatchProbability[nMatches];
*o_patternOffset += 1;
*o_patternOffset = patternLen - *o_patternOffset;
*o_textOffset = *o_patternOffset;
*o_nEditsGapless = (*o_nEdits <= scoreLimit) ? *o_nEdits : -1;
*o_nEdits += *o_patternOffset; // Add gaps at the end
*matchProbability *= lv_indelProbabilities[*o_patternOffset];
return maxScore;
}
else { // We could not find a longer gapless alignment beyond seedLen
*o_nEdits = ScoreAboveLimit;
*o_nEditsGapless = ScoreAboveLimit;
return ScoreAboveLimit;
}
}
int computeScoreBanded(
const char* text,
int textLen,
const char* pattern,
const char *qualityString,
int patternLen,
int w,
int scoreInit,
bool isRC,
int *o_textOffset = NULL,
int *o_patternOffset = NULL,
int *o_nEdits = NULL,
double *matchProbability = NULL,
bool useClippingOptimizations = false,
bool useAltLiftover = false)
{
#ifdef TRACE_AG
printf("\n");
#endif
_ASSERT(w < MAX_K);
_ASSERT(textLen <= MAX_READ_LENGTH + MAX_K);
int localTextOffset, localPatternOffset;
if (NULL == o_textOffset) {
//
// If the user doesn't want textOffset, just use a stack local to avoid
// having to check it all the time.
//
o_textOffset = &localTextOffset;
}
if (NULL == o_patternOffset) {
o_patternOffset = &localPatternOffset;
}
w = __min(MAX_K - 1, w); // enforce limit even in non-debug builds
if (NULL == text) {
// This happens when we're trying to read past the end of the genome.
if (NULL != matchProbability) {
*matchProbability = 0.0;
}
if (NULL != o_nEdits) {
*o_nEdits = -1;
}
return -1;
}
// FIXME: Find better way to do this based on usage
double localMatchProbability;
if (NULL == matchProbability) {
//
// If the user doesn't want matchProbability, just use a stack local to avoid
// having to check it all the time.
//
matchProbability = &localMatchProbability;
}
int localnEdits;
if (NULL == o_nEdits) {
//
// If the user doesn't want matchProbability, just use a stack local to avoid
// having to check it all the time.
//
o_nEdits = &localnEdits;
}
if (w < 0) {
*o_nEdits = ScoreAboveLimit;
return -1;
}
//
// Start with perfect match probability and work our way down.
//
*matchProbability = 1.0;
if (TEXT_DIRECTION == -1) {
text--; // so now it points at the "first" character of t, not after it.
}
int bandWidth = (2 * w + 1) < patternLen ? (2 * w + 1) : patternLen;
int numVec = (bandWidth + VEC_SIZE - 1) / VEC_SIZE; // Number of vectors per Farrar segment
int segLen = numVec * VEC_SIZE;
int numSeg = (patternLen + segLen - 1) / segLen;
int patternIdx = 0;
//
// Generate query profile
//
int16_t* queryResult = (int16_t*)qProfile;
for (int a = 0; a < MAX_ALPHABET_SIZE; a++) {
for (int i = 0; i < numSeg; i++) {
for (int j = 0; j < numVec; j++) {
for (int k = j; k < segLen; k += numVec) {
int idx = i * segLen + k;
if (idx < patternLen) {
uint8_t bp = BASE_VALUE[pattern[idx]];
queryResult[patternIdx] = ntTransitionMatrix[a * MAX_ALPHABET_SIZE + bp];
}
else {
queryResult[patternIdx] = INT16_MIN;
}
patternIdx++;
}
}
}
}
//
// Define constants in their vector form
//
__m128i v_zero = _mm_setzero_si128();
__m128i v_one = _mm_set1_epi16(1);
__m128i v_two = _mm_set1_epi16(2);
__m128i v_four = _mm_set1_epi16(4);
__m128i v_thirtytwo = _mm_set1_epi16(32);
__m128i v_gapOpen = _mm_set1_epi16(gapOpenPenalty);
__m128i v_gapExtend = _mm_set1_epi16(gapExtendPenalty);
__m128i v_scoreInit = _mm_set1_epi16(scoreInit);
__m128i v_mask = _mm_cmpgt_epi16(_mm_set_epi16(0, 0, 0, 0, 0, 0, 0, 1), v_zero);
int endBonus;
if (!isRC) {
if (TEXT_DIRECTION == -1) {
endBonus = fivePrimeEndBonus;
}
else {
endBonus = threePrimeEndBonus;
}
}
else {
if (TEXT_DIRECTION == -1) {
endBonus = threePrimeEndBonus;
}
else {
endBonus = fivePrimeEndBonus;
}
}
//
// Initialize scores of first row
//
uint16_t scoreFirstRow[VEC_SIZE] = {};
for (int segIdx = 0; segIdx < numSeg; segIdx++) {
for (int vecIdx = 0; vecIdx < numVec; vecIdx++) {
for (int elemIdx = 0; elemIdx < VEC_SIZE; elemIdx++) {
int patternIdx = (segIdx * segLen) + (elemIdx * numVec) + vecIdx;
if (patternIdx < patternLen) {
scoreFirstRow[elemIdx] = __max(0, scoreInit - gapOpenPenalty - patternIdx * gapExtendPenalty);
}
}
_ASSERT(VEC_SIZE == 8); // FIXME: Initialization below works only when VEC_SIZE = 8
_mm_store_si128(H + (segIdx * numVec) + vecIdx, _mm_setr_epi16(scoreFirstRow[0], scoreFirstRow[1], scoreFirstRow[2], scoreFirstRow[3],
scoreFirstRow[4], scoreFirstRow[5], scoreFirstRow[6], scoreFirstRow[7]));
_mm_store_si128(Hminus1 + (segIdx * numVec) + vecIdx, v_zero);
_mm_store_si128(E + (segIdx * numVec) + vecIdx, v_zero);
}
}
int score = -1; // Final alignment score to be returned.
// We keep track of the best score and text offset for global and local alignment separately.
// These are used to choose between global and local alignment for the {text, pattern} pair
int bestGlobalAlignmentScore = -1;
int bestGlobalAlignmentTextOffset = -1;
int bestLocalAlignmentScore = -1;
int bestLocalAlignmentTextOffset = -1;
int bestLocalAlignmentPatternOffset = -1;
*o_textOffset = -1; // # Characters of text used for aligning against the pattern
*o_patternOffset = -1; // # Characters of pattern used for obtaining the maximum score. Ideally we would like to use the full pattern
*o_nEdits = -1;
__m128i* Hptr = H;
__m128i* Hminus1ptr = Hminus1;
// Iterate over all rows of text
for (int i = 0; i < textLen; i++) {
const char* t = (text + i * TEXT_DIRECTION);
// Get the query profile for the row
__m128i* qRowProfile = qProfile + BASE_VALUE[*t] * numSeg * numVec;
// Registers to hold intermediate scores for each row
__m128i m, h, temp, e = v_zero, f = v_zero, max = v_zero, X = v_zero;
int maxScoreRow = 0;
int localAlignmentPatternOffset = -1;
int bandBeg = __max(i - w, 0);
int bandEnd = __min(i + w, patternLen -1);
int segBeg = bandBeg / segLen;
int segEnd = bandEnd / segLen;
for (int j = segBeg; j <= segEnd; j++) {
// Load h from the previous row
h = _mm_load_si128(Hptr + (j * numVec) + numVec - 1);
// Shift left h and blend in initial values
h = _mm_slli_si128(h, 2); // shift h left by 2 * 8 bits
__m128i v_hInit;
if (j == 0) {
int hInit = scoreInit;
if (i > 0) {
hInit = __max(0, scoreInit - gapOpenPenalty - (i - 1) * gapExtendPenalty);
}
v_hInit = _mm_set1_epi16(hInit);
}
else {
if (bandBeg > j * segLen) {
v_hInit = v_zero;
}
else {
v_hInit = _mm_load_si128(Hptr + j * numVec - 1);
v_hInit = _mm_srli_si128(v_hInit, 14);
}
}
// h = _mm_blend_epi16(h, v_hInit, 1); // Does not work with SSE !
h = blend_sse(h, v_hInit, v_mask);
__m128i* backtraceActionSeg = backtraceAction + (i * numVec * numSeg) + (j * numVec);
for (int k = 0; (k < numVec) && (j * segLen + k) <= bandEnd; k++) {
__m128i backtraceActionVec;
__m128i mask = _mm_cmpgt_epi16(h, v_zero); // h > 0
__m128i qProfileVec = _mm_load_si128(qRowProfile + j * numVec + k);
m = _mm_adds_epi16(h, qProfileVec);
m = _mm_and_si128(m, mask);
e = _mm_load_si128(E + j * numVec + k);
// h = max{m, e, f}
backtraceActionVec = _mm_and_si128(_mm_cmpgt_epi16(e, m), v_one); // action = e > m ? 1 : 0
h = _mm_max_epi16(m, e);
__m128i tmpResult = _mm_and_si128(_mm_cmpgt_epi16(f, h), v_two);
backtraceActionVec = _mm_or_si128(tmpResult, _mm_andnot_si128(tmpResult, backtraceActionVec)); // action = f > h ? 2 : action
h = _mm_max_epi16(h, f);
max = _mm_max_epi16(max, h);
// Store h for the next row
_mm_store_si128(Hminus1ptr + j * numVec + k, h);
// e = max{m - gapOpen, e - gapExtend}
e = _mm_subs_epi16(e, v_gapExtend);
temp = _mm_subs_epi16(m, v_gapOpen);
temp = _mm_max_epi16(temp, v_zero);
tmpResult = _mm_and_si128(_mm_cmpgt_epi16(e, temp), v_four);
backtraceActionVec = _mm_or_si128(backtraceActionVec, tmpResult);
e = _mm_max_epi16(e, temp);
_mm_store_si128(E + j * numVec + k, e);
// f = max{m - gapOpen, f- gapExtend}
f = _mm_subs_epi16(f, v_gapExtend);
tmpResult = _mm_and_si128(_mm_cmpgt_epi16(f, temp), v_thirtytwo);
backtraceActionVec = _mm_or_si128(backtraceActionVec, tmpResult);
f = _mm_max_epi16(f, temp);
// Store traceback information
_mm_store_si128(backtraceActionSeg + k, backtraceActionVec);
// Load the next score vector
h = _mm_load_si128(Hptr + j * numVec + k);
} // end segment
//
// Farrar's algorithm does lazy f evaluation. Since f rarely influences final score h, the algorithm speculates f = zero initially
// Re-evaluate if f could influence h after we have made a first pass through the row
//
for (int k = 0; k < (VEC_SIZE - 1); k++) {
// Save f value at boundary for next segment
X = _mm_max_epi16(X, _mm_srli_si128(f, 14));
// Extract the last f vector
f = _mm_slli_si128(f, 2);
for (int v = 0; (v < numVec) && (j * segLen + v) <= bandEnd; v++) {
h = _mm_load_si128(Hminus1ptr + j * numVec + v);
// action = f > h ? 2 : action
__m128i tmpResult = _mm_and_si128(_mm_cmpgt_epi16(f, h), v_two);
__m128i backtraceActionVec = _mm_load_si128(backtraceActionSeg + v);
__m128i tmpResult2 = _mm_andnot_si128(tmpResult, backtraceActionVec);
backtraceActionVec = _mm_or_si128(tmpResult, tmpResult2);
h = _mm_max_epi16(h, f);
_mm_store_si128(Hminus1ptr + j * numVec + v, h);
max = _mm_max_epi16(max, h);
temp = _mm_subs_epu16(h, v_gapOpen);
f = _mm_subs_epu16(f, v_gapExtend);
tmpResult = _mm_and_si128(_mm_cmpgt_epi16(f, temp), v_thirtytwo);
backtraceActionVec = _mm_or_si128(backtraceActionVec, tmpResult);
_mm_store_si128(backtraceActionSeg + v, backtraceActionVec);
// Converged if no element of f can influence h
bool converged = !(_mm_movemask_epi8(_mm_cmpgt_epi16(f, temp))); // !! converts int to bool
if (converged) goto got_answer;
}
}
got_answer:
// Pass on f for next segment
f = X;
} // end pattern
maxScoreRow = getMax(max);
#ifdef TRACE_AG
__m128i rowScore;
for (int j = 0; j < segBeg; j++) {
for (int k = 0; k < numVec; k++) {
printElem(v_zero);
}
}
for (int j = segBeg; j <= segEnd; j++) {
for (int k = 0; k < numVec && (j * segLen + k) <= bandEnd; k++) {
rowScore = _mm_load_si128(Hminus1ptr + j * numVec + k);
printElem(rowScore);
}
}
printf("\n");
#endif
if (bandEnd == patternLen - 1) {
//
// Global alignment score (i.e., score when aligning to the end of the pattern)
//
int vecIdx = ((bandEnd / segLen) * numVec) + ((bandEnd % segLen) % numVec);
int elemIdx = (bandEnd % segLen) / numVec;
__m128i v_globalAlignmentScore = _mm_load_si128(Hminus1ptr + vecIdx);
int globalAlignmentScore = getElem(elemIdx, v_globalAlignmentScore);
if (globalAlignmentScore >= bestGlobalAlignmentScore) {
bestGlobalAlignmentScore = globalAlignmentScore;
bestGlobalAlignmentTextOffset = i;
}
}
if (maxScoreRow == 0) break;
if (maxScoreRow > bestLocalAlignmentScore) { // If we obtained a better score this round
//
// Get index in pattern where maximum score was obtained
//
for (int j = segBeg; j <= segEnd; j++) {
for (int k = 0; (k < numVec) && (j * segLen + k) <= bandEnd; k++) {
__m128i h = _mm_load_si128(Hminus1ptr + j * numVec + k); // Load a vector of score values
__m128i mask = _mm_cmpeq_epi16(h, _mm_set1_epi16(maxScoreRow)); // Create a mask of 1's in cells where score = maxScoreRow
int result = _mm_movemask_epi8(_mm_packs_epi16(mask, v_zero)); // Convert vector result to 8-bit
unsigned long zeroes;
if (result) {
CountLeadingZeroes(result, zeroes);
int patternOffset = j * segLen + zeroes * numVec + k;
localAlignmentPatternOffset = (localAlignmentPatternOffset > patternOffset) ? localAlignmentPatternOffset : patternOffset;
_ASSERT(localAlignmentPatternOffset < patternLen); // Scores outside the pattern boundaries should never be the maximum in the row
}
}
}
bestLocalAlignmentScore = maxScoreRow;
bestLocalAlignmentTextOffset = i;
bestLocalAlignmentPatternOffset = localAlignmentPatternOffset;
}
// Swap roles of H and Hminus1 for the next row
__m128i* hTemp = Hminus1ptr;
Hminus1ptr = Hptr;
Hptr = hTemp;
} // end text
// Choose between local and global alignment for patternOffset
if ((bestLocalAlignmentScore != bestGlobalAlignmentScore) && (bestLocalAlignmentScore >= bestGlobalAlignmentScore + endBonus)) {
// Local alignment preferred
*o_patternOffset = bestLocalAlignmentPatternOffset;
*o_textOffset = bestLocalAlignmentTextOffset;
score = bestLocalAlignmentScore;
if (useClippingOptimizations) {
//
// Check if we can match more bases near the end of the soft-clipped read by deleting a character from the reference.
// This helps reduce some INDEL false negatives introduced by using a high gap open penalty
//
int patternOffsetAdj = *o_patternOffset - 1;
int textOffsetAdj = *o_textOffset;
int countEndMatches = 0;
while ((patternOffsetAdj + 1 != patternLen) && pattern[patternOffsetAdj + 1] == *(text + (textOffsetAdj + 1) * TEXT_DIRECTION)) {
countEndMatches++;
patternOffsetAdj++;
textOffsetAdj++;
}
if (countEndMatches >= 3) { // matched too few bases, don't use the alignment with deletion. FIXME: check if 3 is enough!
*o_patternOffset = patternOffsetAdj;
*o_textOffset = textOffsetAdj;
} else {
//
// Check if we can match more bases near the end of the soft-clipped read by inserting a character to the pattern.
// This helps reduce some INDEL false negatives introduced by using a high gap open penalty
//
patternOffsetAdj = *o_patternOffset + 1;
textOffsetAdj = *o_textOffset;
countEndMatches = 0;
while ((patternOffsetAdj < patternLen) && pattern[patternOffsetAdj] == *(text + (textOffsetAdj)*TEXT_DIRECTION)) {
countEndMatches++;
patternOffsetAdj++;
textOffsetAdj++;
}
if (countEndMatches >= 3) { // matched too few bases, don't use the alignment with insertion. FIXME: check if 3 is enough!
*o_patternOffset = patternOffsetAdj - 1;
*o_textOffset = textOffsetAdj - 1;
}
}
if (*o_patternOffset == bestLocalAlignmentPatternOffset && *o_textOffset == bestLocalAlignmentTextOffset) {
patternOffsetAdj = *o_patternOffset;
textOffsetAdj = *o_textOffset;
if (!useAltLiftover) { // base quality aware optimization leads to spurious INDELs at the ends of reads after liftover. Disabled
//
// Try not to clip high quality bases (>= 65) from the read. These will be reported as insertions in the final alignment
//
int countInsertions = 0;
while (patternOffsetAdj != patternLen - 1 && qualityString[patternOffsetAdj] >= 65 && qualityString[patternOffsetAdj + 1] >= 65) {
patternOffsetAdj += 1;
countInsertions++;
}
if (patternOffsetAdj == patternLen - 1) {
*o_patternOffset = patternOffsetAdj;
}
else if (patternOffsetAdj >= *o_patternOffset + 2) {
int tmpOffset = patternOffsetAdj + 1;
int countRemHighQualityBases = 0;
int remPatternLen = patternLen - tmpOffset;
while (tmpOffset != patternLen - 1) {
if (qualityString[tmpOffset] >= 65) {
countRemHighQualityBases++;
}
tmpOffset++;
}
_ASSERT(remPatternLen != 0);
if (((float)countRemHighQualityBases) / remPatternLen < 0.1) {
*o_patternOffset = patternOffsetAdj;
}
}
}
}
}
}
else {
// Global alignment preferred
*o_patternOffset = patternLen - 1;
*o_textOffset = bestGlobalAlignmentTextOffset;
score = bestGlobalAlignmentScore;
}
if (score > scoreInit) {
// Perform traceback and compute nEdits
int rowIdx = *o_textOffset, colIdx = *o_patternOffset, matrixIdx;
BacktraceActionType action = M, prevAction = M;
int actionCount = 1;
int nMatches = 0, nMismatches = 0, nGaps = 0;
// Start traceback from the cell (i,j) with the maximum score
while (rowIdx >= 0 && colIdx >= 0) {
int vecIdx = (colIdx / segLen) * numVec + ((colIdx % segLen) % numVec);
int elemIdx = (colIdx % segLen) / numVec;
uint16_t* backtracePointersVec = (uint16_t*)(backtraceAction + (rowIdx * numVec * numSeg) + vecIdx);
//
// The traceback matrix (H, E, or F) we need to look at depends on the current action.
// We index the corresponding matrix using the current action as described below:
// If current action is M, bits[1:0] are used
// If current action is D, bits[3:2] are used
// If current action is I, bits[5:4] are used
//
matrixIdx = action << 1;
//
// Two bits are used to encode the backtrace action type
//
action = (BacktraceActionType) ((backtracePointersVec[elemIdx] >> matrixIdx) & 3);
if (action == M) {
if (pattern[colIdx] != text[rowIdx * TEXT_DIRECTION]) {
// Compute probabilties of mismatches
*matchProbability *= lv_phredToProbability[qualityString[colIdx]];
nMismatches++;
}
else {
nMatches++;
}
rowIdx--; colIdx--;
}
else if (action == D) {
rowIdx--;
}
else { // action == I
colIdx--;
action = I; // FIXME: we choose I, whenever action == 2 or 3. Make action == 2, since matrixIdx depends on it
}
// Ignore transitions from H. Compute number of indels in sequence for matchProbability
if (prevAction != M) {
if (prevAction == action) {
actionCount++;
}
else {
// Update match probabilties with indel probabilties here
nGaps += actionCount;
*matchProbability *= lv_indelProbabilities[actionCount];
actionCount = 1;
}
}
prevAction = action;
}
if (rowIdx >= 0) { // deletion just after the seed
actionCount = rowIdx + 1;
nGaps += actionCount;
*matchProbability *= lv_indelProbabilities[actionCount];
}
if (colIdx >= 0) { // insertion just after the seed
actionCount = colIdx + 1;
nGaps += actionCount;
*matchProbability *= lv_indelProbabilities[actionCount];
}
*o_nEdits = nMismatches + nGaps;
// *o_nEdits = (*o_nEdits <= w) ? *o_nEdits : -1; // return -1 if we have more edits than threshold w
*matchProbability *= lv_perfectMatchProbability[nMatches];
*o_textOffset += 1;
*o_patternOffset += 1;
*o_textOffset = patternLen - *o_textOffset;
*o_patternOffset = patternLen - *o_patternOffset;
*matchProbability *= lv_indelProbabilities[*o_patternOffset];
return score;
}
else {
return -1;
}
}
int computeScore(
const char* text,
int textLen,
const char* pattern,
const char *qualityString,
int patternLen,
int w,
int scoreInit,
bool isRC,
int *o_textOffset = NULL,
int *o_patternOffset = NULL,
int *o_nEdits = NULL,
double *matchProbability = NULL,
bool useClippingOptimizations = false,
bool useAltLiftover = false)
{
#ifdef TRACE_AG
printf("\n");
#endif
_ASSERT(w < MAX_K);
_ASSERT(textLen <= MAX_READ_LENGTH + MAX_K);
int localTextOffset, localPatternOffset;
if (NULL == o_textOffset) {
//
// If the user doesn't want textOffset, just use a stack local to avoid
// having to check it all the time.
//
o_textOffset = &localTextOffset;
}
if (NULL == o_patternOffset) {
o_patternOffset = &localPatternOffset;
}
w = __min(MAX_K - 1, w); // enforce limit even in non-debug builds
if (NULL == text) {
// This happens when we're trying to read past the end of the genome.
if (NULL != matchProbability) {
*matchProbability = 0.0;
}
if (NULL != o_nEdits) {
*o_nEdits = -1;
}
return -1;
}
// FIXME: Find better way to do this based on usage
double localMatchProbability;
if (NULL == matchProbability) {
//
// If the user doesn't want matchProbability, just use a stack local to avoid
// having to check it all the time.
//
matchProbability = &localMatchProbability;
}
int localnEdits;
if (NULL == o_nEdits) {
//
// If the user doesn't want matchProbability, just use a stack local to avoid
// having to check it all the time.
//
o_nEdits = &localnEdits;
}
if (w < 0) {
*o_nEdits = ScoreAboveLimit;
return -1;
}
//
// Start with perfect match probability and work our way down.
//
*matchProbability = 1.0;
if (TEXT_DIRECTION == -1) {
text--; // so now it points at the "first" character of t, not after it.
}
//
// PATTERN (p)
// VEC0 VEC1
// p[0]p[1].. p[8]p[9]..
//
//
// STRIPED_PATTERN (p)
// VEC0 VEC1
// p[0]p[8].. p[1]p[9]..
//
int numVec = (patternLen + VEC_SIZE - 1) / VEC_SIZE; // Number of vector segments
int paddedPatternLen = numVec * VEC_SIZE;
int patternIdx = 0;
//
// Generate query profile
//
int16_t* queryResult = (int16_t*)qProfile;
for (int i = 0; i < MAX_ALPHABET_SIZE; i++) {
for (int j = 0; j < numVec; j++) {
for (int k = j; k < paddedPatternLen; k += numVec) {
if (k < patternLen) {
uint8_t bp = BASE_VALUE[pattern[k]];
queryResult[patternIdx] = ntTransitionMatrix[i * MAX_ALPHABET_SIZE + bp];
}
else {
queryResult[patternIdx] = INT16_MIN;
}
patternIdx++;
}
}
}
//
// Define constants in their vector form
//
__m128i v_zero = _mm_setzero_si128();
__m128i v_one = _mm_set1_epi16(1);
__m128i v_two = _mm_set1_epi16(2);
__m128i v_four = _mm_set1_epi16(4);
__m128i v_thirtytwo = _mm_set1_epi16(32);
__m128i v_gapOpen = _mm_set1_epi16(gapOpenPenalty);
__m128i v_gapExtend = _mm_set1_epi16(gapExtendPenalty);
__m128i v_scoreInit = _mm_set1_epi16(scoreInit);
__m128i v_mask = _mm_cmpgt_epi16(_mm_set_epi16(0, 0, 0, 0, 0, 0, 0, 1), v_zero);
int endBonus;
if (!isRC) {
if (TEXT_DIRECTION == -1) {
endBonus = fivePrimeEndBonus;
}
else {
endBonus = threePrimeEndBonus;
}
}
else {
if (TEXT_DIRECTION == -1) {
endBonus = threePrimeEndBonus;
}
else {
endBonus = fivePrimeEndBonus;
}
}
//
// Initialize scores of first row
//
uint16_t scoreFirstRow[VEC_SIZE] = {};
for (int vecIdx = 0; vecIdx < numVec; vecIdx++) {
for (int elemIdx = 0; elemIdx < VEC_SIZE; elemIdx++) {
int patternIdx = elemIdx * numVec + vecIdx;
if (patternIdx < patternLen) {
scoreFirstRow[elemIdx] = __max(0, scoreInit - gapOpenPenalty - patternIdx * gapExtendPenalty);
}
}
_ASSERT(VEC_SIZE == 8); // FIXME: Initialization below works only when VEC_SIZE = 8
_mm_store_si128(H + vecIdx, _mm_setr_epi16(scoreFirstRow[0], scoreFirstRow[1], scoreFirstRow[2], scoreFirstRow[3],
scoreFirstRow[4], scoreFirstRow[5], scoreFirstRow[6], scoreFirstRow[7]));
_mm_store_si128(E + vecIdx, v_zero);
}
int score = -1; // Final alignment score to be returned.
// We keep track of the best score and text offset for global and local alignment separately.
// These are used to choose between global and local alignment for the {text, pattern} pair
int bestGlobalAlignmentScore = -1;
int bestGlobalAlignmentTextOffset = -1;
int bestLocalAlignmentScore = -1;
int bestLocalAlignmentTextOffset = -1;
int bestLocalAlignmentPatternOffset = -1;
*o_textOffset = -1; // # Characters of text used for aligning against the pattern
*o_patternOffset = -1; // # Characters of pattern used for obtaining the maximum score. Ideally we would like to use the full pattern
*o_nEdits = -1;
__m128i* Hptr = H;
__m128i* Hminus1ptr = Hminus1;
// Iterate over all rows of text
for (int i = 0; i < textLen; i++) {
const char* t = (text + i * TEXT_DIRECTION);
// Get the query profile for the row
__m128i* qRowProfile = qProfile + BASE_VALUE[*t] * numVec;
// Registers to hold intermediate scores for each row
__m128i m, h, temp, e = v_zero, f = v_zero, max = v_zero;
int maxScoreRow = 0;
int localAlignmentPatternOffset = -1;
// Load h from the previous row
h = _mm_load_si128(Hptr + numVec - 1);
// Shift left h and blend in initial values
h = _mm_slli_si128(h, 2); // shift h left by 2 * 8 bits
int hInit = scoreInit;
if (i > 0) {
hInit = __max(0, scoreInit - gapOpenPenalty - (i - 1) * gapExtendPenalty);
}
__m128i v_hInit = _mm_set1_epi16(hInit);
// h = _mm_blend_epi16(h, v_hInit, 1); // Does not work with SSE !
h = blend_sse(h, v_hInit, v_mask);
for (int j = 0; j < numVec; j++) {
__m128i backtraceActionVec;
__m128i mask = _mm_cmpgt_epi16(h, v_zero); // h > 0
// Below implements: m = m > 0 : m + qRowProfile[j] : 0
m = _mm_adds_epi16(h, *qRowProfile++);
m = _mm_and_si128(m, mask);
e = _mm_load_si128(E + j);
// h = max{m, e, f}
backtraceActionVec = _mm_and_si128(_mm_cmpgt_epi16(e, m), v_one); // action = e > m ? 1 : 0
h = _mm_max_epi16(m, e);
__m128i tmpResult = _mm_and_si128(_mm_cmpgt_epi16(f, h), v_two);
backtraceActionVec = _mm_or_si128(tmpResult, _mm_andnot_si128(tmpResult, backtraceActionVec)); // action = f > h ? 2 : action
h = _mm_max_epi16(h, f);
max = _mm_max_epi16(max, h);
// Store h for the next row
_mm_store_si128(Hminus1ptr + j, h);
// e = max{m - gapOpen, e - gapExtend}
e = _mm_subs_epi16(e, v_gapExtend);
temp = _mm_subs_epi16(m, v_gapOpen);
temp = _mm_max_epi16(temp, v_zero);
tmpResult = _mm_and_si128(_mm_cmpgt_epi16(e, temp), v_four);
backtraceActionVec = _mm_or_si128(backtraceActionVec, tmpResult);
e = _mm_max_epi16(e, temp);
_mm_store_si128(E + j, e);
// f = max{m - gapOpen, f- gapExtend}
f = _mm_subs_epi16(f, v_gapExtend);
tmpResult = _mm_and_si128(_mm_cmpgt_epi16(f, temp), v_thirtytwo);
backtraceActionVec = _mm_or_si128(backtraceActionVec, tmpResult);
f = _mm_max_epi16(f, temp);
// Store traceback information
_mm_store_si128(backtraceAction + (i * numVec + j), backtraceActionVec);
// Load the next score vector
h = _mm_load_si128(Hptr + j);
} // end pattern
//
// Farrar's algorithm does lazy f evaluation. Since f rarely influences final score h, the algorithm speculates f = zero initially
// Re-evaluate if f could influence h after we have made a first pass through the row
//
for (int k = 0; k < VEC_SIZE; k++) {
// Extract the last f vector
f = _mm_slli_si128(f, 2);
for (int j = 0; j < numVec; j++) {
h = _mm_load_si128(Hminus1ptr + j);
// action = f > h ? 2 : action
__m128i tmpResult = _mm_and_si128(_mm_cmpgt_epi16(f, h), v_two);
__m128i backtraceActionVec = _mm_load_si128(backtraceAction + (i * numVec + j));
__m128i tmpResult2 = _mm_andnot_si128(tmpResult, backtraceActionVec);
backtraceActionVec = _mm_or_si128(tmpResult, tmpResult2);
h = _mm_max_epi16(h, f);
_mm_store_si128(Hminus1ptr + j, h);
max = _mm_max_epi16(max, h);
temp = _mm_subs_epu16(h, v_gapOpen);
f = _mm_subs_epu16(f, v_gapExtend);
tmpResult = _mm_and_si128(_mm_cmpgt_epi16(f, temp), v_thirtytwo);
backtraceActionVec = _mm_or_si128(backtraceActionVec, tmpResult);
_mm_store_si128(backtraceAction + (i * numVec + j), backtraceActionVec);
// Converged if no element of f can influence h
bool converged = !(_mm_movemask_epi8(_mm_cmpgt_epi16(f, temp))); // !! converts int to bool
if (converged) goto got_answer;
}
}
got_answer:
maxScoreRow = getMax(max);
#ifdef TRACE_AG
__m128i rowScore;
for (int i = 0; i < numVec; i++) {
rowScore = _mm_load_si128(Hminus1ptr + i);
printElem(rowScore);
}
printf("\n");
#endif
// Global alignment score (i.e., score when aligning to the end of the pattern)
__m128i v_globalAlignmentScore = _mm_load_si128(Hminus1ptr + ((patternLen - 1) % numVec));
int globalAlignmentScore = getElem((patternLen - 1) / numVec, v_globalAlignmentScore);
if (globalAlignmentScore >= bestGlobalAlignmentScore) {
bestGlobalAlignmentScore = globalAlignmentScore;
bestGlobalAlignmentTextOffset = i;
}
if (maxScoreRow == 0) break;
if (maxScoreRow > bestLocalAlignmentScore) { // If we obtained a better score this round
// Get index in pattern where maximum score was obtained
for (int j = 0; j < numVec; ++j) {
__m128i h = _mm_load_si128(Hminus1ptr + j); // Load a vector of score values
__m128i mask = _mm_cmpeq_epi16(h, _mm_set1_epi16(maxScoreRow)); // Create a mask of 1's in cells where score = maxScoreRow
int result = _mm_movemask_epi8(_mm_packs_epi16(mask, v_zero)); // Convert vector result to 8-bit
unsigned long zeroes;
if (result) {
CountLeadingZeroes(result, zeroes);
int patternOffset = zeroes * numVec + j;
localAlignmentPatternOffset = (localAlignmentPatternOffset > patternOffset) ? localAlignmentPatternOffset : patternOffset;
_ASSERT(localAlignmentPatternOffset < patternLen); // Scores outside the pattern boundaries should never be the maximum in the row
}
}
bestLocalAlignmentScore = maxScoreRow;
bestLocalAlignmentTextOffset = i;
bestLocalAlignmentPatternOffset = localAlignmentPatternOffset;
}
// Swap roles of H and Hminus1 for the next row
__m128i* hTemp = Hminus1ptr;
Hminus1ptr = Hptr;
Hptr = hTemp;
} // end text
// Choose between local and global alignment for patternOffset
if ((bestLocalAlignmentScore != bestGlobalAlignmentScore) && (bestLocalAlignmentScore >= bestGlobalAlignmentScore + endBonus)) {
// Local alignment preferred
*o_patternOffset = bestLocalAlignmentPatternOffset;
*o_textOffset = bestLocalAlignmentTextOffset;
score = bestLocalAlignmentScore;
if (useClippingOptimizations) {
//
// Check if we can match more bases near the end of the soft-clipped read by deleting a character from the reference.
// This helps reduce some INDEL false negatives introduced by using a high gap open penalty
//
int patternOffsetAdj = *o_patternOffset - 1;
int textOffsetAdj = *o_textOffset;
int countEndMatches = 0;
while ((patternOffsetAdj + 1 != patternLen) && pattern[patternOffsetAdj + 1] == *(text + (textOffsetAdj + 1) * TEXT_DIRECTION)) {
countEndMatches++;
patternOffsetAdj++;
textOffsetAdj++;
}
if (countEndMatches >= 3) { // matched too few bases, don't use the alignment with deletion. FIXME: check if 3 is enough!
*o_patternOffset = patternOffsetAdj;
*o_textOffset = textOffsetAdj;
}
else {
//
// Check if we can match more bases near the end of the soft-clipped read by inserting a character to the pattern.
// This helps reduce some INDEL false negatives introduced by using a high gap open penalty
//
patternOffsetAdj = *o_patternOffset + 1;
textOffsetAdj = *o_textOffset;
countEndMatches = 0;
while ((patternOffsetAdj < patternLen) && pattern[patternOffsetAdj] == *(text + (textOffsetAdj)*TEXT_DIRECTION)) {
countEndMatches++;
patternOffsetAdj++;
textOffsetAdj++;
}
if (countEndMatches >= 3) { // matched too few bases, don't use the alignment with insertion. FIXME: check if 3 is enough!
*o_patternOffset = patternOffsetAdj - 1;
*o_textOffset = textOffsetAdj - 1;
}
}
if (*o_patternOffset == bestLocalAlignmentPatternOffset && *o_textOffset == bestLocalAlignmentTextOffset) {
patternOffsetAdj = *o_patternOffset;
textOffsetAdj = *o_textOffset;
if (!useAltLiftover) { // base quality aware optimization leads to spurious INDELs at the ends of reads after liftover. Disabled
//
// Try not to clip high quality bases (>= 65) from the read. These will be reported as insertions in the final alignment
//
int countInsertions = 0;
while (patternOffsetAdj != patternLen - 1 && qualityString[patternOffsetAdj] >= 65 && qualityString[patternOffsetAdj + 1] >= 65) {
patternOffsetAdj += 1;
countInsertions++;
}
if (patternOffsetAdj == patternLen - 1) {
*o_patternOffset = patternOffsetAdj;
}
else if (patternOffsetAdj >= *o_patternOffset + 2) {
int tmpOffset = patternOffsetAdj + 1;
int countRemHighQualityBases = 0;
int remPatternLen = patternLen - tmpOffset;
while (tmpOffset != patternLen - 1) {
if (qualityString[tmpOffset] >= 65) {
countRemHighQualityBases++;
}
tmpOffset++;
}
_ASSERT(remPatternLen != 0);
if (((float)countRemHighQualityBases) / remPatternLen < 0.1) {
*o_patternOffset = patternOffsetAdj;
}
}
}
}
}
}
else {
// Global alignment preferred
*o_patternOffset = patternLen - 1;
*o_textOffset = bestGlobalAlignmentTextOffset;
score = bestGlobalAlignmentScore;
}
if (score > scoreInit) {
// Perform traceback and compute nEdits
int rowIdx = *o_textOffset, colIdx = *o_patternOffset, matrixIdx;
BacktraceActionType action = M, prevAction = M;
int actionCount = 1;
int nMatches = 0, nMismatches = 0, nGaps = 0;
// Start traceback from the cell (i,j) with the maximum score
while (rowIdx >= 0 && colIdx >= 0) {
uint16_t* backtracePointersRow = (uint16_t*)(backtraceAction + (rowIdx * numVec));
//
// The traceback matrix (H, E, or F) we need to look at depends on the current action.
// We index the corresponding matrix using the current action as described below:
// If current action is M, bits[1:0] are used
// If current action is D, bits[3:2] are used
// If current action is I, bits[5:4] are used
//
matrixIdx = action << 1;
//
// Two bits are used to encode the backtrace action type
//
int stripedColIdx = (colIdx % numVec) * VEC_SIZE + (colIdx / numVec);
action = (BacktraceActionType) ((backtracePointersRow[stripedColIdx] >> matrixIdx) & 3);
if (action == M) {
if (pattern[colIdx] != text[rowIdx * TEXT_DIRECTION]) {
// Compute probabilties of mismatches
*matchProbability *= lv_phredToProbability[qualityString[colIdx]];
nMismatches++;
}
else {
nMatches++;
}
rowIdx--; colIdx--;
}
else if (action == D) {
rowIdx--;
}
else { // action == I
colIdx--;
action = I; // FIXME: we choose I, whenever action == 2 or 3. Make action == 2, since matrixIdx depends on it
}
// Ignore transitions from H. Compute number of indels in sequence for matchProbability
if (prevAction != M) {
if (prevAction == action) {
actionCount++;
}
else {
// Update match probabilties with indel probabilties here
nGaps += actionCount;
*matchProbability *= lv_indelProbabilities[actionCount];
actionCount = 1;
}
}
prevAction = action;
}
if (rowIdx >= 0) { // deletion just after the seed
actionCount = rowIdx + 1;
nGaps += actionCount;
*matchProbability *= lv_indelProbabilities[actionCount];
}
if (colIdx >= 0) { // insertion just after the seed
actionCount = colIdx + 1;
nGaps += actionCount;
*matchProbability *= lv_indelProbabilities[actionCount];
}
*o_nEdits = nMismatches + nGaps;
// *o_nEdits = (*o_nEdits <= w) ? *o_nEdits : -1; // return -1 if we have more edits than threshold w
*matchProbability *= lv_perfectMatchProbability[nMatches];
*o_textOffset += 1;
*o_patternOffset += 1;
*o_textOffset = patternLen - *o_textOffset;
*o_patternOffset = patternLen - *o_patternOffset;
*matchProbability *= lv_indelProbabilities[*o_patternOffset];
return score;
}
else {
return -1;
}
}
void *operator new(size_t size) { return BigAlloc(size); }
void operator delete(void *ptr) { BigDealloc(ptr); }
void *operator new(size_t size, BigAllocator *allocator) { _ASSERT(size == sizeof(AffineGapVectorized<TEXT_DIRECTION>)); return allocator->allocate(size); }
void operator delete(void *ptr, BigAllocator *allocator) {/*Do nothing. The memory is freed when the allocator is deleted.*/ }
private:
//
// Scores for each nucleotide <-> nucleotide transition
//
int ntTransitionMatrix[MAX_ALPHABET_SIZE * MAX_ALPHABET_SIZE];
//
// Affine gap scoring parameters
//
int matchReward;
int subPenalty;
int gapOpenPenalty;
int gapExtendPenalty;
int fivePrimeEndBonus;
int threePrimeEndBonus;
__m128i qProfile[MAX_ALPHABET_SIZE * MAX_VEC_SEGMENTS];
__m128i H[MAX_VEC_SEGMENTS];
__m128i Hminus1[MAX_VEC_SEGMENTS];
__m128i E[MAX_VEC_SEGMENTS];
//
// Pointers to traceback alignment, one for each of the three affine-gap matrices, F, E and H
// Traceback actions are encoded as follows: Bit 5 to Bit 0 - F[5:4], E[3:2], H[1:0]
// Although we need only 1 bit to encode paths into E and F matrix, we use 2 bits to simplify decoding
//
__m128i backtraceAction[(MAX_READ_LENGTH + MAX_K) * MAX_VEC_SEGMENTS];
};
class AffineGapVectorizedWithCigar {
public:
AffineGapVectorizedWithCigar();
AffineGapVectorizedWithCigar(int i_matchReward, int i_subPenalty, int i_gapOpenPenalty, int i_gapExtendPenalty);
void init(int i_matchReward, int i_subPenalty, int i_gapOpenPenalty, int i_gapExtendPenalty);
// Compute the affine gap score between two strings and write the CIGAR string in cigarBuf.
// Returns -1 if the edit distance exceeds k or -2 if we run out of space in cigarBuf.
int computeGlobalScore(const char* text, int textLen, const char* pattern, const char* quality, int patternLen, int w,
char* cigarBuf, int cigarBufLen, bool useM,
CigarFormat format = COMPACT_CIGAR_STRING,
int* o_cigarBufUsed = NULL, int *o_netDel = NULL, int *o_tailIns = NULL);
int computeGlobalScoreBanded(const char* text, int textLen, const char* pattern, const char* quality, int patternLen, int w, int scoreInit,
char* cigarBuf, int cigarBufLen, bool useM,
CigarFormat format = COMPACT_CIGAR_STRING,
int* o_cigarBufUsed = NULL, int* o_netDel = NULL, int* o_tailIns = NULL);
int computeGlobalScoreNormalized(const char* text, int textLen,
const char* pattern, const char* quality, int patternLen,
int k,
char *cigarBuf, int cigarBufLen, bool useM,
CigarFormat format, int* o_cigarBufUsed,
int* o_addFrontClipping, int *o_netDel = NULL, int* o_tailIns = NULL);
bool writeCigar(char** o_buf, int* o_buflen, int count, char code, CigarFormat format);
private:
//
// Scores for each nucleotide <-> nucleotide transition
//
int ntTransitionMatrix[MAX_ALPHABET_SIZE * MAX_ALPHABET_SIZE];
//
// Affine gap scoring parameters
//
int matchReward;
int subPenalty;
int gapOpenPenalty;
int gapExtendPenalty;
int minScoreParam;
int maxScoreParam;
//
// Precompute query profile which is a table containing the result of
// matching each letter of the alphabet with each character of the pattern
// and filling in the appropriate transition score from the ntTransMatrix.
// This precomputation saves looking up the ntTransition matrix for each
// (ref_i, query_j) in the inner dynamic programming loop.
//
__m128i qProfile[MAX_ALPHABET_SIZE * MAX_VEC_SEGMENTS];
//
// H and E arrays used for storing scores in every row
//
__m128i H[MAX_VEC_SEGMENTS];
__m128i Hminus1[MAX_VEC_SEGMENTS];
__m128i E[MAX_VEC_SEGMENTS];
//
// Pointers to traceback alignment, one for each of the three affine-gap matrices, F, E and H
// Traceback actions are encoded as follows: Bit 5 to Bit 0 - F[5:4], E[3:2], H[1:0]
// Although we need only 1 bit to encode paths into E and F matrix, we use 2 bits to simplify decoding
//
__m128i backtraceAction[(MAX_READ_LENGTH + MAX_K) * MAX_VEC_SEGMENTS];
//
// Structure used for storing (action, count) pairs from backtracking
//
typedef struct {
BacktraceActionType action[MAX_READ_LENGTH];
int count[MAX_READ_LENGTH];
} LocalCigarResult;
LocalCigarResult res;
int computeFinalCigarString(
const char* text,
int textLen,
const char* pattern,
int patternLen,
int n_res,
int min_i,
const char *cigarBufStart,
char** cigarBuf,
int cigarBufLen,
bool useM,
CigarFormat format,
int* o_cigarBufUsed,
int* o_netDel
);
};
| {
"content_hash": "3189030584fe04d69222830d3c1df17b",
"timestamp": "",
"source": "github",
"line_count": 1474,
"max_line_length": 160,
"avg_line_length": 40.434871099050206,
"alnum_prop": 0.5107632422274794,
"repo_name": "amplab/snap",
"id": "e6a04096c6f4fda4aaecdaa38b32985842d86198",
"size": "59601",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SNAPLib/AffineGapVectorized.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "810"
},
{
"name": "C",
"bytes": "399915"
},
{
"name": "C++",
"bytes": "1998993"
},
{
"name": "Makefile",
"bytes": "2040"
},
{
"name": "Python",
"bytes": "13516"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace FeedIo;
use FeedIo\Parser\JsonParser;
use FeedIo\Parser\XmlParser;
use FeedIo\Reader\Fixer\HttpLastModified;
use FeedIo\Reader\Fixer\PublicId;
use FeedIo\Reader\FixerAbstract;
use FeedIo\Reader\FixerSet;
use FeedIo\Rule\DateTimeBuilder;
use FeedIo\Rule\DateTimeBuilderInterface;
use FeedIo\Standard\Atom;
use FeedIo\Standard\Json;
use FeedIo\Standard\Rdf;
use FeedIo\Standard\Rss;
use Psr\Log\LoggerInterface;
use OutOfRangeException;
class Specification implements SpecificationInterface
{
protected array $standards;
protected FixerSet $fixerSet;
public function __construct(
protected LoggerInterface $logger,
protected ?DateTimeBuilderInterface $dateTimeBuilder = null,
) {
if (is_null($this->dateTimeBuilder)) {
$this->dateTimeBuilder = new DateTimeBuilder($this->logger);
}
$this->standards = $this->getDefaultStandards();
$this->fixerSet = new FixerSet();
/** @var FixerAbstract $fixer */
foreach ([new HttpLastModified(), new PublicId()] as $fixer) {
$fixer->setLogger($this->logger);
$this->fixerSet->add($fixer);
}
}
/**
* If you need to replace an existing standard with one of yours, you can extend the class and override this method
* to redefine the list of default standards.
*
* @return array
*/
protected function getDefaultStandards(): array
{
return [
'json' => new Json($this->dateTimeBuilder),
'atom' => new Atom($this->dateTimeBuilder),
'rss' => new Rss($this->dateTimeBuilder),
'rdf' => new Rdf($this->dateTimeBuilder),
];
}
/**
* Adds a new standard to the set, unless you specify a name already taken like 'rss' so you'll overwrite it.
*
* @param string $name
* @param StandardAbstract $standard
* @return $this
*/
public function addStandard(string $name, StandardAbstract $standard): self
{
$name = strtolower($name);
$this->standards[$name] = $standard;
return $this;
}
public function getStandard(string $name): StandardAbstract
{
if (array_key_exists($name, $this->standards)) {
return $this->standards[$name];
}
throw new OutOfRangeException("No standard found for $name");
}
public function getAllStandards(): array
{
return $this->standards;
}
public function getFixerSet(): FixerSet
{
return $this->fixerSet;
}
public function getDateTimeBuilder(): DateTimeBuilderInterface
{
return $this->dateTimeBuilder;
}
public function newParser(string $format, StandardAbstract $standard): ParserAbstract
{
if (strtolower($format) === 'json') {
return new JsonParser($standard, $this->logger);
}
return new XmlParser($standard, $this->logger);
}
}
| {
"content_hash": "04aad703e07d7ec882d46af6badf8f8d",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 119,
"avg_line_length": 27.925233644859812,
"alnum_prop": 0.6358768406961178,
"repo_name": "OleVik/grav-plugin-twigfeeds",
"id": "4699aefef784aa10bef1b4d748cce5cd7e936268",
"size": "2988",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "vendor/debril/feed-io/src/FeedIo/Specification.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "46032"
}
],
"symlink_target": ""
} |
require_relative '../../spec_helper'
module Asana
describe Tag do
before do
VCR.insert_cassette('tags', :record => :all)
Asana.configure do |c|
c.api_key = ENV['ASANA_API_KEY']
end
end
after do
VCR.eject_cassette
end
describe '.all' do
it 'should return all of the user\'s tags' do
tags = Tag.all
tags.must_be_instance_of Array
tags.first.must_be_instance_of Tag
end
end
describe '.create' do
it 'should raise an ActiveResource::MethodNotAllowed exception' do
tag = Tag.new
lambda { tag.save }.must_raise ActiveResource::MethodNotAllowed
end
end
describe '.find' do
it 'should return a single tag' do
tag = Tag.find(Tag.all.first.id)
tag.must_be_instance_of Tag
end
end
describe '#destroy' do
it 'should raise an ActiveResource::MethodNotAllowed exception' do
tag = Tag.all.first
lambda { tag.destroy}.must_raise ActiveResource::MethodNotAllowed
end
end
describe '#modify' do
it 'should modify the given tag with a new name' do
tag = Workspace.all.first.create_tag(:name => 'asana-test-tag-foo')
tag.modify(:name => 'asana-test-tag-bar').name.must_equal 'asana-test-tag-bar'
end
end
describe '#tasks' do
it 'should return all tasks for the given tag' do
tag = Tag.all.first
tasks = tag.tasks
tasks.must_be_instance_of Array
tasks.first.must_be_instance_of Task
end
end
end
end
| {
"content_hash": "b5e497e9cbe703d03e348bbc8a25b91a",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 86,
"avg_line_length": 25.063492063492063,
"alnum_prop": 0.609879670677644,
"repo_name": "suhongrui/gitlab",
"id": "36f9600169fbbbee56a128bf9f536d6ac109ce21",
"size": "1579",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vendor/bundle/ruby/2.1.0/gems/asana-0.0.6/spec/asana/resources/tag_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "113763"
},
{
"name": "CoffeeScript",
"bytes": "109865"
},
{
"name": "Cucumber",
"bytes": "113031"
},
{
"name": "HTML",
"bytes": "372689"
},
{
"name": "JavaScript",
"bytes": "29449"
},
{
"name": "Ruby",
"bytes": "1841958"
},
{
"name": "Shell",
"bytes": "12768"
}
],
"symlink_target": ""
} |
// Copyright (c) 2012-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clientversion.h"
#include "tinyformat.h"
#include <string>
/**
* Name of client reported in the 'version' message. Report the same name
* for both worldbitd and worldbit-qt, to make it harder for attackers to
* target servers or GUI users specifically.
*/
const std::string CLIENT_NAME("Worldbit Core");
/**
* Client version number
*/
#define CLIENT_VERSION_SUFFIX ""
/**
* The following part of the code determines the CLIENT_BUILD variable.
* Several mechanisms are used for this:
* * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
* generated by the build environment, possibly containing the output
* of git-describe in a macro called BUILD_DESC
* * secondly, if this is an exported version of the code, GIT_ARCHIVE will
* be defined (automatically using the export-subst git attribute), and
* GIT_COMMIT will contain the commit id.
* * then, three options exist for determining CLIENT_BUILD:
* * if BUILD_DESC is defined, use that literally (output of git-describe)
* * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
* * otherwise, use v[maj].[min].[rev].[build]-unk
* finally CLIENT_VERSION_SUFFIX is added
*/
//! First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#include "build.h"
#endif
//! git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
#define GIT_COMMIT_ID "$Format:%h$"
#define GIT_COMMIT_DATE "$Format:%cD$"
#endif
#define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix)
#define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
#ifdef BUILD_SUFFIX
#define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)
#elif defined(GIT_COMMIT_ID)
#define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#else
#define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#endif
#endif
#ifndef BUILD_DATE
#ifdef GIT_COMMIT_DATE
#define BUILD_DATE GIT_COMMIT_DATE
#else
#define BUILD_DATE __DATE__ ", " __TIME__
#endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
static std::string FormatVersion(int nVersion)
{
if (nVersion % 100 == 0)
return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100);
else
return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100);
}
std::string FormatFullVersion()
{
return CLIENT_BUILD;
}
/**
* Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki)
*/
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
{
std::vector<std::string>::const_iterator it(comments.begin());
ss << "(" << *it;
for(++it; it != comments.end(); ++it)
ss << "; " << *it;
ss << ")";
}
ss << "/";
return ss.str();
}
| {
"content_hash": "8e76a9d94b0d4d6a4fed18530c777a00",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 147,
"avg_line_length": 35.6875,
"alnum_prop": 0.6887665749311984,
"repo_name": "worldbit/worldbit",
"id": "c3fbbee769c1def98bfc51a2ec3ba83993fff640",
"size": "3997",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/clientversion.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1315071"
},
{
"name": "C++",
"bytes": "5307484"
},
{
"name": "CSS",
"bytes": "124359"
},
{
"name": "HTML",
"bytes": "50621"
},
{
"name": "Java",
"bytes": "2100"
},
{
"name": "M4",
"bytes": "147950"
},
{
"name": "Makefile",
"bytes": "97518"
},
{
"name": "Objective-C",
"bytes": "4965"
},
{
"name": "Objective-C++",
"bytes": "7232"
},
{
"name": "Protocol Buffer",
"bytes": "2308"
},
{
"name": "Python",
"bytes": "706785"
},
{
"name": "QMake",
"bytes": "2059"
},
{
"name": "Roff",
"bytes": "3844"
},
{
"name": "Shell",
"bytes": "35823"
}
],
"symlink_target": ""
} |
from __future__ import division, with_statement
import platform
import numpy as np
import pyfits as fits
from . import PyfitsTestCase
from .util import ignore_warnings
class TestUintFunctions(PyfitsTestCase):
utypes = ('u2', 'u4', 'u8')
utype_map = {'u2' :np.uint16, 'u4': np.uint32, 'u8': np.uint64}
itype_map = {'u2': np.int16, 'u4': np.int32, 'u8': np.int64}
format_map = {'u2': 'I', 'u4': 'J', 'u8': 'K'}
def test_uint(self):
# Test of 64-bit compressed image is disabled. cfitsio library doesn't
# seem to like it
# TODO: Confirm whether the 64-bit compressed case is still broken on
# CFITSIO
for utype, compressed in [
('u2',False), ('u4',False), ('u8',False), ('u2',True),
('u4',True)]: # ,('u8',True)
self._test_uint(utype, compressed)
def _test_uint(self, utype, compressed):
bits = 8 * int(utype[1])
if platform.architecture()[0] == '64bit' or bits != 64:
if compressed:
hdu = fits.CompImageHDU(np.array([-3, -2, -1, 0, 1, 2, 3]))
hdu_number = 1
else:
hdu = fits.PrimaryHDU(np.array([-3, -2, -1, 0, 1, 2, 3]))
hdu_number = 0
hdu.scale('int%s' % bits, '', bzero=2 ** (bits-1))
with ignore_warnings():
hdu.writeto(self.temp('tempfile.fits'), clobber=True)
with fits.open(self.temp('tempfile.fits'), uint=True) as hdul:
assert hdul[hdu_number].data.dtype == self.utype_map[utype]
assert (hdul[hdu_number].data == np.array(
[(2 ** bits) - 3, (2 ** bits) - 2, (2 ** bits) - 1,
0, 1, 2, 3],
dtype=self.utype_map[utype])).all()
with ignore_warnings():
hdul.writeto(self.temp('tempfile1.fits'), clobber=True)
with fits.open(self.temp('tempfile1.fits'),
uint16=True) as hdul1:
d1 = hdul[hdu_number].data
d2 = hdul1[hdu_number].data
assert (d1 == d2).all()
if not compressed:
# TODO: Enable these lines if CompImageHDUs ever grow
# .section support
sec = hdul[hdu_number].section[:1]
assert sec.dtype.name == 'uint%s' % bits
assert (sec == d1[:1]).all()
def test_uint_columns(self):
"""Test basic functionality of tables with columns containing
pseudo-unsigned integers. See
https://github.com/astropy/astropy/pull/906
"""
for utype in ('u2', 'u4', 'u8'):
self._test_uint_columns(utype)
def _test_uint_columns(self, utype):
# Construct array
bits = 8*int(utype[1])
if platform.architecture()[0] == '64bit' or bits != 64:
bzero = self.utype_map[utype](2**(bits-1))
one = self.utype_map[utype](1)
u0 = np.arange(bits+1,dtype=self.utype_map[utype])
u = 2**u0 - one
if bits == 64:
u[63] = bzero - one
u[64] = u[63] + u[63] + one
uu = (u - bzero).view(self.itype_map[utype])
# Construct a table from explicit column
col = fits.Column(name=utype, array=u,
format=self.format_map[utype], bzero=bzero)
table = fits.BinTableHDU.from_columns([col])
assert (table.data[utype] == u).all()
# This used to be table.data.base, but now after adding a table to
# a BinTableHDU it gets stored as a view of the original table,
# even if the original was already a FITS_rec. So now we need
# table.data.base.base
assert (table.data.base.base[utype] == uu).all()
hdu0 = fits.PrimaryHDU()
hdulist = fits.HDUList([hdu0,table])
with ignore_warnings():
hdulist.writeto(self.temp('tempfile.fits'), clobber=True)
# Test write of unsigned int
del hdulist
with fits.open(self.temp('tempfile.fits'), uint=True) as hdulist2:
hdudata = hdulist2[1].data
assert (hdudata[utype] == u).all()
assert (hdudata[utype].dtype == self.utype_map[utype])
assert (hdudata.base[utype] == uu).all()
# Construct recarray then write out that.
v = u.view(dtype=[(utype, self.utype_map[utype])])
with ignore_warnings():
fits.writeto(self.temp('tempfile2.fits'), v, clobber=True)
with fits.open(self.temp('tempfile2.fits'), uint=True) as hdulist3:
hdudata3 = hdulist3[1].data
assert (hdudata3.base[utype] ==
table.data.base.base[utype]).all()
assert (hdudata3[utype] == table.data[utype]).all()
assert (hdudata3[utype] == u).all()
| {
"content_hash": "c6b1d61207e31c0c7fa6a0dd1f99afed",
"timestamp": "",
"source": "github",
"line_count": 122,
"max_line_length": 79,
"avg_line_length": 41.59016393442623,
"alnum_prop": 0.5147812376823019,
"repo_name": "embray/PyFITS",
"id": "a85c32a198f3abfdd668d4b0965ed4d0b85abac2",
"size": "5074",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/pyfits/tests/test_uint.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "4758355"
},
{
"name": "C++",
"bytes": "14224"
},
{
"name": "CSS",
"bytes": "587"
},
{
"name": "Objective-C",
"bytes": "30568"
},
{
"name": "Python",
"bytes": "1178644"
},
{
"name": "Shell",
"bytes": "3075"
}
],
"symlink_target": ""
} |
package org.wso2.carbon.esb.mediator.test.iterate;
import org.apache.axis2.AxisFault;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.esb.integration.common.utils.ESBIntegrationTest;
import org.wso2.esb.integration.common.utils.ESBTestConstant;
import static org.testng.Assert.assertTrue;
/**
* This class will test Iterator Mediator, when there is no iterator expression specified.
*/
public class IterateExpressionLessTestCase extends ESBIntegrationTest {
@BeforeClass(alwaysRun = true)
public void uploadSynapseConfig() throws Exception {
super.init();
}
/**
* This is a negative test under iterator mediator.It will not specify an iterator expression and will try to create
* a sequence.A sequence cannot be created because SequenceMediator Sequence named Value cannot be found.
*/
@Test(groups = {"wso2.esb"}, description = "Testing when there is no iterate expression is specified")
public void testIterateExpressionLessSequenceAdding() throws Exception {
try {
loadESBConfigurationFromClasspath("/artifacts/ESB/mediatorconfig/iterate/iterator_expressionLess.xml");
Assert.fail("This Configuration can not be saved successfully"); // This will execute when the exception is not thrown as expected
} catch (AxisFault message) {
assertTrue(message.getMessage().contains(ESBTestConstant.ERROR_ADDING_SEQUENCE)
, "Error adding sequence : null not contain in Error Message");
}
}
@AfterClass(alwaysRun = true)
public void close() throws Exception {
super.cleanup();
}
}
| {
"content_hash": "5a6c7bace6918608537bbfd1bdc9667c",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 142,
"avg_line_length": 37.255319148936174,
"alnum_prop": 0.7292975442604226,
"repo_name": "mpmunasinghe/product-ei",
"id": "1245bf2c8ead3b28675629ee959a32ee0652bcff",
"size": "2398",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "integration/mediation-tests/tests-mediator-1/src/test/java/org/wso2/carbon/esb/mediator/test/iterate/IterateExpressionLessTestCase.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "85589"
},
{
"name": "CSS",
"bytes": "195050"
},
{
"name": "HTML",
"bytes": "43922"
},
{
"name": "Java",
"bytes": "6632897"
},
{
"name": "JavaScript",
"bytes": "5393945"
},
{
"name": "PLSQL",
"bytes": "10466"
},
{
"name": "PLpgSQL",
"bytes": "18229"
},
{
"name": "Ruby",
"bytes": "13608"
},
{
"name": "Shell",
"bytes": "276368"
},
{
"name": "XSLT",
"bytes": "39758"
}
],
"symlink_target": ""
} |
var express = require('express');
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var yargs = require('yargs');
var args = yargs
.alias('p', 'production')
.argv;
var app = new express();
var port = 8000;
process.env.NODE_ENV = args.production ? 'production' : 'development';
console.log('NODE_ENV => ', process.env.NODE_ENV);
// In development mode serve the scripts using webpack-dev-middleware
if (process.env.NODE_ENV === 'development') {
var config = require('../../webpack.config');
var compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
app.use(webpackHotMiddleware(compiler));
} else {
app.use('/dist', express.static('dist', {maxAge: '200d'}));
}
app.use('/assets', express.static('assets', {maxAge: '200d'}));
app.get("*", function(req, res) {
res.sendFile(__dirname + '/index.html');
})
app.listen(port, function(error) {
if (error) {
console.error(error);
} else {
console.info("==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port);
}
})
| {
"content_hash": "c93c37e8a32fe67c59816c7975109cb7",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 107,
"avg_line_length": 30.923076923076923,
"alnum_prop": 0.6749585406301825,
"repo_name": "mareksuscak/surfing-gallery",
"id": "ce1e5d3a0056d6b16cf4b85c9187ef52f0c15a77",
"size": "1209",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/server/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3355"
},
{
"name": "HTML",
"bytes": "189"
},
{
"name": "JavaScript",
"bytes": "17161"
}
],
"symlink_target": ""
} |
package com.netflix.astyanax.partitioner;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import org.apache.cassandra.dht.RandomPartitioner;
import com.google.common.collect.Lists;
import com.netflix.astyanax.connectionpool.TokenRange;
import com.netflix.astyanax.connectionpool.impl.TokenRangeImpl;
public class BigInteger127Partitioner implements Partitioner {
public static final BigInteger MINIMUM = new BigInteger("" + 0);
public static final BigInteger MAXIMUM = new BigInteger("" + 2).pow(127);
public static final BigInteger ONE = new BigInteger("1");
private static final RandomPartitioner partitioner = new RandomPartitioner();
@Override
public String getMinToken() {
return MINIMUM.toString();
}
@Override
public String getMaxToken() {
return MAXIMUM.toString();
}
@Override
public List<TokenRange> splitTokenRange(String first, String last, int count) {
List<TokenRange> tokens = Lists.newArrayList();
for (int i = 0; i < count; i++) {
String startToken = getTokenMinusOne(getSegmentToken(count, i, new BigInteger(first), new BigInteger(last)));
String endToken;
if (i == count-1 && last.equals(getMaxToken()))
endToken = getMinToken();
else
endToken = getSegmentToken(count, i+1, new BigInteger(first), new BigInteger(last));
tokens.add(new TokenRangeImpl(startToken, endToken, new ArrayList<String>()));
}
return tokens;
}
@Override
public List<TokenRange> splitTokenRange(int count) {
return splitTokenRange(getMinToken(), getMaxToken(), count);
}
@Override
public String getTokenForKey(ByteBuffer key) {
return partitioner.getToken(key).toString();
}
@Override
public String getTokenMinusOne(String token) {
BigInteger bigInt = new BigInteger(token);
// if zero rotate to the Maximum else minus one.
if (bigInt.equals(MINIMUM))
return MAXIMUM.toString();
else
return bigInt.subtract(ONE).toString();
}
public static String getSegmentToken(int size, int position, BigInteger minInitialToken, BigInteger maxInitialToken ) {
BigInteger decValue = minInitialToken;
if (position != 0)
decValue = maxInitialToken.multiply(new BigInteger("" + position)).divide(new BigInteger("" + size));
return decValue.toString();
}
}
| {
"content_hash": "d5b0cbed8b2c4be06717a6d1733d9ab5",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 123,
"avg_line_length": 34.5,
"alnum_prop": 0.6709753231492362,
"repo_name": "0x6e6562/astyanax",
"id": "0b3357b073268b334b1ea27d3a46d2accf4f0be1",
"size": "2553",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/netflix/astyanax/partitioner/BigInteger127Partitioner.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
class AudiosController < ApplicationController
helper :categories, :comments, :feed, :forums, :licenses, :maps, :markup, :medias,
:render_controls, :configuration
#mixin in the markers_to_markup from maps_helper
include MapsHelper
#media controller helper mixin
include MediasControllerHelper
#common controller mixinc
include MediasCommonMixin
before_filter :login_required,
:only => [:upload, :job_list, :categorise, :delete, :edit, :download, :favourite, :favourites, :stat_audios,
:admin_delete, :admin_delete_reason, :library, :my, :update, :preferences, :recode_all_user, :recode_audio]
cache_sweeper :media_sweeper, :only => [ :delete, :update, :categorise ]
def index
@page_title = 'Viewing Popular Audio Files'
end
def view
@media = safe_find(params[:id])
valid_request_object_do(@media, 'Audio not found or is awaiting approval') do
get_licenses_and_calc_price if request.post? #this is here cos requires by both html and js handlers
respond_to do |format|
format.html do
get_media_lic_options_and_price
if params[:submit_buy] && request.post?
Order.transaction do
order = get_order_from_session
order = Order.add_media_to_order(order, @media, request.remote_ip, { :licenses => @licenses})
session[:order_id] = order.id
end
#done... redirect to cart
redirect_to orders_cart_path
else
@page_title = @media.title
Media.increment_views_count(@media, current_user)
@my_tags = @media.my_tag_names(current_user) if logged_in?
@audios_by_tag = @media.similar_taggables(:limit => 8, :conditions => 'approved = 1')
@comment = flash[:failed] || Comment.new
@can_edit = @media.can_edit(current_user)
end
end
format.js do
if request.post?
render :text => @price
else
render :partial => 'audios/popup_details', :locals => {:audio => @media}
end
end
end
end
end
def upload
@page_title = 'Upload Audio Files'
@unsorted = current_user.audios.unsorted.converted
@jobs = Job.add_position_to_jobs(current_user.audio_jobs.not_failed)
end
def preferences
@page_title = 'Audio File Preferences'
@prefs = current_user.audio_preferences
#
return unless request.post?
#saving
@prefs = UserAudioPreference.find_or_initialize_by_user_id(params[:id])
@prefs.attributes = params[:prefs]
@prefs.save
#
flash[:notice] = 'Audio preferences saved' if @prefs.errors.blank?
end
def recode_all_user
JobSpinner.spin_job do
Job.enqueue_onto_queue!(:long, BackgroundWorker, :recode_all_user_audio,
"Recode User #{current_user.login} Audio Files ",
{:user_id => current_user.id})
end
flash[:notice] = 'Audio Recode job queued. An email will be sent once the job is complete'
#
@page_title = 'Audio File Preferences'
@prefs = current_user.audio_preferences
render :action => :preferences
end
def recode_audio
audio = Audio.find_by_id params[:id]
valid_request_object_do(audio) do
if audio.can_edit(current_user)
properties = MediaAudioProperty.find_or_initialize_by_audio_id(audio.id)
properties.attributes = params[:properties]
if properties.save
JobSpinner.spin_job do
Job.enqueue_onto_queue!(:long, BackgroundWorker, :recode_audio, "Recode Audio File ID: #{audio.id} ",
{:audio_id => audio.id})
end
flash[:notice] = "Audio Recode job queued. Please wait a moment while we recode: #{audio.title}"
redirect_to audio_path(audio)
else
edit(properties)
end
else
redirect_to audio_path(audio)
end
end
end
def upload_audio
return(render :nothing => true, :status => 401) unless request.post?
user = User.find_by_token(params[:id])
unless user.nil?
#save and schedule conversion job
unless params[:Filedata].blank?
begin
status = Audio.save_and_queue_audio_job(params[:Filedata], user)
if status > 0
logger.fatal("ERROR - Audio Processing: #{Audio.status_to_text(status)}")
render :text => 'error', :status => 500 + status
else
render :text => 'OK', :status => 200
end
rescue Exception => detail
logger.fatal(['FATAL AUDIO ERROR - Audio Upload Exception.', detail.message, detail.backtrace.join("\n")].join{"\n"})
#send back a status 500
render :text => 'failed', :status => 500
end
else
render :nothing => true, :status => 515
end
else
render :nothing => true, :status => 520
end
end
def categorise
return(render :nothing => true, :status => 401) unless request.post?
audios = params[:audio]
#iterate through videos... get video..apply values then save
@errors = {}
errored = []
Audio.transaction do
audios.each do |id, audio|
if audio.delete(:audio_upload)
Audio.categorise_and_approve_media_by_id(id, audio, params[:categories], current_user) do |v|
errored << v if v.errors.length > 0
end
end
end
end
if errored.length > 0
upload
@unsorted = errored
render :action => :upload
else
redirect_to :action => 'upload'
end
end
#only and admin or video owner can delete a video
def delete
audio = Audio.find_by_id params[:id]
valid_request_object_do(audio) do
if audio.can_delete(current_user)
Audio.transaction { audio.destroy }
respond_to do |format|
format.html { redirect_to audios_path}
format.js do #called from upload
render :update do |page|
page.remove "audio_div_#{audio.id}"
end
end
end
else
render :text => 'Invalid Request', :status => 401
end
end
end
def edit(properties = nil)
@media = Audio.find_by_id(params[:id])
valid_request_object_do(@media, 'Invalid Audio file') do
Audio.transaction do
#setup or update audio licenses incase new ones have been added
MediaLicensePrice.setup_media_licenses_for_media_and_user(@media) if Configuration.multiple_license_prices
end
get_media_lic_options_and_price
#can only edit your own media
if @media.can_edit(current_user)
@selected = @media.categories.collect { |cat| cat.id.to_i }
@properties = properties || @media.audio_properties #called from recode_audio
else
render :action => 'view'
end
end
end
def update
@audio = Audio.find_by_id(params[:id])
valid_request_object_do(@audio) do
#save changes only if I am the owner or admin
if @audio.can_edit(current_user)
Audio.transaction do
#injection prevention... user can set own price here if HTML tag known
@audio.attributes = params[:media]
if current_user.host_plan.can_set_price
#multiple prices can be set here.. check if form param exists.
if params[:license]
MediaLicensePrice.save_media_license_prices(@audio, params[:license])
end
else
@audio.photo_price = Configuration.default_new_media_price if params['photo_price'] && (params['photo_price'].to_f > Configuration.default_new_media_price)
end
@audio.save!
@audio.categories = Category.find(params[:categories])
@audio.tag_with_by_user(params[:media][:text_tags].downcase, current_user) unless params[:media][:text_tags].nil?
#do
end
#clear cache
expire_left_block
redirect_to audio_view_path(@audio.id, @audio.title)
else
render :nothing => true, :status => 401
end
end
end
def favourite
Audio.add_to_favourite_by_media_id_and_user(params[:id], current_user)
respond_to do |format|
format.html {media = Audio.find_by_id(params[:id]); redirect_to audio_view_path(media.id, media.title)}
format.js {render :nothing => true}
end
end
def favourites
@media = Audio.favourited_by(current_user).paginate :page => params[:page], :per_page => Configuration.photos_per_page,
:include => :user, :order => 'medias.created_on DESC'
@page_title = 'My Favourite Audio Files'
end
def stat_audios
@page_title = 'Viewing my Audio Files - By Stats'
@recent = paginate_audio_collection(current_user.audios.most_recent)
@top_rated = paginate_audio_collection(current_user.audios.top_rated)
@most_popular = paginate_audio_collection(current_user.audios.most_popular)
@talked_about = paginate_audio_collection(current_user.audios.most_talked)
end
def admin_delete
can_admin? do
audio = Audio.find(params[:id])
user = audio.user.login
#
Audio.transaction do
UserMailer::deliver_notify_delete_audio(audio, current_user, params[:reason])
audio.destroy
end
expire_left_block
redirect_to "/audios/all_by/#{user}"
end
end
def admin_delete_reason
can_admin? do
@audio = Audio.find_by_id(params[:id])
render :action => :admin_delete_reason, :layout => false
end
end
def library
@page_title = 'My Audio Library'
@lightboxes = Audio.lightboxes.by_user(current_user).paginate :order => 'created_at DESC', :page => params[:lightbox_page],
:per_page => Configuration.photos_per_page
#TODO currently not displaying licenses
@licenses = Audio.licenses.by_user(current_user).paginate :order => 'created_at DESC', :page => params[:license_page]
end
def my
@media = Audio.categorised.approved.by_user(current_user).paginate :page => params[:page], :per_page => Configuration.more_photos_per_page,
:include => :user, :order => 'created_on DESC'
@page_title = 'Viewing my Audio Files'
end
def more_recent
@page_title = 'Viewing Recent Audio Files'
@audios = paginate_audio_collection(Audio.most_recent)
render :action => :more
end
def more_viewed
@page_title = 'Viewing Most Listened Audio Files'
@audios = paginate_audio_collection(Audio.most_popular)
render :action => :more
end
def more_votes
@page_title = 'Viewing Most Voted Audio Files'
@audios = paginate_audio_collection(Audio.most_voted)
render :action => :more
end
def more_discussed
@page_title = 'Viewing Most Talked About Audio Files'
@audios = paginate_audio_collection(Audio.most_talked)
render :action => :more
end
def more_favourites
@page_title = 'Viewing Most Favourited Audio Files'
@audios = paginate_audio_collection(Audio.most_favourited)
render :action => :more
end
def more_sellers
@page_title = 'Viewing Best Selling Audio Files'
@audios = paginate_audio_collection(Audio.best_selling)
render :action => :more
end
def job_list
jobs = Job.add_position_to_jobs(current_user.audio_jobs.not_failed)
unless jobs.nil?
respond_to do |format|
format.js {render :partial => 'jobs/list', :locals => {:jobs => jobs}}
format.xml {jobs.to_xml}
format.html{render :nothing => true, :status => 401}
end
else
render :nothing => true
end
end
def markers
markers = Audio.media_markers_by_class.all :limit => 500
render :text => markers_to_markup(markers)
end
def user_markers
user = User.find(params[:id])
markers = user.audio_markers
render :text => markers_to_markup(markers)
end
protected
def safe_find(id)
if admin?
Audio.find_by_id(id)
else
Audio.get(id)
end
end
def paginate_audio_collection(collection, options={})
options[:page] ||= params[:page]
options[:per_page] ||= Configuration.more_photos_per_page
collection.paginate :page => options[:page], :per_page => options[:per_page]
end
end
| {
"content_hash": "eeb9121049ed323b9418fc8338fafb35",
"timestamp": "",
"source": "github",
"line_count": 375,
"max_line_length": 168,
"avg_line_length": 33.114666666666665,
"alnum_prop": 0.6168465131261073,
"repo_name": "nazar/MediaCMS",
"id": "cb793eda349b1ce0fc8a288c2764c1a34a02be3c",
"size": "12418",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/controllers/audios_controller.rb",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "5928"
},
{
"name": "JavaScript",
"bytes": "1734571"
},
{
"name": "Perl",
"bytes": "333"
},
{
"name": "Ruby",
"bytes": "724360"
},
{
"name": "Shell",
"bytes": "209"
}
],
"symlink_target": ""
} |
package anemos
import "fmt"
func (uri Uri) String() string {
return fmt.Sprintf("%s:%s:%s:%s:%s:%s",
uri.Kind,
uri.Provider,
uri.Operation,
uri.Name,
uri.Id,
uri.Status)
}
| {
"content_hash": "d97b7db417162eb57132f57021957f97",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 40,
"avg_line_length": 13.428571428571429,
"alnum_prop": 0.6223404255319149,
"repo_name": "anemos-io/engine",
"id": "b62e2f9e367723a2bf62faedd4d16317149bdaeb",
"size": "188",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "uri.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "42420"
},
{
"name": "Protocol Buffer",
"bytes": "1089"
}
],
"symlink_target": ""
} |
class MissedDetectionTrigger
{
public:
enum
{
STATE_IDLE,
STATE_INHIBIT,
STATE_DETECT,
};
MissedDetectionTrigger();
virtual ~MissedDetectionTrigger();
bool update(bool is_ok);
bool isTriggered(void) const;
bool isDetecting(void) const;
double getDetectMsecRemaining(void) const;
int getInhibitSecondsRemaining(void) const;
void reset();
void start();
void set(const double t_miss_ms, const double t_inh_ms);
public:
int state;
double detect_timeout_ms;
double inhibit_timeout_ms;
bool is_triggered;
bool is_detecting;
std::chrono::time_point<std::chrono::steady_clock> tp_update;
std::chrono::time_point<std::chrono::steady_clock> tp_detect_start;
std::chrono::time_point<std::chrono::steady_clock> tp_inhibit_start;
};
#endif // MISSED_DETECTION_TRIGGER_H_
| {
"content_hash": "dc3eb4345e758281c0e2057a5dc62ff2",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 72,
"avg_line_length": 22.846153846153847,
"alnum_prop": 0.6565656565656566,
"repo_name": "mwgit00/cpox",
"id": "14c1b29f2af67c392f90f634e104dfc70d3518d9",
"size": "983",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "console/MissedDetectionTrigger.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "6630"
},
{
"name": "C#",
"bytes": "33764"
},
{
"name": "C++",
"bytes": "114086"
}
],
"symlink_target": ""
} |
package org.eknet.neoswing.loader;
import com.tinkerpop.blueprints.Graph;
import java.util.ArrayList;
import java.util.List;
/**
* @author <a href="mailto:eike.kettner@gmail.com">Eike Kettner</a>
* @since 14.11.12 22:57
*/
public class OrientDbLoader extends AbstractGraphLoader {
public static final String NAME = "com.orientechnologies.orient.core.db.graph.OGraphDatabase";
private static final String bpOrient = "com.tinkerpop.blueprints.impls.orient.OrientGraph";
//http://code.google.com/p/orient/wiki/Concepts#Database_URL
private static final List<String> orientdbSchemes = new ArrayList<String>() {{
add("local:");
add("memory:");
add("remote:");
}};
public OrientDbLoader(ClassLoader classLoader) {
super(classLoader);
}
public OrientDbLoader() {
}
@Override
public Graph loadGraph(Object... args) {
try {
//noinspection unchecked
Class<? extends Graph> graphClass = (Class<? extends Graph>) classLoader.loadClass(bpOrient);
Object first = args[0];
if (first instanceof String) {
if (!hasScheme((String) first)) {
args[0] = orientdbSchemes.get(0) + first;
}
}
return findMatchingCtor(graphClass, args).newInstance(args);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public String getName() {
return NAME;
}
@Override
public boolean isSupported() {
return isClassAvailable(NAME) && isClassAvailable(bpOrient);
}
private static boolean hasScheme(String url) {
for (String scheme : orientdbSchemes) {
if (url.trim().startsWith(scheme)) {
return true;
}
}
return false;
}
}
| {
"content_hash": "8db8a92f7f08304b283ddb44aa30e542",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 99,
"avg_line_length": 24.242857142857144,
"alnum_prop": 0.6664702416028285,
"repo_name": "eikek/neoswing",
"id": "1a85b715549ce880769f1d9176a972a89c37b78d",
"size": "2292",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/eknet/neoswing/loader/OrientDbLoader.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "200928"
}
],
"symlink_target": ""
} |
ChatPermitter
<img src=https://poggit.pmmp.io/ci.badge/haniokasai/ChatPermitter/ChatPermitter>
ダウンロード https://poggit.pmmp.io/ci/haniokasai/ChatPermitter/ChatPermitter
https://blog.haniokasai.com/2017/08/chatpermitter.html
| {
"content_hash": "3873f20e41566329b6a4205214e3f9c2",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 80,
"avg_line_length": 32.142857142857146,
"alnum_prop": 0.8222222222222222,
"repo_name": "haniokasai/ChatPermitter",
"id": "b3a5dbe18cc3a4c59da11fec82b961307f3fff11",
"size": "255",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "10551"
}
],
"symlink_target": ""
} |
package ca.antonious.viewcelladapter.viewcells.builtins;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;
import android.widget.TextView;
import ca.antonious.viewcelladapter.R;
import ca.antonious.viewcelladapter.viewcells.AbstractViewCell;
/**
* Created by George on 2017-04-29.
*/
public abstract class BaseMaterialSettingViewCell<TViewCell extends BaseMaterialSettingViewCell.BaseMaterialSettingViewHolder> extends AbstractViewCell<TViewCell> {
protected int settingId;
protected String label;
protected int labelTextSizeSp;
protected String secondaryText;
protected int secondaryTextSizeSp;
public BaseMaterialSettingViewCell(int settingId,
String label,
int labelTextSizeSp,
String secondaryText,
int secondaryTextSizeSp) {
this.settingId = settingId;
this.label = label;
this.labelTextSizeSp = labelTextSizeSp;
this.secondaryText = secondaryText;
this.secondaryTextSizeSp = secondaryTextSizeSp;
}
@Override
public int getItemId() {
return settingId;
}
public static class BaseMaterialSettingViewHolder extends RecyclerView.ViewHolder {
private TextView labelTextView;
private TextView secondaryTextTextView;
public BaseMaterialSettingViewHolder(View itemView) {
super(itemView);
labelTextView = (TextView) itemView.findViewById(R.id.label);
secondaryTextTextView = (TextView) itemView.findViewById(R.id.secondary_text);
}
public void setLabel(String label) {
labelTextView.setText(label);
}
public void setLabelTextSizeSp(int textSizeSp) {
labelTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSizeSp);
}
public void setSecondaryText(String secondaryText) {
if (secondaryText.isEmpty()) {
secondaryTextTextView.setVisibility(View.GONE);
} else {
secondaryTextTextView.setVisibility(View.VISIBLE);
}
secondaryTextTextView.setText(secondaryText);
}
public void setSecondaryTextTextSizeSp(int textSizeSp) {
secondaryTextTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSizeSp);
}
public void setOnBackgroundClickedListener(View.OnClickListener onClickListener) {
itemView.setOnClickListener(onClickListener);
}
}
public static abstract class Builder<T extends BaseMaterialSettingViewCell> {
protected int settingId;
protected String label;
protected int labelTextSizeSp;
protected String secondaryText;
protected int secondaryTextSizeSp;
public Builder() {
this.settingId = -1;
this.label = "";
this.labelTextSizeSp = 16;
this.secondaryText = "";
this.secondaryTextSizeSp = 12;
}
public Builder id(int id) {
this.settingId = id;
return this;
}
public Builder label(String label) {
this.label = label;
return this;
}
public Builder labelTextSizeSp(int textSizeSp) {
this.labelTextSizeSp = textSizeSp;
return this;
}
public Builder secondaryText(String secondaryText) {
this.secondaryText = secondaryText;
return this;
}
public Builder secondaryTextSizeSp(int textSizeSp) {
this.secondaryTextSizeSp = textSizeSp;
return this;
}
public abstract T build();
}
}
| {
"content_hash": "f23b6792600dc15691898f8eb02ec391",
"timestamp": "",
"source": "github",
"line_count": 118,
"max_line_length": 164,
"avg_line_length": 32.271186440677965,
"alnum_prop": 0.6334033613445378,
"repo_name": "gantonious/ViewCellAdapter",
"id": "6838b86745eaa302162e43c46497df9898188628",
"size": "3808",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "viewcelladapter/src/main/java/ca/antonious/viewcelladapter/viewcells/builtins/BaseMaterialSettingViewCell.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "175063"
},
{
"name": "Shell",
"bytes": "119"
}
],
"symlink_target": ""
} |
(function(){ 'use strict';
// register controller on the module
angular.module('runculator.app')
.controller('AppController', AppController);
AppController.$inject = ['$translate','$timeout','runculatorConfig'];
function AppController($translate, $timeout, runculatorConfig){
/* jshint validthis: true */
var vm = this;
// bindable members:
vm.changeLanguage = changeLanguage;
vm.closeError = closeError;
vm.data = {
availableLanguages: runculatorConfig.availableLanguages,
selectedLanguage: {
id: $translate.proposedLanguage() || 'pl'
}
};
vm.errors = [];
vm.goBack = goBack;
vm.removeErrors = removeErrors;
vm.setError = setError;
vm.getResult = getResult;
///////////////////
function changeLanguage(langKey){
$translate.use(langKey);
}
function setError(type, errorId){
$translate(errorId).then(function(errTranslation){
vm.errors = [ { type: type, msg: errTranslation } ];
}, function(errId){
vm.errors = [ { type: type, msg: errId } ];
});
}
function closeError(index){
vm.errors.splice(index,1);
}
function removeErrors(){
vm.errors = [];
}
function goBack(whichCtrl){
if(whichCtrl){
whichCtrl.result = null;
}
}
function getResult(viewModel, service, data){
viewModel.calculated = false;
function fetchResult(){
viewModel.result = service.getResult(data);
viewModel.calculated = true;
}
$timeout(fetchResult, 300);
}
}
})(); | {
"content_hash": "6d4da73e80461262b2494341ca53cd7f",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 70,
"avg_line_length": 21.3768115942029,
"alnum_prop": 0.6549152542372881,
"repo_name": "dev-runner/RunCulator",
"id": "88f39a81b92f24dd87cd724c90e915fcb032e9da",
"size": "1475",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/shared/app/appController.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3559"
},
{
"name": "HTML",
"bytes": "31636"
},
{
"name": "JavaScript",
"bytes": "60500"
}
],
"symlink_target": ""
} |
require 'lugg/request'
module Lugg
describe Request do
subject { described_class.new('test') }
it 'considers two objects with the same source equal' do
other = Request.new('test')
expect(subject).to eql(other)
expect(subject == other).to be_true
end
it 'can not modify the contents of the source' do
expect { subject.source.downcase! }.not_to change { subject.source }
end
context 'for an actual request' do
let(:fixture) { File.open(File.expand_path('../../fixtures/example.log', __FILE__)).each_line.first(6).join("\n") }
subject { described_class.new(fixture) }
its(:method) { should eql('GET') }
its(:path) { should eql('/offenses/search') }
its(:uri) { should eql('/offenses/search?q=r315twe&_=1385727839720') }
its(:query) { should eql('q=r315twe&_=1385727839720') }
its(:ip) { should eql('212.78.221.106') }
its(:timestamp) { should eql(Time.new(2013, 11, 29, 13, 24, 16, '+01:00')) }
its(:controller) { should eql('OffensesController') }
its(:action) { should eql('OffensesController#search') }
its(:status) { should eql('OK') }
its(:code) { should eql(200) }
its(:duration) { should eql(37) }
its(:params) { should eql('q' => 'r315twe', '_' => '1385727839720') }
its(:format) { should eql('JSON') }
end
end
end
| {
"content_hash": "0afbbfa12324a5383575ea14d2ca4fe5",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 121,
"avg_line_length": 39.611111111111114,
"alnum_prop": 0.5855539971949509,
"repo_name": "avdgaag/lugg",
"id": "bd4e2b2aa47cffd80ec5fd84764c66a8a51b8135",
"size": "1426",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/lugg/request_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "21486"
}
],
"symlink_target": ""
} |
package client.app.taxes.tasks;
import share.app.dictionary.Category.Categories;
import share.app.taxes.Tax;
import client.app.system.dictionary.DictionaryManager;
import client.app.taxes.gui.def.GUIEditTax;
import client.app.taxes.operations.OperationsTaxes;
public class EditTax extends BaseTax
{
private final Tax original;
public EditTax(Tax original)
{
this.original = original;
}
@Override
public void start()
{
setTitle(getLiteral(GUIEditTax.Literals.TITLE_EDIT_TAX));
this.gui.type.setItems(DictionaryManager.get(Categories.TAX));
this.gui.type.set(this.original.type);
this.gui.value.set(this.original.value);
this.gui.start.set(this.original.start);
this.gui.type.focus();
}
private void editTax()
{
if (validate())
{
Tax newTax = new Tax(0, this.gui.type.get(), "", this.gui.value.getValue(), this.gui.start.get());
boolean response = OperationsTaxes.call().editTax(this.original, newTax);
if (response)
{
close(true);
}
else
{
showWarning(GUIEditTax.Literals.TAX_NOT_EDITED);
this.gui.type.focus();
}
}
}
@Override
public void closing()
{
if (formChanged())
{
if (showConfirm(GUIEditTax.Literals.ASK_CLOSE_WINDOW))
{
close();
}
else
{
setFocus();
}
}
else
{
close();
}
}
private boolean formChanged()
{
return ((!this.gui.type.equals(this.original.type)) || (!this.gui.value.equals(this.original.value)) || (!this.gui.start.equals(this.original.start)));
}
@Override
public void event(Event event)
{
switch (event)
{
case SAVE:
editTax();
break;
case CANCEL:
closing();
break;
default:
break;
}
}
} | {
"content_hash": "8fe58e7d7440d508ed68e9d23c69c61e",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 153,
"avg_line_length": 19.788888888888888,
"alnum_prop": 0.631106120157215,
"repo_name": "vndly/saas",
"id": "a9931135da407fd2a530140be17982368b7710a5",
"size": "1781",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/src/client/app/taxes/tasks/EditTax.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "594322"
}
],
"symlink_target": ""
} |
package org.bouncycastle.pqc.crypto.xmss;
/**
* WOTS+ private key.
*/
final class WOTSPlusPrivateKeyParameters
{
private final byte[][] privateKey;
protected WOTSPlusPrivateKeyParameters(WOTSPlusParameters params, byte[][] privateKey)
{
super();
if (params == null)
{
throw new NullPointerException("params == null");
}
if (privateKey == null)
{
throw new NullPointerException("privateKey == null");
}
if (XMSSUtil.hasNullPointer(privateKey))
{
throw new NullPointerException("privateKey byte array == null");
}
if (privateKey.length != params.getLen())
{
throw new IllegalArgumentException("wrong privateKey format");
}
for (int i = 0; i < privateKey.length; i++)
{
if (privateKey[i].length != params.getTreeDigestSize())
{
throw new IllegalArgumentException("wrong privateKey format");
}
}
this.privateKey = XMSSUtil.cloneArray(privateKey);
}
protected byte[][] toByteArray()
{
return XMSSUtil.cloneArray(privateKey);
}
}
| {
"content_hash": "193b4bcb4403f2d7f263654ebb0dd34e",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 90,
"avg_line_length": 27.318181818181817,
"alnum_prop": 0.5740432612312812,
"repo_name": "bcgit/bc-java",
"id": "1ac19f19602e3f39a3928a47b0472b7333c88ed0",
"size": "1202",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/main/java/org/bouncycastle/pqc/crypto/xmss/WOTSPlusPrivateKeyParameters.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "12956"
},
{
"name": "HTML",
"bytes": "66943"
},
{
"name": "Java",
"bytes": "31612485"
},
{
"name": "Shell",
"bytes": "97225"
}
],
"symlink_target": ""
} |
package com.graphhopper.routing.util;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.graphhopper.reader.Relation;
import com.graphhopper.reader.Way;
import com.graphhopper.util.Helper;
public class BusFlagEncoder extends AbstractFlagEncoder
{
protected final Map<String, Integer> trackTypeSpeedMap = new HashMap<String, Integer>();
protected final Set<String> badSurfaceSpeedMap = new HashSet<String>();
/**
* A map which associates string to speed. Get some impression:
* http://www.itoworld.com/map/124#fullscreen
* http://wiki.openstreetmap.org/wiki/OSM_tags_for_routing/Maxspeed
*/
protected final Map<String, Integer> defaultSpeedMap = new HashMap<String, Integer>();
/**
* Should be only instantied via EncodingManager
*/
public BusFlagEncoder()
{
this(5, 5, 0);
}
public BusFlagEncoder( String propertiesStr )
{
this((int) parseLong(propertiesStr, "speedBits", 5), parseDouble(propertiesStr,
"speedFactor", 5), parseBoolean(propertiesStr, "turnCosts", false) ? 3 : 0);
}
public BusFlagEncoder( int speedBits, double speedFactor, int maxTurnCosts )
{
super(speedBits, speedFactor, maxTurnCosts);
restrictions.addAll(Arrays.asList("motorcar", "motor_vehicle", "vehicle", "access"));
restrictedValues.add("private");
restrictedValues.add("agricultural");
restrictedValues.add("forestry");
restrictedValues.add("no");
restrictedValues.add("restricted");
restrictedValues.add("delivery");
intendedValues.add("yes");
intendedValues.add("permissive");
potentialBarriers.add("gate");
potentialBarriers.add("lift_gate");
potentialBarriers.add("kissing_gate");
potentialBarriers.add("swing_gate");
absoluteBarriers.add("bollard");
absoluteBarriers.add("stile");
absoluteBarriers.add("turnstile");
absoluteBarriers.add("cycle_barrier");
absoluteBarriers.add("motorcycle_barrier");
absoluteBarriers.add("block");
trackTypeSpeedMap.put("grade1", 20); // paved
trackTypeSpeedMap.put("grade2", 15); // now unpaved - gravel mixed with ...
trackTypeSpeedMap.put("grade3", 10); // ... hard and soft materials
trackTypeSpeedMap.put("grade4", 5); // ... some hard or compressed materials
trackTypeSpeedMap.put("grade5", 5); // ... no hard materials. soil/sand/grass
badSurfaceSpeedMap.add("cobblestone");
badSurfaceSpeedMap.add("grass_paver");
badSurfaceSpeedMap.add("gravel");
badSurfaceSpeedMap.add("sand");
badSurfaceSpeedMap.add("paving_stones");
badSurfaceSpeedMap.add("dirt");
badSurfaceSpeedMap.add("ground");
badSurfaceSpeedMap.add("grass");
// autobahn
defaultSpeedMap.put("motorway", 100);
defaultSpeedMap.put("motorway_link", 70);
defaultSpeedMap.put("motorroad", 90);
// bundesstraße
defaultSpeedMap.put("trunk", 70);
defaultSpeedMap.put("trunk_link", 65);
// linking bigger town
defaultSpeedMap.put("primary", 65);
defaultSpeedMap.put("primary_link", 60);
// linking towns + villages
defaultSpeedMap.put("secondary", 60);
defaultSpeedMap.put("secondary_link", 50);
// streets without middle line separation
defaultSpeedMap.put("tertiary", 50);
defaultSpeedMap.put("tertiary_link", 40);
defaultSpeedMap.put("unclassified", 30);
defaultSpeedMap.put("residential", 30);
// spielstraße
defaultSpeedMap.put("living_street", 5);
defaultSpeedMap.put("service", 20);
// unknown road
defaultSpeedMap.put("road", 20);
// forestry stuff
defaultSpeedMap.put("track", 15);
defaultSpeedMap.put("Motorway", 100);
defaultSpeedMap.put("A Road", 55);
defaultSpeedMap.put("B Road", 35);
defaultSpeedMap.put("Minor Road", 35);
defaultSpeedMap.put("Local Street", 35);
defaultSpeedMap.put("Alley", 35);
defaultSpeedMap.put("A Road-Single Carriageway", 55);
defaultSpeedMap.put("B Road", 35);
defaultSpeedMap.put("Minor Road", 35);
defaultSpeedMap.put("Local Street", 35);
defaultSpeedMap.put("Alley", 35);
defaultSpeedMap.put("Motorway", 100);
defaultSpeedMap.put("A Road", 55);
defaultSpeedMap.put("B Road", 35);
defaultSpeedMap.put("Minor Road", 35);
defaultSpeedMap.put("Local Street", 35);
defaultSpeedMap.put("Alley", 35);
defaultSpeedMap.put("A Road-Dual Carriageway", 55);
defaultSpeedMap.put("B Road", 35);
defaultSpeedMap.put("Minor Road", 35);
defaultSpeedMap.put("Local Street", 35);
defaultSpeedMap.put("Alley", 35);
defaultSpeedMap.put("Motorway-Slip Road", 100);
defaultSpeedMap.put("A Road-Slip Road", 55);
defaultSpeedMap.put("B Road", 35);
defaultSpeedMap.put("Minor Road", 35);
defaultSpeedMap.put("Local Street", 35);
defaultSpeedMap.put("Alley", 35);
defaultSpeedMap.put("Motorway-Roundabout", 100);
defaultSpeedMap.put("A Road-Roundabout", 55);
defaultSpeedMap.put("B Road-Roundabout", 35);
defaultSpeedMap.put("Minor Road-Roundabout", 35);
defaultSpeedMap.put("Local Street-Roundabout", 35);
// Should we be including these in car flags?
defaultSpeedMap.put("Pedestrianised Street", 0);
defaultSpeedMap.put("Private Road - Restricted Access", 35);
defaultSpeedMap.put("Private Road - Publicly Accessible", 35);
defaultSpeedMap.put("Alley", 0);
// osgb:type
// vehicleQualifierTypeExclusions.add("Buses");
vehicleQualifierTypeExclusions.add("Coaches");
vehicleQualifierTypeExclusions.add("Mopeds");
vehicleQualifierTypeExclusions.add("Motor Cycles");
vehicleQualifierTypeExclusions.add("HGV's");
vehicleQualifierTypeExclusions.add("LGV's");
vehicleQualifierTypeExclusions.add("Towed Caravans");
vehicleQualifierTypeExclusions.add("Cycles");
vehicleQualifierTypeExclusions.add("Tracked Vehicles");
// osgb:use
vehicleQualifierTypeExclusions.add("Taxi");
vehicleQualifierTypeExclusions.add("Taxis"); // Added from analysing the actual data
vehicleQualifierTypeExclusions.add("School Bus");
vehicleQualifierTypeExclusions.add("Patron");
vehicleQualifierTypeExclusions.add("Access");
vehicleQualifierTypeExclusions.add("Resident");
vehicleQualifierTypeExclusions.add("Emergency Vehicle");
// vehicleQualifierTypeExclusions.add("Public Transport");
vehicleQualifierTypeExclusions.add("Authorised Vehicle");
// vehicleQualifierTypeExclusions.add("Local Bus");
// vehicleQualifierTypeExclusions.add("Local Buses"); // Added from analysing the actual
// data
vehicleQualifierTypeExclusions.add("Escorted Traffic");
vehicleQualifierTypeExclusions.add("Loading And Unloading"); // Added from analysing the
// actual data
vehicleQualifierTypeInclusions.add("Motor Vehicles");
vehicleQualifierTypeInclusions.add("All Vehicles");
// temp inclusions for testing
vehicleQualifierTypeInclusions.add("Buses");
vehicleQualifierTypeInclusions.add("Local Bus");
vehicleQualifierTypeInclusions.add("Local Buses");
vehicleQualifierTypeInclusions.add("Public Transport");
}
/**
* Define the place of the speedBits in the edge flags for car.
*/
@Override
public int defineWayBits( int index, int shift )
{
// first two bits are reserved for route handling in superclass
shift = super.defineWayBits(index, shift);
speedEncoder = new EncodedDoubleValue("Speed", shift, speedBits, speedFactor,
defaultSpeedMap.get("secondary"), defaultSpeedMap.get("motorway"));
return shift + speedEncoder.getBits();
}
protected double getSpeed( Way way )
{
String highwayValue = way.getTag("highway");
Integer speed = defaultSpeedMap.get(highwayValue);
if (speed == null)
throw new IllegalStateException(toString() + ", no speed found for:" + highwayValue);
if (highwayValue.equals("track"))
{
String tt = way.getTag("tracktype");
if (!Helper.isEmpty(tt))
{
Integer tInt = trackTypeSpeedMap.get(tt);
if (tInt != null)
speed = tInt;
}
}
return speed;
}
@Override
public long acceptWay( Way way )
{
String highwayValue = way.getTag("highway");
if (highwayValue == null)
{
if (way.hasTag("route", ferries))
{
String motorcarTag = way.getTag("motorcar");
if (motorcarTag == null)
motorcarTag = way.getTag("motor_vehicle");
if (motorcarTag == null && !way.hasTag("foot") && !way.hasTag("bicycle")
|| "yes".equals(motorcarTag))
return acceptBit | ferryBit;
}
return 0;
}
if ("track".equals(highwayValue))
{
String tt = way.getTag("tracktype");
if (tt != null && !tt.equals("grade1"))
return 0;
}
if (!defaultSpeedMap.containsKey(highwayValue))
return 0;
if (way.hasTag("impassable", "yes") || way.hasTag("status", "impassable"))
return 0;
// do not drive street cars into fords
boolean carsAllowed = way.hasTag(restrictions, intendedValues);
if (isBlockFords() && ("ford".equals(highwayValue) || way.hasTag("ford")) && !carsAllowed)
return 0;
// check access restrictions
if (way.hasTag(restrictions, restrictedValues) && !carsAllowed)
return 0;
// do not drive cars over railways (sometimes incorrectly mapped!)
if (way.hasTag("railway") && !way.hasTag("railway", acceptedRailways))
return 0;
return acceptBit;
}
@Override
public long handleWayTags( Way way, long allowed, long relationFlags )
{
if (!isAccept(allowed))
return 0;
long encoded;
if (!isFerry(allowed))
{
// get assumed speed from highway type
double speed = getSpeed(way);
speed = applyMaxSpeed(way, speed, true);
// limit speed to max 30 km/h if bad surface
if (speed > 30 && way.hasTag("surface", badSurfaceSpeedMap))
speed = 30;
encoded = setSpeed(0, speed);
boolean isRoundabout = way.hasTag("junction", "roundabout");
if (isRoundabout)
encoded = setBool(encoded, K_ROUNDABOUT, true);
if (way.hasTag("oneway", oneways) || isRoundabout)
{
if (way.hasTag("oneway", "-1"))
encoded |= backwardBit;
else
encoded |= forwardBit;
} else
encoded |= directionBitMask;
} else
{
encoded = handleFerryTags(way, defaultSpeedMap.get("living_street"),
defaultSpeedMap.get("service"), defaultSpeedMap.get("residential"));
encoded |= directionBitMask;
}
return encoded;
}
public String getWayInfo( Way way )
{
String str = "";
String highwayValue = way.getTag("highway");
// for now only motorway links
if ("motorway_link".equals(highwayValue))
{
String destination = way.getTag("destination");
if (!Helper.isEmpty(destination))
{
int counter = 0;
for (String d : destination.split(";"))
{
if (d.trim().isEmpty())
continue;
if (counter > 0)
str += ", ";
str += d.trim();
counter++;
}
}
}
if (str.isEmpty())
return str;
// I18N
if (str.contains(","))
return "destinations: " + str;
else
return "destination: " + str;
}
@Override
public String toString()
{
return "bus";
}
@Override
public long handleRelationTags( Relation relation, long oldRelationFlags )
{
return oldRelationFlags;
}
}
| {
"content_hash": "5d9c757b3a4eb5b0604f516d44fdb414",
"timestamp": "",
"source": "github",
"line_count": 352,
"max_line_length": 92,
"avg_line_length": 31.03125,
"alnum_prop": 0.7051176416735329,
"repo_name": "engaric/graphhopper",
"id": "d8a254eda5aafd526666a062b671e8dc59885a0d",
"size": "10925",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/main/java/com/graphhopper/routing/util/BusFlagEncoder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "29019"
},
{
"name": "Gherkin",
"bytes": "257135"
},
{
"name": "HTML",
"bytes": "18540"
},
{
"name": "Java",
"bytes": "2928898"
},
{
"name": "JavaScript",
"bytes": "376593"
},
{
"name": "Shell",
"bytes": "23743"
}
],
"symlink_target": ""
} |
import Sharp from "sharp";
import { dirname } from "path";
export default class Image {
constructor(fsPath, urlPath, maxScale) {
this.fsPath = fsPath;
this.urlPath = urlPath;
this.maxScale = maxScale;
}
getShortPath(newFileName) {
return `${dirname(this.urlPath)}/${newFileName}`;
}
resizeImg(newImpPath, scale) {
return new Promise((resolve, reject) => {
const image = Sharp(this.fsPath);
image
.metadata()
.then(metadata => {
const pxToMaxResolution = metadata.width / this.maxScale;
return image
.resize(Math.round(pxToMaxResolution * scale))
.toFile(newImpPath)
.then(resolve)
.catch(reject);
})
.catch(reject);
});
}
}
| {
"content_hash": "d2f9c791a01250bd55a1355417c9a7c4",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 67,
"avg_line_length": 25,
"alnum_prop": 0.5870967741935483,
"repo_name": "retyui/postcss-image-set-generator",
"id": "8bdfcd2aa237ed5e3dddf9879ee92d1ed8206c3f",
"size": "775",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Image.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "21234"
}
],
"symlink_target": ""
} |
//
// IDmeWebVerifyKeychainData.h
// WebVerifySample
//
// Copyright © 2016 ID.me, Inc. All rights reserved.
//
#ifndef IDmeWebVerifyKeychainData_h
#define IDmeWebVerifyKeychainData_h
#import <Foundation/Foundation.h>
@interface IDmeWebVerifyKeychainData : NSObject
-(NSString* _Nullable)getLatestUsedScope;
-(NSString* _Nullable)accessTokenForScope:(NSString* _Nonnull)scope;
-(NSDate* _Nullable)expirationDateForScope:(NSString* _Nonnull)scope;
-(NSString* _Nullable)refreshTokenForScope:(NSString* _Nonnull)scope;
-(NSDate * _Nullable)refreshExpirationDateForScope:(NSString * _Nonnull)scope;
// TODO: discuss if refreshToken should be nullable
-(void)setToken:(NSString * _Nonnull)accessToken
expirationDate:(NSDate * _Nonnull)expirationDate
refreshToken:(NSString * _Nonnull)refreshToken
refreshExpDate:(NSDate * _Nonnull)refreshExpDate
forScope:(NSString * _Nonnull)scope;
-(void)clean;
-(BOOL)isClean;
@end
#endif /* IDmeWebVerifyKeychainData_h */
| {
"content_hash": "3cca57cb17bbb2a46e45b6b4d45ed790",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 78,
"avg_line_length": 29.636363636363637,
"alnum_prop": 0.7740286298568507,
"repo_name": "IDme/ID.me-WebVerify-SDK-iOS",
"id": "9eb372b3007c5e67424816ebf83dbfb004e96ca4",
"size": "979",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source/IDmeWebVerifyKeychainData.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "75005"
},
{
"name": "Ruby",
"bytes": "695"
}
],
"symlink_target": ""
} |
<Type Name="SunSliceAccum" FullName="MonoMac.OpenGL.SunSliceAccum">
<TypeSignature Language="C#" Value="public enum SunSliceAccum" />
<TypeSignature Language="ILAsm" Value=".class public auto ansi sealed SunSliceAccum extends System.Enum" />
<AssemblyInfo>
<AssemblyName>MonoMac</AssemblyName>
<AssemblyVersion>0.0.0.0</AssemblyVersion>
</AssemblyInfo>
<Base>
<BaseTypeName>System.Enum</BaseTypeName>
</Base>
<Docs>
<summary>To be added.</summary>
<remarks>To be added.</remarks>
</Docs>
<Members>
<Member MemberName="SliceAccumSun">
<MemberSignature Language="C#" Value="SliceAccumSun" />
<MemberSignature Language="ILAsm" Value=".field public static literal valuetype MonoMac.OpenGL.SunSliceAccum SliceAccumSun = int32(34252)" />
<MemberType>Field</MemberType>
<AssemblyInfo>
<AssemblyVersion>0.0.0.0</AssemblyVersion>
</AssemblyInfo>
<ReturnValue>
<ReturnType>MonoMac.OpenGL.SunSliceAccum</ReturnType>
</ReturnValue>
<Docs>
<summary>To be added.</summary>
</Docs>
</Member>
</Members>
</Type>
| {
"content_hash": "5d9c9a4eed16bc8f8e985779ace90971",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 147,
"avg_line_length": 36.193548387096776,
"alnum_prop": 0.6844919786096256,
"repo_name": "dlech/monomac",
"id": "8a96f7c68967968b909af6efe90fcb7389018168",
"size": "1122",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "docs/en/MonoMac.OpenGL/SunSliceAccum.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "8653888"
},
{
"name": "Makefile",
"bytes": "8973"
}
],
"symlink_target": ""
} |
"""
Base class for stroke and fill providing color and alpha channel.
"""
import abc
class RgbaColor(metaclass=abc.ABCMeta):
"""Abstract RGB color with an alpha channel."""
def __init__(self, viewport):
super().__init__()
self._viewport = viewport
self._color = '#000000'
self._alpha = 1.0
self._apply(self._color, self._alpha)
def apply(self):
"""Apply color and alpha channel on demand."""
self._apply(self._color, self._alpha)
@abc.abstractmethod
def _apply(self, color, alpha):
"""Set color and alpha channel of a property such as fill or stroke."""
pass
@property
def color(self):
"""Return color as string."""
return self._color
@color.setter
def color(self, value):
"""Set color (mnemonic such as "black" or a hexadecimal string)."""
assert isinstance(value, str), 'color must be string'
self._color = value
self._apply(self._color, self._alpha)
@property
def alpha(self):
"""Return alpha channel."""
return self._alpha
@alpha.setter
def alpha(self, value):
"""Set alpha channel (must be between 0.0 and 1.0 inclusive)."""
assert isinstance(value, (int, float))
assert 0.0 <= value <= 1.0, 'alpha out of bounds'
self._alpha = value
self._apply(self._color, self._alpha)
| {
"content_hash": "7eb9b07292ec9a921df48ef377689ed9",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 79,
"avg_line_length": 26.754716981132077,
"alnum_prop": 0.5888575458392101,
"repo_name": "bzaczynski/ogre",
"id": "81178e471d8d50d2e8cd954564f291963e0807e9",
"size": "2541",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ogre/pdf/rgba.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "249150"
}
],
"symlink_target": ""
} |
package com.github.blacklocus.rdsecho.utl;
import com.amazonaws.services.rds.model.DBInstance;
import com.amazonaws.services.rds.model.DBSnapshot;
import com.amazonaws.services.rds.model.Tag;
import com.github.blacklocus.rdsecho.EchoCfg;
import com.github.blacklocus.rdsecho.EchoConst;
import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
public class EchoUtil {
private static final Logger LOG = LoggerFactory.getLogger(EchoUtil.class);
final RdsFind rdsFind = new RdsFind();
final EchoCfg cfg = EchoCfg.getInstance();
public String getTagEchoManaged() {
return String.format(EchoConst.TAG_ECHO_MANAGED_FMT, cfg.name());
}
public String getTagEchoStage() {
return String.format(EchoConst.TAG_ECHO_STAGE_FMT, cfg.name());
}
public Optional<DBInstance> lastEchoInstance() {
return RdsFind.newestInstance(rdsFind.instances(rdsFind.instanceHasTag(
cfg.region(), cfg.accountNumber(), getTagEchoManaged(), "true")));
}
public Optional<DBInstance> promotedInstance() {
return Optional.fromNullable(Iterables.getOnlyElement(rdsFind.instances(rdsFind.instanceHasTag(
cfg.region(), cfg.accountNumber(), getTagEchoStage(), EchoConst.STAGE_PROMOTED
)), null));
}
public Optional<Tag> instanceStage(String dbInstanceIdentifier) {
return rdsFind.instanceTag(
RdsFind.instanceArn(cfg.region(), cfg.accountNumber(), dbInstanceIdentifier),
RdsFind.tagName(getTagEchoStage()));
}
public Optional<DBSnapshot> latestSnapshot() {
return RdsFind.newestSnapshot(rdsFind.snapshots(cfg.snapshotDbInstanceIdentifier(), RdsFind.snapshotIsAvailable()));
}
public static String getTLD(String domain) {
String[] split = domain.split("\\.");
return split[split.length - 2] + '.' + split[split.length - 1];
}
public static boolean prompt(String confirm, String format, Object... args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
LOG.info(String.format(format, args));
try {
String userConfirm = reader.readLine();
return confirm.equals(userConfirm);
} catch (IOException e) {
throw new RuntimeException();
}
}
public static List<Tag> parseTags(String[] rawTags) {
List<Tag> tags = Lists.newArrayList();
for(String rawTag : rawTags) {
String[] splitTag = rawTag.split("=", 2);
if(splitTag.length == 2) {
tags.add(new Tag().withKey(splitTag[0]).withValue(splitTag[1]));
}
}
return tags;
}
}
| {
"content_hash": "74afd54d1cd2961bfa3fc525853c4e62",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 124,
"avg_line_length": 35.34939759036145,
"alnum_prop": 0.6768916155419223,
"repo_name": "blacklocus/rds-echo",
"id": "46f34c0221c29d3758d055108805f95db5890725",
"size": "4077",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/github/blacklocus/rdsecho/utl/EchoUtil.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "83773"
},
{
"name": "Shell",
"bytes": "64"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "a8104d92babb0e944fbf3b5dbad0ac00",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "d7a054da51e95615c67a4a9f5258855259088561",
"size": "184",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Tephrosia/Tephrosia oblongata/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.xcolab.view.taglibs.xcolab.jspTags.discussion.actions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.xcolab.client.admin.attributes.platform.PlatformAttributeKey;
import org.xcolab.client.comment.ICommentClient;
import org.xcolab.client.comment.IThreadClient;
import org.xcolab.client.comment.exceptions.CommentNotFoundException;
import org.xcolab.client.comment.exceptions.ThreadNotFoundException;
import org.xcolab.client.comment.pojo.IComment;
import org.xcolab.client.comment.pojo.IThread;
import org.xcolab.commons.html.HtmlUtil;
import org.xcolab.commons.servlet.flash.AlertMessage;
import org.xcolab.view.taglibs.xcolab.jspTags.discussion.DiscussionPermissions;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Controller
public class EditDiscussionMessageActionController extends BaseDiscussionsActionController {
@Autowired
private ICommentClient commentClient;
@Autowired
private IThreadClient threadClient;
@PostMapping("/discussions/editComment")
public void handleAction(HttpServletRequest request, HttpServletResponse response,
@RequestParam long commentId, @RequestParam("comment") String content,
@RequestParam(value = "contestId", required = false) Long contestId)
throws IOException, CommentNotFoundException, ThreadNotFoundException {
IComment comment = commentClient.getComment(commentId);
IThread thread = threadClient.getThread(comment.getThreadId());
DiscussionPermissions discussionPermissions = getDiscussionPermissions(request, thread);
if (!discussionPermissions.getCanAdminMessage(comment)) {
AlertMessage.danger("You are not allowed to edit this message.").flash(request);
String redirectUrl = request.getHeader(HttpHeaders.REFERER);
response.sendRedirect(redirectUrl);
return;
}
final String baseUri = PlatformAttributeKey.COLAB_URL.get();
comment.setContent(HtmlUtil.cleanSome(content, baseUri));
commentClient.updateComment(comment);
String redirectUrl = request.getHeader(HttpHeaders.REFERER);
response.sendRedirect(redirectUrl);
}
}
| {
"content_hash": "a7d76d4e3a336bf936f79dca071674e4",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 96,
"avg_line_length": 43.10344827586207,
"alnum_prop": 0.7808,
"repo_name": "CCI-MIT/XCoLab",
"id": "b2beb4c1a6d8619335f8bedd169ce5d0f4f88111",
"size": "2500",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "view/src/main/java/org/xcolab/view/taglibs/xcolab/jspTags/discussion/actions/EditDiscussionMessageActionController.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "22697"
},
{
"name": "HTML",
"bytes": "69904"
},
{
"name": "Java",
"bytes": "4089581"
},
{
"name": "JavaScript",
"bytes": "1172118"
},
{
"name": "SCSS",
"bytes": "201019"
},
{
"name": "Shell",
"bytes": "13707"
}
],
"symlink_target": ""
} |
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Cache;
class ElectionsController extends Controller
{
const CACHE_PREFIX = 'elections:';
const CACHE_TIMEOUT = 1440;
protected $civicinfo;
public function __construct() {
$this->civicinfo = new \App\Services\GoogleCivicInfo;
}
public function index(Request $request) {
if ($request->get('addr')) {
return $this->getElectionInfo($request->get('addr'));
}
$cachekey = self::CACHE_PREFIX.'metadata';
return Cache::remember($cachekey, self::CACHE_TIMEOUT, function() {
return $this->civicinfo->getUpcomingElections();
});
}
protected function getElectionInfo($address) {
$cachekey = self::CACHE_PREFIX.$address;
return Cache::remember($cachekey, self::CACHE_TIMEOUT, function() use ($address) {
return $this->civicinfo->getElectionInfoByAddress($address);
});
}
}
| {
"content_hash": "138ebe78217e6adafb400c4597f25930",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 24.305555555555557,
"alnum_prop": 0.7097142857142857,
"repo_name": "athill/informedelectorate.net",
"id": "ea379bafda341318b7ad5ecdc0c48eb90fe68442",
"size": "875",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "app/Http/Controllers/ElectionsController.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Blade",
"bytes": "9056"
},
{
"name": "Handlebars",
"bytes": "138"
},
{
"name": "JavaScript",
"bytes": "56971"
},
{
"name": "PHP",
"bytes": "95910"
},
{
"name": "Shell",
"bytes": "491"
},
{
"name": "Vue",
"bytes": "563"
}
],
"symlink_target": ""
} |
package org.osgi.resource.dto;
import java.util.List;
import org.osgi.dto.DTO;
import org.osgi.resource.Wiring;
/**
* Data Transfer Object for a Wiring node.
*
* @author $Id$
* @NotThreadSafe
*/
public class WiringDTO extends DTO {
/**
* The unique identifier of the wiring node.
*
* <p>
* This identifier is transiently assigned and may vary across restarts.
*/
public int id;
/**
* The references to the capabilities for the wiring node.
*
* @see Wiring#getResourceCapabilities(String)
*/
public List<CapabilityRefDTO> capabilities;
/**
* The references to the requirements for the wiring node.
*
* @see Wiring#getResourceRequirements(String)
*/
public List<RequirementRefDTO> requirements;
/**
* The provided wires for the wiring node.
*
* @see Wiring#getProvidedResourceWires(String)
*/
public List<WireDTO> providedWires;
/**
* The required wires for the wiring node.
*
* @see Wiring#getRequiredResourceWires(String)
*/
public List<WireDTO> requiredWires;
/**
* The identifier of the resource associated with the wiring node.
*
* @see ResourceDTO#id
* @see Wiring#getResource()
*/
public int resource;
}
| {
"content_hash": "de75bef5424336b97cacc86ded45398e",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 76,
"avg_line_length": 21.783333333333335,
"alnum_prop": 0.6350420811017597,
"repo_name": "osgi/osgi",
"id": "28737b9ba213fb49b8ebe824b1b2592be065257e",
"size": "2126",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "org.osgi.resource/src/org/osgi/resource/dto/WiringDTO.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "11308"
},
{
"name": "C",
"bytes": "11077"
},
{
"name": "CSS",
"bytes": "63392"
},
{
"name": "HTML",
"bytes": "1425271"
},
{
"name": "Java",
"bytes": "17327563"
},
{
"name": "JavaScript",
"bytes": "684425"
},
{
"name": "Makefile",
"bytes": "8343"
},
{
"name": "NewLisp",
"bytes": "4473"
},
{
"name": "Perl",
"bytes": "7202"
},
{
"name": "Python",
"bytes": "9377"
},
{
"name": "Roff",
"bytes": "64"
},
{
"name": "Ruby",
"bytes": "10888"
},
{
"name": "Shell",
"bytes": "48677"
},
{
"name": "SystemVerilog",
"bytes": "5465"
},
{
"name": "XSLT",
"bytes": "8082406"
}
],
"symlink_target": ""
} |
title: 'Second Post'
date: 2015-03-21 02:46:34
categories: blog development
tags: code
---
#Second post
## like a boss
| {
"content_hash": "092bbd28da36ee6949ca584df65e60c8",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 28,
"avg_line_length": 12.2,
"alnum_prop": 0.6967213114754098,
"repo_name": "danipy/danipy.github.io",
"id": "ea4cb1d837f532e7e299c7570adc8c817f5e8e23",
"size": "126",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2016-03-21-second-post.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11626"
},
{
"name": "HTML",
"bytes": "4780"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/mongi.iml" filepath="$PROJECT_DIR$/.idea/mongi.iml" />
</modules>
</component>
</project> | {
"content_hash": "5e3227af7e75be29153cbdc67a02f430",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 104,
"avg_line_length": 32.75,
"alnum_prop": 0.6526717557251909,
"repo_name": "StrangerMdj/mongi",
"id": "7db57e4724444a9a1c2ffcebbe1a7507a036c7e3",
"size": "262",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/modules.xml",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "0987eca048fff027cdf75329095f5c4e",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "581a84eeb18862328da3e25de8724558b61d4498",
"size": "185",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Oxalidales/Connaraceae/Rourea/Rourea blanchetiana/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package com.google.cloud.bigtable.admin.v2.models;
import static com.google.common.truth.Truth.assertThat;
import com.google.bigtable.admin.v2.ColumnFamily;
import com.google.bigtable.admin.v2.GcRule;
import com.google.bigtable.admin.v2.Table.TimestampGranularity;
import com.google.bigtable.admin.v2.TableName;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Map.Entry;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class TableTest {
@Test
public void testFromProto() {
TableName testName = TableName.of("my-project", "my-instance", "my-table");
com.google.bigtable.admin.v2.Table proto =
com.google.bigtable.admin.v2.Table.newBuilder()
.setName(testName.toString())
.setGranularity(TimestampGranularity.MILLIS)
.putClusterStates(
"cluster1",
com.google.bigtable.admin.v2.Table.ClusterState.newBuilder()
.setReplicationState(
com.google.bigtable.admin.v2.Table.ClusterState.ReplicationState.READY)
.build())
.putClusterStates(
"cluster2",
com.google.bigtable.admin.v2.Table.ClusterState.newBuilder()
.setReplicationState(
com.google.bigtable.admin.v2.Table.ClusterState.ReplicationState
.INITIALIZING)
.build())
.putColumnFamilies("cf1", ColumnFamily.newBuilder().build())
.putColumnFamilies(
"cf2",
ColumnFamily.newBuilder()
.setGcRule(GcRule.newBuilder().setMaxNumVersions(1))
.build())
.putColumnFamilies(
"cf3",
ColumnFamily.newBuilder()
.setGcRule(
GcRule.newBuilder()
.setMaxAge(
com.google.protobuf.Duration.newBuilder()
.setSeconds(1)
.setNanos(99)))
.build())
.build();
Table result = Table.fromProto(proto);
assertThat(result.getInstanceId()).isEqualTo("my-instance");
assertThat(result.getId()).isEqualTo("my-table");
assertThat(result.getReplicationStatesByClusterId())
.containsExactly(
"cluster1", Table.ReplicationState.READY,
"cluster2", Table.ReplicationState.INITIALIZING);
assertThat(result.getColumnFamilies()).hasSize(3);
for (Entry<String, ColumnFamily> entry : proto.getColumnFamiliesMap().entrySet()) {
assertThat(result.getColumnFamilies())
.contains(
com.google.cloud.bigtable.admin.v2.models.ColumnFamily.fromProto(
entry.getKey(), entry.getValue()));
}
}
@Test
public void testReplicationStateEnumUpToDate() {
List<com.google.bigtable.admin.v2.Table.ClusterState.ReplicationState> validProtoValues =
Lists.newArrayList(
com.google.bigtable.admin.v2.Table.ClusterState.ReplicationState.values());
List<Table.ReplicationState> validModelValues =
Lists.newArrayList(Table.ReplicationState.values());
List<Table.ReplicationState> actualModelValues = Lists.newArrayList();
for (com.google.bigtable.admin.v2.Table.ClusterState.ReplicationState protoValue :
validProtoValues) {
Table.ReplicationState modelValue = Table.ReplicationState.fromProto(protoValue);
actualModelValues.add(modelValue);
}
assertThat(actualModelValues).containsExactlyElementsIn(validModelValues);
}
}
| {
"content_hash": "47f0de8d69dd2068ce84de21b8dfd3c6",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 95,
"avg_line_length": 39.36842105263158,
"alnum_prop": 0.6280748663101604,
"repo_name": "googleapis/java-bigtable",
"id": "b94be17e7f7a8979e1e78e5f56e65b400822a476",
"size": "4334",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/admin/v2/models/TableTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "801"
},
{
"name": "Java",
"bytes": "8304597"
},
{
"name": "Python",
"bytes": "7665"
},
{
"name": "Shell",
"bytes": "23981"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<meta charset=utf-8>
<title>Redirecting...</title>
<link rel=canonical href="../也/index.html">
<meta http-equiv=refresh content="0; url='../也/index.html'">
<h1>Redirecting...</h1>
<a href="../也/index.html">Click here if you are not redirected.</a>
<script>location='../也/index.html'</script>
| {
"content_hash": "208c5af82365ef8f6bef4501125807b7",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 67,
"avg_line_length": 38.5,
"alnum_prop": 0.6785714285714286,
"repo_name": "hochanh/hochanh.github.io",
"id": "b103cd58993671b95cba6ae30c80e793f0e33395",
"size": "316",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rtk/v4/2094.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "6969"
},
{
"name": "JavaScript",
"bytes": "5041"
}
],
"symlink_target": ""
} |
"""empty message
Revision ID: e62680af2bfa
Revises: 190163627111
Create Date: 2016-04-01 12:22:17.505613
"""
# revision identifiers, used by Alembic.
revision = 'e62680af2bfa'
down_revision = '190163627111'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('roles', sa.Column('default', sa.Boolean(), nullable=True))
op.add_column('roles', sa.Column('permissions', sa.Integer(), nullable=True))
op.create_index(op.f('ix_roles_default'), 'roles', ['default'], unique=False)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_roles_default'), table_name='roles')
op.drop_column('roles', 'permissions')
op.drop_column('roles', 'default')
### end Alembic commands ###
| {
"content_hash": "9f28a03a745da466dcc92cef010a1bf7",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 81,
"avg_line_length": 29.2,
"alnum_prop": 0.6792237442922374,
"repo_name": "lancecopper/flasky_blog",
"id": "67132694466b0852519e5fccc13628f58d423a92",
"size": "876",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "migrations/versions/e62680af2bfa_.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7640"
},
{
"name": "HTML",
"bytes": "528058"
},
{
"name": "JavaScript",
"bytes": "20876"
},
{
"name": "Mako",
"bytes": "412"
},
{
"name": "Python",
"bytes": "83837"
}
],
"symlink_target": ""
} |
package org.eclipse.jnosql.artemis.graph;
import jakarta.nosql.NonUniqueResultException;
import jakarta.nosql.mapping.IdNotFoundException;
import jakarta.nosql.mapping.PreparedStatement;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Transaction;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Stream;
/**
* This interface that represents the common operation between an entity
* and {@link org.apache.tinkerpop.gremlin.structure.Vertex}
*/
public interface GraphTemplate {
/**
* Inserts entity
*
* @param entity entity to be saved
* @param <T> the instance type
* @return the entity saved
* @throws NullPointerException when document is null
* @throws jakarta.nosql.mapping.IdNotFoundException when entity has not {@link jakarta.nosql.mapping.Id}
*/
<T> T insert(T entity);
/**
* Updates entity
*
* @param entity entity to be updated
* @param <T> the instance type
* @return the entity saved
* @throws IllegalStateException when document is null
* @throws jakarta.nosql.mapping.IdNotFoundException when an entity is null
*/
<T> T update(T entity);
/**
* Deletes a {@link org.apache.tinkerpop.gremlin.structure.Vertex}
*
* @param id the id to be used in the query {@link org.apache.tinkerpop.gremlin.structure.T#id}
* @param <T> the id type
* @throws NullPointerException when id is null
*/
<T> void delete(T id);
/**
* Deletes a {@link org.apache.tinkerpop.gremlin.structure.Edge}
*
* @param id the id to be used in the query {@link org.apache.tinkerpop.gremlin.structure.T#id}
* @param <T> the id type
* @throws NullPointerException when either label and id are null
*/
<T> void deleteEdge(T id);
/**
* Find an entity given {@link org.apache.tinkerpop.gremlin.structure.T#label} and
* {@link org.apache.tinkerpop.gremlin.structure.T#id}
*
* @param id the id to be used in the query {@link org.apache.tinkerpop.gremlin.structure.T#id}
* @param <T> the entity type
* @param <K> the id type
* @return the entity found otherwise {@link Optional#empty()}
* @throws NullPointerException when id is null
*/
<T, K> Optional<T> find(K id);
/**
* Inserts entities
*
* @param entities entities to be saved
* @param <T> the instance type
* @return the entity saved
* @throws NullPointerException when document is null
* @throws jakarta.nosql.mapping.IdNotFoundException when entity has not {@link jakarta.nosql.mapping.Id}
*/
<T> Iterable<T> insert(Iterable<T> entities);
/**
* Updates entities
*
* @param entities entity to be updated
* @param <T> the instance type
* @return the entity saved
* @throws IllegalStateException when document is null
* @throws jakarta.nosql.mapping.IdNotFoundException when an entity is null
*/
<T> Iterable<T> update(Iterable<T> entities);
/**
* Deletes {@link org.apache.tinkerpop.gremlin.structure.Vertex} instances
*
* @param ids the ids to be used in the query {@link org.apache.tinkerpop.gremlin.structure.T#id}
* @param <T> the id type
* @throws NullPointerException when id is null
*/
<T> void delete(Iterable<T> ids);
/**
* Deletes {@link org.apache.tinkerpop.gremlin.structure.Edge} instances
*
* @param ids the ids to be used in the query {@link org.apache.tinkerpop.gremlin.structure.T#id}
* @param <T> the id type
* @throws NullPointerException when either label and id are null
*/
<T> void deleteEdge(Iterable<T> ids);
/**
* Either find or create an Edge between this two entities.
* {@link org.apache.tinkerpop.gremlin.structure.Edge}
* <pre>entityOUT ---label---> entityIN.</pre>
*
* @param incoming the incoming entity
* @param label the Edge label
* @param outgoing the outgoing entity
* @param <I> the incoming type
* @param <O> the outgoing type
* @return the {@link EdgeEntity} of these two entities
* @throws NullPointerException Either when any elements are null or the entity is null
* @throws jakarta.nosql.mapping.IdNotFoundException when {@link jakarta.nosql.mapping.Id} annotation is missing in the entities
* @throws jakarta.nosql.mapping.EntityNotFoundException when neither outgoing or incoming is found
*/
<O, I> EdgeEntity edge(O outgoing, String label, I incoming);
/**
* Either find or create an Edge between this two entities.
* {@link org.apache.tinkerpop.gremlin.structure.Edge}
* <pre>entityOUT ---label---> entityIN.</pre>
*
* @param incoming the incoming entity
* @param label the Edge label
* @param outgoing the outgoing entity
* @param <I> the incoming type
* @param <O> the outgoing type
* @return the {@link EdgeEntity} of these two entities
* @throws NullPointerException Either when any elements are null or the entity is null
* @throws jakarta.nosql.mapping.IdNotFoundException when {@link jakarta.nosql.mapping.Id} annotation is missing in the entities
* @throws jakarta.nosql.mapping.EntityNotFoundException when neither outgoing or incoming is found
*/
default <O, I> EdgeEntity edge(O outgoing, Supplier<String> label, I incoming) {
Objects.requireNonNull(label, "supplier is required");
return edge(outgoing, label.get(), incoming);
}
/**
* returns the edges of from a vertex id
*
* @param id the id
* @param direction the direction
* @param labels the edge labels
* @param <K> the K type
* @return the Edges
* @throws NullPointerException where there is any parameter null
*/
<K> Collection<EdgeEntity> getEdgesById(K id, Direction direction, String... labels);
/**
* returns the edges of from a vertex id
*
* @param id the id
* @param direction the direction
* @param labels the edge labels
* @param <K> the K type
* @return the Edges
* @throws NullPointerException where there is any parameter null
*/
<K> Collection<EdgeEntity> getEdgesById(K id, Direction direction, Supplier<String>... labels);
/**
* returns the edges of from a vertex id
*
* @param id the id
* @param direction the direction
* @param <K> the K type
* @return the Edges
* @throws NullPointerException where there is any parameter null
*/
<K> Collection<EdgeEntity> getEdgesById(K id, Direction direction);
/**
* returns the edges of from an entity
*
* @param entity the entity
* @param direction the direction
* @param labels the edge labels
* @param <T> the entity type
* @return the Edges
* @throws NullPointerException where there is any parameter null
*/
<T> Collection<EdgeEntity> getEdges(T entity, Direction direction, String... labels);
/**
* returns the edges of from an entity
*
* @param entity the entity
* @param direction the direction
* @param labels the edge labels
* @param <T> the entity type
* @return the Edges
* @throws NullPointerException where there is any parameter null
*/
<T> Collection<EdgeEntity> getEdges(T entity, Direction direction, Supplier<String>... labels);
/**
* returns the edges of from an entity
*
* @param entity the entity
* @param direction the direction
* @param <T> the entity type
* @return the Edges
* @throws NullPointerException where there is any parameter null
*/
<T> Collection<EdgeEntity> getEdges(T entity, Direction direction);
/**
* Finds an {@link EdgeEntity} from the Edge Id
*
* @param edgeId the edge id
* @param <E> the edge id type
* @return the {@link EdgeEntity} otherwise {@link Optional#empty()}
* @throws IllegalStateException when edgeId is null
*/
<E> Optional<EdgeEntity> edge(E edgeId);
/**
* Gets a {@link VertexTraversal} to run a query in the graph
*
* @param vertexIds get ids
* @return a {@link VertexTraversal} instance
* @throws IllegalStateException if any id element is null
*/
VertexTraversal getTraversalVertex(Object... vertexIds);
/**
* Gets a {@link EdgeTraversal} to run a query in the graph
*
* @param edgeIds get ids
* @return a {@link VertexTraversal} instance
* @throws IllegalStateException if any id element is null
*/
EdgeTraversal getTraversalEdge(Object... edgeIds);
/**
* Gets the current transaction
*
* @return the current {@link Transaction}
*/
Transaction getTransaction();
/**
* Executes a Gremlin gremlin then bring the result as a {@link List}
*
* @param gremlin the query gremlin
* @param <T> the entity type
* @return the result as {@link List}
* @throws NullPointerException when the gremlin is null
*/
<T> Stream<T> query(String gremlin);
/**
* Executes a Gremlin query then bring the result as a unique result
*
* @param gremlin the gremlin query
* @param <T> the entity type
* @return the result as {@link List}
* @throws NullPointerException when the query is null
* @throws NonUniqueResultException if returns more than one result
*/
<T> Optional<T> singleResult(String gremlin);
/**
* Creates a {@link PreparedStatement} from the query
*
* @param gremlin the gremlin query
* @return a {@link PreparedStatement} instance
* @throws NullPointerException when the query is null
*/
PreparedStatement prepare(String gremlin);
/**
* Finds by Id.
*
* @param entityClass the entity class
* @param id the id value
* @param <T> the entity class type
* @param <K> the id type
* @return the entity instance otherwise {@link Optional#empty()}
* @throws NullPointerException when either the entityClass or id are null
* @throws IdNotFoundException when the entityClass does not have the Id annotation
*/
<T, K> Optional<T> find(Class<T> entityClass, K id);
/**
* Returns the number of vertices from label
*
* @param label the label
* @return the number of elements
* @throws NullPointerException when label is null
* @throws UnsupportedOperationException when the database dot not have support
*/
long count(String label);
/**
* Returns the number of vertices from label
*
* @param <T> the entity type
* @param entityClass the label
* @return the number of elements
* @throws NullPointerException when label is null
* @throws UnsupportedOperationException when the database dot not have support
*/
<T> long count(Class<T> entityClass);
}
| {
"content_hash": "338c43c8ccdc3bff4830d9079b80e6c6",
"timestamp": "",
"source": "github",
"line_count": 322,
"max_line_length": 136,
"avg_line_length": 35.55590062111801,
"alnum_prop": 0.6394444929688182,
"repo_name": "JNOSQL/diana",
"id": "6d0112984fd13a3bc46cc089e7309d47573a3fcf",
"size": "12030",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "artemis/artemis-graph/src/main/java/org/eclipse/jnosql/artemis/graph/GraphTemplate.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "375379"
}
],
"symlink_target": ""
} |
namespace ROCKSDB_NAMESPACE {
// Index that leverages an internal hash table to quicken the lookup for a given
// key.
class HashIndexReader : public BlockBasedTable::IndexReaderCommon {
public:
static Status Create(const BlockBasedTable* table,
FilePrefetchBuffer* prefetch_buffer,
InternalIterator* meta_index_iter, bool use_cache,
bool prefetch, bool pin,
BlockCacheLookupContext* lookup_context,
std::unique_ptr<IndexReader>* index_reader);
InternalIteratorBase<IndexValue>* NewIterator(
const ReadOptions& read_options, bool disable_prefix_seek,
IndexBlockIter* iter, GetContext* get_context,
BlockCacheLookupContext* lookup_context) override;
size_t ApproximateMemoryUsage() const override {
size_t usage = ApproximateIndexBlockMemoryUsage();
#ifdef ROCKSDB_MALLOC_USABLE_SIZE
usage += malloc_usable_size(const_cast<HashIndexReader*>(this));
#else
if (prefix_index_) {
usage += prefix_index_->ApproximateMemoryUsage();
}
usage += sizeof(*this);
#endif // ROCKSDB_MALLOC_USABLE_SIZE
return usage;
}
private:
HashIndexReader(const BlockBasedTable* t, CachableEntry<Block>&& index_block)
: IndexReaderCommon(t, std::move(index_block)) {}
std::unique_ptr<BlockPrefixIndex> prefix_index_;
};
} // namespace ROCKSDB_NAMESPACE
| {
"content_hash": "c5d6ea85abc9fadcd746f115143d94a6",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 80,
"avg_line_length": 38.24324324324324,
"alnum_prop": 0.6855123674911661,
"repo_name": "TeamSPoon/logicmoo_workspace",
"id": "fecd1e5c8b5f8b27e6d8a6908647def76efa6bb1",
"size": "1962",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "packs_lib/rocksdb/rocksdb/table/block_based/hash_index_reader.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "342"
},
{
"name": "C",
"bytes": "1"
},
{
"name": "C++",
"bytes": "1"
},
{
"name": "CSS",
"bytes": "126627"
},
{
"name": "HTML",
"bytes": "839172"
},
{
"name": "Java",
"bytes": "11116"
},
{
"name": "JavaScript",
"bytes": "238700"
},
{
"name": "PHP",
"bytes": "42253"
},
{
"name": "Perl 6",
"bytes": "23"
},
{
"name": "Prolog",
"bytes": "440882"
},
{
"name": "PureBasic",
"bytes": "1334"
},
{
"name": "Rich Text Format",
"bytes": "3436542"
},
{
"name": "Roff",
"bytes": "42"
},
{
"name": "Shell",
"bytes": "61603"
},
{
"name": "TeX",
"bytes": "99504"
}
],
"symlink_target": ""
} |
#if !defined(FUSION_INCLUDE_DEDUCE_SEQUENCE)
#define FUSION_INCLUDE_DEDUCE_SEQUENCE
#include <lslboost/fusion/support/deduce_sequence.hpp>
#endif
| {
"content_hash": "a021953e6810c4dccf01f4d40bf80c3a",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 54,
"avg_line_length": 21.285714285714285,
"alnum_prop": 0.7986577181208053,
"repo_name": "gazzlab/LSL-gazzlab-branch",
"id": "4394eff6353b8e581ce88d5c8a9566e3c6b3a2c0",
"size": "511",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "liblsl/external/lslboost/fusion/include/deduce_sequence.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "63003"
},
{
"name": "C++",
"bytes": "53791427"
},
{
"name": "Objective-C",
"bytes": "39516"
},
{
"name": "Perl",
"bytes": "2051"
},
{
"name": "Python",
"bytes": "4119"
},
{
"name": "Shell",
"bytes": "2310"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<!--[if IE 8]> <html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9"> <![endif]-->
<!--[if !IE]><!--> <html dir="rtl" lang="en"> <!--<![endif]-->
<head>
<title>Unify - Responsive Website Template</title>
<!-- Meta -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Favicon -->
<link rel="shortcut icon" href="favicon.ico">
<!-- Web Fonts -->
<link rel='stylesheet' type='text/css' href='//fonts.googleapis.com/css?family=Open+Sans:400,300,600&subset=cyrillic,latin'>
<!-- CSS Global Compulsory -->
<link rel="stylesheet" href="../assets/plugins/bootstrap/css/bootstrap-rtl.min.css">
<link rel="stylesheet" href="../assets/css/css-rtl/style-rtl.css">
<!-- CSS Header and Footer -->
<link rel="stylesheet" href="../assets/css/css-rtl/headers/header-default-rtl.css">
<link rel="stylesheet" href="../assets/css/css-rtl/footers/footer-v1-rtl.css">
<!-- CSS Implementing Plugins -->
<link rel="stylesheet" href="../assets/plugins/animate.css">
<link rel="stylesheet" href="../assets/plugins/line-icons/line-icons.css">
<link rel="stylesheet" href="../assets/plugins/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="../assets/plugins/parallax-slider/css/parallax-slider-rtl.css">
<link rel="stylesheet" href="../assets/plugins/owl-carousel2/assets/owl.carousel.css">
<!-- Style Switcher -->
<link rel="stylesheet" href="../assets/css/plugins/style-switcher.css">
<!-- CSS Theme -->
<link rel="stylesheet" href="../assets/css/css-rtl/theme-colors/default.css" id="style_color">
<link rel="stylesheet" href="../assets/css/css-rtl/theme-skins/dark.css">
<!-- RTL Customization -->
<link rel="stylesheet" href="../assets/css/css-rtl/rtl.css">
<!-- CSS Customization -->
<link rel="stylesheet" href="../assets/css/css-rtl/custom-rtl.css">
</head>
<body>
<div class="wrapper">
<!--=== Header ===-->
<div class="header">
<div class="container">
<!-- Logo -->
<a class="logo" href="index.html">
<img src="../assets/img/logo1-default.png" alt="Logo">
</a>
<!-- End Logo -->
<!-- Topbar -->
<div class="topbar">
<ul class="loginbar pull-right">
<li class="hoverSelector">
<i class="fa fa-globe"></i>
<a>Languages</a>
<ul class="languages hoverSelectorBlock">
<li class="active">
<a href="#">English <i class="fa fa-check"></i></a>
</li>
<li><a href="#">Spanish</a></li>
<li><a href="#">Russian</a></li>
<li><a href="#">German</a></li>
</ul>
</li>
<li class="topbar-devider"></li>
<li><a href="page_faq.html">Help</a></li>
<li class="topbar-devider"></li>
<li><a href="page_login.html">Login</a></li>
</ul>
</div>
<!-- End Topbar -->
<!-- Toggle get grouped for better mobile display -->
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-responsive-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="fa fa-bars"></span>
</button>
<!-- End Toggle -->
</div><!--/end container-->
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse mega-menu navbar-responsive-collapse">
<div class="container">
<ul class="nav navbar-nav">
<!-- Home -->
<li class="dropdown active">
<a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown">
Home
</a>
<ul class="dropdown-menu">
<li class="active"><a href="index.html">Option 1: Default Page</a></li>
<!-- One Page -->
<li class="dropdown-submenu">
<a href="javascript:void(0);">Option 2: One Page</a>
<ul class="dropdown-menu">
<li><a target="_blank" href="../One-Pages/RTL/index.html">- One Page Template</a></li>
<li><a target="_blank" href="../One-Pages/RTL/dark-page-example.html">- One Page Dark Theme</a></li>
</ul>
</li>
<!-- End One Page -->
<!-- Shop UI Page -->
<li class="dropdown-submenu">
<a href="javascript:void(0);">Option 3: Shop UI</a>
<ul class="dropdown-menu">
<li><a target="_blank" href="../E-Commerce/RTL/index.html">- Home Page</a></li>
<li><a target="_blank" href="../E-Commerce/RTL/shop-ui-inner.html">- Product Page</a></li>
<li><a target="_blank" href="../E-Commerce/RTL/shop-ui-filter-grid.html">- Filter Grid Page</a></li>
<li><a target="_blank" href="../E-Commerce/RTL/shop-ui-filter-list.html">- Filter List Page</a></li>
<li><a target="_blank" href="../E-Commerce/RTL/shop-ui-add-to-cart.html">- Checkout Page</a></li>
<li><a target="_blank" href="../E-Commerce/RTL/shop-ui-login.html">- Login Page</a></li>
<li><a target="_blank" href="../E-Commerce/RTL/shop-ui-register.html">- Registration Page</a></li>
</ul>
</li>
<!-- End Shop UI -->
<li><a href="page_home8.html">Option 4: Home Discover</a></li>
<li><a href="page_home9.html">Option 5: Home Creative</a></li>
<li><a href="page_home10.html">Option 6: Home Inspire</a></li>
<li><a href="page_home11.html">Option 7: Home Desire</a></li>
<li><a href="page_jobs.html">Option 8: Home Jobs</a></li>
<li><a href="page_home3.html">Option 9: Amazing Content</a></li>
<li><a href="page_home6.html">Option 10: Home Magazine</a></li>
<li class="dropdown-submenu">
<a href="javascript:void(0);">Option 11: Home Sidebar</a>
<ul class="dropdown-menu">
<li><a href="page_home12.html">- Home Left Sidebar</a></li>
<li><a href="page_home13.html">- Home Right Sidebar</a></li>
</ul>
</li>
<li><a href="page_home1.html">Option 12: Home Basic v1</a></li>
<li><a href="page_home2.html">Option 13: Home Basic v2</a></li>
<li><a href="page_home5.html">Option 14: Home Basic v3</a></li>
<li><a href="page_home4.html">Option 15: Home Basic v4</a></li>
<li><a href="page_home7.html">Option 16: Home Basic v5</a></li>
</ul>
</li>
<!-- End Home -->
<!-- Pages -->
<li class="dropdown">
<a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown">
Pages
</a>
<ul class="dropdown-menu">
<!-- About Pages -->
<li class="dropdown-submenu">
<a href="javascript:void(0);">About Pages</a>
<ul class="dropdown-menu">
<li><a href="page_about2.html">About Us </a></li>
<li><a href="page_about3.html">About Us 1</a></li>
<li><a href="page_about1.html">About Us 2</a></li>
<li><a href="page_about.html">About Us 3</a></li>
<li><a href="page_about_me.html">About Me </a></li>
<li><a href="page_about_me1.html">About Me 1</a></li>
<li><a href="page_about_me2.html">About Me 2</a></li>
<li><a href="page_about_our_team.html">About Our Team</a></li>
<li><a href="page_about_our_team1.html">About Our Team 1</a></li>
<li><a href="page_about_our_team2.html">About Our Team 2</a></li>
</ul>
</li>
<!-- End About Pages -->
<!-- Service Pages -->
<li class="dropdown-submenu">
<a href="javascript:void(0);">Service Pages</a>
<ul class="dropdown-menu">
<li><a href="page_services.html">Our Services</a></li>
<li><a href="page_services1.html">Our Services 1</a></li>
<li><a href="page_services2.html">Our Services 2</a></li>
<li><a href="page_services3.html">Our Services 3</a></li>
</ul>
</li>
<!-- End Service Pages -->
<!-- Contacts -->
<li class="dropdown-submenu">
<a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown">
Contact Pages
</a>
<ul class="dropdown-menu">
<li><a href="page_contact1.html">Contacts Default</a></li>
<li><a href="page_contact2.html">Contacts Option 1</a></li>
<li><a href="page_contact3.html">Contacts Option 2</a></li>
<li><a href="page_contact4.html">Contacts Option 3</a></li>
<li><a href="page_contact_advanced.php">Contacts Advanced</a></li>
</ul>
</li>
<!-- End Contacts -->
<!-- Profile Pages -->
<li class="dropdown-submenu">
<a href="javascript:void(0);">Profile Pages</a>
<ul class="dropdown-menu">
<li><a href="page_profile.html">Profile Main Page</a></li>
<li><a href="page_profile_me.html">Profile Overview</a></li>
<li><a href="page_profile_users.html">Profile Users</a></li>
<li><a href="page_profile_projects.html">Profile Projects</a></li>
<li><a href="page_profile_comments.html">Profile Comments</a></li>
<li><a href="page_profile_history.html">Profile History</a></li>
<li><a href="page_profile_settings.html">Profile Settings</a></li>
</ul>
</li>
<!-- End Profile Pages -->
<!-- Job Pages -->
<li class="dropdown-submenu">
<a href="javascript:void(0);">Job Pages</a>
<ul class="dropdown-menu">
<li><a href="page_jobs.html">Jobs Main Page</a></li>
<li><a href="page_jobs1.html">Jobs Main Page 1</a></li>
<li><a href="page_jobs_inner.html">Jobs Description Default</a></li>
<li><a href="page_jobs_inner1.html">Jobs Description Basic</a></li>
<li><a href="page_jobs_inner2.html">Jobs Description Min</a></li>
</ul>
</li>
<!-- End Job Pages -->
<!-- Pricing Tables -->
<li class="dropdown-submenu">
<a href="javascript:void(0);">Pricing Tables</a>
<ul class="dropdown-menu">
<li><a href="page_pricing_colorful.html">Colorful Pricing Tables</a></li>
<li><a href="page_pricing_flat.html">Flat Pricing Tables</a></li>
<li><a href="page_pricing_light.html">Light Pricing Tables</a></li>
<li><a href="page_pricing_mega.html">Mega Pricing Tables</a></li>
<li><a href="page_pricing.html">Default Pricing Tables</a></li>
</ul>
</li>
<!-- End Pricing Tables -->
<!-- Login and Registration -->
<li class="dropdown-submenu">
<a href="javascript:void(0);">Login and Registration</a>
<ul class="dropdown-menu">
<li><a href="page_registration.html">Registration Page</a></li>
<li><a href="page_login.html">Login Page</a></li>
<li><a href="page_registration1.html">Registration Option</a></li>
<li><a href="page_login1.html">Login Option</a></li>
</ul>
</li>
<!-- End Login and Registration -->
<!-- FAQs Pages -->
<li class="dropdown-submenu">
<a href="javascript:void(0);">FAQs Pages</a>
<ul class="dropdown-menu">
<li><a href="page_faq1.html">FAQs Page</a></li>
<li><a href="page_faq.html">FAQs Basic</a></li>
</ul>
</li>
<!-- End FAQs Pages -->
<!-- Email Tempaltes -->
<li class="dropdown-submenu">
<a href="javascript:void(0);">Email Templates</a>
<ul class="dropdown-menu">
<li class="dropdown-submenu">
<a href="javascript:void(0);">Email Corporate</a>
<ul class="dropdown-menu">
<li><a target="_blank" href="../Email-Templates/corporate/email_corporate_aqua.html">Corporate Aqua Color</a></li>
<li><a target="_blank" href="../Email-Templates/corporate/email_corporate_blue.html">Corporate Blue Color</a></li>
<li><a target="_blank" href="../Email-Templates/corporate/email_corporate_brown.html">Corporate Brown Color</a></li>
<li><a target="_blank" href="../Email-Templates/corporate/email_corporate_dark_blue.html">Corporate Dark Blue Color</a></li>
<li><a target="_blank" href="../Email-Templates/corporate/email_corporate_green.html">Corporate Green Color</a></li>
<li><a target="_blank" href="../Email-Templates/corporate/email_corporate_light_green.html">Corporate Light Green Color</a></li>
<li><a target="_blank" href="../Email-Templates/corporate/email_corporate_grey.html">Corporate Grey Color</a></li>
<li><a target="_blank" href="../Email-Templates/corporate/email_corporate_orange.html">Corporate Orange Color</a></li>
<li><a target="_blank" href="../Email-Templates/corporate/email_corporate_purple.html">Corporate Purple Color</a></li>
<li><a target="_blank" href="../Email-Templates/corporate/email_corporate_red.html">Corporate Red Color</a></li>
</ul>
</li>
<li class="dropdown-submenu">
<a href="javascript:void(0);">Email Flat</a>
<ul class="dropdown-menu">
<li><a target="_blank" href="../Email-Templates/flat/email_flat_aqua.html">Flat Aqua Color</a></li>
<li><a target="_blank" href="../Email-Templates/flat/email_flat_blue.html">Flat Blue Color</a></li>
<li><a target="_blank" href="../Email-Templates/flat/email_flat_brown.html">Flat Brown Color</a></li>
<li><a target="_blank" href="../Email-Templates/flat/email_flat_dark_blue.html">Flat Dark Blue Color</a></li>
<li><a target="_blank" href="../Email-Templates/flat/email_flat_green.html">Flat Green Color</a></li>
<li><a target="_blank" href="../Email-Templates/flat/email_flat_light_green.html">Flat Light Green Color</a></li>
<li><a target="_blank" href="../Email-Templates/flat/email_flat_grey.html">Flat Grey Color</a></li>
<li><a target="_blank" href="../Email-Templates/flat/email_flat_orange.html">Flat Orange Color</a></li>
<li><a target="_blank" href="../Email-Templates/flat/email_flat_purple.html">Flat Purple Color</a></li>
<li><a target="_blank" href="../Email-Templates/flat/email_flat_red.html">Flat Red Color</a></li>
</ul>
</li>
<li class="dropdown-submenu">
<a href="javascript:void(0);">Email Modern</a>
<ul class="dropdown-menu">
<li><a target="_blank" href="../Email-Templates/modern/email_modern_aqua.html">Modern Aqua Color</a></li>
<li><a target="_blank" href="../Email-Templates/modern/email_modern_blue.html">Modern Blue Color</a></li>
<li><a target="_blank" href="../Email-Templates/modern/email_modern_brown.html">Modern Brown Color</a></li>
<li><a target="_blank" href="../Email-Templates/modern/email_modern_dark_blue.html">Modern Dark Blue Color</a></li>
<li><a target="_blank" href="../Email-Templates/modern/email_modern_green.html">Modern Green Color</a></li>
<li><a target="_blank" href="../Email-Templates/modern/email_modern_light_green.html">Modern Light Green Color</a></li>
<li><a target="_blank" href="../Email-Templates/modern/email_modern_grey.html">Modern Grey Color</a></li>
<li><a target="_blank" href="../Email-Templates/modern/email_modern_orange.html">Modern Orange Color</a></li>
<li><a target="_blank" href="../Email-Templates/modern/email_modern_purple.html">Modern Purple Color</a></li>
<li><a target="_blank" href="../Email-Templates/modern/email_modern_red.html">Modern Red Color</a></li>
</ul>
</li>
</ul>
</li>
<!-- End Email Tempaltes -->
<!-- Search Results -->
<li class="dropdown-submenu">
<a href="javascript:void(0);">Search Results</a>
<ul class="dropdown-menu">
<li><a href="page_search_inner_full_width.html">Search Results Full Width</a></li>
<li><a href="page_search_inner_left_sidebar.html">Search Result Left Sidebar</a></li>
<li><a href="page_search_table.html">Search Result Tables</a></li>
</ul>
</li>
<!-- End Search Results -->
<!-- Coming Soon -->
<li class="dropdown-submenu">
<a href="javascript:void(0);">Coming Soon Pages</a>
<ul class="dropdown-menu">
<li><a href="page_coming_soon.html">Coming Soon</a></li>
<li><a href="page_coming_soon1.html">Coming Soon 1</a></li>
</ul>
</li>
<!-- End Coming Soon -->
<!-- Error Pages -->
<li class="dropdown-submenu">
<a href="javascript:void(0);">Error Pages</a>
<ul class="dropdown-menu">
<li><a href="page_404_error.html">404 Error Default</a></li>
<li><a href="page_404_error1.html">404 Error Option 1</a></li>
<li><a href="page_404_error2.html">404 Error Option 2</a></li>
<li><a href="page_404_error3.html">404 Error Option 3</a></li>
</ul>
</li>
<!-- End Error Pages -->
<!-- Invoice Page -->
<li><a href="page_invoice.html">Invoice Page</a></li>
<!-- End Invoice Page -->
<!-- Clients Page -->
<li><a href="page_clients.html">Clients Page</a></li>
<!-- End Clients Page -->
<!-- Column Pages -->
<li><a href="page_3_columns.html">Three Columns Page</a></li>
<!-- End Column Pages -->
<!-- Privacy Policy -->
<li><a href="page_privacy.html">Privacy Policy</a></li>
<!-- End Privacy Policy -->
<!-- Terms of Service -->
<li><a href="page_terms.html">Terms of Service</a></li>
<!-- End Terms of Service -->
<!-- Sub Level Menu -->
<li class="dropdown-submenu">
<a href="javascript:void(0);">Sub Level 1</a>
<ul class="dropdown-menu no-bottom-space">
<li><a href="index.hmtl">Sub Level 2</a></li>
<li class="dropdown-submenu">
<a href="javascript:void(0);">Sub Level 2</a>
<ul class="dropdown-menu">
<li><a href="index.hmtl">Sub Level 3</a></li>
<li><a href="index.hmtl">Sub Level 3</a></li>
<li><a href="index.hmtl">Sub Level 3</a></li>
<li><a href="index.hmtl">Sub Level 3</a></li>
</ul>
</li>
<li><a href="index.hmtl">Sub Level 2</a></li>
<li class="dropdown-submenu">
<a href="javascript:void(0);">Sub Level 2</a>
<ul class="dropdown-menu no-bottom-space">
<li><a href="index.hmtl">Sub Level 3</a></li>
<li><a href="index.hmtl">Sub Level 3</a></li>
<li><a href="index.hmtl">Sub Level 3</a></li>
</ul>
</li>
</ul>
</li>
<!-- End Sub Level Menu -->
</ul>
</li>
<!-- End Pages -->
<!-- Blog -->
<li class="dropdown">
<a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown">
Blog
</a>
<ul class="dropdown-menu">
<li class="dropdown-submenu">
<a href="javascript:void(0);">Blog Large Image</a>
<ul class="dropdown-menu">
<li><a href="blog_large_right_sidebar1.html">Right Sidebar</a></li>
<li><a href="blog_large_left_sidebar1.html">Left Sidebar</a></li>
<li><a href="blog_large_full_width1.html">Full Width</a></li>
</ul>
</li>
<li class="dropdown-submenu">
<a href="javascript:void(0);">Blog Medium Image</a>
<ul class="dropdown-menu">
<li><a href="blog_medium_right_sidebar1.html">Right Sidebar</a></li>
<li><a href="blog_medium_left_sidebar1.html">Left Sidebar</a></li>
<li><a href="blog_medium_full_width1.html">Full Width</a></li>
</ul>
</li>
<li class="dropdown-submenu">
<a href="javascript:void(0);">Blog Item Pages</a>
<ul class="dropdown-menu">
<li><a href="blog_large_right_sidebar_item1.html">Right Sidebar Item</a></li>
<li><a href="blog_large_left_sidebar_item1.html">Left Sidebar Item</a></li>
<li><a href="blog_large_full_width_item1.html">Full Width Item</a></li>
</ul>
</li>
<li class="dropdown-submenu">
<a href="javascript:void(0);">Blog Simple Pages</a>
<ul class="dropdown-menu">
<li><a href="blog_large_right_sidebar.html">Right Sidebar Large</a></li>
<li><a href="blog_medium_right_sidebar.html">Right Sidebar Medium</a></li>
<li><a href="blog_large_full_width.html">Full Width</a></li>
<li><a href="blog_large_right_sidebar_item.html">Right Sidebar Item</a></li>
<li><a href="blog_large_full_width_item.html">Full Width Item</a></li>
</ul>
</li>
<li><a href="blog_masonry_3col.html">Masonry Grid Blog</a></li>
<li><a href="blog_timeline.html">Blog Timeline</a></li>
</ul>
</li>
<!-- End Blog -->
<!-- Portfolio -->
<li class="dropdown">
<a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown">
Portfolio
</a>
<ul class="dropdown-menu">
<li class="dropdown-submenu">
<a href="javascript:void(0);">No Space Boxed</a>
<ul class="dropdown-menu">
<li><a href="portfolio_2_columns_grid_no_space.html">2 Columns</a></li>
<li><a href="portfolio_3_columns_grid_no_space.html">3 Columns</a></li>
<li><a href="portfolio_4_columns_grid_no_space.html">4 Columns</a></li>
</ul>
</li>
<li class="dropdown-submenu">
<a href="javascript:void(0);">Grid Boxed</a>
<ul class="dropdown-menu">
<li><a href="portfolio_2_columns_grid.html">2 Columns</a></li>
<li><a href="portfolio_3_columns_grid.html">3 Columns</a></li>
<li><a href="portfolio_4_columns_grid.html">4 Columns</a></li>
</ul>
</li>
<li class="dropdown-submenu">
<a href="javascript:void(0);">Grid Text Boxed</a>
<ul class="dropdown-menu">
<li><a href="portfolio_2_columns_grid_text.html">2 Columns</a></li>
<li><a href="portfolio_3_columns_grid_text.html">3 Columns</a></li>
<li><a href="portfolio_4_columns_grid_text.html">4 Columns</a></li>
</ul>
</li>
<li class="dropdown-submenu">
<a href="javascript:void(0);">No Space Full Width</a>
<ul class="dropdown-menu">
<li><a href="portfolio_2_columns_fullwidth_no_space.html">2 Columns</a></li>
<li><a href="portfolio_3_columns_fullwidth_no_space.html">3 Columns</a></li>
<li><a href="portfolio_4_columns_fullwidth_no_space.html">4 Columns</a></li>
<li><a href="portfolio_5_columns_fullwidth_no_space.html">5 Columns</a></li>
<li><a href="portfolio_6_columns_fullwidth_no_space.html">6 Columns</a></li>
</ul>
</li>
<li class="dropdown-submenu">
<a href="javascript:void(0);">Grid Full Width</a>
<ul class="dropdown-menu">
<li><a href="portfolio_2_columns_fullwidth.html">2 Columns</a></li>
<li><a href="portfolio_3_columns_fullwidth.html">3 Columns</a></li>
<li><a href="portfolio_4_columns_fullwidth.html">4 Columns</a></li>
<li><a href="portfolio_5_columns_fullwidth.html">5 Columns</a></li>
<li><a href="portfolio_6_columns_fullwidth.html">6 Columns</a></li>
</ul>
</li>
<li class="dropdown-submenu">
<a href="javascript:void(0);">Grid Text Full Width</a>
<ul class="dropdown-menu">
<li><a href="portfolio_2_columns_fullwidth_text.html">2 Columns</a></li>
<li><a href="portfolio_3_columns_fullwidth_text.html">3 Columns</a></li>
<li><a href="portfolio_4_columns_fullwidth_text.html">4 Columns</a></li>
<li><a href="portfolio_5_columns_fullwidth_text.html">5 Columns</a></li>
<li><a href="portfolio_6_columns_fullwidth_text.html">6 Columns</a></li>
</ul>
</li>
<li><a href="portfolio_hover_colors.html">Portfolio Hover Colors</a></li>
<li class="dropdown-submenu">
<a href="javascript:void(0);">Portfolio Items</a>
<ul class="dropdown-menu">
<li><a href="portfolio_single_item.html">Single Item</a></li>
<li><a href="portfolio_old_item.html">Basic Item 1</a></li>
<li><a href="portfolio_old_item1.html">Basic Item 2</a></li>
</ul>
</li>
<li class="dropdown-submenu">
<a href="javascript:void(0);">Portfolio Basic Pages</a>
<ul class="dropdown-menu">
<li><a href="portfolio_old_text_blocks.html">Basic Grid Text</a></li>
<li><a href="portfolio_old_2_column.html">Basic 2 Columns</a></li>
<li><a href="portfolio_old_3_column.html">Basic 3 Columns</a></li>
<li><a href="portfolio_old_4_column.html">Basic 4 Columns</a></li>
</ul>
</li>
</ul>
</li>
<!-- End Portfolio -->
<!-- Features -->
<li class="dropdown">
<a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown">
Features
</a>
<ul class="dropdown-menu">
<li class="dropdown-submenu">
<a href="javascript:void(0);">Headers</a>
<ul class="dropdown-menu">
<li><a href="feature_header_default.html">Header Default</a></li>
<li><a href="feature_header_v1.html">Header v1</a></li>
<li><a href="feature_header_v2.html">Header v2</a></li>
<li><a href="feature_header_v3.html">Header v3</a></li>
<li><a href="feature_header_v4.html">Header v4</a></li>
<li><a href="feature_header_v5.html">Header v5</a></li>
<li><a href="feature_header_v6_transparent.html">Header v6 Transparent</a></li>
<li><a href="feature_header_v6_semi_dark_transparent.html">Header v6 Dark Transparent</a></li>
<li><a href="feature_header_v6_semi_white_transparent.html">Header v6 White Transparent</a></li>
<li><a href="feature_header_v6_border_bottom.html">Header v6 Border Bottom</a></li>
<li><a href="feature_header_v6_classic_dark.html">Header v6 Classic Dark</a></li>
<li><a href="feature_header_v6_classic_white.html">Header v6 Classic White</a></li>
<li><a href="feature_header_v6_dark_dropdown.html">Header v6 Dark Dropdown</a></li>
<li><a href="feature_header_v6_dark_scroll.html">Header v6 Dark on Scroll</a></li>
<li><a href="feature_header_v6_dark_search.html">Header v6 Dark Search</a></li>
<li><a href="feature_header_v6_dark_res_nav.html">Header v6 Dark in Responsive</a></li>
</ul>
</li>
<li class="dropdown-submenu">
<a href="javascript:void(0);">Footers</a>
<ul class="dropdown-menu">
<li><a href="feature_footer_default.html#footer-default">Footer Default</a></li>
<li><a href="feature_footer_v1.html#footer-v1">Footer v1</a></li>
<li><a href="feature_footer_v2.html#footer-v2">Footer v2</a></li>
<li><a href="feature_footer_v3.html#footer-v3">Footer v3</a></li>
<li><a href="feature_footer_v4.html#footer-v4">Footer v4</a></li>
<li><a href="feature_footer_v5.html#footer-v5">Footer v5</a></li>
<li><a href="feature_footer_v6.html#footer-v6">Footer v6</a></li>
<li><a href="feature_footer_v7.html#footer-v7">Footer v7</a></li>
</ul>
</li>
<li><a href="feature_gallery.html">Gallery Examples</a></li>
<li><a href="feature_animations.html">Animations on Scroll</a></li>
<li><a href="feature_parallax_counters.html">Parallax Counters</a></li>
<li><a href="feature_parallax_blocks.html">Parallax Blocks</a></li>
<li><a href="feature_funny_boxes.html">Funny Boxes</a></li>
</ul>
</li>
<!-- End Features -->
<!-- Shortcodes -->
<li class="dropdown mega-menu-fullwidth">
<a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown">
Shortcodes
</a>
<ul class="dropdown-menu">
<li>
<div class="mega-menu-content disable-icons">
<div class="container">
<div class="row equal-height">
<div class="col-md-3 equal-height-in">
<ul class="list-unstyled equal-height-list">
<li><h3>Typography & Components</h3></li>
<!-- Typography -->
<li><a href="shortcode_typo_general.html"><i class="fa fa-sort-alpha-asc"></i> General Typography</a></li>
<li><a href="shortcode_typo_headings.html"><i class="fa fa-magic"></i> Headings Options</a></li>
<li><a href="shortcode_typo_dividers.html"><i class="fa fa-ellipsis-h"></i> Dividers</a></li>
<li><a href="shortcode_typo_blockquote.html"><i class="fa fa-quote-left"></i> Blockquote Blocks</a></li>
<li><a href="shortcode_typo_boxshadows.html"><i class="fa fa-asterisk"></i> Box Shadows</a></li>
<li><a href="shortcode_typo_testimonials.html"><i class="fa fa-comments"></i> Testimonials</a></li>
<li><a href="shortcode_typo_tagline_boxes.html"><i class="fa fa-tasks"></i> Tagline Boxes</a></li>
<li><a href="shortcode_typo_grid.html"><i class="fa fa-align-justify"></i> Grid Layouts</a></li>
<!-- End Typography -->
<!-- Components -->
<li><a href="shortcode_compo_messages.html"><i class="fa fa-comment"></i> Alerts & Messages</a></li>
<li><a href="shortcode_compo_labels.html"><i class="fa fa-tags"></i> Labels & Badges</a></li>
<li><a href="shortcode_compo_media.html"><i class="fa fa-volume-down"></i> Audio/Videos & Images</a></li>
<li><a href="shortcode_compo_pagination.html"><i class="fa fa-arrows-h"></i> Paginations</a></li>
<!-- End Components -->
</ul>
</div>
<div class="col-md-3 equal-height-in">
<ul class="list-unstyled equal-height-list">
<li><h3>Buttons & Icons</h3></li>
<!-- Buttons -->
<li><a href="shortcode_btn_general.html"><i class="fa fa-flask"></i> General Buttons</a></li>
<li><a href="shortcode_btn_brands.html"><i class="fa fa-html5"></i> Brand & Social Buttons</a></li>
<li><a href="shortcode_btn_effects.html"><i class="fa fa-bolt"></i> Loading & Hover Effects</a></li>
<!-- End Buttons -->
<!-- Icons -->
<li><a href="shortcode_icon_general.html"><i class="fa fa-chevron-circle-right"></i> General Icons</a></li>
<li><a href="shortcode_icon_fa.html"><i class="fa fa-chevron-circle-right"></i> Font Awesome Icons</a></li>
<li><a href="shortcode_icon_line.html"><i class="fa fa-chevron-circle-right"></i> Line Icons</a></li>
<li><a href="shortcode_icon_glyph.html"><i class="fa fa-chevron-circle-right"></i> Glyphicons Icons (Bootstrap)</a></li>
<li><a href="shortcode_icon_glyph_pro.html"><i class="fa fa-chevron-circle-right"></i> Glyphicons Icons Pro</a></li>
<!-- End Icons -->
</ul>
</div>
<div class="col-md-3 equal-height-in">
<ul class="list-unstyled equal-height-list">
<li><h3>Common elements</h3></li>
<!-- Content Boxes -->
<li><a href="shortcode_box_general.html"><i class="fa fa-cog"></i> General Content Boxes</a></li>
<li><a href="shortcode_box_colored.html"><i class="fa fa-align-center"></i> Colored Boxes</a></li>
<li><a href="shortcode_thumbnails.html"><i class="fa fa-image"></i> Thumbnails</a></li>
<li><a href="shortcode_accordion_and_tabs.html"><i class="fa fa-list-ol"></i> Accordion & Tabs</a></li>
<li><a href="shortcode_timeline1.html"><i class="fa fa-dot-circle-o"></i> Timeline Option 1</a></li>
<li><a href="shortcode_timeline2.html"><i class="fa fa-dot-circle-o"></i> Timeline Option 2</a></li>
<li><a href="shortcode_table_general.html"><i class="fa fa-table"></i> Tables</a></li>
<li><a href="shortcode_compo_progress_bars.html"><i class="fa fa-align-left"></i> Progress Bars</a></li>
<li><a href="shortcode_compo_panels.html"><i class="fa fa-columns"></i> Panels</a></li>
<!-- End Common Elements -->
</ul>
</div>
<div class="col-md-3 equal-height-in">
<ul class="list-unstyled equal-height-list">
<li><h3>Forms & Infographics</h3></li>
<!-- Forms -->
<li><a href="shortcode_form_general.html"><i class="fa fa-bars"></i> Common Bootstrap Forms</a></li>
<li><a href="shortcode_form_general1.html"><i class="fa fa-bars"></i> General Unify Forms</a></li>
<li><a href="shortcode_form_advanced.html"><i class="fa fa-bars"></i> Advanced Forms</a></li>
<li><a href="shortcode_form_layouts.html"><i class="fa fa-bars"></i> Form Layouts</a></li>
<li><a href="shortcode_form_layouts_advanced.html"><i class="fa fa-bars"></i> Advanced Layout Forms</a></li>
<li><a href="shortcode_form_states.html"><i class="fa fa-bars"></i> Form States</a></li>
<li><a href="shortcode_form_sliders.html"><i class="fa fa-bars"></i> Form Sliders</a></li>
<li><a href="shortcode_form_modals.html"><i class="fa fa-bars"></i> Modals</a></li>
<!-- End Forms -->
<!-- Infographics -->
<li><a href="shortcode_carousels.html"><i class="fa fa-sliders"></i> Carousel Examples</a></li>
<li><a href="shortcode_compo_charts.html"><i class="fa fa-pie-chart"></i> Charts & Countdowns</a></li>
<li><a href="shortcode_maps_google.html"><i class="fa fa-map-marker"></i> Google Maps</a></li>
<li><a href="shortcode_maps_vector.html"><i class="fa fa-align-center"></i> Vector Maps</a></li>
<!-- End Infographics -->
</ul>
</div>
</div>
</div>
</div>
</li>
</ul>
</li>
<!-- End Shortcodes -->
<!-- Misc Pages -->
<li class="dropdown">
<a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown">
Misc
</a>
<ul class="dropdown-menu pull-right">
<li><a href="page_misc_blank.html">Blank page</a></li>
<li><a href="page_misc_boxed.html">Boxed Page</a></li>
<li><a href="page_misc_boxed_img.html">Boxed Image Page</a></li>
<li><a href="page_misc_boxed_fixed_header.html">Boxed Fixed Menu</a></li>
<li><a href="page_misc_fixed_header.html">Fixed Menu</a></li>
<li><a href="page_misc_dark.html">Dark Page</a></li>
<li><a href="page_misc_dark_boxed.html">Dark Boxed Page</a></li>
<li><a href="page_misc_dark_other_color.html">Dark Page with Theme Color</a></li>
<li><a href="page_misc_sticky_footer.html">Sticky Footer Example</a></li>
</ul>
</li>
<!-- End Misc Pages -->
<!-- Search Block -->
<li>
<i class="search fa fa-search search-btn"></i>
<div class="search-open">
<div class="input-group animated fadeInDown">
<input type="text" class="form-control" placeholder="Search">
<span class="input-group-btn">
<button class="btn-u" type="button">Go</button>
</span>
</div>
</div>
</li>
<!-- End Search Block -->
</ul>
</div><!--/end container-->
</div><!--/navbar-collapse-->
</div>
<!--=== End Header ===-->
<!--=== Slider ===-->
<div class="slider-inner">
<div id="da-slider" class="da-slider">
<div class="da-slide">
<h2><i>CLEAN & FRESH</i> <br /> <i>FULLY RESPONSIVE</i> <br /> <i>DESIGN</i></h2>
<p><i>Lorem ipsum dolor amet</i> <br /> <i>tempor incididunt ut</i> <br /> <i>veniam omnis </i></p>
<div class="da-img"><img class="img-responsive" src="../assets/plugins/parallax-slider/img/1.png" alt=""></div>
</div>
<div class="da-slide">
<h2><i>RESPONSIVE VIDEO</i> <br /> <i>SUPPORT AND</i> <br /> <i>MANY MORE</i></h2>
<p><i>Lorem ipsum dolor amet</i> <br /> <i>tempor incididunt ut</i></p>
<div class="da-img">
<iframe src="http://player.vimeo.com/video/47911018" width="530" height="300" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
</div>
</div>
<div class="da-slide">
<h2><i>USING BEST WEB</i> <br /> <i>SOLUTIONS WITH</i> <br /> <i>HTML5/CSS3</i></h2>
<p><i>Lorem ipsum dolor amet</i> <br /> <i>tempor incididunt ut</i> <br /> <i>veniam omnis </i></p>
<div class="da-img"><img src="../assets/plugins/parallax-slider/img/html5andcss3.png" alt="image01" /></div>
</div>
<div class="da-arrows">
<span class="da-arrows-prev"></span>
<span class="da-arrows-next"></span>
</div>
</div>
</div><!--/slider-->
<!--=== End Slider ===-->
<!--=== Purchase Block ===-->
<div class="purchase">
<div class="container">
<div class="row">
<div class="col-md-9 animated fadeInLeft">
<span>Unify is a clean and fully responsive incredible Template.</span>
<p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi vehicula sem ut volutpat. Ut non libero magna fusce condimentum eleifend enim a feugiat corrupti quos.</p>
</div>
<div class="col-md-3 btn-buy animated fadeInRight">
<a href="#" class="btn-u btn-u-lg"><i class="fa fa-cloud-download"></i> Download Now</a>
</div>
</div>
</div>
</div><!--/row-->
<!-- End Purchase Block -->
<!--=== Content Part ===-->
<div class="container content-sm">
<!-- Service Blocks -->
<div class="row margin-bottom-30">
<div class="col-md-4">
<div class="service">
<i class="fa fa-compress service-icon"></i>
<div class="desc">
<h4>Fully Responsive</h4>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus etiam sem...</p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="service">
<i class="fa fa-cogs service-icon"></i>
<div class="desc">
<h4>HTML5 + CSS3</h4>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus etiam sem...</p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="service">
<i class="fa fa-rocket service-icon"></i>
<div class="desc">
<h4>Launch Ready</h4>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus etiam sem...</p>
</div>
</div>
</div>
</div>
<!-- End Service Blokcs -->
<!-- Recent Works -->
<div class="headline"><h2>Recent Works</h2></div>
<div class="row margin-bottom-20">
<div class="col-md-3 col-sm-6">
<div class="thumbnails thumbnail-style thumbnail-kenburn">
<div class="thumbnail-img">
<div class="overflow-hidden">
<img class="img-responsive" src="../assets/img/main/img1.jpg" alt="">
</div>
<a class="btn-more hover-effect" href="#">read more +</a>
</div>
<div class="caption">
<h3><a class="hover-effect" href="#">Project One</a></h3>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, justo sit amet risus etiam porta sem.</p>
</div>
</div>
</div>
<div class="col-md-3 col-sm-6">
<div class="thumbnails thumbnail-style thumbnail-kenburn">
<div class="thumbnail-img">
<div class="overflow-hidden">
<img class="img-responsive" src="../assets/img/main/img12.jpg" alt="">
</div>
<a class="btn-more hover-effect" href="#">read more +</a>
</div>
<div class="caption">
<h3><a class="hover-effect" href="#">Project Two</a></h3>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, justo sit amet risus etiam porta sem.</p>
</div>
</div>
</div>
<div class="col-md-3 col-sm-6">
<div class="thumbnails thumbnail-style thumbnail-kenburn">
<div class="thumbnail-img">
<div class="overflow-hidden">
<img class="img-responsive" src="../assets/img/main/img3.jpg" alt="">
</div>
<a class="btn-more hover-effect" href="#">read more +</a>
</div>
<div class="caption">
<h3><a class="hover-effect" href="#">Project Three</a></h3>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, justo sit amet risus etiam porta sem.</p>
</div>
</div>
</div>
<div class="col-md-3 col-sm-6">
<div class="thumbnails thumbnail-style thumbnail-kenburn">
<div class="thumbnail-img">
<div class="overflow-hidden">
<img class="img-responsive" src="../assets/img/main/img17.jpg" alt="">
</div>
<a class="btn-more hover-effect" href="#">read more +</a>
</div>
<div class="caption">
<h3><a class="hover-effect" href="#">Project Four</a></h3>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, justo sit amet risus etiam porta sem.</p>
</div>
</div>
</div>
</div>
<!-- End Recent Works -->
<!-- Info Blokcs -->
<div class="row margin-bottom-30">
<!-- Welcome Block -->
<div class="col-md-8 md-margin-bottom-40">
<div class="headline"><h2>Welcome To Unify</h2></div>
<div class="row">
<div class="col-sm-4">
<img class="img-responsive margin-bottom-20" src="../assets/img/main/img18.jpg" alt="">
</div>
<div class="col-sm-8">
<p>Unify is an incredibly beautiful responsive Bootstrap Template for corporate and creative professionals. It works on all major web browsers, tablets and phone.</p>
<ul class="list-unstyled margin-bottom-20">
<li><i class="fa fa-check color-green"></i> Donec id elit non mi porta gravida</li>
<li><i class="fa fa-check color-green"></i> Corporate and Creative</li>
<li><i class="fa fa-check color-green"></i> Responsive Bootstrap Template</li>
<li><i class="fa fa-check color-green"></i> Corporate and Creative</li>
</ul>
</div>
</div>
<blockquote class="hero-unify">
<p>Award winning digital agency. We bring a personal and effective approach to every project we work on, which is why. Unify is an incredibly beautiful responsive Bootstrap Template for corporate professionals.</p>
<small>CEO, Jack Bour</small>
</blockquote>
</div><!--/col-md-8-->
<!-- Latest Shots -->
<div class="col-md-4">
<div class="headline"><h2>Latest Shots</h2></div>
<div id="myCarousel" class="carousel slide carousel-v1">
<div class="carousel-inner">
<div class="item active">
<img src="../assets/img/main/img4.jpg" alt="">
<div class="carousel-caption">
<p>Facilisis odio, dapibus ac justo acilisis gestinas.</p>
</div>
</div>
<div class="item">
<img src="../assets/img/main/img2.jpg" alt="">
<div class="carousel-caption">
<p>Cras justo odio, dapibus ac facilisis into egestas.</p>
</div>
</div>
<div class="item">
<img src="../assets/img/main/img24.jpg" alt="">
<div class="carousel-caption">
<p>Justo cras odio apibus ac afilisis lingestas de.</p>
</div>
</div>
</div>
<div class="carousel-arrow">
<a class="left carousel-control" href="#myCarousel" data-slide="prev">
<i class="fa fa-angle-left"></i>
</a>
<a class="right carousel-control" href="#myCarousel" data-slide="next">
<i class="fa fa-angle-right"></i>
</a>
</div>
</div>
</div><!--/col-md-4-->
</div>
<!-- End Info Blokcs -->
<!-- Owl Clients v1 -->
<div class="headline"><h2>Our Clients</h2></div>
<div class="owl-clients-v1">
<div class="item">
<img src="../assets/img/clients4/1.png" alt="">
</div>
<div class="item">
<img src="../assets/img/clients4/2.png" alt="">
</div>
<div class="item">
<img src="../assets/img/clients4/3.png" alt="">
</div>
<div class="item">
<img src="../assets/img/clients4/4.png" alt="">
</div>
<div class="item">
<img src="../assets/img/clients4/5.png" alt="">
</div>
<div class="item">
<img src="../assets/img/clients4/6.png" alt="">
</div>
<div class="item">
<img src="../assets/img/clients4/7.png" alt="">
</div>
<div class="item">
<img src="../assets/img/clients4/8.png" alt="">
</div>
<div class="item">
<img src="../assets/img/clients4/9.png" alt="">
</div>
</div>
<!-- End Owl Clients v1 -->
</div><!--/container-->
<!-- End Content Part -->
<!--=== Footer Version 1 ===-->
<div class="footer-v1">
<div class="footer">
<div class="container">
<div class="row">
<!-- About -->
<div class="col-md-3 md-margin-bottom-40">
<a href="index.html"><img id="logo-footer" class="footer-logo" src="../assets/img/logo2-default.png" alt=""></a>
<p>About Unify dolor sit amet, consectetur adipiscing elit. Maecenas eget nisl id libero tincidunt sodales.</p>
<p>Duis eleifend fermentum ante ut aliquam. Cras mi risus, dignissim sed adipiscing ut, placerat non arcu.</p>
</div><!--/col-md-3-->
<!-- End About -->
<!-- Latest -->
<div class="col-md-3 md-margin-bottom-40">
<div class="posts">
<div class="headline"><h2>Latest Posts</h2></div>
<ul class="list-unstyled latest-list">
<li>
<a href="#">Incredible content</a>
<small>May 8, 2014</small>
</li>
<li>
<a href="#">Best shoots</a>
<small>June 23, 2014</small>
</li>
<li>
<a href="#">New Terms and Conditions</a>
<small>September 15, 2014</small>
</li>
</ul>
</div>
</div><!--/col-md-3-->
<!-- End Latest -->
<!-- Link List -->
<div class="col-md-3 md-margin-bottom-40">
<div class="headline"><h2>Useful Links</h2></div>
<ul class="list-unstyled link-list">
<li><a href="#">About us</a><i class="fa fa-angle-right"></i></li>
<li><a href="#">Portfolio</a><i class="fa fa-angle-right"></i></li>
<li><a href="#">Latest jobs</a><i class="fa fa-angle-right"></i></li>
<li><a href="#">Community</a><i class="fa fa-angle-right"></i></li>
<li><a href="#">Contact us</a><i class="fa fa-angle-right"></i></li>
</ul>
</div><!--/col-md-3-->
<!-- End Link List -->
<!-- Address -->
<div class="col-md-3 map-img md-margin-bottom-40">
<div class="headline"><h2>Contact Us</h2></div>
<address class="md-margin-bottom-40">
25, Lorem Lis Street, Orange <br />
California, US <br />
Phone: 800 123 3456 <br />
Fax: 800 123 3456 <br />
Email: <a href="mailto:info@anybiz.com" class="">info@anybiz.com</a>
</address>
</div><!--/col-md-3-->
<!-- End Address -->
</div>
</div>
</div><!--/footer-->
<div class="copyright">
<div class="container">
<div class="row">
<div class="col-md-6">
<p>
2015 © All Rights Reserved.
<a href="#">Privacy Policy</a> | <a href="#">Terms of Service</a>
</p>
</div>
<!-- Social Links -->
<div class="col-md-6">
<ul class="footer-socials list-inline">
<li>
<a href="#" class="tooltips" data-toggle="tooltip" data-placement="top" title="" data-original-title="Facebook">
<i class="fa fa-facebook"></i>
</a>
</li>
<li>
<a href="#" class="tooltips" data-toggle="tooltip" data-placement="top" title="" data-original-title="Skype">
<i class="fa fa-skype"></i>
</a>
</li>
<li>
<a href="#" class="tooltips" data-toggle="tooltip" data-placement="top" title="" data-original-title="Google Plus">
<i class="fa fa-google-plus"></i>
</a>
</li>
<li>
<a href="#" class="tooltips" data-toggle="tooltip" data-placement="top" title="" data-original-title="Linkedin">
<i class="fa fa-linkedin"></i>
</a>
</li>
<li>
<a href="#" class="tooltips" data-toggle="tooltip" data-placement="top" title="" data-original-title="Pinterest">
<i class="fa fa-pinterest"></i>
</a>
</li>
<li>
<a href="#" class="tooltips" data-toggle="tooltip" data-placement="top" title="" data-original-title="Twitter">
<i class="fa fa-twitter"></i>
</a>
</li>
<li>
<a href="#" class="tooltips" data-toggle="tooltip" data-placement="top" title="" data-original-title="Dribbble">
<i class="fa fa-dribbble"></i>
</a>
</li>
</ul>
</div>
<!-- End Social Links -->
</div>
</div>
</div><!--/copyright-->
</div>
<!--=== End Footer Version 1 ===-->
</div><!--/wrapper-->
<!-- JS Global Compulsory -->
<script src="../assets/plugins/jquery/jquery.min.js"></script>
<script src="../assets/plugins/jquery/jquery-migrate.min.js"></script>
<script src="../assets/plugins/bootstrap/js/bootstrap.min.js"></script>
<!-- JS Implementing Plugins -->
<script src="../assets/plugins/back-to-top.js"></script>
<script src="../assets/plugins/smoothScroll.js"></script>
<script src="../assets/plugins/parallax-slider/js/modernizr.js"></script>
<script src="../assets/plugins/parallax-slider/js/jquery.cslider.js"></script>
<script src="../assets/plugins/owl-carousel2/owl.carousel.min.js"></script>
<!-- JS Customization -->
<script src="../assets/js/custom.js"></script>
<!-- JS Page Level -->
<script src="../assets/js/app.js"></script>
<script src="../assets/js/plugins/owl-carousel-rtl.js"></script>
<script src="../assets/js/plugins/style-switcher-rtl.js"></script>
<script src="../assets/js/plugins/parallax-slider.js"></script>
<script>
jQuery(document).ready(function() {
App.init();
OwlCarousel.initOwlCarousel();
StyleSwitcher.initStyleSwitcher();
ParallaxSlider.initParallaxSlider();
});
</script>
<!--[if lt IE 9]>
<script src="../assets/plugins/respond.js"></script>
<script src="../assets/plugins/html5shiv.js"></script>
<script src="../assets/plugins/placeholder-IE-fixes.js"></script>
<![endif]-->
</body>
</html> | {
"content_hash": "a9c8a082f7aedd5bd353d3339cca2493",
"timestamp": "",
"source": "github",
"line_count": 1113,
"max_line_length": 292,
"avg_line_length": 63.906558849955076,
"alnum_prop": 0.4082077381621865,
"repo_name": "code1492/jenkinstest",
"id": "1b3606fa788b3e7ee86a86072fe1720dcef9fde0",
"size": "71128",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "static/plugins/Unify-v1.9.5/HTML/RTL/index.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9917148"
},
{
"name": "CoffeeScript",
"bytes": "16723"
},
{
"name": "HTML",
"bytes": "42978922"
},
{
"name": "JavaScript",
"bytes": "6213156"
},
{
"name": "Nginx",
"bytes": "861"
},
{
"name": "PHP",
"bytes": "325502"
},
{
"name": "Python",
"bytes": "24656"
},
{
"name": "Ruby",
"bytes": "161"
},
{
"name": "Shell",
"bytes": "1061"
},
{
"name": "Vue",
"bytes": "204"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.