repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
yowatana/AliPhysics | PWGLF/SPECTRA/PiKaPr/TOF/pp13/AddTaskTOFMC.C | 2141 | AliAnalysisTaskTOFMC *AddTaskTOFMC(Int_t nTPC_CR=70, Int_t Chi2_TPCcluser=4, Int_t DCAz=2)
{
// Creates, configures and attaches to the train a cascades check task.
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskStrangenessVsMultiplicity", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddTaskdE_D", "This task requires an input event handler");
return NULL;
}
TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
// Create and configure the task
AliAnalysisTaskTOFMC *taskTOFMC = new AliAnalysisTaskTOFMC("AliAnalysisTaskTOFMC", nTPC_CR,Chi2_TPCcluser, DCAz);
AliESDtrackCuts *fTrackCuts = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(kFALSE,1);
fTrackCuts->SetMinNCrossedRowsTPC(nTPC_CR);
fTrackCuts->SetMaxChi2PerClusterTPC(Chi2_TPCcluser);
fTrackCuts->SetMaxDCAToVertexZ(DCAz);
taskTOFMC->SetTrackCuts(fTrackCuts);
taskTOFMC->SetTrackCuts2(fTrackCuts);
mgr->AddTask(taskTOFMC);
TString outputFileName = AliAnalysisManager::GetCommonFileName();
outputFileName += ":PWGLF_pp13VsMult";
TString OutputListname = Form("fOutputList_CR%i_Chi2TPCcluser%i_DCAz%i",nTPC_CR, Chi2_TPCcluser, DCAz);
// if (mgr->GetMCtruthEventHandler()) outputFileName += "_MC";
Printf("Set OutputFileName : \n %s\n", outputFileName.Data() );
AliAnalysisDataContainer *coutputList = mgr->CreateContainer(OutputListname,
TList::Class(),
AliAnalysisManager::kOutputContainer, //"MC_PiKaPr_TOF_std.root");
outputFileName );
mgr->ConnectInput (taskTOFMC, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(taskTOFMC, 1, coutputList);
return taskTOFMC;
}
| bsd-3-clause |
FriedrichK/django-excel-sync | excel_sync/tests/db/models/__init__.py | 26 | from integration import *
| bsd-3-clause |
tilhom/myblog_yii2 | backend/views/post/view.php | 1324 | <?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $model common\models\Post */
$this->title = $model->title;
$this->params['breadcrumbs'][] = ['label' => 'Posts', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="post-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'title',
'content:ntext',
'tags:ntext',
[
'attribute'=>'status',
'value'=>\common\models\Lookup::item('PostStatus',$model->status),
],
'create_time:datetime',
'update_time:datetime',
[
'attribute'=>'author_id',
'label'=>'Author',
'value' => $model->author->username,
]
],
]) ?>
</div>
| bsd-3-clause |
xe1gyq/OpenAttestation | services/AttestationService/src/main/java/com/intel/mtwilson/as/business/HostBO.java | 20989 | /*
* Copyright (c) 2013, Intel Corporation.
* All rights reserved.
*
* The contents of this file are released under the BSD license, you may not use this file except in compliance with the License.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.intel.mtwilson.as.business;
import com.intel.mountwilson.as.common.ASException;
import com.intel.mountwilson.manifest.data.IManifest;
import com.intel.mountwilson.manifest.data.PcrManifest;
import com.intel.mtwilson.agent.HostAgent;
import com.intel.mtwilson.agent.HostAgentFactory;
import com.intel.mtwilson.as.controller.TblHostsJpaController;
import com.intel.mtwilson.as.controller.TblLocationPcrJpaController;
import com.intel.mtwilson.as.controller.TblMleJpaController;
import com.intel.mtwilson.as.controller.TblPcrManifestJpaController;
import com.intel.mtwilson.as.controller.TblTaLogJpaController;
import com.intel.mtwilson.as.controller.exceptions.IllegalOrphanException;
import com.intel.mtwilson.as.controller.exceptions.NonexistentEntityException;
import com.intel.mtwilson.as.data.TblHosts;
import com.intel.mtwilson.as.data.TblMle;
import com.intel.mtwilson.as.data.TblTaLog;
import com.intel.mtwilson.as.helper.BaseBO;
import com.intel.mtwilson.crypto.CryptographyException;
import com.intel.mtwilson.crypto.X509Util;
import com.intel.mtwilson.datatypes.*;
import com.intel.mtwilson.util.ResourceFinder;
import java.io.FileInputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.InputStream;
import java.net.InetAddress;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.persistence.EntityManagerFactory;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* All settings should be via setters, not via constructor, because this class may be instantiated by a factory.
*
* @author dsmagadx
*/
public class HostBO extends BaseBO {
private static final String COMMAND_LINE_MANIFEST = "/b.b00 vmbTrustedBoot=true tboot=0x0x101a000";
private static final String LOCATION_PCR = "22";
private Logger log = LoggerFactory.getLogger(getClass());
private TblMle biosMleId = null;
private TblMle vmmMleId = null;
public String addHost(TxtHost host) {
String certificate = null;
String location = null;
String ipAddress = null;
HashMap<String, ? extends IManifest> pcrMap = null;
log.debug("About the add the host to the DB");
try {
ipAddress = InetAddress.getByName(host.getHostName().toString()).getHostAddress();
if (!ipAddress.equalsIgnoreCase(host.getIPAddress().toString())) {
throw new ASException(ErrorCode.AS_HOST_IPADDRESS_NOT_MATCHED, host.getHostName().toString(),host.getIPAddress().toString());
}
checkForDuplicate(host);
getBiosAndVMM(host);
log.info("Getting Server Identity.");
TblHosts tblHosts = new TblHosts();
tblHosts.setTlsPolicyName("TRUST_FIRST_CERTIFICATE");
tblHosts.setTlsKeystore(null);
log.debug("stdalex addHost cs == " + host.getAddOn_Connection_String());
tblHosts.setAddOnConnectionInfo(host.getAddOn_Connection_String());
if (host.getHostName() != null) {
tblHosts.setName(host.getHostName().toString());
}
if (host.getIPAddress() != null) {
tblHosts.setIPAddress(host.getIPAddress().toString());
}
if (host.getPort() != null) {
tblHosts.setPort(host.getPort());
}
if (canFetchAIKCertificateForHost(host.getVmm().getName())) { // datatype.Vmm
if (!host.getAddOn_Connection_String().toLowerCase()
.contains("citrix")) {
certificate = getAIKCertificateForHost(tblHosts, host);
// we have to check that the aik certificate was signed by a trusted privacy ca
X509Certificate hostAikCert = X509Util
.decodePemCertificate(certificate);
hostAikCert.checkValidity();
// read privacy ca certificate
InputStream privacyCaIn = new FileInputStream( ResourceFinder.getFile("PrivacyCA.cer"));
// XXX TODO currently we only support one privacy CA cert...
// in the future we should read a PEM format file with possibly multiple trusted privacy ca certs
X509Certificate privacyCaCert = X509Util.decodeDerCertificate(IOUtils.toByteArray(privacyCaIn));
IOUtils.closeQuietly(privacyCaIn);
privacyCaCert.checkValidity();
// verify the trusted privacy ca signed this aik cert
hostAikCert.verify(privacyCaCert.getPublicKey());
// NoSuchAlgorithmException,InvalidKeyException,NoSuchProviderException,SignatureException
}
} else {
// ESX host so get the location for the host and store in the table
pcrMap = getHostPcrManifest(tblHosts, host);
// BUG #497 sending both the new TblHosts record and the TxtHost object just to get the TlsPolicy into
// the initial call so that with the trust_first_certificate policy we will obtain the host certificate now while adding it
log.info("Getting location for host from VCenter");
location = getLocation(pcrMap);
}
log.info(
"Saving Host in database with TlsPolicyName {} and TlsKeystoreLength {}",
tblHosts.getTlsPolicyName(),tblHosts.getTlsKeystore() == null ? "null" : tblHosts.getTlsKeystore().length);
log.debug("Saving the host details in the DB");
saveHostInDatabase(tblHosts, host, certificate, location, pcrMap);
} catch (ASException ase) {
throw ase;
} catch (CryptographyException e) {
throw new ASException(e, ErrorCode.AS_ENCRYPTION_ERROR, e.getCause() == null ? e.getMessage() : e.getCause().getMessage());
} catch (Exception e) {
log.debug("beggining stack trace --------------");
e.printStackTrace();
log.debug("end stack trace --------------");
throw new ASException(e);
}
return "true";
}
private String getLocation(HashMap<String, ? extends IManifest> pcrMap) {
if (pcrMap != null) {// Pcr map will be null for host which dont support TPM
if(pcrMap.containsKey(LOCATION_PCR))
return new TblLocationPcrJpaController(getEntityManagerFactory())
.findTblLocationPcrByPcrValue(((PcrManifest) pcrMap.get(LOCATION_PCR)).getPcrValue());
}
return null;
}
// BUG #497 adding TblHosts parameter to this call so we can send the TlsPolicy to the HostAgentFactory for making the connection
private HashMap<String, ? extends IManifest> getHostPcrManifest(
TblHosts tblHosts, TxtHost host) {
try {
// bug #538 check the host capability before we try to get a manifest
HostAgent agent = getHostAgent(tblHosts);
if (agent.isTpmAvailable()) {
HashMap<String, ? extends IManifest> pcrMap = getPcrModuleManifestMap(tblHosts, host);
return pcrMap;
} else {
throw new ASException(ErrorCode.AS_VMW_TPM_NOT_SUPPORTED, tblHosts.getName());
}
} catch (ASException e) {
if (!e.getErrorCode().equals(ErrorCode.AS_VMW_TPM_NOT_SUPPORTED)) {
throw e;
} else {
log.info("VMWare host does not support TPM. Ignoring the error for now");
}
return null;
}
}
private HashMap<String, ? extends IManifest> getPcrModuleManifestMap( TblHosts tblHosts, TxtHost host) {
HostAgentFactory hostAgentFactory = getHostAgentFactory();
HashMap<String, ? extends IManifest> pcrMap = hostAgentFactory.getManifest(tblHosts);
return pcrMap;
}
private boolean canFetchAIKCertificateForHost(String vmmName) {
return (!vmmName.contains("ESX"));
}
public String updateHost(TxtHost host) {
try {
TblHosts tblHosts = getHostByName(host.getHostName()); // datatype.Hostname
if (tblHosts == null) {
throw new ASException(ErrorCode.AS_HOST_NOT_FOUND, host
.getHostName().toString());
}
getBiosAndVMM(host);
// need to update with the new connection string before we attempt to connect to get any updated info from
//host (aik cert, manifest,etc)
if (tblHosts.getTlsPolicyName() == null && tblHosts.getTlsPolicyName().isEmpty()) {
// XXX new code to test
tblHosts.setTlsPolicyName("TRUST_FIRST_CERTIFICATE");
// XXX bug #497 the TxtHost object doesn't have the ssl
// certificate and policy
}
tblHosts.setAddOnConnectionInfo(host.getAddOn_Connection_String());
if (host.getHostName() != null) {
tblHosts.setName(host.getHostName().toString());
}
if (host.getIPAddress() != null) {
tblHosts.setIPAddress(host.getIPAddress().toString());
}
if (host.getPort() != null) {
tblHosts.setPort(host.getPort());
}
log.info("Getting identity.");
if (canFetchAIKCertificateForHost(host.getVmm().getName())) { // datatype.Vmm
String certificate = getAIKCertificateForHost(tblHosts, host);
tblHosts.setAIKCertificate(certificate);
} else { // ESX host so get the location for the host and store in
// the
if (vmmMleId.getId().intValue() != tblHosts.getVmmMleId().getId().intValue()) {
log.info("VMM is updated. Update the host specific manifest");
// BUG #497 added tblHosts parameter
HashMap<String, ? extends IManifest> pcrMap = getHostPcrManifest( tblHosts, host);
// Building objects and validating that manifests are
// created ahead of create of host
}
}
log.info("Saving Host in database");
tblHosts.setBiosMleId(biosMleId);
tblHosts.setDescription(host.getDescription());
tblHosts.setEmail(host.getEmail());
if (host.getIPAddress() != null)
tblHosts.setIPAddress(host.getIPAddress().toString()); // datatype.IPAddress
tblHosts.setPort(host.getPort());
tblHosts.setVmmMleId(vmmMleId);
log.info("Updating Host in database");
getHostsJpaController().edit(tblHosts);
} catch (ASException ase) {
throw ase;
} catch (CryptographyException e) {
throw new ASException(e, ErrorCode.AS_ENCRYPTION_ERROR,
e.getCause() == null ? e.getMessage() : e.getCause()
.getMessage());
} catch (Exception e) {
throw new ASException(e);
}
// return new HostResponse(ErrorCode.OK);
return "true";
}
public String deleteHost(Hostname hostName) { // datatype.Hostname
try {
TblHosts tblHosts = getHostByName(hostName);
if (tblHosts == null) {
throw new ASException(ErrorCode.AS_HOST_NOT_FOUND, hostName);
}
log.info("Deleting Host from database");
deleteTALogs(tblHosts.getId());
getHostsJpaController().destroy(tblHosts.getId());
} catch (ASException ase) {
throw ase;
} catch (CryptographyException e) {
throw new ASException(ErrorCode.SYSTEM_ERROR, e.getCause() == null ? e.getMessage() : e.getCause().getMessage(), e);
} catch (Exception e) {
throw new ASException(e);
}
// return new HostResponse(ErrorCode.OK);
return "true";
}
private void deleteTALogs(Integer hostId) throws IllegalOrphanException {
TblTaLogJpaController tblTaLogJpaController = getTaLogJpaController();
List<TblTaLog> taLogs = tblTaLogJpaController.findLogsByHostId(hostId, new Date());
if (taLogs != null) {
for (TblTaLog taLog : taLogs) {
try {
tblTaLogJpaController.destroy(taLog.getId());
} catch (NonexistentEntityException e) {
log.warn("Ta Log is already deleted " + taLog.getId());
}
}
log.info("Deleted all the logs for the given host " + hostId);
}
}
private String getAIKCertificateForHost(TblHosts tblHosts, TxtHost host) {
HostAgent agent = getHostAgent(tblHosts);
if( agent.isAikAvailable() ) {
X509Certificate cert = agent.getAikCertificate();
try {
return X509Util.encodePemCertificate(cert);
}
catch(Exception e) {
log.error("Cannot encode AIK certificate: "+e.toString(), e);
return null;
}
}
return null;
}
private void getBiosAndVMM(TxtHost host) {
TblMleJpaController mleController = getMleJpaController();
this.biosMleId = mleController.findBiosMle(host.getBios().getName(),
host.getBios().getVersion(), host.getBios().getOem());
if (biosMleId == null) {
throw new ASException(ErrorCode.AS_BIOS_INCORRECT, host.getBios().getName(),host.getBios().getVersion(),host.getBios().getOem());
}
this.vmmMleId = mleController.findVmmMle(host.getVmm().getName(), host
.getVmm().getVersion(), host.getVmm().getOsName(), host
.getVmm().getOsVersion());
if (vmmMleId == null) {
throw new ASException(ErrorCode.AS_VMM_INCORRECT, host.getVmm().getName(),host.getVmm().getVersion(),host.getVmm().getOsName(),host.getVmm().getOsVersion());
}
}
private void saveHostInDatabase(TblHosts newRecordWithTlsPolicyAndKeystore,TxtHost host, String certificate, String location,
HashMap<String, ? extends IManifest> pcrMap) throws CryptographyException {
// Building objects and validating that manifests are created ahead of create of host
TblHosts tblHosts = newRecordWithTlsPolicyAndKeystore; // new TblHosts();
log.info(
"saveHostInDatabase with tls policy {} and keystore size {}",
tblHosts.getTlsPolicyName(),
tblHosts.getTlsKeystore() == null ? "null" : tblHosts
.getTlsKeystore().length);
log.error(
"saveHostInDatabase with tls policy {} and keystore size {}",
tblHosts.getTlsPolicyName(),
tblHosts.getTlsKeystore() == null ? "null" : tblHosts
.getTlsKeystore().length);
TblHostsJpaController hostController = getHostsJpaController();
tblHosts.setAddOnConnectionInfo(host.getAddOn_Connection_String());
tblHosts.setBiosMleId(biosMleId);
tblHosts.setDescription(host.getDescription());
tblHosts.setEmail(host.getEmail());
if (host.getIPAddress() != null) {
tblHosts.setIPAddress(host.getIPAddress().toString()); // datatype.IPAddress
}
tblHosts.setName(host.getHostName().toString()); // datatype.Hostname
if (host.getPort() != null) {
tblHosts.setPort(host.getPort());
}
tblHosts.setVmmMleId(vmmMleId);
tblHosts.setAIKCertificate(certificate); // null is ok
if (location != null) {
tblHosts.setLocation(location);
}
// create the host
log.debug("COMMITING NEW HOST DO DATABASE");
hostController.create(tblHosts);
}
public HostResponse isHostRegistered(String hostnameOrAddress) {
try {
TblHostsJpaController tblHostsJpaController = new TblHostsJpaController(
getEntityManagerFactory());
TblHosts tblHosts = tblHostsJpaController
.findByName(hostnameOrAddress);
if (tblHosts != null) {
return new HostResponse(ErrorCode.OK); // host name exists in database
}
tblHosts = tblHostsJpaController.findByIPAddress(hostnameOrAddress);
if (tblHosts != null) {
return new HostResponse(ErrorCode.OK); // host IP address exists in database
}
return new HostResponse(ErrorCode.AS_HOST_NOT_FOUND);
} catch (ASException e) {
throw e;
} catch (Exception e) {
throw new ASException(e);
}
}
private void checkForDuplicate(TxtHost host) throws CryptographyException {
TblHostsJpaController tblHostsJpaController = getHostsJpaController();
TblHosts tblHosts1 = tblHostsJpaController.findByName(host.getHostName()
.toString()); // datatype.Hostname
TblHosts tblHosts2 = tblHostsJpaController.findByIPAddress(host.getIPAddress()
.toString());
if (tblHosts1 != null) {
throw new ASException(
ErrorCode.AS_HOST_EXISTS,
host.getHostName());
}
if (tblHosts2 != null) {
throw new ASException(
ErrorCode.AS_IPADDRESS_EXISTS,
host.getIPAddress().toString());
}
}
/**
* This is not a REST API method, it is public because it is used by
* HostTrustBO.
*
* @param hostName
* @return
* @throws CryptographyException
*/
public TblHosts getHostByName(Hostname hostName) throws CryptographyException { // datatype.Hostname
TblHosts tblHosts = null;
try {
InetAddress addr = InetAddress.getByName(hostName.toString());
String hostname = addr.getHostName();
log.debug("hostname:" +hostname);
String ip = addr.getHostAddress();
log.debug("ip:" +ip);
tblHosts = new TblHostsJpaController(getEntityManagerFactory()).findByName(hostname);
tblHosts = tblHosts!=null? tblHosts :new TblHostsJpaController(getEntityManagerFactory()).findByName(ip);
} catch (UnknownHostException e) {
log.error("Unknown host", e);
}
return tblHosts;
}
public TblHosts getHostByIpAddress(String ipAddress) throws CryptographyException {
TblHosts tblHosts = new TblHostsJpaController(getEntityManagerFactory())
.findByIPAddress(ipAddress);
return tblHosts;
}
/**
* Author: Sudhir
*
* Searches for the hosts using the criteria specified.
*
* @param searchCriteria: If in case the user has not provided any search criteria, then all the hosts
* would be returned back to the caller
* @return
*/
public List<TxtHostRecord> queryForHosts(String searchCriteria) {
try {
TblHostsJpaController tblHostsJpaController = new TblHostsJpaController(
getEntityManagerFactory());
List<TxtHostRecord> txtHostList = new ArrayList<TxtHostRecord>();
List<TblHosts> tblHostList;
if (searchCriteria != null && !searchCriteria.isEmpty())
tblHostList = tblHostsJpaController.findHostsByNameSearchCriteria(searchCriteria);
else
tblHostList = tblHostsJpaController.findTblHostsEntities();
if (tblHostList != null) {
log.info(String.format("Found [%d] host results for search criteria [%s]",tblHostList.size(), searchCriteria));
for (TblHosts tblHosts : tblHostList) {
TxtHostRecord hostObj = createTxtHostFromDatabaseRecord(tblHosts);
txtHostList.add(hostObj);
}
} else {
log.info(String.format("Found no hosts for search criteria [%s]",searchCriteria));
}
return txtHostList;
} catch (ASException e) {
throw e;
} catch (CryptographyException e) {
throw new ASException(e, ErrorCode.AS_ENCRYPTION_ERROR, e.getCause() == null ? e.getMessage() : e.getCause().getMessage());
} catch (Exception e) {
throw new ASException(e);
}
}
public TxtHostRecord createTxtHostFromDatabaseRecord(TblHosts tblHost) {
TxtHostRecord hostObj = new TxtHostRecord();
hostObj.HostName = tblHost.getName();
hostObj.IPAddress = tblHost.getIPAddress();
hostObj.Port = tblHost.getPort();
hostObj.AddOn_Connection_String = tblHost.getAddOnConnectionInfo();
hostObj.Description = tblHost.getDescription();
hostObj.Email = tblHost.getEmail();
hostObj.Location = tblHost.getLocation();
hostObj.BIOS_Name = tblHost.getBiosMleId().getName();
hostObj.BIOS_Oem = tblHost.getBiosMleId().getOemId().getName();
hostObj.BIOS_Version = tblHost.getBiosMleId().getVersion();
hostObj.VMM_Name = tblHost.getVmmMleId().getName();
hostObj.VMM_Version = tblHost.getVmmMleId().getVersion();
hostObj.VMM_OSName = tblHost.getVmmMleId().getOsId().getName();
hostObj.VMM_OSVersion = tblHost.getVmmMleId().getOsId().getVersion();
return hostObj;
}
public TblHostsJpaController getHostsJpaController () throws CryptographyException {
return new TblHostsJpaController(getEntityManagerFactory());
}
public TblMleJpaController getMleJpaController() {
return new TblMleJpaController(getEntityManagerFactory());
}
public HostAgent getHostAgent(TblHosts tblHosts) {
return new HostAgentFactory().getHostAgent(tblHosts);
}
public HostAgentFactory getHostAgentFactory() {
return new HostAgentFactory();
}
public TblTaLogJpaController getTaLogJpaController() {
return new TblTaLogJpaController(getEntityManagerFactory());
}
}
| bsd-3-clause |
akrylysov/yozuch | tests/test_rstparser.py | 3380 | import codecs
import os
import datetime
from yozuch.rstparser import RstParser
from tests import YozuchTestCase
class RstParserTest(YozuchTestCase):
def read_file(self, filename):
path = os.path.join(self.ROOT_DIR, 'data', filename)
with codecs.open(path, 'r', 'utf-8-sig') as f:
return path, f.read()
def parse(self, filename, **kwargs):
path, text = self.read_file(filename)
doc = self.parser.parse(text, path, **kwargs)
if doc is not None:
self.parser.publish(doc)
return doc
def setUp(self):
super(RstParserTest, self).setUp()
self.parser = RstParser(self.config['RST_OPTIONS'])
def test_post(self):
doc = self.parse(os.path.join('posts', 'post.rst'))
self.assertEqual(doc.title, '测试')
self.assertEqual(doc.summary, None)
self.assertEqual(doc.date, datetime.datetime(2013, 10, 2))
self.assertEqual(doc.metadata['tags'], ['tag1'])
self.assertEqual(doc.author, 'author1')
self.assertEqual(doc.metadata['author'], 'author1')
self.assertFalse(self._is_logger_errors())
def test_post_additional_meta(self):
doc = self.parse(os.path.join('posts', '2013-09-20-post-file-metadata.rst'),
additional_meta={'date': datetime.datetime(2013, 9, 20), 'slug': 'post-file-metadata'})
self.assertEqual(doc.title, 'Title')
self.assertEqual(doc.slug, 'post-file-metadata')
self.assertEqual(doc.content, '<p>Content.</p>\n')
self.assertEqual(doc.summary, None)
self.assertEqual(doc.date, datetime.datetime(2013, 9, 20))
self.assertEqual(doc.metadata['category'], 'cat2')
self.assertEqual(doc.metadata['tags'], ['tag1', 'tag 2'])
self.assertFalse(self._is_logger_errors())
def test_post_additional_default_meta(self):
doc = self.parse(os.path.join('posts', 'post-readmore.rst'), additional_meta={'category': 'additional'})
self.assertEqual(doc.metadata['category'], 'additional')
self.assertFalse(self._is_logger_errors())
def test_post_readmore(self):
doc = self.parse(os.path.join('posts', 'post-readmore.rst'))
self.assertEqual(doc.title, 'ReadMore')
self.assertEqual(doc.content, '<p>foo</p>\n<div class="section" id="section">\n<h3>Section<a class="headerlink" href="#section" title="Permalink to this headline">¶</a></h3>\n<p>bar</p>\n<p>baz</p>\n</div>\n')
self.assertEqual(doc.summary, '<p>foo</p>\n<div class="section" id="section">\n<h3>Section<a class="headerlink" href="#section" title="Permalink to this headline">¶</a></h3>\n<p>bar</p>\n</div>')
self.assertEqual(doc.date, datetime.datetime(2011, 1, 1))
self.assertFalse(self._is_logger_errors())
def test_post_error(self):
doc = self.parse(os.path.join('posts', 'post-error.rst'))
self.assertEqual(doc, None)
self.assertEqual(len(self.logger_handler.messages['error']), 1)
def test_page(self):
doc = self.parse(os.path.join('documents', 'page.rst'))
self.assertEqual(doc.title, 'Заголовок')
self.assertEqual(doc.slug, None)
self.assertEqual(doc.content, '<p>Содержимое</p>\n')
self.assertEqual(doc.summary, None)
self.assertFalse(self._is_logger_errors())
| bsd-3-clause |
vnesek/nmote-smpp | src/main/java/com/nmote/ems/PortAddressingIE.java | 2158 | /*
* Copyright (c) Nmote d.o.o. 2003-2015. All rights reserved.
* See LICENSE.txt for licensing information.
*/
package com.nmote.ems;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
* PortAddressingIE
*/
public class PortAddressingIE extends IE {
private static final long serialVersionUID = 1L;
public PortAddressingIE(int identifier) {
super(identifier);
if (identifier == 4) {
eightBit = true;
} else if (identifier == 5) {
eightBit = false;
} else {
throw new IllegalArgumentException();
}
}
public int getDestinationPort() {
return destinationPort;
}
@Override
public byte getIdentifier() {
return (byte) (eightBit ? 4 : 5);
}
@Override
public int getLength() {
return eightBit ? 2 : 4;
}
public int getOriginatorPort() {
return originatorPort;
}
@Override
public void load(InputStream in) throws IOException {
if (eightBit) {
setDestinationPort(readAndThrowEOF(in));
setOriginatorPort(readAndThrowEOF(in));
} else {
setDestinationPort(read16AndThrowEOF(in));
setOriginatorPort(read16AndThrowEOF(in));
}
}
@Override
public void save(OutputStream out) throws IOException {
if (eightBit) {
out.write(destinationPort);
out.write(originatorPort);
} else {
write16(out, destinationPort);
write16(out, originatorPort);
}
}
public void setDestinationPort(int i) {
if (i < 0 || i > 65535) {
throw new IllegalArgumentException();
}
destinationPort = i;
eightBit = destinationPort <= 255 && originatorPort <= 255;
}
public void setOriginatorPort(int i) {
if (i < 0 || i > 65535) {
throw new IllegalArgumentException();
}
originatorPort = i;
eightBit = destinationPort <= 255 && originatorPort <= 255;
}
@Override
public String toString() {
return new ToStringBuilder(this).append("dst", destinationPort).append("org", originatorPort).toString();
}
private int originatorPort;
private int destinationPort;
private boolean eightBit;
} | bsd-3-clause |
bitcraft/pyglet | contrib/scene2d/tests/scene2d/SPRITE_MODEL.py | 2672 | #!/usr/bin/env python
"""Testing the sprite model.
This test should just run without failing.
"""
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
from pyglet.window import Window
from pyglet.image import SolidColorImagePattern
from scene2d import Sprite, Image2d
class SpriteModelTest(unittest.TestCase):
def setUp(self):
self.w = Window(width=1, height=1, visible=False)
self.s = Sprite(10, 10, 10, 10,
Image2d.from_image(SolidColorImagePattern((0, 0, 0,
0)).create_image(
1, 1)))
assert (self.s.x, self.s.y) == (10, 10)
def tearDown(self):
self.w.close()
def test_top(self):
assert self.s.top == 20
self.s.top = 10
assert (self.s.x, self.s.y) == (10, 0)
def test_bottom(self):
assert self.s.bottom == 10
self.s.bottom = 0
assert (self.s.x, self.s.y) == (10, 0)
def test_right(self):
assert self.s.right == 20
self.s.right = 10
assert (self.s.x, self.s.y) == (0, 10)
def test_left(self):
assert self.s.left == 10
self.s.left = 0
assert (self.s.x, self.s.y) == (0, 10)
def test_center(self):
assert self.s.center == (15, 15)
self.s.center = (5, 5)
assert (self.s.x, self.s.y) == (0, 0)
def test_midtop(self):
assert self.s.midtop == (15, 20)
self.s.midtop = (5, 5)
assert (self.s.x, self.s.y) == (0, -5)
def test_midbottom(self):
assert self.s.midbottom == (15, 10)
self.s.midbottom = (5, 5)
assert (self.s.x, self.s.y) == (0, 5)
def test_midleft(self):
assert self.s.midleft == (10, 15)
self.s.midleft = (5, 5)
assert (self.s.x, self.s.y) == (5, 0)
def test_midright(self):
assert self.s.midright == (20, 15)
self.s.midright = (5, 5)
assert (self.s.x, self.s.y) == (-5, 0)
def test_topleft(self):
assert self.s.topleft == (10, 20)
self.s.topleft = (5, 5)
assert (self.s.x, self.s.y) == (5, -5)
def test_topright(self):
assert self.s.topright == (20, 20)
self.s.topright = (5, 5)
assert (self.s.x, self.s.y) == (-5, -5)
def test_bottomright(self):
assert self.s.bottomright == (20, 10)
self.s.bottomright = (5, 5)
assert (self.s.x, self.s.y) == (-5, 5)
def test_bottomleft(self):
assert self.s.bottomleft == (10, 10)
self.s.bottomleft = (5, 5)
assert (self.s.x, self.s.y) == (5, 5)
unittest.main()
| bsd-3-clause |
cdotstout/sky_engine | shell/platform/android/io/flutter/plugin/platform/PlatformViewsController.java | 20508 | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugin.platform;
import static android.view.MotionEvent.PointerCoords;
import static android.view.MotionEvent.PointerProperties;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.UiThread;
import androidx.annotation.VisibleForTesting;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.embedding.engine.systemchannels.PlatformViewsChannel;
import io.flutter.plugin.editing.TextInputPlugin;
import io.flutter.view.AccessibilityBridge;
import io.flutter.view.TextureRegistry;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Manages platform views.
*
* <p>Each {@link io.flutter.app.FlutterPluginRegistry} has a single platform views controller. A
* platform views controller can be attached to at most one Flutter view.
*/
public class PlatformViewsController implements PlatformViewsAccessibilityDelegate {
private static final String TAG = "PlatformViewsController";
// API level 20 is required for VirtualDisplay#setSurface which we use when resizing a platform
// view.
private static final int MINIMAL_SDK = Build.VERSION_CODES.KITKAT_WATCH;
private final PlatformViewRegistryImpl registry;
// The context of the Activity or Fragment hosting the render target for the Flutter engine.
private Context context;
// The View currently rendering the Flutter UI associated with these platform views.
private View flutterView;
// The texture registry maintaining the textures into which the embedded views will be rendered.
private TextureRegistry textureRegistry;
private TextInputPlugin textInputPlugin;
// The system channel used to communicate with the framework about platform views.
private PlatformViewsChannel platformViewsChannel;
// The accessibility bridge to which accessibility events form the platform views will be
// dispatched.
private final AccessibilityEventsDelegate accessibilityEventsDelegate;
// TODO(mattcarroll): Refactor overall platform views to facilitate testing and then make
// this private. This is visible as a hack to facilitate testing. This was deemed the least
// bad option at the time of writing.
@VisibleForTesting /* package */ final HashMap<Integer, VirtualDisplayController> vdControllers;
// Maps a virtual display's context to the platform view hosted in this virtual display.
// Since each virtual display has it's unique context this allows associating any view with the
// platform view that
// it is associated with(e.g if a platform view creates other views in the same virtual display.
private final HashMap<Context, View> contextToPlatformView;
private final PlatformViewsChannel.PlatformViewsHandler channelHandler =
new PlatformViewsChannel.PlatformViewsHandler() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public long createPlatformView(
@NonNull PlatformViewsChannel.PlatformViewCreationRequest request) {
ensureValidAndroidVersion();
if (!validateDirection(request.direction)) {
throw new IllegalStateException(
"Trying to create a view with unknown direction value: "
+ request.direction
+ "(view id: "
+ request.viewId
+ ")");
}
if (vdControllers.containsKey(request.viewId)) {
throw new IllegalStateException(
"Trying to create an already created platform view, view id: " + request.viewId);
}
PlatformViewFactory viewFactory = registry.getFactory(request.viewType);
if (viewFactory == null) {
throw new IllegalStateException(
"Trying to create a platform view of unregistered type: " + request.viewType);
}
Object createParams = null;
if (request.params != null) {
createParams = viewFactory.getCreateArgsCodec().decodeMessage(request.params);
}
int physicalWidth = toPhysicalPixels(request.logicalWidth);
int physicalHeight = toPhysicalPixels(request.logicalHeight);
validateVirtualDisplayDimensions(physicalWidth, physicalHeight);
TextureRegistry.SurfaceTextureEntry textureEntry = textureRegistry.createSurfaceTexture();
VirtualDisplayController vdController =
VirtualDisplayController.create(
context,
accessibilityEventsDelegate,
viewFactory,
textureEntry,
physicalWidth,
physicalHeight,
request.viewId,
createParams,
(view, hasFocus) -> {
if (hasFocus) {
platformViewsChannel.invokeViewFocused(request.viewId);
}
});
if (vdController == null) {
throw new IllegalStateException(
"Failed creating virtual display for a "
+ request.viewType
+ " with id: "
+ request.viewId);
}
// If our FlutterEngine is already attached to a Flutter UI, provide that Android
// View to this new platform view.
if (flutterView != null) {
vdController.onFlutterViewAttached(flutterView);
}
vdControllers.put(request.viewId, vdController);
View platformView = vdController.getView();
platformView.setLayoutDirection(request.direction);
contextToPlatformView.put(platformView.getContext(), platformView);
// TODO(amirh): copy accessibility nodes to the FlutterView's accessibility tree.
return textureEntry.id();
}
@Override
public void disposePlatformView(int viewId) {
ensureValidAndroidVersion();
VirtualDisplayController vdController = vdControllers.get(viewId);
if (vdController == null) {
throw new IllegalStateException(
"Trying to dispose a platform view with unknown id: " + viewId);
}
if (textInputPlugin != null) {
textInputPlugin.clearPlatformViewClient(viewId);
}
contextToPlatformView.remove(vdController.getView().getContext());
vdController.dispose();
vdControllers.remove(viewId);
}
@Override
public void resizePlatformView(
@NonNull PlatformViewsChannel.PlatformViewResizeRequest request,
@NonNull Runnable onComplete) {
ensureValidAndroidVersion();
final VirtualDisplayController vdController = vdControllers.get(request.viewId);
if (vdController == null) {
throw new IllegalStateException(
"Trying to resize a platform view with unknown id: " + request.viewId);
}
int physicalWidth = toPhysicalPixels(request.newLogicalWidth);
int physicalHeight = toPhysicalPixels(request.newLogicalHeight);
validateVirtualDisplayDimensions(physicalWidth, physicalHeight);
// Resizing involved moving the platform view to a new virtual display. Doing so
// potentially results in losing an active input connection. To make sure we preserve
// the input connection when resizing we lock it here and unlock after the resize is
// complete.
lockInputConnection(vdController);
vdController.resize(
physicalWidth,
physicalHeight,
new Runnable() {
@Override
public void run() {
unlockInputConnection(vdController);
onComplete.run();
}
});
}
@Override
public void onTouch(@NonNull PlatformViewsChannel.PlatformViewTouch touch) {
ensureValidAndroidVersion();
float density = context.getResources().getDisplayMetrics().density;
PointerProperties[] pointerProperties =
parsePointerPropertiesList(touch.rawPointerPropertiesList)
.toArray(new PointerProperties[touch.pointerCount]);
PointerCoords[] pointerCoords =
parsePointerCoordsList(touch.rawPointerCoords, density)
.toArray(new PointerCoords[touch.pointerCount]);
if (!vdControllers.containsKey(touch.viewId)) {
throw new IllegalStateException(
"Sending touch to an unknown view with id: " + touch.viewId);
}
View view = vdControllers.get(touch.viewId).getView();
MotionEvent event =
MotionEvent.obtain(
touch.downTime.longValue(),
touch.eventTime.longValue(),
touch.action,
touch.pointerCount,
pointerProperties,
pointerCoords,
touch.metaState,
touch.buttonState,
touch.xPrecision,
touch.yPrecision,
touch.deviceId,
touch.edgeFlags,
touch.source,
touch.flags);
view.dispatchTouchEvent(event);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public void setDirection(int viewId, int direction) {
ensureValidAndroidVersion();
if (!validateDirection(direction)) {
throw new IllegalStateException(
"Trying to set unknown direction value: "
+ direction
+ "(view id: "
+ viewId
+ ")");
}
View view = vdControllers.get(viewId).getView();
if (view == null) {
throw new IllegalStateException(
"Sending touch to an unknown view with id: " + direction);
}
view.setLayoutDirection(direction);
}
@Override
public void clearFocus(int viewId) {
View view = vdControllers.get(viewId).getView();
view.clearFocus();
}
private void ensureValidAndroidVersion() {
if (Build.VERSION.SDK_INT < MINIMAL_SDK) {
throw new IllegalStateException(
"Trying to use platform views with API "
+ Build.VERSION.SDK_INT
+ ", required API level is: "
+ MINIMAL_SDK);
}
}
};
public PlatformViewsController() {
registry = new PlatformViewRegistryImpl();
vdControllers = new HashMap<>();
accessibilityEventsDelegate = new AccessibilityEventsDelegate();
contextToPlatformView = new HashMap<>();
}
/**
* Attaches this platform views controller to its input and output channels.
*
* @param context The base context that will be passed to embedded views created by this
* controller. This should be the context of the Activity hosting the Flutter application.
* @param textureRegistry The texture registry which provides the output textures into which the
* embedded views will be rendered.
* @param dartExecutor The dart execution context, which is used to setup a system channel.
*/
public void attach(
Context context, TextureRegistry textureRegistry, @NonNull DartExecutor dartExecutor) {
if (this.context != null) {
throw new AssertionError(
"A PlatformViewsController can only be attached to a single output target.\n"
+ "attach was called while the PlatformViewsController was already attached.");
}
this.context = context;
this.textureRegistry = textureRegistry;
platformViewsChannel = new PlatformViewsChannel(dartExecutor);
platformViewsChannel.setPlatformViewsHandler(channelHandler);
}
/**
* Detaches this platform views controller.
*
* <p>This is typically called when a Flutter applications moves to run in the background, or is
* destroyed. After calling this the platform views controller will no longer listen to it's
* previous messenger, and will not maintain references to the texture registry, context, and
* messenger passed to the previous attach call.
*/
@UiThread
public void detach() {
platformViewsChannel.setPlatformViewsHandler(null);
platformViewsChannel = null;
context = null;
textureRegistry = null;
}
/**
* This {@code PlatformViewsController} and its {@code FlutterEngine} is now attached to an
* Android {@code View} that renders a Flutter UI.
*/
public void attachToView(@NonNull View flutterView) {
this.flutterView = flutterView;
// Inform all existing platform views that they are now associated with
// a Flutter View.
for (VirtualDisplayController controller : vdControllers.values()) {
controller.onFlutterViewAttached(flutterView);
}
}
/**
* This {@code PlatformViewController} and its {@code FlutterEngine} are no longer attached to an
* Android {@code View} that renders a Flutter UI.
*
* <p>All platform views controlled by this {@code PlatformViewController} will be detached from
* the previously attached {@code View}.
*/
public void detachFromView() {
this.flutterView = null;
// Inform all existing platform views that they are no longer associated with
// a Flutter View.
for (VirtualDisplayController controller : vdControllers.values()) {
controller.onFlutterViewDetached();
}
}
@Override
public void attachAccessibilityBridge(AccessibilityBridge accessibilityBridge) {
accessibilityEventsDelegate.setAccessibilityBridge(accessibilityBridge);
}
@Override
public void detachAccessibiltyBridge() {
accessibilityEventsDelegate.setAccessibilityBridge(null);
}
/**
* Attaches this controller to a text input plugin.
*
* <p>While a text input plugin is available, the platform views controller interacts with it to
* facilitate delegation of text input connections to platform views.
*
* <p>A platform views controller should be attached to a text input plugin whenever it is
* possible for the Flutter framework to receive text input.
*/
public void attachTextInputPlugin(TextInputPlugin textInputPlugin) {
this.textInputPlugin = textInputPlugin;
}
/** Detaches this controller from the currently attached text input plugin. */
public void detachTextInputPlugin() {
textInputPlugin = null;
}
/**
* Returns true if Flutter should perform input connection proxying for the view.
*
* <p>If the view is a platform view managed by this platform views controller returns true. Else
* if the view was created in a platform view's VD, delegates the decision to the platform view's
* {@link View#checkInputConnectionProxy(View)} method. Else returns false.
*/
public boolean checkInputConnectionProxy(View view) {
if (!contextToPlatformView.containsKey(view.getContext())) {
return false;
}
View platformView = contextToPlatformView.get(view.getContext());
if (platformView == view) {
return true;
}
return platformView.checkInputConnectionProxy(view);
}
public PlatformViewRegistry getRegistry() {
return registry;
}
/**
* Invoked when the {@link io.flutter.embedding.engine.FlutterEngine} that owns this {@link
* PlatformViewsController} attaches to JNI.
*/
public void onAttachedToJNI() {
// Currently no action needs to be taken after JNI attachment.
}
/**
* Invoked when the {@link io.flutter.embedding.engine.FlutterEngine} that owns this {@link
* PlatformViewsController} detaches from JNI.
*/
public void onDetachedFromJNI() {
// Dispose all virtual displays so that any future updates to textures will not be
// propagated to the native peer.
flushAllViews();
}
public void onPreEngineRestart() {
flushAllViews();
}
@Override
public View getPlatformViewById(Integer id) {
VirtualDisplayController controller = vdControllers.get(id);
if (controller == null) {
return null;
}
return controller.getView();
}
private void lockInputConnection(@NonNull VirtualDisplayController controller) {
if (textInputPlugin == null) {
return;
}
textInputPlugin.lockPlatformViewInputConnection();
controller.onInputConnectionLocked();
}
private void unlockInputConnection(@NonNull VirtualDisplayController controller) {
if (textInputPlugin == null) {
return;
}
textInputPlugin.unlockPlatformViewInputConnection();
controller.onInputConnectionUnlocked();
}
private static boolean validateDirection(int direction) {
return direction == View.LAYOUT_DIRECTION_LTR || direction == View.LAYOUT_DIRECTION_RTL;
}
@SuppressWarnings("unchecked")
private static List<PointerProperties> parsePointerPropertiesList(Object rawPropertiesList) {
List<Object> rawProperties = (List<Object>) rawPropertiesList;
List<PointerProperties> pointerProperties = new ArrayList<>();
for (Object o : rawProperties) {
pointerProperties.add(parsePointerProperties(o));
}
return pointerProperties;
}
@SuppressWarnings("unchecked")
private static PointerProperties parsePointerProperties(Object rawProperties) {
List<Object> propertiesList = (List<Object>) rawProperties;
PointerProperties properties = new MotionEvent.PointerProperties();
properties.id = (int) propertiesList.get(0);
properties.toolType = (int) propertiesList.get(1);
return properties;
}
@SuppressWarnings("unchecked")
private static List<PointerCoords> parsePointerCoordsList(Object rawCoordsList, float density) {
List<Object> rawCoords = (List<Object>) rawCoordsList;
List<PointerCoords> pointerCoords = new ArrayList<>();
for (Object o : rawCoords) {
pointerCoords.add(parsePointerCoords(o, density));
}
return pointerCoords;
}
@SuppressWarnings("unchecked")
private static PointerCoords parsePointerCoords(Object rawCoords, float density) {
List<Object> coordsList = (List<Object>) rawCoords;
PointerCoords coords = new MotionEvent.PointerCoords();
coords.orientation = (float) (double) coordsList.get(0);
coords.pressure = (float) (double) coordsList.get(1);
coords.size = (float) (double) coordsList.get(2);
coords.toolMajor = (float) (double) coordsList.get(3) * density;
coords.toolMinor = (float) (double) coordsList.get(4) * density;
coords.touchMajor = (float) (double) coordsList.get(5) * density;
coords.touchMinor = (float) (double) coordsList.get(6) * density;
coords.x = (float) (double) coordsList.get(7) * density;
coords.y = (float) (double) coordsList.get(8) * density;
return coords;
}
// Creating a VirtualDisplay larger than the size of the device screen size
// could cause the device to restart: https://github.com/flutter/flutter/issues/28978
private void validateVirtualDisplayDimensions(int width, int height) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
if (height > metrics.heightPixels || width > metrics.widthPixels) {
String message =
"Creating a virtual display of size: "
+ "["
+ width
+ ", "
+ height
+ "] may result in problems"
+ "(https://github.com/flutter/flutter/issues/2897)."
+ "It is larger than the device screen size: "
+ "["
+ metrics.widthPixels
+ ", "
+ metrics.heightPixels
+ "].";
Log.w(TAG, message);
}
}
private int toPhysicalPixels(double logicalPixels) {
float density = context.getResources().getDisplayMetrics().density;
return (int) Math.round(logicalPixels * density);
}
private void flushAllViews() {
for (VirtualDisplayController controller : vdControllers.values()) {
controller.dispose();
}
vdControllers.clear();
}
}
| bsd-3-clause |
jadb/monohook | src/Monohook.php | 2998 | <?php
/*
* This file is part of the Monohook package.
*
* (c) Jad Bitar <jadbitar@mac.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monohook;
use Monohook\Processor\AbstractProcessor;
use Monohook\Provider\ProviderInterface;
/**
* Monohook.
*
* @package Monohook
* @author Jad Bitar <jadbitar@mac.com>
*/
class Monohook
{
/**
* Provider - version control system wrapper.
*
* @var Monohook\Provider\ProviderInterface
*/
public $Provider;
/**
* Processors stack.
*
* @var array
*/
protected $processors;
/**
* Constructor.
*
* @param Provider $Provider
* @param array $config
*/
public function __construct(ProviderInterface $Provider, array $config)
{
$this->Provider = $Provider;
$this->config($config);
}
/**
* Configures hook.
*
* @param array $config
* @return void
*/
public function config($config = array())
{
if (empty($this->processors)) {
$this->processors = array();
}
if (empty($config)) {
return;
}
$defaults = array();
if (!empty($config[0])) {
if (empty($config['*'])) {
$config['*'] = $config[0];
}
unset($config[0]);
}
if (!empty($config['*'])) {
$defaults = $config['*'];
}
$processors = current(array_merge(array($this->Provider->getHook() => $defaults), $config));
foreach ($processors as $processor) {
$this->pushProcessor($processor);
}
}
/**
* Gets next processor in stack.
*
* @return mixed
*/
public function popProcessor()
{
if (empty($this->processors)) {
throw new \LogicException('You tried to pop from an empty hook stack.');
}
return array_shift($this->processors);
}
/**
* Add processor to stack.
*
* @param mixed $callback
* @return void
*/
public function pushProcessor($callback)
{
if (!is_callable($callback)) {
throw new \InvalidArgumentException(
'Hooks must be valid callables (callback or object with an __invoke method), '
. var_export($callback, true)
. ' given.'
);
}
array_push($this->processors, $callback);
}
/**
* Runs all attached processors.
*
* @return void
*/
public function run()
{
$result = AbstractProcessor::PASS;
$this->Provider->stash();
foreach ((array) $this->processors as $processor) {
if (!call_user_func($processor, $this->Provider)) {
$result = AbstractProcessor::FAIL;
}
}
$this->Provider->unstash();
return $result;
}
}
| bsd-3-clause |
tangjian60/mi | communal/config/data/company.php | 1722 | <?php
/**
* 企业职位设置表单字段map
* User: hzc
* Date: 2016/3/24
* Time: 17:19
*/
return[
'salary' =>[
0 =>['min'=> 0,'max'=>99999999],
1 =>['min'=> 0,'max'=>1000],
2 =>['min'=> 1001,'max'=>2000],
3 =>['min'=> 2001,'max'=>3000],
4 =>['min'=> 3001,'max'=>4000],
5 =>['min'=> 4001,'max'=>5000],
6 =>['min'=> 5001,'max'=>6000],
7 =>['min'=> 6001,'max'=>8000],
8 =>['min'=> 8001,'max'=>10000],
9 =>['min'=> 10001,'max'=>15000],
10 =>['min'=> 15001,'max'=>20000],
11 =>['min'=> 20001,'max'=>30000],
12 =>['min'=> 30001,'max'=>50000],
13 =>['min'=> 50000,'max'=>80000],
14 =>['min'=> 80000,'max'=>100000],
15 =>['min'=> 100000,'max'=>99999999],
],
'salaryString' =>[
0 =>'面议',
1 =>'1000以下',
2 =>'1000以下',
3 =>'2001~3000',
4 =>'3001~4000',
5 =>'3001~4000',
6 =>'5001~6000',
7 =>'6001~8000',
8 =>'8001~10000',
9 =>'10001~15000',
10 =>'15001~20000',
11 =>'20001~30000',
12 =>'30001~50000',
13 =>'50000~80000',
14 =>'80000~100000',
15 =>'100000以上',
],
'degree'=>[
0 => '不限',
1 => '初中',
2 => '高中',
3 => '中技',
4 => '中专',
5 => '大专',
6 => '本科',
7 => '硕士',
8 => '博士'
],
'workYearString' =>[
0 => '不限',
1 => '1年以上',
2 => '2年以上',
3 => '3年以上',
5 => '5年以上',
8 => '8年以上',
10 => '10年以上'
]
]; | bsd-3-clause |
fmilano/mitk | Plugins/org.blueberry.ui.qt/src/internal/handlers/berryShowViewHandler.cpp | 2929 | /*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "berryShowViewHandler.h"
#include "berryIWorkbenchCommandConstants.h"
#include "berryHandlerUtil.h"
#include "berryUIException.h"
#include "berryIWorkbenchPage.h"
#include "berryIViewDescriptor.h"
#include "berryPlatformUI.h"
#include "berryWorkbenchPlugin.h"
#include "internal/berryQtShowViewDialog.h"
#include <berryCommandExceptions.h>
#include <vector>
namespace berry
{
ShowViewHandler::ShowViewHandler()
{
}
Object::Pointer ShowViewHandler::Execute(const ExecutionEvent::ConstPointer& event)
{
IWorkbenchWindow::Pointer window = HandlerUtil::GetActiveWorkbenchWindowChecked(event);
// Get the view identifier, if any.
const ExecutionEvent::ParameterMap& parameters = event->GetParameters();
ExecutionEvent::ParameterMap::const_iterator result = parameters.find(IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_PARM_ID);
QString viewId = result != parameters.end() ? result.value() : QString::null;
result = parameters.find(IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_SECONDARY_ID);
QString secondary = result != parameters.end() ? result.value() : QString::null;
if (viewId.isEmpty())
{
this->OpenOther(window);
}
else
{
try
{
this->OpenView(viewId, secondary, window);
}
catch (const PartInitException& e)
{
throw ExecutionException("Part could not be initialized", e);
}
}
return Object::Pointer(nullptr);
}
void ShowViewHandler::OpenOther(IWorkbenchWindow::Pointer window)
{
const IWorkbenchPage::Pointer page = window->GetActivePage();
if (page.IsNull())
{
return;
}
QtShowViewDialog dialog(window.GetPointer(), WorkbenchPlugin::GetDefault()->GetViewRegistry());
int returnCode = dialog.exec();
if (returnCode == QDialog::Rejected)
{
return;
}
const QList<QString> descriptors = dialog.GetSelection();
for (QString id : descriptors)
{
try
{
this->OpenView(id, QString(), window);
}
catch (const PartInitException& e)
{
BERRY_WARN << e.what();
// StatusUtil.handleStatus(e.getStatus(),
// WorkbenchMessages.ShowView_errorTitle
// + ": " + e.getMessage(), //$NON-NLS-1$
// StatusManager.SHOW);
}
}
}
void ShowViewHandler::OpenView(const QString& viewId, const QString& secondaryId, IWorkbenchWindow::Pointer activeWorkbenchWindow)
{
const IWorkbenchPage::Pointer activePage = activeWorkbenchWindow->GetActivePage();
if (activePage.IsNull())
{
return;
}
activePage->ShowView(viewId, secondaryId, IWorkbenchPage::VIEW_ACTIVATE);
}
}
| bsd-3-clause |
werwolf41/colorshop | backend/views/yii2-app/catalog/product/update.php | 547 | <?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model common\models\Product */
$this->title = 'Изменить товар: ' . $model->name;
$this->params['breadcrumbs'][] = ['label' => 'Товары', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->name, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = 'Update';
?>
<div class="product-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
| bsd-3-clause |
mcr/ietfdb | ietf/ipr/new.py | 18312 | # Copyright The IETF Trust 2007, All Rights Reserved
import re
import models
import ietf.utils
from django import forms
from datetime import datetime
from django.shortcuts import render_to_response as render, get_object_or_404
from django.template import RequestContext
from django.http import Http404
from django.conf import settings
from ietf.utils import log
from ietf.utils.mail import send_mail
from ietf.ipr.view_sections import section_table
from ietf.idtracker.models import Rfc, InternetDraft
# ----------------------------------------------------------------
# Create base forms from models
# ----------------------------------------------------------------
phone_re = re.compile(r'^\+?[0-9 ]*(\([0-9]+\))?[0-9 -]+( ?x ?[0-9]+)?$')
phone_error_message = """Phone numbers may have a leading "+", and otherwise only contain numbers [0-9]; dash, period or space; parentheses, and an optional extension number indicated by 'x'."""
from django.forms import ModelForm
class BaseIprForm(ModelForm):
licensing_option = forms.IntegerField(widget=forms.RadioSelect(choices=models.LICENSE_CHOICES), required=False)
is_pending = forms.IntegerField(widget=forms.RadioSelect(choices=((1, "YES"), (2, "NO"))), required=False)
applies_to_all = forms.IntegerField(widget=forms.RadioSelect(choices=((1, "YES"), (2, "NO"))), required=False)
class Meta:
model = models.IprDetail
exclude = ('rfc_document', 'id_document_tag') # 'legacy_url_0','legacy_url_1','legacy_title_1','legacy_url_2','legacy_title_2')
class BaseContactForm(ModelForm):
telephone = forms.RegexField(phone_re, error_message=phone_error_message)
fax = forms.RegexField(phone_re, error_message=phone_error_message, required=False)
class Meta:
model = models.IprContact
exclude = ('ipr', 'contact_type')
# Some subclassing:
# The contact form will be part of the IprForm, so it needs a widget.
# Define one.
class MultiformWidget(forms.Widget):
def value_from_datadict(self, data, name):
return data
class ContactForm(BaseContactForm):
widget = MultiformWidget()
def add_prefix(self, field_name):
return self.prefix and ('%s_%s' % (self.prefix, field_name)) or field_name
# ----------------------------------------------------------------
# Form processing
# ----------------------------------------------------------------
def new(request, type, update=None, submitter=None):
"""Make a new IPR disclosure.
This is a big function -- maybe too big. Things would be easier if we didn't have
one form containing fields from 4 tables -- don't build something like this again...
"""
debug = ""
section_list = section_table[type].copy()
section_list.update({"title":False, "new_intro":False, "form_intro":True,
"form_submit":True, "form_legend": True, })
class IprForm(BaseIprForm):
holder_contact = None
rfclist = forms.CharField(required=False)
draftlist = forms.CharField(required=False)
stdonly_license = forms.BooleanField(required=False)
hold_contact_is_submitter = forms.BooleanField(required=False)
ietf_contact_is_submitter = forms.BooleanField(required=False)
if section_list.get("holder_contact", False):
holder_contact = ContactForm(prefix="hold")
if section_list.get("ietf_contact", False):
ietf_contact = ContactForm(prefix="ietf")
if section_list.get("submitter", False):
submitter = ContactForm(prefix="subm")
def __init__(self, *args, **kw):
contact_type = {1:"holder_contact", 2:"ietf_contact", 3:"submitter"}
contact_initial = {}
if update:
for contact in update.contact.all():
contact_initial[contact_type[contact.contact_type]] = contact.__dict__
if submitter:
if type == "third-party":
contact_initial["ietf_contact"] = submitter
else:
contact_initial["submitter"] = submitter
kwnoinit = kw.copy()
kwnoinit.pop('initial', None)
for contact in ["holder_contact", "ietf_contact", "submitter"]:
if section_list.get(contact, False):
setattr(self, contact, ContactForm(prefix=contact[:4], initial=contact_initial.get(contact, {}), *args, **kwnoinit))
rfclist_initial = ""
if update:
if settings.USE_DB_REDESIGN_PROXY_CLASSES:
from ietf.ipr.models import IprDocAlias
rfclist_initial = " ".join(a.doc_alias.name.upper() for a in IprDocAlias.objects.filter(doc_alias__name__startswith="rfc", ipr=update))
else:
rfclist_initial = " ".join(["RFC%d" % rfc.document_id for rfc in update.rfcs.all()])
self.base_fields["rfclist"] = forms.CharField(required=False, initial=rfclist_initial)
draftlist_initial = ""
if update:
if settings.USE_DB_REDESIGN_PROXY_CLASSES:
from ietf.ipr.models import IprDocAlias
draftlist_initial = " ".join(a.doc_alias.name + ("-%s" % a.rev if a.rev else "") for a in IprDocAlias.objects.filter(ipr=update).exclude(doc_alias__name__startswith="rfc"))
else:
draftlist_initial = " ".join([draft.document.filename + (draft.revision and "-%s" % draft.revision or "") for draft in update.drafts.all()])
self.base_fields["draftlist"] = forms.CharField(required=False, initial=draftlist_initial)
if section_list.get("holder_contact", False):
self.base_fields["hold_contact_is_submitter"] = forms.BooleanField(required=False)
if section_list.get("ietf_contact", False):
self.base_fields["ietf_contact_is_submitter"] = forms.BooleanField(required=False)
self.base_fields["stdonly_license"] = forms.BooleanField(required=False)
BaseIprForm.__init__(self, *args, **kw)
# Special validation code
def clean(self):
if section_list.get("ietf_doc", False):
# would like to put this in rfclist to get the error
# closer to the fields, but clean_data["draftlist"]
# isn't set yet.
rfclist = self.cleaned_data.get("rfclist", None)
draftlist = self.cleaned_data.get("draftlist", None)
other = self.cleaned_data.get("other_designations", None)
if not rfclist and not draftlist and not other:
raise forms.ValidationError("One of the Document fields below must be filled in")
return self.cleaned_data
def clean_rfclist(self):
rfclist = self.cleaned_data.get("rfclist", None)
if rfclist:
rfclist = re.sub("(?i) *[,;]? *rfc[- ]?", " ", rfclist)
rfclist = rfclist.strip().split()
for rfc in rfclist:
try:
if settings.USE_DB_REDESIGN_PROXY_CLASSES:
from ietf.doc.models import DocAlias
DocAlias.objects.get(name="rfc%s" % int(rfc))
else:
Rfc.objects.get(rfc_number=int(rfc))
except:
raise forms.ValidationError("Unknown RFC number: %s - please correct this." % rfc)
rfclist = " ".join(rfclist)
return rfclist
def clean_draftlist(self):
draftlist = self.cleaned_data.get("draftlist", None)
if draftlist:
draftlist = re.sub(" *[,;] *", " ", draftlist)
draftlist = draftlist.strip().split()
drafts = []
for draft in draftlist:
if draft.endswith(".txt"):
draft = draft[:-4]
if re.search("-[0-9][0-9]$", draft):
filename = draft[:-3]
rev = draft[-2:]
else:
filename = draft
rev = None
try:
if settings.USE_DB_REDESIGN_PROXY_CLASSES:
from ietf.doc.models import DocAlias
id = DocAlias.objects.get(name=filename)
# proxy attribute for code below
id.revision = id.document.rev
else:
id = InternetDraft.objects.get(filename=filename)
except Exception, e:
log("Exception: %s" % e)
raise forms.ValidationError("Unknown Internet-Draft: %s - please correct this." % filename)
if rev and id.revision != rev:
raise forms.ValidationError("Unexpected revision '%s' for draft %s - the current revision is %s. Please check this." % (rev, filename, id.revision))
drafts.append("%s-%s" % (filename, id.revision))
return " ".join(drafts)
return ""
def clean_licensing_option(self):
licensing_option = self.cleaned_data['licensing_option']
if section_list.get('licensing', False):
if licensing_option in (None, ''):
raise forms.ValidationError, 'This field is required.'
return licensing_option
def is_valid(self):
if not BaseIprForm.is_valid(self):
return False
for contact in ["holder_contact", "ietf_contact", "submitter"]:
if hasattr(self, contact) and getattr(self, contact) != None and not getattr(self, contact).is_valid():
return False
return True
# If we're POSTed, but we got passed a submitter, it was the
# POST of the "get updater" form, so we don't want to validate
# this one. When we're posting *this* form, submitter is None,
# even when updating.
if (request.method == 'POST' or '_testpost' in request.REQUEST) and not submitter:
if request.method == 'POST':
data = request.POST.copy()
else:
data = request.GET.copy()
data["submitted_date"] = datetime.now().strftime("%Y-%m-%d")
data["third_party"] = section_list["third_party"]
data["generic"] = section_list["generic"]
data["status"] = "0"
data["comply"] = "1"
for src in ["hold", "ietf"]:
if "%s_contact_is_submitter" % src in data:
for subfield in ["name", "title", "department", "address1", "address2", "telephone", "fax", "email"]:
try:
data[ "subm_%s" % subfield ] = data[ "%s_%s" % (src,subfield) ]
except Exception, e:
#log("Caught exception: %s"%e)
pass
form = IprForm(data)
if form.is_valid():
# Save data :
# IprDetail, IprUpdate, IprContact+, IprDraft+, IprRfc+, IprNotification
# Save IprDetail
instance = form.save(commit=False)
legal_name_genitive = data['legal_name'] + "'" if data['legal_name'].endswith('s') else data['legal_name'] + "'s"
if type == "generic":
instance.title = legal_name_genitive + " General License Statement"
if type == "specific":
data["ipr_summary"] = get_ipr_summary(form.cleaned_data)
instance.title = legal_name_genitive + """ Statement about IPR related to %(ipr_summary)s""" % data
if type == "third-party":
data["ipr_summary"] = get_ipr_summary(form.cleaned_data)
ietf_name_genitive = data['ietf_name'] + "'" if data['ietf_name'].endswith('s') else data['ietf_name'] + "'s"
instance.title = ietf_name_genitive + """ Statement about IPR related to %(ipr_summary)s belonging to %(legal_name)s""" % data
# A long document list can create a too-long title;
# saving a too-long title raises an exception,
# so prevent truncation in the database layer by
# performing it explicitly.
if len(instance.title) > 255:
instance.title = instance.title[:252] + "..."
instance.save()
if update:
updater = models.IprUpdate(ipr=instance, updated=update, status_to_be=1, processed=0)
updater.save()
contact_type = {"hold":1, "ietf":2, "subm": 3}
# Save IprContact(s)
for prefix in ["hold", "ietf", "subm"]:
# cdata = {"ipr": instance.ipr_id, "contact_type":contact_type[prefix]}
cdata = {"ipr": instance, "contact_type":contact_type[prefix]}
for item in data:
if item.startswith(prefix+"_"):
cdata[item[5:]] = data[item]
try:
del cdata["contact_is_submitter"]
except KeyError:
pass
contact = models.IprContact(**dict([(str(a),b) for a,b in cdata.items()]))
contact.save()
# store this contact in the instance for the email
# similar to what views.show() does
if prefix == "hold":
instance.holder_contact = contact
elif prefix == "ietf":
instance.ietf_contact = contact
elif prefix == "subm":
instance.submitter = contact
# contact = ContactForm(cdata)
# if contact.is_valid():
# contact.save()
# else:
# log("Invalid contact: %s" % contact)
# Save IprDraft(s)
for draft in form.cleaned_data["draftlist"].split():
if settings.USE_DB_REDESIGN_PROXY_CLASSES:
name = draft[:-3]
rev = draft[-2:]
from ietf.doc.models import DocAlias
models.IprDocAlias.objects.create(
doc_alias=DocAlias.objects.get(name=name),
ipr=instance,
rev=rev)
else:
id = InternetDraft.objects.get(filename=draft[:-3])
iprdraft = models.IprDraft(document=id, ipr=instance, revision=draft[-2:])
iprdraft.save()
# Save IprRfc(s)
for rfcnum in form.cleaned_data["rfclist"].split():
if settings.USE_DB_REDESIGN_PROXY_CLASSES:
from ietf.doc.models import DocAlias
models.IprDocAlias.objects.create(
doc_alias=DocAlias.objects.get(name="rfc%s" % int(rfcnum)),
ipr=instance,
rev="")
else:
rfc = Rfc.objects.get(rfc_number=int(rfcnum))
iprrfc = models.IprRfc(document=rfc, ipr=instance)
iprrfc.save()
send_mail(request, settings.IPR_EMAIL_TO, ('IPR Submitter App', 'ietf-ipr@ietf.org'), 'New IPR Submission Notification', "ipr/new_update_email.txt", {"ipr": instance, "update": update})
return render("ipr/submitted.html", {"update": update}, context_instance=RequestContext(request))
else:
if 'ietf_contact_is_submitter' in data:
form.ietf_contact_is_submitter_checked = True
if 'hold_contact_is_submitter' in data:
form.hold_contact_is_submitter_checked = True
for error in form.errors:
log("Form error for field: %s: %s"%(error, form.errors[error]))
# Fall through, and let the partially bound form, with error
# indications, be rendered again.
pass
else:
if update:
form = IprForm(initial=update.__dict__)
else:
form = IprForm()
form.unbound_form = True
# ietf.utils.log(dir(form.ietf_contact_is_submitter))
return render("ipr/details_edit.html", {"ipr": form, "section_list":section_list, "debug": debug}, context_instance=RequestContext(request))
def update(request, ipr_id=None):
"""Update a specific IPR disclosure"""
ipr = get_object_or_404(models.IprDetail, ipr_id=ipr_id)
if not ipr.status in [1,3]:
raise Http404
type = "specific"
if ipr.generic:
type = "generic"
if ipr.third_party:
type = "third-party"
# We're either asking for initial permission or we're in
# the general ipr form. If the POST argument has the first
# field of the ipr form, then we must be dealing with that,
# so just pass through - otherwise, collect the updater's
# info first.
submitter = None
if not(request.POST.has_key('legal_name')):
class UpdateForm(BaseContactForm):
def __init__(self, *args, **kwargs):
super(UpdateForm, self).__init__(*args, **kwargs)
self.fields["update_auth"] = forms.BooleanField()
if request.method == 'POST':
form = UpdateForm(request.POST)
elif '_testpost' in request.REQUEST:
form = UpdateForm(request.GET)
else:
form = UpdateForm()
if not(form.is_valid()):
for error in form.errors:
log("Form error for field: %s: %s"%(error, form.errors[error]))
return render("ipr/update.html", {"form": form, "ipr": ipr, "type": type}, context_instance=RequestContext(request))
else:
submitter = form.cleaned_data
return new(request, type, ipr, submitter)
def get_ipr_summary(data):
rfc_ipr = [ "RFC %s" % item for item in data["rfclist"].split() ]
draft_ipr = data["draftlist"].split()
ipr = rfc_ipr + draft_ipr
if data["other_designations"]:
ipr += [ data["other_designations"] ]
if len(ipr) == 1:
ipr = ipr[0]
elif len(ipr) == 2:
ipr = " and ".join(ipr)
else:
ipr = ", ".join(ipr[:-1]) + ", and " + ipr[-1]
return ipr
# changes done by convert-096.py:changed newforms to forms
# cleaned_data
| bsd-3-clause |
amanzi/ats-dev | src/pks/flow/constitutive_relations/sources/plant_wilting_factor_evaluator.cc | 3384 | /*
The plant wilting factor evaluator is an algebraic evaluator of a given model.
Wilting factor.
Beta, or the water availability factor, or the plant wilting factor.
Beta = (p_closed - p) / (p_closed - p_open)
where p is the capillary pressure or soil mafic potential, and closed
and open indicate the values at which stomates are fully open or fully
closed (the wilting point).
Generated via evaluator_generator.
*/
#include "plant_wilting_factor_evaluator.hh"
#include "plant_wilting_factor_model.hh"
namespace Amanzi {
namespace Flow {
namespace Relations {
// Constructor from ParameterList
PlantWiltingFactorEvaluator::PlantWiltingFactorEvaluator(Teuchos::ParameterList& plist) :
SecondaryVariableFieldEvaluator(plist)
{
Teuchos::ParameterList& sublist = plist_.sublist("plant_wilting_factor parameters");
for (auto p : sublist) {
if (!sublist.isSublist(p.first)) {
Errors::Message message("PlantWiltingFactorEvaluator: expected list of models.");
Exceptions::amanzi_throw(message);
}
auto& model_plist = sublist.sublist(p.first);
models_.emplace_back(std::make_pair(model_plist.get<std::string>("region"),
Teuchos::rcp(new PlantWiltingFactorModel(model_plist))));
}
InitializeFromPlist_();
}
// Virtual copy constructor
Teuchos::RCP<FieldEvaluator>
PlantWiltingFactorEvaluator::Clone() const
{
return Teuchos::rcp(new PlantWiltingFactorEvaluator(*this));
}
// Initialize by setting up dependencies
void
PlantWiltingFactorEvaluator::InitializeFromPlist_()
{
// Set up my dependencies
// - defaults to prefixed via domain
Key domain_name = Keys::getDomainPrefix(my_key_);
// - pull Keys from plist
// dependency: capillary_pressure_gas_liq
pc_key_ = plist_.get<std::string>("capillary pressure gas liq key",
domain_name+"capillary_pressure_gas_liq");
dependencies_.insert(pc_key_);
}
void
PlantWiltingFactorEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S,
const Teuchos::Ptr<CompositeVector>& result)
{
Teuchos::RCP<const CompositeVector> pc = S->GetFieldData(pc_key_);
for (auto region_model : models_) {
const Epetra_MultiVector& pc_v = *pc->ViewComponent("cell", false);
Epetra_MultiVector& result_v = *result->ViewComponent("cell",false);
AmanziMesh::Entity_ID_List cells;
pc->Mesh()->get_set_entities(region_model.first, AmanziMesh::CELL,
AmanziMesh::Parallel_type::OWNED, &cells);
for (auto c : cells) {
result_v[0][c] = region_model.second->PlantWiltingFactor(pc_v[0][c]);
}
}
}
void
PlantWiltingFactorEvaluator::EvaluateFieldPartialDerivative_(const Teuchos::Ptr<State>& S,
Key wrt_key, const Teuchos::Ptr<CompositeVector>& result)
{
Teuchos::RCP<const CompositeVector> pc = S->GetFieldData(pc_key_);
if (wrt_key == pc_key_) {
for (auto region_model : models_) {
const Epetra_MultiVector& pc_v = *pc->ViewComponent("cell", false);
Epetra_MultiVector& result_v = *result->ViewComponent("cell",false);
AmanziMesh::Entity_ID_List cells;
pc->Mesh()->get_set_entities(region_model.first, AmanziMesh::CELL,
AmanziMesh::Parallel_type::OWNED, &cells);
for (auto c : cells) {
result_v[0][c] = region_model.second->DPlantWiltingFactorDCapillaryPressureGasLiq(pc_v[0][c]);
}
}
} else {
AMANZI_ASSERT(0);
}
}
} //namespace
} //namespace
} //namespace
| bsd-3-clause |
moscrif/ide | Iface/Entities/FindResult.cs | 682 | using System;
using System.Xml;
using System.Xml.Serialization;
namespace Moscrif.IDE.Iface.Entities
{
public class FindResult
{
public FindResult()
{
}
public FindResult(object key, object val)
{
this.Key=key;
this.Value= val;
}
public FindResult(object key, object val,object StartOffset,object EndOffset)
{
this.Key=key;
this.Value= val;
this.StartOffset = StartOffset;
this.EndOffset = EndOffset;
}
public object Key{
get;
set;
}
public object Value{
get;
set;
}
public object StartOffset{
get;
set;
}
public object EndOffset{
get;
set;
}
}
}
| bsd-3-clause |
prnawa/Data.Infrastructure | Data.Infrastructure.EF/Properties/AssemblyInfo.cs | 1420 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Data.Infrastructure.EF")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Data.Infrastructure.EF")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c6b6070a-c1bc-4b98-bd6e-2002d2c1fd98")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| bsd-3-clause |
google/quiche | common/platform/api/quiche_time_utils_test.cc | 2000 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "common/platform/api/quiche_time_utils.h"
#include "absl/types/optional.h"
#include "common/platform/api/quiche_test.h"
namespace quiche {
namespace {
TEST(QuicheTimeUtilsTest, Basic) {
EXPECT_EQ(1, QuicheUtcDateTimeToUnixSeconds(1970, 1, 1, 0, 0, 1));
EXPECT_EQ(365 * 86400, QuicheUtcDateTimeToUnixSeconds(1971, 1, 1, 0, 0, 0));
// Some arbitrary timestamps closer to the present, compared to the output of
// "Date(...).getTime()" from the JavaScript console.
EXPECT_EQ(1152966896,
QuicheUtcDateTimeToUnixSeconds(2006, 7, 15, 12, 34, 56));
EXPECT_EQ(1591130001, QuicheUtcDateTimeToUnixSeconds(2020, 6, 2, 20, 33, 21));
EXPECT_EQ(absl::nullopt,
QuicheUtcDateTimeToUnixSeconds(1970, 2, 29, 0, 0, 1));
EXPECT_NE(absl::nullopt,
QuicheUtcDateTimeToUnixSeconds(1972, 2, 29, 0, 0, 1));
}
TEST(QuicheTimeUtilsTest, Bounds) {
EXPECT_EQ(absl::nullopt,
QuicheUtcDateTimeToUnixSeconds(1970, 1, 32, 0, 0, 1));
EXPECT_EQ(absl::nullopt,
QuicheUtcDateTimeToUnixSeconds(1970, 4, 31, 0, 0, 1));
EXPECT_EQ(absl::nullopt, QuicheUtcDateTimeToUnixSeconds(1970, 1, 0, 0, 0, 1));
EXPECT_EQ(absl::nullopt,
QuicheUtcDateTimeToUnixSeconds(1970, 13, 1, 0, 0, 1));
EXPECT_EQ(absl::nullopt, QuicheUtcDateTimeToUnixSeconds(1970, 0, 1, 0, 0, 1));
EXPECT_EQ(absl::nullopt,
QuicheUtcDateTimeToUnixSeconds(1970, 1, 1, 24, 0, 0));
EXPECT_EQ(absl::nullopt,
QuicheUtcDateTimeToUnixSeconds(1970, 1, 1, 0, 60, 0));
}
TEST(QuicheTimeUtilsTest, LeapSecond) {
EXPECT_EQ(QuicheUtcDateTimeToUnixSeconds(2015, 6, 30, 23, 59, 60),
QuicheUtcDateTimeToUnixSeconds(2015, 7, 1, 0, 0, 0));
EXPECT_EQ(QuicheUtcDateTimeToUnixSeconds(2015, 6, 30, 25, 59, 60),
absl::nullopt);
}
} // namespace
} // namespace quiche
| bsd-3-clause |
ernest21/ConstrcionDeSoftwaresemaforo | direccion.py | 63 | class Directions:
north = 0
south = 1
east = 2
west = 3 | bsd-3-clause |
fregaham/KiWi | src/action/kiwi/api/pagelink/PageLinkServiceLocal.java | 257 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package kiwi.api.pagelink;
import javax.ejb.Local;
/**
*
* @author Stefan
*/
@Local
public interface PageLinkServiceLocal extends PageLinkService {
}
| bsd-3-clause |
kendzi/kendzi-math | kendzi-straight-skeleton/src/test/java/kendzi/math/geometry/skeleton/path/FaceQueueUtilTest.java | 2688 | package kendzi.math.geometry.skeleton.path;
import static org.junit.Assert.*;
import javax.vecmath.Point2d;
import kendzi.math.geometry.skeleton.circular.Edge;
import org.junit.Test;
public class FaceQueueUtilTest {
@Test
public void test1() {
FaceNode n1 = debugNewQueue("n1", true);
FaceNode n2 = debugNewQueue("n2");
PathQueue<FaceNode> q1 = n1.list();
PathQueue<FaceNode> q2 = n2.list();
FaceQueueUtil.connectQueues(n1, n2);
assertEquals(2, q1.size());
assertEquals(0, q2.size());
assertFalse(((FaceQueue) q1).isClosed());
assertTrue(((FaceQueue) q2).isClosed());
}
@Test
public void test2() {
FaceNode n1 = debugNewQueue("n1", true);
FaceNode n2 = debugNode("n2");
n1.addPush(n2);
PathQueue<FaceNode> q1 = n1.list();
PathQueue<FaceNode> q2 = n2.list();
FaceQueueUtil.connectQueues(n1, n2);
assertEquals(2, q1.size());
assertEquals(q1, q2);
assertTrue(((FaceQueue) q1).isClosed());
assertTrue(((FaceQueue) q2).isClosed());
}
@Test(expected = IllegalStateException.class)
public void test3() {
FaceNode n1 = debugNewQueue("n1", true);
FaceNode n2 = debugNode("n2");
FaceNode n3 = debugNode("n3");
n1.addPush(n2);
n2.addPush(n3);
FaceQueueUtil.connectQueues(n1, n2);
fail();
}
@Test(expected = IllegalStateException.class)
public void test4() {
FaceNode n1 = debugNewQueue("n1", true);
FaceNode n2 = debugNewQueue("n2", true);
// connecting two queues with different edges
FaceQueueUtil.connectQueues(n1, n2);
fail();
}
@Test(expected = IllegalStateException.class)
public void test5() {
FaceNode n1 = debugNewQueue("n1", true);
FaceNode n2 = debugNewQueue("n2", true);
n1.addPush(n2);
fail();
}
private FaceNode debugNode(final String name) {
return new FaceNode(null) {
@Override
public String toString() {
return name;
}
};
}
private FaceNode debugNewQueue(final String name, boolean edge) {
FaceQueue fq = new FaceQueue();
FaceNode fn = new FaceNode(null) {
@Override
public String toString() {
return name;
}
};
fq.addFirst(fn);
if (edge) {
fq.setEdge(new Edge(new Point2d(), new Point2d()));
}
return fn;
}
private FaceNode debugNewQueue(String name) {
return debugNewQueue(name, false);
}
}
| bsd-3-clause |
michelafrinic/WHOIS | whois-update/src/main/java/net/ripe/db/whois/update/domain/UpdateContext.java | 10541 | package net.ripe.db.whois.update.domain;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import net.ripe.db.whois.common.Message;
import net.ripe.db.whois.common.Messages;
import net.ripe.db.whois.common.dao.RpslObjectUpdateInfo;
import net.ripe.db.whois.common.domain.CIString;
import net.ripe.db.whois.common.rpsl.ObjectMessages;
import net.ripe.db.whois.common.rpsl.RpslAttribute;
import net.ripe.db.whois.common.rpsl.RpslObject;
import net.ripe.db.whois.update.authentication.Subject;
import net.ripe.db.whois.update.dns.DnsCheckRequest;
import net.ripe.db.whois.update.dns.DnsCheckResponse;
import net.ripe.db.whois.update.log.LoggerContext;
import javax.annotation.CheckForNull;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
public class UpdateContext {
private static final AtomicInteger NEXT_NR_SINCE_RESTART = new AtomicInteger();
private final List<Paragraph> ignored = Lists.newArrayList();
private final Messages globalMessages = new Messages();
// TODO: [AH] this seems to be the same as generatedkeys; could be dropped?
private final Map<Update, CIString> placeHolderForUpdate = Maps.newHashMap();
private final Map<CIString, GeneratedKey> generatedKeys = Maps.newHashMap();
private final Map<Update, Context> contexts = Maps.newLinkedHashMap();
private final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponses = Maps.newHashMap();
private final LoggerContext loggerContext;
private int nrSinceRestart;
private boolean dryRun;
public UpdateContext(final LoggerContext loggerContext) {
this.loggerContext = loggerContext;
this.nrSinceRestart = NEXT_NR_SINCE_RESTART.incrementAndGet();
}
public boolean isDryRun() {
return dryRun;
}
public void dryRun() {
loggerContext.logDryRun();
this.dryRun = true;
}
public int getNrSinceRestart() {
return nrSinceRestart;
}
public void addDnsCheckResponse(final DnsCheckRequest request, final DnsCheckResponse response) {
final DnsCheckResponse previous = dnsCheckResponses.put(request, response);
if (previous != null) {
throw new IllegalStateException("Existing response for request: " + request);
}
}
@CheckForNull
public DnsCheckResponse getCachedDnsCheckResponse(final DnsCheckRequest dnsCheckRequest) {
return dnsCheckResponses.get(dnsCheckRequest);
}
public void addMessages(final UpdateContainer updateContainer, final ObjectMessages objectMessages) {
getOrCreateContext(updateContainer).objectMessages.addAll(objectMessages);
loggerContext.logMessages(updateContainer, objectMessages);
}
public void addMessage(final UpdateContainer updateContainer, final Message message) {
getOrCreateContext(updateContainer).objectMessages.addMessage(message);
loggerContext.logMessage(updateContainer, message);
}
public void addMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message) {
getOrCreateContext(updateContainer).objectMessages.addMessage(attribute, message);
loggerContext.logMessage(updateContainer, attribute, message);
}
public ObjectMessages getMessages(final UpdateContainer updateContainer) {
return getOrCreateContext(updateContainer).objectMessages;
}
public void setAction(final UpdateContainer updateContainer, final Action action) {
getOrCreateContext(updateContainer).action = action;
loggerContext.logAction(updateContainer, action);
}
public PreparedUpdate getPreparedUpdate(final UpdateContainer updateContainer) {
return getOrCreateContext(updateContainer).preparedUpdate;
}
public boolean hasErrors(final UpdateContainer updateContainer) {
return getOrCreateContext(updateContainer).objectMessages.hasErrors();
}
public int getErrorCount(final UpdateContainer updateContainer) {
return getOrCreateContext(updateContainer).objectMessages.getErrorCount();
}
public void status(final UpdateContainer updateContainer, final UpdateStatus status) {
getOrCreateContext(updateContainer).status = status;
loggerContext.logStatus(updateContainer, status);
}
public UpdateStatus getStatus(final UpdateContainer updateContainer) {
return getOrCreateContext(updateContainer).status;
}
public void subject(final UpdateContainer updateContainer, final Subject subject) {
getOrCreateContext(updateContainer).subject = subject;
}
public Subject getSubject(final UpdateContainer updateContainer) {
return getOrCreateContext(updateContainer).subject;
}
public void updateInfo(final UpdateContainer updateContainer, final RpslObjectUpdateInfo updateInfo) {
getOrCreateContext(updateContainer).updateInfo = updateInfo;
}
public RpslObjectUpdateInfo getUpdateInfo(final UpdateContainer updateContainer) {
return getOrCreateContext(updateContainer).updateInfo;
}
public void versionId(final UpdateContainer updateContainer, final int versionId) {
getOrCreateContext(updateContainer).versionId = versionId;
}
public int getVersionId(final UpdateContainer updateContainer) {
return getOrCreateContext(updateContainer).versionId;
}
public void setPreparedUpdate(final PreparedUpdate preparedUpdate) {
final Context context = getOrCreateContext(preparedUpdate);
context.preparedUpdate = preparedUpdate;
}
public void ignore(final Paragraph paragraph) {
if (!paragraph.getContent().isEmpty()) {
ignored.add(paragraph);
}
if (!paragraph.getCredentials().ofType(PasswordOverrideCredential.class).isEmpty()) {
addGlobalMessage(UpdateMessages.overrideIgnored());
}
}
public void addGlobalMessage(final Message message) {
globalMessages.add(message);
}
List<Paragraph> getIgnoredParagraphs() {
return ignored;
}
// TODO [AK] Used by velocity templates, add test cases!
@SuppressWarnings("UnusedDeclaration")
Set<Update> getUpdates() {
final Set<Update> updates = contexts.keySet();
final Set<Update> result = Sets.newLinkedHashSetWithExpectedSize(updates.size());
for (final Update update : result) {
if (contexts.get(update).preparedUpdate != null) {
result.add(update);
}
}
return result;
}
public Messages getGlobalMessages() {
return globalMessages;
}
public String printGlobalMessages() {
final StringBuilder sb = new StringBuilder();
printMessages(globalMessages.getWarnings(), sb);
printMessages(globalMessages.getErrors(), sb);
return sb.toString();
}
private void printMessages(final Iterable<Message> messages, final StringBuilder sb) {
for (final Message message : messages) {
sb.append(UpdateMessages.print(message));
}
}
public void addGeneratedKey(final UpdateContainer updateContainer, final CIString keyPlaceholder, final GeneratedKey generatedKey) {
final Update update = updateContainer.getUpdate();
if (placeHolderForUpdate.put(update, keyPlaceholder) != null) {
throw new IllegalStateException("Multiple place holders for update: " + update.getSubmittedObject().getFormattedKey());
}
generatedKeys.put(keyPlaceholder, generatedKey);
}
public void failedUpdate(final UpdateContainer updateContainer, final Message... messages) {
final Update update = updateContainer.getUpdate();
final CIString placeHolder = placeHolderForUpdate.remove(update);
if (placeHolder != null) {
generatedKeys.remove(placeHolder);
}
for (Message message : messages) {
addMessage(updateContainer, message);
}
if (getStatus(update).equals(UpdateStatus.SUCCESS) || getStatus(update).equals(UpdateStatus.PENDING_AUTHENTICATION)) {
status(update, UpdateStatus.FAILED);
}
}
@CheckForNull
public GeneratedKey getGeneratedKey(final CIString keyPlaceholder) {
return generatedKeys.get(keyPlaceholder);
}
public Ack createAck() {
final List<UpdateResult> updateResults = Lists.newArrayList();
for (final Update update : contexts.keySet()) {
updateResults.add(createUpdateResult(update));
}
final List<Paragraph> ignoredParagraphs = getIgnoredParagraphs();
return new Ack(updateResults, ignoredParagraphs);
}
public UpdateResult createUpdateResult(final UpdateContainer updateContainer) {
final Context context = getOrCreateContext(updateContainer);
final Update update = updateContainer.getUpdate();
final RpslObject originalObject;
final RpslObject updatedObject;
if (context.preparedUpdate != null) {
originalObject = context.preparedUpdate.getReferenceObject();
updatedObject = context.preparedUpdate.getUpdatedObject();
} else {
originalObject = null;
updatedObject = update.getSubmittedObject();
}
return new UpdateResult(update, originalObject, updatedObject, context.action, context.status, context.objectMessages, context.retryCount, dryRun);
}
public void prepareForReattempt(final UpdateContainer update) {
final Context context = contexts.remove(update.getUpdate());
getOrCreateContext(update).retryCount = context.retryCount + 1;
}
private Context getOrCreateContext(final UpdateContainer updateContainer) {
final Update update = updateContainer.getUpdate();
Context context = contexts.get(update);
if (context == null) {
context = new Context();
contexts.put(update, context);
}
return context;
}
private static class Context {
private final ObjectMessages objectMessages = new ObjectMessages();
private Action action;
private PreparedUpdate preparedUpdate;
private Subject subject;
private UpdateStatus status = UpdateStatus.SUCCESS;
private int retryCount;
private RpslObjectUpdateInfo updateInfo;
private int versionId = -1;
}
}
| bsd-3-clause |
apkbox/nano-rpc | third_party/protobuf-csharp-port/src/src/ProtocolBuffers/MessageStreamWriter.cs | 2671 | #region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System.IO;
namespace Google.ProtocolBuffers {
/// <summary>
/// Writes multiple messages to the same stream. Each message is written
/// as if it were an element of a repeated field 1 in a larger protocol buffer.
/// This class takes no ownership of the stream it is given; it never closes the
/// stream.
/// </summary>
public sealed class MessageStreamWriter<T> where T : IMessage<T> {
private readonly CodedOutputStream codedOutput;
/// <summary>
/// Creates an instance which writes to the given stream.
/// </summary>
/// <param name="output">Stream to write messages to.</param>
public MessageStreamWriter(Stream output) {
codedOutput = CodedOutputStream.CreateInstance(output);
}
public void Write(T message) {
codedOutput.WriteMessage(1, message);
}
public void Flush() {
codedOutput.Flush();
}
}
}
| bsd-3-clause |
godaddy/spree_gateway | spec/models/gateway/braintree_gateway_spec.rb | 11127 | require 'spec_helper'
describe Spree::Gateway::BraintreeGateway do
before(:each) do
Spree::Gateway.update_all :active => false
@gateway = Spree::Gateway::BraintreeGateway.create!(:name => "Braintree Gateway", :environment => "sandbox", :active => true)
@gateway.set_preference(:environment, "sandbox" )
@gateway.set_preference(:merchant_id, "zbn5yzq9t7wmwx42" )
@gateway.set_preference(:public_key, "ym9djwqpkxbv3xzt")
@gateway.set_preference(:private_key, "4ghghkyp2yy6yqc8")
@gateway.save!
with_payment_profiles_off do
@country = FactoryGirl.create(:country, :name => "United States", :iso_name => "UNITED STATES", :iso3 => "USA", :iso => "US", :numcode => 840)
@state = FactoryGirl.create(:state, :name => "Maryland", :abbr => "MD", :country => @country)
@address = FactoryGirl.create(:address,
:firstname => 'John',
:lastname => 'Doe',
:address1 => '1234 My Street',
:address2 => 'Apt 1',
:city => 'Washington DC',
:zipcode => '20123',
:phone => '(555)555-5555',
:state => @state,
:country => @country
)
@order = FactoryGirl.create(:order_with_totals, :bill_address => @address, :ship_address => @address)
@order.update!
@credit_card = FactoryGirl.create(:credit_card, :verification_value => '123', :number => '5105105105105100', :month => 9, :year => Time.now.year + 1, :first_name => 'John', :last_name => 'Doe', :cc_type => 'mastercard')
@payment = FactoryGirl.create(:payment, :source => @credit_card, :order => @order, :payment_method => @gateway, :amount => 10.00)
@payment.payment_method.environment = "test"
end
end
describe 'merchant_account_id' do
before do
@gateway.set_preference(:merchant_account_id, merchant_account_id)
end
context "with merchant_account_id empty" do
let(:merchant_account_id) { "" }
it 'should not be present in options' do
@gateway.options.keys.include?(:merchant_account_id).should be_false
end
end
context 'with merchant_account_id set on gateway' do
let(:merchant_account_id) { 'test' }
it 'should have a perferred_merchant_account_id' do
@gateway.preferred_merchant_account_id.should == merchant_account_id
end
it 'should have a preferences[:merchant_account_id]' do
@gateway.preferences.keys.include?(:merchant_account_id).should be_true
end
it 'should be present in options' do
@gateway.options.keys.include?(:merchant_account_id).should be_true
end
end
end
it "should be braintree gateway" do
@gateway.provider_class.should == ::ActiveMerchant::Billing::BraintreeBlueGateway
end
describe "preferences" do
it "should not include server + test_mode" do
lambda { @gateway.preferences.fetch(:server) }.should raise_error(StandardError)
end
end
describe "authorize" do
it "should return a success response with an authorization code" do
result = @gateway.authorize(500, @credit_card)
result.success?.should be_true
result.authorization.should match(/\A\w{6}\z/)
Braintree::Transaction::Status::Authorized.should == Braintree::Transaction.find(result.authorization).status
end
shared_examples "a valid credit card" do
it 'should work through the spree payment interface' do
Spree::Config.set :auto_capture => false
@payment.log_entries.size.should == 0
@payment.process!
@payment.log_entries.size.should == 1
@payment.response_code.should match /\A\w{6}\z/
@payment.state.should == 'pending'
transaction = ::Braintree::Transaction.find(@payment.response_code)
transaction.status.should == Braintree::Transaction::Status::Authorized
card_number = @credit_card.number[0..5] + "******" + @credit_card.number[-4..-1]
transaction.credit_card_details.masked_number.should == card_number
transaction.credit_card_details.expiration_date.should == "09/#{Time.now.year + 1}"
transaction.customer_details.first_name.should == 'John'
transaction.customer_details.last_name.should == 'Doe'
end
end
context "when the card is a mastercard" do
before do
@credit_card.number = '5105105105105100'
@credit_card.cc_type = 'mastercard'
@credit_card.save
end
it_behaves_like "a valid credit card"
end
context "when the card is a visa" do
before do
@credit_card.number = '4111111111111111'
@credit_card.cc_type = 'visa'
@credit_card.save
end
it_behaves_like "a valid credit card"
end
context "when the card is an amex" do
before do
@credit_card.number = '378282246310005'
@credit_card.verification_value = '1234'
@credit_card.cc_type = 'amex'
@credit_card.save
end
it_behaves_like "a valid credit card"
end
context "when the card is a JCB" do
before do
@credit_card.number = '3530111333300000'
@credit_card.cc_type = 'jcb'
@credit_card.save
end
it_behaves_like "a valid credit card"
end
context "when the card is a diners club" do
before do
@credit_card.number = '36050000000003'
@credit_card.cc_type = 'dinersclub'
@credit_card.save
end
it_behaves_like "a valid credit card"
end
end
describe "capture" do
it " should capture a previous authorization" do
@payment.process!
assert_equal 1, @payment.log_entries.size
assert_match /\A\w{6}\z/, @payment.response_code
transaction = ::Braintree::Transaction.find(@payment.response_code)
transaction.status.should == Braintree::Transaction::Status::Authorized
capture_result = @gateway.capture(@payment,:ignored_arg_credit_card, :ignored_arg_options)
capture_result.success?.should be_true
transaction = ::Braintree::Transaction.find(@payment.response_code)
transaction.status.should == Braintree::Transaction::Status::SubmittedForSettlement
end
pending "raise an error if capture fails using spree interface" do
Spree::Config.set :auto_capture => false
@payment.log_entries.size.should == 0
@payment.process!
@payment.log_entries.size.should == 1
transaction = ::Braintree::Transaction.find(@payment.response_code)
transaction.status.should == Braintree::Transaction::Status::Authorized
@payment.payment_source.capture(@payment) # as done in PaymentsController#fire
# transaction = ::Braintree::Transaction.find(@payment.response_code)
# transaction.status.should == Braintree::Transaction::Status::SubmittedForSettlement
# lambda do
# @payment.payment_source.capture(@payment)
# end.should raise_error(Spree::Core::GatewayError, "Cannot submit for settlement unless status is authorized. (91507)")
end
end
describe 'purchase' do
it 'should return a success response with an authorization code' do
result = @gateway.purchase(500, @credit_card)
result.success?.should be_true
result.authorization.should match(/\A\w{6}\z/)
Braintree::Transaction::Status::SubmittedForSettlement.should == Braintree::Transaction.find(result.authorization).status
end
it 'should work through the spree payment interface with payment profiles' do
purchase_using_spree_interface
transaction = ::Braintree::Transaction.find(@payment.response_code)
transaction.credit_card_details.token.should_not be_nil
end
it 'should work through the spree payment interface without payment profiles' do
with_payment_profiles_off do
purchase_using_spree_interface(false)
transaction = ::Braintree::Transaction.find(@payment.response_code)
transaction.credit_card_details.token.should be_nil
end
end
end
describe "credit" do
pending "should work through the spree interface" do
@payment.amount += 100.00
purchase_using_spree_interface
credit_using_spree_interface
end
end
describe "void" do
pending "should work through the spree credit_card / payment interface" do
assert_equal 0, @payment.log_entries.size
@payment.process!
assert_equal 1, @payment.log_entries.size
@payment.response_code.should match(/\A\w{6}\z/)
transaction = Braintree::Transaction.find(@payment.response_code)
transaction.status.should == Braintree::Transaction::Status::SubmittedForSettlement
@credit_card.void(@payment)
transaction = Braintree::Transaction.find(transaction.id)
transaction.status.should == Braintree::Transaction::Status::Voided
end
end
describe "update_card_number" do
it "passes through gateway_payment_profile_id" do
credit_card = { 'token' => 'testing', 'last_4' => '1234', 'masked_number' => '5555**5555' }
@gateway.update_card_number(@payment.source, credit_card)
@payment.source.gateway_payment_profile_id.should == "testing"
end
end
def credit_using_spree_interface
@payment.log_entries.size.should == 1
@payment.source.credit(@payment) # as done in PaymentsController#fire
@payment.log_entries.size.should == 2
#Let's get the payment record associated with the credit
@payment = @order.payments.last
@payment.response_code.should match(/\A\w{6}\z/)
transaction = ::Braintree::Transaction.find(@payment.response_code)
transaction.type.should == Braintree::Transaction::Type::Credit
transaction.status.should == Braintree::Transaction::Status::SubmittedForSettlement
transaction.credit_card_details.masked_number.should == "510510******5100"
transaction.credit_card_details.expiration_date.should == "09/#{Time.now.year + 1}"
transaction.customer_details.first_name.should == "John"
transaction.customer_details.last_name.should == "Doe"
end
def purchase_using_spree_interface(profile=true)
Spree::Config.set :auto_capture => true
@payment.send(:create_payment_profile) if profile
@payment.log_entries.size == 0
@payment.process! # as done in PaymentsController#create
@payment.log_entries.size == 1
@payment.response_code.should match /\A\w{6}\z/
@payment.state.should == 'completed'
transaction = ::Braintree::Transaction.find(@payment.response_code)
Braintree::Transaction::Status::SubmittedForSettlement.should == transaction.status
transaction.credit_card_details.masked_number.should == "510510******5100"
transaction.credit_card_details.expiration_date.should == "09/#{Time.now.year + 1}"
transaction.customer_details.first_name.should == 'John'
transaction.customer_details.last_name.should == 'Doe'
end
def with_payment_profiles_off(&block)
Spree::Gateway::BraintreeGateway.class_eval do
def payment_profiles_supported?
false
end
end
yield
ensure
Spree::Gateway::BraintreeGateway.class_eval do
def payment_profiles_supported?
true
end
end
end
end
| bsd-3-clause |
mhauskn/HyperNEAT | NE/HyperNEAT/Hypercube_NEAT/src/evaluate.cpp | 8590 | #include "HCUBE_Defines.h"
#include "JGTL_CommandLineParser.h"
#ifndef HCUBE_NOGUI
# include "HCUBE_MainApp.h"
#endif
#include "HCUBE_ExperimentRun.h"
#include "Experiments/HCUBE_AtariExperiment.h"
#include "Experiments/HCUBE_AtariNoGeomExperiment.h"
#include "Experiments/HCUBE_AtariFTNeatExperiment.h"
#include "Experiments/HCUBE_AtariFTNeatPixelExperiment.h"
#include "Experiments/HCUBE_AtariIntrinsicExperiment.h"
#include "Experiments/HCUBE_AtariCMAExperiment.h"
#ifndef HCUBE_NOGUI
namespace HCUBE
{
IMPLEMENT_APP_NO_MAIN(MainApp)
}
#endif
using namespace boost;
using namespace HCUBE;
using namespace NEAT;
int HyperNEAT_main(int argc,char **argv) {
CommandLineParser commandLineParser(argc,argv);
Globals* globals = Globals::init();
if (commandLineParser.HasSwitch("-I") && // Experiment params
commandLineParser.HasSwitch("-F") && // Fitness file to write to
commandLineParser.HasSwitch("-P") && // Population file to read from
commandLineParser.HasSwitch("-N") && // Individual number within pop file
commandLineParser.HasSwitch("-G")) // Rom file to run
{
globals = Globals::init(commandLineParser.GetArgument("-I",0));
int experimentType = int(globals->getParameterValue("ExperimentType") + 0.001);
cout << "[HyperNEAT core] Loading Experiment: " << experimentType << endl;
HCUBE::ExperimentRun experimentRun;
experimentRun.setupExperiment(experimentType, "output.xml");
string populationFile = commandLineParser.GetArgument("-P",0);
experimentRun.createPopulation(populationFile);
cout << "[HyperNEAT core] Population Created\n";
if (commandLineParser.HasSwitch("-R")) {
double seed = stringTo<double>(commandLineParser.GetArgument("-R",0));
globals->setParameterValue("RandomSeed",seed);
globals->initRandom();
}
unsigned int individualId = stringTo<unsigned int>(commandLineParser.GetArgument("-N",0));
cout << "[HyperNEAT core] Evaluating individual: " << individualId << endl;
// Cast the experiment into the correct subclass and initialize with rom file
string rom_file = commandLineParser.GetArgument("-G",0);
shared_ptr<Experiment> e = experimentRun.getExperiment();
if (experimentType == 30 || experimentType == 35 || experimentType == 36) {
shared_ptr<AtariExperiment> exp = static_pointer_cast<AtariExperiment>(e);
exp->initializeExperiment(rom_file.c_str());
} else if (experimentType == 31 || experimentType == 39 || experimentType == 40) {
shared_ptr<AtariNoGeomExperiment> exp = static_pointer_cast<AtariNoGeomExperiment>(e);
exp->initializeExperiment(rom_file.c_str());
} else if (experimentType == 32 || experimentType == 37 || experimentType == 38) {
shared_ptr<AtariFTNeatExperiment> exp = static_pointer_cast<AtariFTNeatExperiment>(e);
exp->initializeExperiment(rom_file.c_str());
} else if (experimentType == 33) {
// This is the Hybrid experiment and can thus be either HyperNEAT or FT-NEAT
if (globals->hasParameterValue("HybridConversionFinished") &&
globals->getParameterValue("HybridConversionFinished") == 1.0) {
// Make the FT-NEAT experiment active
experimentRun.setActiveExperiment(1);
e = experimentRun.getExperiment();
shared_ptr<AtariFTNeatExperiment> exp = static_pointer_cast<AtariFTNeatExperiment>(e);
exp->initializeExperiment(rom_file.c_str());
} else {
// shared_ptr<AtariExperiment> exp = static_pointer_cast<AtariExperiment>(e);
// exp->initializeExperiment(rom_file.c_str());
// This is a nasty-hack like short circuit of the
// normal evaluation procedure. It is used for
// HyperNEAT evaluation in Hybrid experiments. The
// crux of this method is to convert the hyperneat
// indvidual to be evaluated into a FT-individual and
// then perform the eval using FT methods. This should
// ensure that when the swap is done, fitness does not
// drop off as a result of using different types of
// networks to evaluate individuals.
// This is the early generational case before the swap has happened
shared_ptr<AtariExperiment> atariExp = static_pointer_cast<AtariExperiment>(e);
// Initialize both experiments
atariExp->initializeExperiment(rom_file.c_str());
experimentRun.setActiveExperiment(1);
e = experimentRun.getExperiment();
shared_ptr<AtariFTNeatExperiment> ftExp = static_pointer_cast<AtariFTNeatExperiment>(e);
ftExp->initializeExperiment(rom_file.c_str());
// Get the individual to evaluate
shared_ptr<NEAT::GeneticPopulation> population = experimentRun.getPopulation();
shared_ptr<NEAT::GeneticGeneration> generation = population->getGeneration();
shared_ptr<NEAT::GeneticIndividual> HyperNEAT_individual = generation->getIndividual(individualId);
atariExp->substrate.populateSubstrate(HyperNEAT_individual);
NEAT::LayeredSubstrate<float>* HyperNEAT_substrate = &atariExp->substrate;
GeneticPopulation* FTNEAT_population = ftExp->createInitialPopulation(1);
shared_ptr<GeneticIndividual> FTNEAT_individual = FTNEAT_population->getGeneration()->getIndividual(0);
ftExp->convertIndividual(FTNEAT_individual, HyperNEAT_substrate);
ftExp->evaluateIndividual(FTNEAT_individual);
float fitness = FTNEAT_individual->getFitness();
string individualFitnessFile = commandLineParser.GetArgument("-F",0);
cout << "[HyperNEAT core] Fitness found to be " << fitness << ". Writing to: " <<
individualFitnessFile << endl;
ofstream fout(individualFitnessFile.c_str());
fout << fitness << endl;
fout.close();
cout << "[HyperNEAT core] Individual evaluation fin." << endl;
exit(0);
}
} else if (experimentType == 34) {
shared_ptr<AtariIntrinsicExperiment> exp = static_pointer_cast<AtariIntrinsicExperiment>(e);
exp->initializeExperiment(rom_file.c_str());
} else if (experimentType == 41) {
shared_ptr<AtariCMAExperiment> exp = static_pointer_cast<AtariCMAExperiment>(e);
exp->initializeExperiment(rom_file.c_str());
exp->individualToEvaluate = individualId;
assert(commandLineParser.HasSwitch("-g"));
unsigned int generationNum = stringTo<unsigned int>(commandLineParser.GetArgument("-g",0));
cout << "Using generation number " << generationNum << endl;
exp->generationNumber = generationNum;
exp->setResultsPath(populationFile);
}
float fitness = experimentRun.evaluateIndividual(individualId);
string individualFitnessFile =
commandLineParser.GetArgument("-F",0);
cout << "[HyperNEAT core] Fitness found to be " << fitness << ". Writing to: " <<
individualFitnessFile << endl;
ofstream fout(individualFitnessFile.c_str());
fout << fitness << endl;
fout.close();
cout << "[HyperNEAT core] Individual evaluation fin." << endl;
} else {
cout << "./atari_evaluate [-R (seed) -g (generationNum)] -I (datafile) -P (populationfile) -N (individualId) "
"-F (fitnessFile) -G (romFile)\n";
cout << "\t\t(datafile) HyperNEAT experiment data file - typically data/AtariExperiment.dat\n";
cout << "\t\t(populationfile) current population file containing all the individuals - "
"typically generationXX.xml.gz\n";
cout << "\t\t(individualId) unsigned int specifying which particular individual from the above"
"population file we are evaluating\n";
cout << "\t\t(fitnessFile) fitness value once estimated written to file - "
"typically fitness.XX.individualId\n";
cout << "\t\t(romFile) the Atari rom file to evaluate the agent against.\n";
}
globals->deinit();
}
int main(int argc,char **argv) {
HyperNEAT_main(argc,argv);
}
| bsd-3-clause |
JaneliaSciComp/Neuroptikon | Source/lib/CrossPlatform/networkx/generators/threshold.py | 28878 | """
Threshold Graphs - Creation, manipulation and identification.
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)\nPieter Swart (swart@lanl.gov)\nDan Schult (dschult@colgate.edu)"""
# Copyright (C) 2004-2008 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
#
__all__=[]
import random # for swap_d
from math import sqrt
import networkx
def is_threshold_graph(G):
"""
Returns True if G is a threshold graph.
"""
return is_threshold_sequence(G.degree())
def is_threshold_sequence(degree_sequence):
"""
Returns True if the sequence is a threshold degree seqeunce.
Uses the property that a threshold graph must be constructed by
adding either dominating or isolated nodes. Thus, it can be
deconstructed iteratively by removing a node of degree zero or a
node that connects to the remaining nodes. If this deconstruction
failes then the sequence is not a threshold sequence.
"""
ds=degree_sequence[:] # get a copy so we don't destroy original
ds.sort()
while ds:
if ds[0]==0: # if isolated node
ds.pop(0) # remove it
continue
if ds[-1]!=len(ds)-1: # is the largest degree node dominating?
return False # no, not a threshold degree sequence
ds.pop() # yes, largest is the dominating node
ds=[ d-1 for d in ds ] # remove it and decrement all degrees
return True
def creation_sequence(degree_sequence,with_labels=False,compact=False):
"""
Determines the creation sequence for the given threshold degree sequence.
The creation sequence is a list of single characters 'd'
or 'i': 'd' for dominating or 'i' for isolated vertices.
Dominating vertices are connected to all vertices present when it
is added. The first node added is by convention 'd'.
This list can be converted to a string if desired using "".join(cs)
If with_labels==True:
Returns a list of 2-tuples containing the vertex number
and a character 'd' or 'i' which describes the type of vertex.
If compact==True:
Returns the creation sequence in a compact form that is the number
of 'i's and 'd's alternating.
Examples:
[1,2,2,3] represents d,i,i,d,d,i,i,i
[3,1,2] represents d,d,d,i,d,d
Notice that the first number is the first vertex to be used for
construction and so is always 'd'.
with_labels and compact cannot both be True.
Returns None if the sequence is not a threshold sequence
"""
if with_labels and compact:
raise ValueError,"compact sequences cannot be labeled"
# make an indexed copy
if isinstance(degree_sequence,dict): # labeled degree seqeunce
ds = [ [degree,label] for (label,degree) in degree_sequence.items() ]
else:
ds=[ [d,i] for i,d in enumerate(degree_sequence) ]
ds.sort()
cs=[] # creation sequence
while ds:
if ds[0][0]==0: # isolated node
(d,v)=ds.pop(0)
if len(ds)>0: # make sure we start with a d
cs.insert(0,(v,'i'))
else:
cs.insert(0,(v,'d'))
continue
if ds[-1][0]!=len(ds)-1: # Not dominating node
return None # not a threshold degree sequence
(d,v)=ds.pop()
cs.insert(0,(v,'d'))
ds=[ [d[0]-1,d[1]] for d in ds ] # decrement due to removing node
if with_labels: return cs
if compact: return make_compact(cs)
return [ v[1] for v in cs ] # not labeled
def make_compact(creation_sequence):
"""
Returns the creation sequence in a compact form
that is the number of 'i's and 'd's alternating.
Examples:
[1,2,2,3] represents d,i,i,d,d,i,i,i.
[3,1,2] represents d,d,d,i,d,d.
Notice that the first number is the first vertex
to be used for construction and so is always 'd'.
Labeled creation sequences lose their labels in the
compact representation.
"""
first=creation_sequence[0]
if isinstance(first,str): # creation sequence
cs = creation_sequence[:]
elif isinstance(first,tuple): # labeled creation sequence
cs = [ s[1] for s in creation_sequence ]
elif isinstance(first,int): # compact creation sequence
return creation_sequence
else:
raise TypeError, "Not a valid creation sequence type"
ccs=[]
count=1 # count the run lengths of d's or i's.
for i in range(1,len(cs)):
if cs[i]==cs[i-1]:
count+=1
else:
ccs.append(count)
count=1
ccs.append(count) # don't forget the last one
return ccs
def uncompact(creation_sequence):
"""
Converts a compact creation sequence for a threshold
graph to a standard creation sequence (unlabeled).
If the creation_sequence is already standard, return it.
See creation_sequence.
"""
first=creation_sequence[0]
if isinstance(first,str): # creation sequence
return creation_sequence
elif isinstance(first,tuple): # labeled creation sequence
return creation_sequence
elif isinstance(first,int): # compact creation sequence
ccscopy=creation_sequence[:]
else:
raise TypeError, "Not a valid creation sequence type"
cs = []
while ccscopy:
cs.extend(ccscopy.pop(0)*['d'])
if ccscopy:
cs.extend(ccscopy.pop(0)*['i'])
return cs
def creation_sequence_to_weights(creation_sequence):
"""
Returns a list of node weights which create the threshold
graph designated by the creation sequence. The weights
are scaled so that the threshold is 1.0. The order of the
nodes is the same as that in the creation sequence.
"""
# Turn input sequence into a labeled creation sequence
first=creation_sequence[0]
if isinstance(first,str): # creation sequence
if isinstance(creation_sequence,list):
wseq = creation_sequence[:]
else:
wseq = list(creation_sequence) # string like 'ddidid'
elif isinstance(first,tuple): # labeled creation sequence
wseq = [ v[1] for v in creation_sequence]
elif isinstance(first,int): # compact creation sequence
wseq = uncompact(creation_sequence)
else:
raise TypeError, "Not a valid creation sequence type"
# pass through twice--first backwards
wseq.reverse()
w=0
prev='i'
for j,s in enumerate(wseq):
if s=='i':
wseq[j]=w
prev=s
elif prev=='i':
prev=s
w+=1
wseq.reverse() # now pass through forwards
for j,s in enumerate(wseq):
if s=='d':
wseq[j]=w
prev=s
elif prev=='d':
prev=s
w+=1
# Now scale weights
if prev=='d': w+=1
wscale=1./float(w)
return [ ww*wscale for ww in wseq]
#return wseq
def weights_to_creation_sequence(weights,threshold=1,with_labels=False,compact=False):
"""
Returns a creation sequence for a threshold graph
determined by the weights and threshold given as input.
If the sum of two node weights is greater than the
threshold value, an edge is created between these nodes.
The creation sequence is a list of single characters 'd'
or 'i': 'd' for dominating or 'i' for isolated vertices.
Dominating vertices are connected to all vertices present
when it is added. The first node added is by convention 'd'.
If with_labels==True:
Returns a list of 2-tuples containing the vertex number
and a character 'd' or 'i' which describes the type of vertex.
If compact==True:
Returns the creation sequence in a compact form that is the number
of 'i's and 'd's alternating.
Examples:
[1,2,2,3] represents d,i,i,d,d,i,i,i
[3,1,2] represents d,d,d,i,d,d
Notice that the first number is the first vertex to be used for
construction and so is always 'd'.
with_labels and compact cannot both be True.
"""
if with_labels and compact:
raise ValueError,"compact sequences cannot be labeled"
# make an indexed copy
if isinstance(weights,dict): # labeled weights
wseq = [ [w,label] for (label,w) in weights.items() ]
else:
wseq = [ [w,i] for i,w in enumerate(weights) ]
wseq.sort()
cs=[] # creation sequence
cutoff=threshold-wseq[-1][0]
while wseq:
if wseq[0][0]<cutoff: # isolated node
(w,label)=wseq.pop(0)
cs.append((label,'i'))
else:
(w,label)=wseq.pop()
cs.append((label,'d'))
cutoff=threshold-wseq[-1][0]
if len(wseq)==1: # make sure we start with a d
(w,label)=wseq.pop()
cs.append((label,'d'))
# put in correct order
cs.reverse()
if with_labels: return cs
if compact: return make_compact(cs)
return [ v[1] for v in cs ] # not labeled
# Manipulating NetworkX.Graphs in context of threshold graphs
def threshold_graph(creation_sequence, create_using=None):
"""
Create a threshold graph from the creation sequence or compact
creation_sequence.
The input sequence can be a
creation sequence (e.g. ['d','i','d','d','d','i'])
labeled creation sequence (e.g. [(0,'d'),(2,'d'),(1,'i')])
compact creation sequence (e.g. [2,1,1,2,0])
Use cs=creation_sequence(degree_sequence,labeled=True)
to convert a degree sequence to a creation sequence.
Returns None if the sequence is not valid
"""
# Turn input sequence into a labeled creation sequence
first=creation_sequence[0]
if isinstance(first,str): # creation sequence
ci = list(enumerate(creation_sequence))
elif isinstance(first,tuple): # labeled creation sequence
ci = creation_sequence[:]
elif isinstance(first,int): # compact creation sequence
cs = uncompact(creation_sequence)
ci = list(enumerate(cs))
else:
print "not a valid creation sequence type"
return None
if create_using is None:
G = networkx.Graph()
elif create_using.is_directed():
raise networkx.NetworkXError("Directed Graph not supported")
else:
G = create_using
G.clear()
G.name="Threshold Graph"
# add nodes and edges
# if type is 'i' just add nodea
# if type is a d connect to everything previous
while ci:
(v,node_type)=ci.pop(0)
if node_type=='d': # dominating type, connect to all existing nodes
for u in G.nodes():
G.add_edge(v,u)
G.add_node(v)
return G
def find_alternating_4_cycle(G):
"""
Returns False if there aren't any alternating 4 cycles.
Otherwise returns the cycle as [a,b,c,d] where (a,b)
and (c,d) are edges and (a,c) and (b,d) are not.
"""
for (u,v) in G.edges():
for w in G.nodes():
if not G.has_edge(u,w) and u!=w:
for x in G.neighbors(w):
if not G.has_edge(v,x) and v!=x:
return [u,v,w,x]
return False
def find_threshold_graph(G, create_using=None):
"""
Return a threshold subgraph that is close to largest in G.
The threshold graph will contain the largest degree node in G.
"""
return threshold_graph(find_creation_sequence(G),create_using)
def find_creation_sequence(G):
"""
Find a threshold subgraph that is close to largest in G.
Returns the labeled creation sequence of that threshold graph.
"""
cs=[]
# get a local pointer to the working part of the graph
H=G
while H.order()>0:
# get new degree sequence on subgraph
dsdict=H.degree(with_labels=True)
ds=[ [d,v] for v,d in dsdict.iteritems() ]
ds.sort()
# Update threshold graph nodes
if ds[-1][0]==0: # all are isolated
cs.extend( zip( dsdict, ['i']*(len(ds)-1)+['d']) )
break # Done!
# pull off isolated nodes
while ds[0][0]==0:
(d,iso)=ds.pop(0)
cs.append((iso,'i'))
# find new biggest node
(d,bigv)=ds.pop()
# add edges of star to t_g
cs.append((bigv,'d'))
# form subgraph of neighbors of big node
H=H.subgraph(H.neighbors(bigv))
cs.reverse()
return cs
### Properties of Threshold Graphs
def triangles(creation_sequence):
"""
Compute number of triangles in the threshold graph with the
given creation sequence.
"""
# shortcut algoritm that doesn't require computing number
# of triangles at each node.
cs=creation_sequence # alias
dr=cs.count("d") # number of d's in sequence
ntri=dr*(dr-1)*(dr-2)/6 # number of triangles in clique of nd d's
# now add dr choose 2 triangles for every 'i' in sequence where
# dr is the number of d's to the right of the current i
for i,typ in enumerate(cs):
if typ=="i":
ntri+=dr*(dr-1)/2
else:
dr-=1
return ntri
def triangle_sequence(creation_sequence):
"""
Return triangle sequence for the given threshold graph creation sequence.
"""
cs=creation_sequence
seq=[]
dr=cs.count("d") # number of d's to the right of the current pos
dcur=(dr-1)*(dr-2)/2 # number of triangles through a node of clique dr
irun=0 # number of i's in the last run
drun=0 # number of d's in the last run
for i,sym in enumerate(cs):
if sym=="d":
drun+=1
tri=dcur+(dr-1)*irun # new triangles at this d
else: # cs[i]="i":
if prevsym=="d": # new string of i's
dcur+=(dr-1)*irun # accumulate shared shortest paths
irun=0 # reset i run counter
dr-=drun # reduce number of d's to right
drun=0 # reset d run counter
irun+=1
tri=dr*(dr-1)/2 # new triangles at this i
seq.append(tri)
prevsym=sym
return seq
def cluster_sequence(creation_sequence):
"""
Return cluster sequence for the given threshold graph creation sequence.
"""
triseq=triangle_sequence(creation_sequence)
degseq=degree_sequence(creation_sequence)
cseq=[]
for i,deg in enumerate(degseq):
tri=triseq[i]
if deg <= 1: # isolated vertex or single pair gets cc 0
cseq.append(0)
continue
max_size=(deg*(deg-1))/2
cseq.append(float(tri)/float(max_size))
return cseq
def degree_sequence(creation_sequence):
"""
Return degree sequence for the threshold graph with the given
creation sequence
"""
cs=creation_sequence # alias
seq=[]
rd=cs.count("d") # number of d to the right
for i,sym in enumerate(cs):
if sym=="d":
rd-=1
seq.append(rd+i)
else:
seq.append(rd)
return seq
def density(creation_sequence):
"""
Return the density of the graph with this creation_sequence.
The density is the fraction of possible edges present.
"""
N=len(creation_sequence)
two_size=sum(degree_sequence(creation_sequence))
two_possible=N*(N-1)
den=two_size/float(two_possible)
return den
def degree_correlation(creation_sequence):
"""
Return the degree-degree correlation over all edges.
"""
cs=creation_sequence
s1=0 # deg_i*deg_j
s2=0 # deg_i^2+deg_j^2
s3=0 # deg_i+deg_j
m=0 # number of edges
rd=cs.count("d") # number of d nodes to the right
rdi=[ i for i,sym in enumerate(cs) if sym=="d"] # index of "d"s
ds=degree_sequence(cs)
for i,sym in enumerate(cs):
if sym=="d":
if i!=rdi[0]:
print "Logic error in degree_correlation",i,rdi
raise ValueError
rdi.pop(0)
degi=ds[i]
for dj in rdi:
degj=ds[dj]
s1+=degj*degi
s2+=degi**2+degj**2
s3+=degi+degj
m+=1
denom=(2*m*s2-s3*s3)
numer=(4*m*s1-s3*s3)
if denom==0:
if numer==0:
return 1
raise ValueError,"Zero Denominator but Numerator is %s"%numer
return numer/float(denom)
def shortest_path(creation_sequence,u,v):
"""
Find the shortest path between u and v in a
threshold graph G with the given creation_sequence.
For an unlabeled creation_sequence, the vertices
u and v must be integers in (0,len(sequence)) refering
to the position of the desired vertices in the sequence.
For a labeled creation_sequence, u and v are labels of veritices.
Use cs=creation_sequence(degree_sequence,with_labels=True)
to convert a degree sequence to a creation sequence.
Returns a list of vertices from u to v.
Example: if they are neighbors, it returns [u,v]
"""
# Turn input sequence into a labeled creation sequence
first=creation_sequence[0]
if isinstance(first,str): # creation sequence
cs = [(i,creation_sequence[i]) for i in xrange(len(creation_sequence))]
elif isinstance(first,tuple): # labeled creation sequence
cs = creation_sequence[:]
elif isinstance(first,int): # compact creation sequence
ci = uncompact(creation_sequence)
cs = [(i,ci[i]) for i in xrange(len(ci))]
else:
raise TypeError, "Not a valid creation sequence type"
verts=[ s[0] for s in cs ]
if v not in verts:
raise ValueError,"Vertex %s not in graph from creation_sequence"%v
if u not in verts:
raise ValueError,"Vertex %s not in graph from creation_sequence"%u
# Done checking
if u==v: return [u]
uindex=verts.index(u)
vindex=verts.index(v)
bigind=max(uindex,vindex)
if cs[bigind][1]=='d':
return [u,v]
# must be that cs[bigind][1]=='i'
cs=cs[bigind:]
while cs:
vert=cs.pop()
if vert[1]=='d':
return [u,vert[0],v]
# All after u are type 'i' so no connection
return -1
def shortest_path_length(creation_sequence,i):
"""
Return the shortest path length from indicated node to
every other node for the threshold graph with the given
creation sequence.
Node is indicated by index i in creation_sequence unless
creation_sequence is labeled in which case, i is taken to
be the label of the node.
Paths lengths in threshold graphs are at most 2.
Length to unreachable nodes is set to -1.
"""
# Turn input sequence into a labeled creation sequence
first=creation_sequence[0]
if isinstance(first,str): # creation sequence
if isinstance(creation_sequence,list):
cs = creation_sequence[:]
else:
cs = list(creation_sequence)
elif isinstance(first,tuple): # labeled creation sequence
cs = [ v[1] for v in creation_sequence]
i = [v[0] for v in creation_sequence].index(i)
elif isinstance(first,int): # compact creation sequence
cs = uncompact(creation_sequence)
else:
raise TypeError, "Not a valid creation sequence type"
# Compute
N=len(cs)
spl=[2]*N # length 2 to every node
spl[i]=0 # except self which is 0
# 1 for all d's to the right
for j in range(i+1,N):
if cs[j]=="d":
spl[j]=1
if cs[i]=='d': # 1 for all nodes to the left
for j in range(i):
spl[j]=1
# and -1 for any trailing i to indicate unreachable
for j in range(N-1,0,-1):
if cs[j]=="d":
break
spl[j]=-1
return spl
def betweenness_sequence(creation_sequence,normalized=True):
"""
Return betweenness for the threshold graph with the given creation
sequence. The result is unscaled. To scale the values
to the iterval [0,1] divide by (n-1)*(n-2).
"""
cs=creation_sequence
seq=[] # betweenness
lastchar='d' # first node is always a 'd'
dr=float(cs.count("d")) # number of d's to the right of curren pos
irun=0 # number of i's in the last run
drun=0 # number of d's in the last run
dlast=0.0 # betweenness of last d
for i,c in enumerate(cs):
if c=='d': #cs[i]=="d":
# betweennees = amt shared with eariler d's and i's
# + new isolated nodes covered
# + new paths to all previous nodes
b=dlast + (irun-1)*irun/dr + 2*irun*(i-drun-irun)/dr
drun+=1 # update counter
else: # cs[i]="i":
if lastchar=='d': # if this is a new run of i's
dlast=b # accumulate betweenness
dr-=drun # update number of d's to the right
drun=0 # reset d counter
irun=0 # reset i counter
b=0 # isolated nodes have zero betweenness
irun+=1 # add another i to the run
seq.append(float(b))
lastchar=c
# normalize by the number of possible shortest paths
if normalized:
order=len(cs)
scale=1.0/((order-1)*(order-2))
seq=[ s*scale for s in seq ]
return seq
def eigenvectors(creation_sequence):
"""
Return a 2-tuple of Laplacian eigenvalues and eigenvectors
for the threshold network with creation_sequence.
The first value is a list of eigenvalues.
The second value is a list of eigenvectors.
The lists are in the same order so corresponding eigenvectors
and eigenvalues are in the same position in the two lists.
Notice that the order of the eigenvalues returned by eigenvalues(cs)
may not correspond to the order of these eigenvectors.
"""
ccs=make_compact(creation_sequence)
N=sum(ccs)
vec=[0]*N
val=vec[:]
# get number of type d nodes to the right (all for first node)
dr=sum(ccs[::2])
nn=ccs[0]
vec[0]=[1./sqrt(N)]*N
val[0]=0
e=dr
dr-=nn
type_d=True
i=1
dd=1
while dd<nn:
scale=1./sqrt(dd*dd+i)
vec[i]=i*[-scale]+[dd*scale]+[0]*(N-i-1)
val[i]=e
i+=1
dd+=1
if len(ccs)==1: return (val,vec)
for nn in ccs[1:]:
scale=1./sqrt(nn*i*(i+nn))
vec[i]=i*[-nn*scale]+nn*[i*scale]+[0]*(N-i-nn)
# find eigenvalue
type_d=not type_d
if type_d:
e=i+dr
dr-=nn
else:
e=dr
val[i]=e
st=i
i+=1
dd=1
while dd<nn:
scale=1./sqrt(i-st+dd*dd)
vec[i]=[0]*st+(i-st)*[-scale]+[dd*scale]+[0]*(N-i-1)
val[i]=e
i+=1
dd+=1
return (val,vec)
def spectral_projection(u,eigenpairs):
"""
Returns the coefficients of each eigenvector
in a projection of the vector u onto the normalized
eigenvectors which are contained in eigenpairs.
eigenpairs should be a list of two objects. The
first is a list of eigenvalues and the second a list
of eigenvectors. The eigenvectors should be lists.
There's not a lot of error checking on lengths of
arrays, etc. so be careful.
"""
coeff=[]
evect=eigenpairs[1]
for ev in evect:
c=sum([ evv*uv for (evv,uv) in zip(ev,u)])
coeff.append(c)
return coeff
def eigenvalues(creation_sequence):
"""
Return sequence of eigenvalues of the Laplacian of the threshold
graph for the given creation_sequence.
Based on the Ferrer's diagram method. The spectrum is integral
and is the conjugate of the degree sequence.
See::
@Article{degree-merris-1994,
author = {Russel Merris},
title = {Degree maximal graphs are Laplacian integral},
journal = {Linear Algebra Appl.},
year = {1994},
volume = {199},
pages = {381--389},
}
"""
degseq=degree_sequence(creation_sequence)
degseq.sort()
eiglist=[] # zero is always one eigenvalue
eig=0
row=len(degseq)
bigdeg=degseq.pop()
while row:
if bigdeg<row:
eiglist.append(eig)
row-=1
else:
eig+=1
if degseq:
bigdeg=degseq.pop()
else:
bigdeg=0
return eiglist
### Threshold graph creation routines
def random_threshold_sequence(n,p,seed=None):
"""
Create a random threshold sequence of size n.
A creation sequence is built by randomly choosing d's with
probabiliy p and i's with probability 1-p.
s=nx.random_threshold_sequence(10,0.5)
returns a threshold sequence of length 10 with equal
probably of an i or a d at each position.
A "random" threshold graph can be built with
G=nx.threshold_graph(s)
"""
if not seed is None:
random.seed(seed)
if not (p<=1 and p>=0):
raise ValueError,"p must be in [0,1]"
cs=['d'] # threshold sequences always start with a d
for i in range(1,n):
if random.random() < p:
cs.append('d')
else:
cs.append('i')
return cs
# maybe *_d_threshold_sequence routines should
# be (or be called from) a single routine with a more descriptive name
# and a keyword parameter?
def right_d_threshold_sequence(n,m):
"""
Create a skewed threshold graph with a given number
of vertices (n) and a given number of edges (m).
The routine returns an unlabeled creation sequence
for the threshold graph.
FIXME: describe algorithm
"""
cs=['d']+['i']*(n-1) # create sequence with n insolated nodes
# m <n : not enough edges, make disconnected
if m < n:
cs[m]='d'
return cs
# too many edges
if m > n*(n-1)/2:
raise ValueError,"Too many edges for this many nodes."
# connected case m >n-1
ind=n-1
sum=n-1
while sum<m:
cs[ind]='d'
ind -= 1
sum += ind
ind=m-(sum-ind)
cs[ind]='d'
return cs
def left_d_threshold_sequence(n,m):
"""
Create a skewed threshold graph with a given number
of vertices (n) and a given number of edges (m).
The routine returns an unlabeled creation sequence
for the threshold graph.
FIXME: describe algorithm
"""
cs=['d']+['i']*(n-1) # create sequence with n insolated nodes
# m <n : not enough edges, make disconnected
if m < n:
cs[m]='d'
return cs
# too many edges
if m > n*(n-1)/2:
raise ValueError,"Too many edges for this many nodes."
# Connected case when M>N-1
cs[n-1]='d'
sum=n-1
ind=1
while sum<m:
cs[ind]='d'
sum += ind
ind += 1
if sum>m: # be sure not to change the first vertex
cs[sum-m]='i'
return cs
def swap_d(cs,p_split=1.0,p_combine=1.0,seed=None):
"""
Perform a "swap" operation on a threshold sequence.
The swap preserves the number of nodes and edges
in the graph for the given sequence.
The resulting sequence is still a threshold sequence.
Perform one split and one combine operation on the
'd's of a creation sequence for a threshold graph.
This operation maintains the number of nodes and edges
in the graph, but shifts the edges from node to node
maintaining the threshold quality of the graph.
"""
if not seed is None:
random.seed(seed)
# preprocess the creation sequence
dlist= [ i for (i,node_type) in enumerate(cs[1:-1]) if node_type=='d' ]
# split
if random.random()<p_split:
choice=random.choice(dlist)
split_to=random.choice(range(choice))
flip_side=choice-split_to
if split_to!=flip_side and cs[split_to]=='i' and cs[flip_side]=='i':
cs[choice]='i'
cs[split_to]='d'
cs[flip_side]='d'
dlist.remove(choice)
# don't add or combine may reverse this action
# dlist.extend([split_to,flip_side])
# print >>sys.stderr,"split at %s to %s and %s"%(choice,split_to,flip_side)
# combine
if random.random()<p_combine and dlist:
first_choice= random.choice(dlist)
second_choice=random.choice(dlist)
target=first_choice+second_choice
if target >= len(cs) or cs[target]=='d' or first_choice==second_choice:
return cs
# OK to combine
cs[first_choice]='i'
cs[second_choice]='i'
cs[target]='d'
# print >>sys.stderr,"combine %s and %s to make %s."%(first_choice,second_choice,target)
return cs
| bsd-3-clause |
gamersmafia/gamersmafia | test/unit/notification_test.rb | 1313 | require 'test_helper'
class NotificationTest < ActiveSupport::TestCase
def create_notification
notif = @u1.notifications.new({
:description => "Fulanito te manda un beso",
:type_id => Notification::UNDEFINED,
})
assert_difference("@u1.notifications.count") do
notif.save
end
@u1.reload
notif
end
test "create notification should mark as unread" do
@u1 = User.find(1)
assert !@u1.has_unread_notifications
self.create_notification
assert @u1.has_unread_notifications
end
test "mark_as_read works" do
@u1 = User.find(1)
assert !@u1.has_unread_notifications
self.create_notification
Notification.mark_as_read(
@u1, @u1.notifications.unread.find(:all).collect {|n| n.id})
assert !@u1.has_unread_notifications
end
test "forget_old_read_notifications" do
@u1 = User.find(1)
notification1 = self.create_notification
notification2 = self.create_notification
notification2.update_column(:created_on, 2.months.ago)
Notification.forget_old_read_notifications
Notification.mark_as_read(
@u1, @u1.notifications.unread.find(:all).collect {|n| n.id})
@u1.reload
assert_difference("@u1.notifications.count", -1) do
Notification.forget_old_read_notifications
end
end
end
| bsd-3-clause |
duke-libraries/ddr-models | spec/routing/user_routing_spec.rb | 1074 | RSpec.describe "users router", type: :routing do
it "should have a new session route" do
expect(get: '/users/sign_in').to route_to(controller: 'users/sessions', action: 'new')
end
it "should have a new session path helper" do
expect(get: new_user_session_path).to route_to(controller: 'users/sessions', action: 'new')
end
it "should have a destroy session route" do
expect(get: '/users/sign_out').to route_to(controller: 'users/sessions', action: 'destroy')
end
it "should have a destroy session path helper" do
expect(get: destroy_user_session_path).to route_to(controller: 'users/sessions', action: 'destroy')
end
it "should have a shibboleth authentication path" do
expect(get: '/users/auth/shibboleth').to route_to(controller: 'users/omniauth_callbacks', action: 'passthru', provider: 'shibboleth')
end
it "should have a shibboleth authentication path helper" do
expect(get: user_omniauth_authorize_path(:shibboleth)).to route_to(controller: 'users/omniauth_callbacks', action: 'passthru', provider: 'shibboleth')
end
end
| bsd-3-clause |
lokik/sfepy | sfepy/homogenization/coefficients.py | 11023 | from __future__ import absolute_import
import numpy as nm
from sfepy.base.base import ordered_iteritems, Struct, basestr
from sfepy.base.ioutils import read_dict_hdf5, write_dict_hdf5
from sfepy.homogenization.utils import iter_sym
import six
from six.moves import range
def coef_arrays_to_dicts(idict, format='%s/%d'):
out = {}
for k, v in six.iteritems(idict):
if isinstance(v, list):
out.update({format %(k, ii): vv for ii, vv in enumerate(v)})
else:
out[k] = v
return out
class Coefficients(Struct):
"""
Class for storing (homogenized) material coefficients.
"""
def from_file_hdf5( filename ):
obj = Coefficients()
obj.__dict__ = read_dict_hdf5( filename )
for key, val in six.iteritems(obj.__dict__):
if type( val ) == list:
for ii, vv in enumerate( val ):
val[ii] = nm.array( vv, dtype = nm.float64 )
return obj
from_file_hdf5 = staticmethod( from_file_hdf5 )
def to_file_hdf5( self, filename ):
write_dict_hdf5( filename, self.__dict__ )
def _escape_latex(self, txt):
return txt.replace('_', '\_').replace('%', '\%')
def _format(self, val):
out = self._a_format % val
if self._a_cdot:
a1, a2 = out.split('e')
if (self._a_filter is not None) and (int(a2) < self._a_filter):
out = '0'
else:
out = '%s \cdot 10^{%s}' % (a1, int(a2))
return out
def _write1d(self, fd, val):
fd.write( r' \begin{equation}' )
fd.write( '\n' )
fd.write( r' \left[' )
fd.write( '\n' )
fd.write(', '.join([self._format(vv) for vv in val]))
fd.write( '\n' )
fd.write( r' \right]' )
fd.write( '\n' )
fd.write( r' \end{equation}' )
fd.write( '\n' )
def _write2d(self, fd, val):
fd.write( r' \begin{equation}' )
fd.write( '\n' )
fd.write( r' \left[\begin{array}{%s}' % ('c' * val.shape[0]) )
fd.write( '\n' )
for ir in range( val.shape[1] ):
for ic in range( val.shape[0] ):
fd.write(' ' + self._format(val[ir,ic]))
if ic < (val.shape[0] - 1):
fd.write( r' & ' )
elif ir < (val.shape[1] - 1):
fd.write( r' \\' )
fd.write( '\n' )
fd.write( '\n' )
fd.write( r' \end{array}\right]' )
fd.write( '\n' )
fd.write( r' \end{equation}' )
fd.write( '\n' )
def _save_dict_latex(self, adict, fd, names, idx=None):
fd.write( r'\begin{itemize}' )
fd.write( '\n' )
for key, val in ordered_iteritems(adict):
if key.startswith('_a_'): continue
try:
lname = names[key]
except:
lname = self._escape_latex(key)
fd.write( '\item %s:' % lname )
fd.write( '\n' )
if isinstance(val, list):
if idx is not None:
val = val[idx]
else:
raise NotImplementedError("'idx' must be set in the case "
"of multi-coefficients!")
if isinstance(val, dict):
self._save_dict_latex(val, fd, names)
elif isinstance(val, basestr):
fd.write(self._escape_latex(val) + '\n')
elif isinstance(val, float):
fd.write('$' + self._format(val) + '$\n')
elif isinstance(val, nm.ndarray):
if val.ndim == 0:
fd.write('$' + self._format(val) + '$\n')
elif val.ndim == 1:
self._write1d(fd, val)
elif val.ndim == 2:
self._write2d(fd, val)
else:
fd.write('%s' % val)
fd.write( r'\end{itemize}' )
fd.write( '\n\n' )
def to_file_latex(self, filename, names, format='%.2e',
cdot=False, filter=None, idx=None):
r"""
Save the coefficients to a file in LaTeX format.
Parameters
----------
filename : str
The name of the output file.
names : dict
Mapping of attribute names to LaTeX names.
format : str
Format string for numbers.
cdot : bool
For '%.e' formats only. If True, replace 'e' by LaTeX '\cdot
10^{exponent}' format.
filter : int
For '%.e' formats only. Typeset as 0, if exponent is less than
`filter`.
idx : int
For multi-coefficients, set the coefficient index.
"""
self._a_format = format
self._a_cdot = cdot
self._a_filter = filter
fd = open(filename, 'w')
self._save_dict_latex(self.__dict__, fd, names, idx)
fd.close()
def _save_dict(self, adict, fd, names, format):
for key, val in ordered_iteritems(adict):
try:
lname = names[key]
except:
lname = key
fd.write('%s:\n' % lname)
if hasattr(val, 'to_file_txt'):
if val.to_file_txt is not None:
val.to_file_txt(fd, format, val)
else:
fd.write('--\n')
elif isinstance(val, dict):
self._save_dict(val, fd, names, format)
fd.write('\n')
elif isinstance(val, list):
if isinstance(val[0], basestr):
fd.write('\n'.join(val) + '\n')
elif isinstance(val, basestr):
fd.write(val + '\n')
elif isinstance(val, float):
fd.write('%e\n' % val)
elif isinstance(val, nm.ndarray):
if val.ndim == 0:
fd.write(format % val)
fd.write('\n')
elif val.ndim == 1:
for ic in range(val.shape[0]):
fd.write(format % val[ic])
if ic < (val.shape[0] - 1):
fd.write(', ')
else:
fd.write('\n')
elif val.ndim == 2:
for ir in range(val.shape[0]):
for ic in range(val.shape[1]):
fd.write(format % val[ir,ic])
if ic < (val.shape[1] - 1):
fd.write(', ')
elif ir < (val.shape[0] - 1):
fd.write(';\n')
fd.write('\n')
elif val.ndim == 3:
for ii in range(val.shape[0]):
fd.write(' step %d:\n' % ii)
for ir in range(val.shape[1]):
for ic in range(val.shape[2]):
fd.write(' ' + format % val[ii,ir,ic])
if ic < (val.shape[2] - 1):
fd.write(', ')
elif ir < (val.shape[1] - 1):
fd.write(';\n')
fd.write('\n')
fd.write('\n')
else:
fd.write('--\n')
fd.write('\n')
def to_file_txt( self, filename, names, format ):
fd = open( filename, 'w' )
self._save_dict(coef_arrays_to_dicts(self.__dict__), fd, names, format)
fd.close()
_table_vector = r"""
\begin{center}
\begin{tabular}{cc}
i & value \\
%s
\end{tabular}
\end{center}
"""
_table_matrix_1 = r"""
\begin{center}
\begin{tabular}{cc}
ij & value \\
%s
\end{tabular}
\end{center}
"""
_table_matrix_2 = r"""
\begin{center}
\begin{tabular}{cc}
ijkl & value \\
%s
\end{tabular}
\end{center}
"""
_itemize = r"""
\begin{itemize}
%s
\end{itemize}
"""
##
# c: 09.07.2008, r: 09.07.2008
def _typeset( self, val, dim, style = 'table', format = '%f',
step = None ):
sym = (dim + 1) * dim // 2
mode = None
if val.ndim == 0:
mode = 'scalar'
elif val.ndim == 1:
if val.shape[0] == 1:
mode = 'scalar'
elif val.shape[0] == dim:
mode = 'vector'
elif val.shape[0] == sym:
mode = 'matrix_t1d'
elif val.ndim == 2:
if val.shape[0] == dim:
mode = 'matrix_2D'
elif val.shape[0] == sym:
mode = 'matrix_t2d'
out = ''
if mode == 'scalar':
out = format % val
elif mode == 'vector':
aux = ' \\\\\n'.join( [r'$_%d$ & %s' % (ir + 1, format % val[ir])
for ir in range( dim )] )
out = self._table_vector % aux
elif mode == 'matrix_t1d':
aux = ' \\\\\n'.join( [r'$_{%d%d}$ & %s' % (ir + 1, ic + 1,
format % val[ii])
for ii, (ir, ic) \
in enumerate( iter_sym( dim ) )] )
out = self._table_matrix_1 % aux
elif mode == 'matrix_2D':
aux = ' \\\\\n'.join( [r'$_{%d%d}$ & %s' % (ir + 1, ic + 1,
format % val[ir,ic])
for ir in range( dim )
for ic in range( dim )] )
out = self._table_matrix_1 % aux
elif mode == 'matrix_t2d':
aux = ' \\\\\n'.join( [r'$_{%d%d%d%d}$ & %s' % (irr + 1, irc + 1,
icr + 1, icc + 1,
format % val[ii,jj])
for ii, (irr, irc) \
in enumerate( iter_sym( dim ) )
for jj, (icr, icc) \
in enumerate( iter_sym( dim ) )] )
out = self._table_matrix_2 % aux
return out
def to_latex( self, attr_name, dim, style = 'table', format = '%f',
step = None ):
val = getattr( self, attr_name )
if step is not None:
val = val[step]
if isinstance( val, dict ):
aux = ''
for key, dval in six.iteritems(val):
aux2 = r'\item %s : %s' % (key,
self._typeset( dval, dim, style,
format, step ))
aux = '\n'.join( (aux, aux2) )
out = self._itemize % aux
else:
out = self._typeset( val, dim, style, format, step )
return out
| bsd-3-clause |
NCIP/lexevs-grid | LexEVSAnalyiticalService/test/src/gov/nih/nci/AllTests.java | 781 | /*
* Copyright: (c) Mayo Foundation for Medical Education and
* Research (MFMER). All rights reserved. MAYO, MAYO CLINIC, and the
* triple-shield Mayo logo are trademarks and service marks of MFMER.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/lexevs-grid/LICENSE.txt for details.
*/
package gov.nih.nci;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.LexGrid.LexBIG.gridTests.testUtility.AllTestsLexEVSAnalyticalGridService;
public class AllTests {
public static Test suite() throws Exception{
TestSuite suite = new TestSuite("Test for gov.nih.nci");
//$JUnit-BEGIN$
suite.addTest(AllTestsLexEVSAnalyticalGridService.suite());
//$JUnit-END$
return suite;
}
}
| bsd-3-clause |
cybyd/cybyd | language/bangla/lang_torrents.php | 1828 | <?php
$language['TORRENT_SEARCH']='টরেন্ট খুঁজুন';
$language['TORRENT_STATUS']='বর্তমান অবস্তা';
$language['CATEGORY_FULL']='বিষয়';
$language['ALL']='সকল টরেন্ট';
$language['ACTIVE_ONLY']='সচল টরেন্ট';
$language['DEAD_ONLY']='অচল টরেন্ট';
$language['SEARCH']='খুঁজুন';
$language['CATEGORY']='বিষয়.';
$language['FILE']='নাম';
$language['COMMENT']='কমেন্ট.';
$language['RATING']='টরেন্ট এর মান';
$language['DOWN']='ডাউনলোড';
$language['ADDED']='যোগ করার তারিখ';
$language['SIZE']='আকার';
$language['UPLOADER']='শেয়ার করেছেন';
$language['SHORT_S']='শেয়ার করছে';
$language['SHORT_L']='বর্তমানে ডাউনলোড চলছে';
$language['SHORT_C']='মোট ডাউনলোড করেছে';
$language['DOWNLOADED']='মোট ডাউনলোড হয়েছে';
$language['SPEED']='গতি';
$language['AVERAGE']='মোট.';
$language['VOTE']='ভোট!';
$language['VOTES_RATING']='মোট ভোট (মূল্যায়ন';
$language['FIVE_STAR']='5 stars';
$language['FOUR_STAR']='4 stars';
$language['ONE_STAR']='1 star';
$language['THREE_STAR']='3 stars';
$language['TWO_STAR']='2 stars';
$language['YOU_RATE']='আপনি মূল্যায়ন করেছেন';
$language['ADD_RATING']='মূল্যায়ন করুন';
$language['RATING']='মূল্যায়ন';
$language['ERR_NO_VOTE']='আপনার অবশ্যই নির্বাচন করে ভোট করতে হবে.';
$language['VOTES']='ভোট';
$language['SHOW_HIDE']='Show/Hide Files';
?> | bsd-3-clause |
preprocessed-connectomes-project/quality-assessment-protocol | scripts/qap_jsons_to_csv.py | 1826 | #!/usr/bin/env python
def main():
import os
import argparse
from qap.script_utils import gather_json_info, json_to_csv
from qap.qap_utils import raise_smart_exception
parser = argparse.ArgumentParser()
parser.add_argument("output_dir", type=str,
help="the main output directory of the QAP run "
"which contains the participant directories")
parser.add_argument("--with_group_reports", action='store_true',
default=False, help="Write a summary report in PDF "
"format.")
parser.add_argument("--with_full_reports", action='store_true',
default=False, help="Write the summary report and "
"the individual participant reports as well.")
args = parser.parse_args()
json_dict = gather_json_info(args.output_dir)
json_to_csv(json_dict)
if args.with_group_reports or args.with_full_reports:
from qap.viz.reports import workflow_report
# TODO: read in combined results dictionary from log JSONs
#logs_dict = gather_json_info("_".join([args.output_dir, "logs"]))
qap_types = ["anatomical_spatial",
"functional_spatial",
"functional_temporal"]
for qap_type in qap_types:
qap_type = "_".join(["qap", qap_type])
run_name = args.output_dir.split("/")[-1]
in_csv = os.path.join(os.getcwd(), '%s.csv' % qap_type)
if not os.path.isfile(in_csv):
continue
reports = workflow_report(in_csv, qap_type, run_name,
out_dir=args.output_dir,
full_reports=args.with_full_reports)
if __name__ == "__main__":
main() | bsd-3-clause |
zfegg/apigility-lab | module/ZfeggAdmin/config/documentation.config.php | 225 | <?php
return array(
'ZfeggAdmin\\V1\\Rest\\Resources\\Controller' => array(
'description' => '资源Restful',
'collection' => array(
'description' => '资源 Conllection',
),
),
);
| bsd-3-clause |
3Seventy/vector370-dotnet | Examples/Common/CallbackReceiver/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs | 495 | using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace CallbackReceiver.Areas.HelpPage.ModelDescriptions
{
/// <summary />
public class EnumTypeModelDescription : ModelDescription
{
/// <summary />
public EnumTypeModelDescription()
{
Values = new Collection<EnumValueDescription>();
}
/// <summary />
public Collection<EnumValueDescription> Values { get; private set; }
}
} | bsd-3-clause |
nikdoof/test-auth | app/sso/migrations/0003_auto__add_ssousernote.py | 6427 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'SSOUserNote'
db.create_table('sso_ssousernote', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='notes', to=orm['auth.User'])),
('note', self.gf('django.db.models.fields.TextField')()),
('created_by', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),
('date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
))
db.send_create_signal('sso', ['SSOUserNote'])
def backwards(self, orm):
# Deleting model 'SSOUserNote'
db.delete_table('sso_ssousernote')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '80', 'unique': 'True'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'max_length': '30', 'unique': 'True'})
},
'contenttypes.contenttype': {
'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'sso.service': {
'Meta': {'object_name': 'Service'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'api': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'settings_json': ('jsonfield.fields.JSONField', [], {'blank': 'True'}),
'url': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'})
},
'sso.serviceaccount': {
'Meta': {'object_name': 'ServiceAccount'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'service': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sso.Service']"}),
'service_uid': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'sso.ssouser': {
'Meta': {'object_name': 'SSOUser'},
'api_service_password': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'profile'", 'unique': 'True', 'to': "orm['auth.User']"})
},
'sso.ssousernote': {
'Meta': {'object_name': 'SSOUserNote'},
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'note': ('django.db.models.fields.TextField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'notes'", 'to': "orm['auth.User']"})
}
}
complete_apps = ['sso']
| bsd-3-clause |
keybase/client | go/client/cmd_simplefs_stat.go | 4321 | // Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.
package client
import (
"errors"
"fmt"
"golang.org/x/net/context"
"github.com/keybase/cli"
"github.com/keybase/client/go/libcmdline"
"github.com/keybase/client/go/libkb"
keybase1 "github.com/keybase/client/go/protocol/keybase1"
)
// CmdSimpleFSStat is the 'fs stat' command.
type CmdSimpleFSStat struct {
libkb.Contextified
path keybase1.Path
spanType *keybase1.RevisionSpanType
}
// NewCmdSimpleFSStat creates a new cli.Command.
func NewCmdSimpleFSStat(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {
return cli.Command{
Name: "stat",
ArgumentHelp: "<path>",
Usage: "stat directory element",
Action: func(c *cli.Context) {
cl.ChooseCommand(&CmdSimpleFSStat{Contextified: libkb.NewContextified(g)}, "stat", c)
cl.SetNoStandalone()
},
Flags: []cli.Flag{
cli.IntFlag{
Name: "rev",
Usage: "a revision number for the KBFS folder",
},
cli.StringFlag{
Name: "time",
Usage: "a time for the KBFS folder (eg \"2018-07-27 22:05\")",
},
cli.StringFlag{
Name: "reltime, relative-time",
Usage: "a relative time for the KBFS folder (eg \"5m\")",
},
cli.BoolFlag{
Name: "show-archived",
Usage: "shows stats for several previous revisions",
},
cli.BoolFlag{
Name: "show-last-archived",
Usage: "shows stats for sequential previous revisions",
},
},
}
}
func prefetchStatusString(e keybase1.Dirent) string {
if e.PrefetchStatus != keybase1.PrefetchStatus_IN_PROGRESS {
return e.PrefetchStatus.String()
}
if e.PrefetchProgress.BytesTotal == 0 {
return keybase1.PrefetchStatus_NOT_STARTED.String()
}
return fmt.Sprintf("%.2f%%",
100*float64(e.PrefetchProgress.BytesFetched)/
float64(e.PrefetchProgress.BytesTotal))
}
// Run runs the command in client/server mode.
func (c *CmdSimpleFSStat) Run() (err error) {
cli, err := GetSimpleFSClient(c.G())
if err != nil {
return err
}
ui := c.G().UI.GetTerminalUI()
ui.Printf("%v\n", c.path)
ctx := context.TODO()
if c.spanType != nil {
opid, err := cli.SimpleFSMakeOpid(ctx)
if err != nil {
return err
}
defer func() {
closeErr := cli.SimpleFSClose(ctx, opid)
if err == nil {
err = closeErr
}
}()
err = cli.SimpleFSGetRevisions(ctx, keybase1.SimpleFSGetRevisionsArg{
OpID: opid,
Path: c.path,
SpanType: *c.spanType,
})
if err != nil {
return err
}
err = cli.SimpleFSWait(ctx, opid)
if err != nil {
return err
}
res, err := cli.SimpleFSReadRevisions(ctx, opid)
if err != nil {
return err
}
for _, r := range res.Revisions {
e := r.Entry
ui.Printf("%d)\t%s\t%s\t%d\t%s\t%s\t%s\n",
r.Revision, keybase1.FormatTime(e.Time),
keybase1.DirentTypeRevMap[e.DirentType],
e.Size, e.Name, e.LastWriterUnverified.Username,
prefetchStatusString(e))
}
} else {
e, err := cli.SimpleFSStat(ctx, keybase1.SimpleFSStatArg{Path: c.path})
if err != nil {
return err
}
ui.Printf("%s\t%s\t%d\t%s\t%s\t%s\n",
keybase1.FormatTime(e.Time),
keybase1.DirentTypeRevMap[e.DirentType],
e.Size, e.Name, e.LastWriterUnverified.Username,
prefetchStatusString(e))
}
return nil
}
// ParseArgv gets the required path argument for this command.
func (c *CmdSimpleFSStat) ParseArgv(ctx *cli.Context) error {
nargs := len(ctx.Args())
var err error
if nargs != 1 {
return errors.New("stat requires a KBFS path argument")
}
// TODO: "rev" should be a real int64, need to update the
// `cli` library for that.
p, err := makeSimpleFSPathWithArchiveParams(
ctx.Args()[0], int64(ctx.Int("rev")), ctx.String("time"),
getRelTime(ctx))
if err != nil {
return err
}
c.path = p
if ctx.Bool("show-archived") {
st := keybase1.RevisionSpanType_DEFAULT
c.spanType = &st
}
if ctx.Bool("show-last-archived") {
if c.spanType != nil {
return errors.New("Cannot specify both -show-archived and " +
"-show-last-archived")
}
st := keybase1.RevisionSpanType_LAST_FIVE
c.spanType = &st
}
return nil
}
// GetUsage says what this command needs to operate.
func (c *CmdSimpleFSStat) GetUsage() libkb.Usage {
return libkb.Usage{
Config: true,
KbKeyring: true,
API: true,
}
}
| bsd-3-clause |
endlessm/chromium-browser | chrome/android/junit/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelperTest.java | 7977 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.compositor.overlays.strip;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.text.TextUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric;
import org.robolectric.annotation.Config;
import org.chromium.base.test.BaseRobolectricTestRunner;
import org.chromium.base.test.util.Feature;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.compositor.layouts.LayoutRenderHost;
import org.chromium.chrome.browser.compositor.layouts.LayoutUpdateHost;
import org.chromium.chrome.browser.compositor.layouts.components.VirtualView;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.tab.TabImpl;
import org.chromium.chrome.browser.tabmodel.EmptyTabModel;
import org.chromium.ui.base.LocalizationUtils;
import java.util.ArrayList;
import java.util.List;
/** Tests for {@link StripLayoutHelper}. */
@RunWith(BaseRobolectricTestRunner.class)
@Config(manifest = Config.NONE, sdk = 21)
public class StripLayoutHelperTest {
@Mock private LayoutUpdateHost mUpdateHost;
@Mock private LayoutRenderHost mRenderHost;
private Activity mActivity;
private TestTabModel mModel = new TestTabModel();
private StripLayoutHelper mStripLayoutHelper;
private boolean mIncognito;
private static final String[] TEST_TAB_TITLES = {"Tab 1", "Tab 2", "Tab 3", "", null};
private static final String CLOSE_TAB = "Close %1$s tab";
private static final String IDENTIFIER = "Tab";
private static final String IDENTIFIER_SELECTED = "Selected Tab";
private static final String INCOGNITO_IDENTIFIER = "Incognito Tab";
private static final String INCOGNITO_IDENTIFIER_SELECTED = "Selected Incognito Tab";
/** Reset the environment before each test. */
@Before
public void beforeTest() {
MockitoAnnotations.initMocks(this);
mActivity = Robolectric.buildActivity(Activity.class).setup().get();
}
/**
* Test method for {@link StripLayoutHelper#getVirtualViews(List<VirtualView>)}.
*
* Checks that it returns the correct order of tabs, including correct content.
*/
@Test
@Feature({"Accessibility"})
public void testSimpleTabOrder() {
initializeTest(false, false, 0);
assertTabStripAndOrder(getExpectedAccessibilityDescriptions(0));
}
/**
* Test method for {@link StripLayoutHelper#getVirtualViews(List<VirtualView>)}.
*
* Checks that it returns the correct order of tabs, even when a tab except the first one is
* selected.
*/
@Test
@Feature({"Accessibility"})
public void testTabOrderWithIndex() {
initializeTest(false, false, 1);
// Tabs should be in left to right order regardless of index
assertTabStripAndOrder(getExpectedAccessibilityDescriptions(1));
}
/**
* Test method for {@link StripLayoutHelper#getVirtualViews(List<VirtualView>)}.
*
* Checks that it returns the correct order of tabs, even in RTL mode.
*/
@Test
@Feature({"Accessibility"})
public void testTabOrderRtl() {
initializeTest(true, false, 0);
// Tabs should be in linear order even in RTL.
// Android will take care of reversing it.
assertTabStripAndOrder(getExpectedAccessibilityDescriptions(0));
}
/**
* Test method for {@link StripLayoutHelper#getVirtualViews(List<VirtualView>)}.
*
* Checks that it returns the correct order of tabs, even in incognito mode.
*/
@Test
@Feature({"Accessibility"})
public void testIncognitoAccessibilityDescriptions() {
initializeTest(false, true, 0);
assertTabStripAndOrder(getExpectedAccessibilityDescriptions(0));
}
private void initializeTest(boolean rtl, boolean incognito, int tabIndex) {
mStripLayoutHelper = createStripLayoutHelper(rtl, incognito);
mIncognito = incognito;
for (int i = 0; i < TEST_TAB_TITLES.length; i++) {
mModel.addTab(TEST_TAB_TITLES[i]);
when(mModel.getTabAt(i).isHidden()).thenReturn(tabIndex != i);
}
mModel.setIndex(tabIndex);
mStripLayoutHelper.setTabModel(mModel, null);
mStripLayoutHelper.tabSelected(0, tabIndex, 0);
// Flush UI updated
}
private void assertTabStripAndOrder(String[] expectedAccessibilityDescriptions) {
// Each tab has a "close button", and there is one additional "new tab" button
final int expectedNumberOfViews = 2 * expectedAccessibilityDescriptions.length + 1;
final List<VirtualView> views = new ArrayList<>();
mStripLayoutHelper.getVirtualViews(views);
assertEquals(expectedNumberOfViews, views.size());
// Tab titles
for (int i = 0; i < expectedNumberOfViews - 1; i++) {
final String expectedDescription = i % 2 == 0
? expectedAccessibilityDescriptions[i / 2]
: String.format(CLOSE_TAB, TEST_TAB_TITLES[i / 2]);
assertEquals(expectedDescription, views.get(i).getAccessibilityDescription());
}
assertEquals(mActivity.getResources().getString(mIncognito
? R.string.accessibility_toolbar_btn_new_incognito_tab
: R.string.accessibility_toolbar_btn_new_tab),
views.get(views.size() - 1).getAccessibilityDescription());
}
private StripLayoutHelper createStripLayoutHelper(boolean rtl, boolean incognito) {
LocalizationUtils.setRtlForTesting(rtl);
final StripLayoutHelper stripLayoutHelper =
new StripLayoutHelper(mActivity, mUpdateHost, mRenderHost, incognito);
// Initialize StackScroller
stripLayoutHelper.onContextChanged(mActivity);
return stripLayoutHelper;
}
private String[] getExpectedAccessibilityDescriptions(int tabIndex) {
final String[] expectedAccessibilityDescriptions = new String[TEST_TAB_TITLES.length];
for (int i = 0; i < TEST_TAB_TITLES.length; i++) {
final boolean isHidden = (i != tabIndex);
String suffix;
if (mIncognito) {
suffix = isHidden ? INCOGNITO_IDENTIFIER : INCOGNITO_IDENTIFIER_SELECTED;
} else {
suffix = isHidden ? IDENTIFIER : IDENTIFIER_SELECTED;
}
String expectedDescription = "";
if (!TextUtils.isEmpty(TEST_TAB_TITLES[i])) {
expectedDescription += TEST_TAB_TITLES[i] + ", ";
}
expectedAccessibilityDescriptions[i] = expectedDescription + suffix;
}
return expectedAccessibilityDescriptions;
}
private static class TestTabModel extends EmptyTabModel {
private final List<Tab> mMockTabs = new ArrayList<>();
private int mMaxId = -1;
private int mIndex;
public void addTab(final String title) {
mMaxId++;
final TabImpl mockTab = mock(TabImpl.class);
final int tabId = mMaxId;
when(mockTab.getId()).thenReturn(tabId);
when(mockTab.getTitle()).thenReturn(title);
mMockTabs.add(mockTab);
}
@Override
public Tab getTabAt(int id) {
return mMockTabs.get(id);
}
@Override
public int getCount() {
return mMockTabs.size();
}
@Override
public int index() {
return mIndex;
}
public void setIndex(int index) {
mIndex = index;
}
}
}
| bsd-3-clause |
jupyter/jupyterlab | packages/mainmenu/test/util.ts | 1821 | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import { IMenuExtender } from '@jupyterlab/mainmenu';
import { Widget } from '@lumino/widgets';
/**
* Given a widget and a set containing IMenuExtenders,
* check the tracker and return the extender, if any,
* that holds the widget.
*/
function findExtender<E extends IMenuExtender<Widget>>(
widget: Widget,
s: Set<E>
): E | undefined {
let extender: E | undefined;
s.forEach(value => {
if (value.tracker.has(widget)) {
extender = value;
}
});
return extender;
}
/**
* A utility function that delegates command execution
* to an IMenuExtender.
*/
export function delegateExecute<E extends IMenuExtender<Widget>>(
widget: Widget,
s: Set<E>,
executor: keyof E
): Promise<any> {
const extender = findExtender(widget, s);
if (!extender) {
return Promise.resolve(void 0);
}
// Coerce the result to be a function. When Typedoc is updated to use
// Typescript 2.8, we can possibly use conditional types to get Typescript
// to recognize this is a function.
const f = (extender[executor] as any) as (w: Widget) => Promise<any>;
return f(widget);
}
/**
* A utility function that delegates whether a command is toggled
* for an IMenuExtender.
*/
export function delegateToggled<E extends IMenuExtender<Widget>>(
widget: Widget,
s: Set<E>,
toggled: keyof E
): boolean {
const extender = findExtender(widget, s);
if (extender && extender[toggled]) {
// Coerce the result to be a function. When Typedoc is updated to use
// Typescript 2.8, we can possibly use conditional types to get Typescript
// to recognize this is a function.
const f = (extender[toggled] as any) as (w: Widget) => boolean;
return f(widget);
}
return false;
}
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE563_Unused_Variable/main.cpp | 160197 | /* NOTE - eventually this file will be automatically updated using a Perl script that understand
* the naming of test case files, functions, and namespaces.
*/
#include <time.h> /* for time() */
#include <stdlib.h> /* for srand() */
#include "std_testcase.h"
#include "testcases.h"
int main(int argc, char * argv[]) {
/* seed randomness */
srand( (unsigned)time(NULL) );
globalArgc = argc;
globalArgv = argv;
#ifndef OMITGOOD
/* Calling C good functions */
/* BEGIN-AUTOGENERATED-C-GOOD-FUNCTION-CALLS */
printLine("Calling CWE563_Unused_Variable__unused_value_struct_22_good();");
CWE563_Unused_Variable__unused_value_struct_22_good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_09_good();");
CWE563_Unused_Variable__unused_value_struct_09_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_03_good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_03_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_16_good();");
CWE563_Unused_Variable__unused_init_variable_long_16_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_13_good();");
CWE563_Unused_Variable__unused_uninit_variable_int_13_good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_11_good();");
CWE563_Unused_Variable__unused_value_long_11_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_02_good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_02_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_14_good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_14_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_01_good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_01_good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_04_good();");
CWE563_Unused_Variable__unused_value_long_04_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_02_good();");
CWE563_Unused_Variable__unused_init_variable_char_02_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_10_good();");
CWE563_Unused_Variable__unused_init_variable_int_10_good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_17_good();");
CWE563_Unused_Variable__unused_value_wchar_t_17_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_10_good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_10_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_16_good();");
CWE563_Unused_Variable__unused_uninit_variable_char_16_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_01_good();");
CWE563_Unused_Variable__unused_init_variable_long_01_good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_06_good();");
CWE563_Unused_Variable__unused_value_long_06_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_15_good();");
CWE563_Unused_Variable__unused_init_variable_int_15_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_15_good();");
CWE563_Unused_Variable__unused_init_variable_long_15_good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_06_good();");
CWE563_Unused_Variable__unused_value_struct_06_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_10_good();");
CWE563_Unused_Variable__unused_init_variable_struct_10_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_03_good();");
CWE563_Unused_Variable__unused_init_variable_char_03_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_09_good();");
CWE563_Unused_Variable__unused_uninit_variable_char_09_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_06_good();");
CWE563_Unused_Variable__unused_uninit_variable_char_06_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_02_good();");
CWE563_Unused_Variable__unused_uninit_variable_int_02_good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_05_good();");
CWE563_Unused_Variable__unused_value_struct_05_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_16_good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_16_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_09_good();");
CWE563_Unused_Variable__unused_init_variable_struct_09_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_17_good();");
CWE563_Unused_Variable__unused_value_int_17_good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_14_good();");
CWE563_Unused_Variable__unused_value_wchar_t_14_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_15_good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_15_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_04_good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_04_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_16_good();");
CWE563_Unused_Variable__unused_init_variable_char_16_good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_08_good();");
CWE563_Unused_Variable__unused_value_wchar_t_08_good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_02_good();");
CWE563_Unused_Variable__unused_value_wchar_t_02_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_17_good();");
CWE563_Unused_Variable__unused_init_variable_int_17_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_04_good();");
CWE563_Unused_Variable__unused_value_int_04_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_03_good();");
CWE563_Unused_Variable__unused_uninit_variable_char_03_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_01_good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_01_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_09_good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_09_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_04_good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_04_good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_10_good();");
CWE563_Unused_Variable__unused_value_long_10_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_17_good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_17_good();
printLine("Calling CWE563_Unused_Variable__unused_static_global_variable_01_good();");
CWE563_Unused_Variable__unused_static_global_variable_01_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_14_good();");
CWE563_Unused_Variable__unused_init_variable_int_14_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_21_good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_21_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_17_good();");
CWE563_Unused_Variable__unused_uninit_variable_char_17_good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_21_good();");
CWE563_Unused_Variable__unused_value_long_21_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_22_good();");
CWE563_Unused_Variable__unused_uninit_variable_char_22_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_02_good();");
CWE563_Unused_Variable__unused_uninit_variable_char_02_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_06_good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_06_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_06_good();");
CWE563_Unused_Variable__unused_init_variable_int_06_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_06_good();");
CWE563_Unused_Variable__unused_init_variable_char_06_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_10_good();");
CWE563_Unused_Variable__unused_uninit_variable_char_10_good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_08_good();");
CWE563_Unused_Variable__unused_value_char_08_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_11_good();");
CWE563_Unused_Variable__unused_value_int64_t_11_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_17_good();");
CWE563_Unused_Variable__unused_init_variable_long_17_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_08_good();");
CWE563_Unused_Variable__unused_init_variable_long_08_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_14_good();");
CWE563_Unused_Variable__unused_uninit_variable_char_14_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_13_good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_13_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_14_good();");
CWE563_Unused_Variable__unused_value_int_14_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_07_good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_07_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_04_good();");
CWE563_Unused_Variable__unused_init_variable_long_04_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_06_good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_06_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_22_good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_22_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_09_good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_09_good();
printLine("Calling CWE563_Unused_Variable__unused_parameter_value_01_good();");
CWE563_Unused_Variable__unused_parameter_value_01_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_14_good();");
CWE563_Unused_Variable__unused_value_int64_t_14_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_14_good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_14_good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_04_good();");
CWE563_Unused_Variable__unused_value_wchar_t_04_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_13_good();");
CWE563_Unused_Variable__unused_value_int_13_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_15_good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_15_good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_21_good();");
CWE563_Unused_Variable__unused_value_struct_21_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_22_good();");
CWE563_Unused_Variable__unused_init_variable_int_22_good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_09_good();");
CWE563_Unused_Variable__unused_value_char_09_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_17_good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_17_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_05_good();");
CWE563_Unused_Variable__unused_init_variable_long_05_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_17_good();");
CWE563_Unused_Variable__unused_uninit_variable_int_17_good();
printLine("Calling CWE563_Unused_Variable__unused_static_global_value_01_good();");
CWE563_Unused_Variable__unused_static_global_value_01_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_16_good();");
CWE563_Unused_Variable__unused_value_int_16_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_07_good();");
CWE563_Unused_Variable__unused_value_int64_t_07_good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_03_good();");
CWE563_Unused_Variable__unused_value_struct_03_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_22_good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_22_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_14_good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_14_good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_18_good();");
CWE563_Unused_Variable__unused_value_struct_18_good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_22_good();");
CWE563_Unused_Variable__unused_value_wchar_t_22_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_10_good();");
CWE563_Unused_Variable__unused_uninit_variable_int_10_good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_03_good();");
CWE563_Unused_Variable__unused_value_long_03_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_06_good();");
CWE563_Unused_Variable__unused_init_variable_struct_06_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_18_good();");
CWE563_Unused_Variable__unused_init_variable_int_18_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_17_good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_17_good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_07_good();");
CWE563_Unused_Variable__unused_value_struct_07_good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_16_good();");
CWE563_Unused_Variable__unused_value_wchar_t_16_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_05_good();");
CWE563_Unused_Variable__unused_uninit_variable_long_05_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_07_good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_07_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_03_good();");
CWE563_Unused_Variable__unused_init_variable_struct_03_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_18_good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_18_good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_15_good();");
CWE563_Unused_Variable__unused_value_wchar_t_15_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_13_good();");
CWE563_Unused_Variable__unused_init_variable_int_13_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_16_good();");
CWE563_Unused_Variable__unused_init_variable_struct_16_good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_21_good();");
CWE563_Unused_Variable__unused_value_char_21_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_06_good();");
CWE563_Unused_Variable__unused_uninit_variable_int_06_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_21_good();");
CWE563_Unused_Variable__unused_uninit_variable_char_21_good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_14_good();");
CWE563_Unused_Variable__unused_value_long_14_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_08_good();");
CWE563_Unused_Variable__unused_init_variable_struct_08_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_02_good();");
CWE563_Unused_Variable__unused_init_variable_long_02_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_13_good();");
CWE563_Unused_Variable__unused_uninit_variable_char_13_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_05_good();");
CWE563_Unused_Variable__unused_init_variable_char_05_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_22_good();");
CWE563_Unused_Variable__unused_uninit_variable_long_22_good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_10_good();");
CWE563_Unused_Variable__unused_value_wchar_t_10_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_10_good();");
CWE563_Unused_Variable__unused_value_int_10_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_11_good();");
CWE563_Unused_Variable__unused_uninit_variable_long_11_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_03_good();");
CWE563_Unused_Variable__unused_init_variable_long_03_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_15_good();");
CWE563_Unused_Variable__unused_uninit_variable_char_15_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_14_good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_14_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_11_good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_11_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_01_good();");
CWE563_Unused_Variable__unused_uninit_variable_int_01_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_15_good();");
CWE563_Unused_Variable__unused_value_int64_t_15_good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_15_good();");
CWE563_Unused_Variable__unused_value_char_15_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_21_good();");
CWE563_Unused_Variable__unused_value_int_21_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_03_good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_03_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_22_good();");
CWE563_Unused_Variable__unused_uninit_variable_int_22_good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_22_good();");
CWE563_Unused_Variable__unused_value_long_22_good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_21_good();");
CWE563_Unused_Variable__unused_value_wchar_t_21_good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_05_good();");
CWE563_Unused_Variable__unused_value_char_05_good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_02_good();");
CWE563_Unused_Variable__unused_value_long_02_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_22_good();");
CWE563_Unused_Variable__unused_value_int64_t_22_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_01_good();");
CWE563_Unused_Variable__unused_value_int64_t_01_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_07_good();");
CWE563_Unused_Variable__unused_value_int_07_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_03_good();");
CWE563_Unused_Variable__unused_value_int_03_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_17_good();");
CWE563_Unused_Variable__unused_init_variable_char_17_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_04_good();");
CWE563_Unused_Variable__unused_uninit_variable_long_04_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_11_good();");
CWE563_Unused_Variable__unused_uninit_variable_int_11_good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_08_good();");
CWE563_Unused_Variable__unused_value_long_08_good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_08_good();");
CWE563_Unused_Variable__unused_value_struct_08_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_10_good();");
CWE563_Unused_Variable__unused_uninit_variable_long_10_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_09_good();");
CWE563_Unused_Variable__unused_init_variable_int_09_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_06_good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_06_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_10_good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_10_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_06_good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_06_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_05_good();");
CWE563_Unused_Variable__unused_uninit_variable_char_05_good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_16_good();");
CWE563_Unused_Variable__unused_value_long_16_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_13_good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_13_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_04_good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_04_good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_07_good();");
CWE563_Unused_Variable__unused_value_char_07_good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_18_good();");
CWE563_Unused_Variable__unused_value_wchar_t_18_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_10_good();");
CWE563_Unused_Variable__unused_init_variable_long_10_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_21_good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_21_good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_15_good();");
CWE563_Unused_Variable__unused_value_struct_15_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_05_good();");
CWE563_Unused_Variable__unused_uninit_variable_int_05_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_13_good();");
CWE563_Unused_Variable__unused_init_variable_long_13_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_08_good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_08_good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_11_good();");
CWE563_Unused_Variable__unused_value_wchar_t_11_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_11_good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_11_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_03_good();");
CWE563_Unused_Variable__unused_init_variable_int_03_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_16_good();");
CWE563_Unused_Variable__unused_uninit_variable_long_16_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_09_good();");
CWE563_Unused_Variable__unused_init_variable_char_09_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_15_good();");
CWE563_Unused_Variable__unused_uninit_variable_long_15_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_02_good();");
CWE563_Unused_Variable__unused_value_int64_t_02_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_22_good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_22_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_18_good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_18_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_09_good();");
CWE563_Unused_Variable__unused_init_variable_long_09_good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_06_good();");
CWE563_Unused_Variable__unused_value_wchar_t_06_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_08_good();");
CWE563_Unused_Variable__unused_init_variable_int_08_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_21_good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_21_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_17_good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_17_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_18_good();");
CWE563_Unused_Variable__unused_init_variable_struct_18_good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_03_good();");
CWE563_Unused_Variable__unused_value_char_03_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_21_good();");
CWE563_Unused_Variable__unused_uninit_variable_int_21_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_05_good();");
CWE563_Unused_Variable__unused_init_variable_int_05_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_18_good();");
CWE563_Unused_Variable__unused_value_int_18_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_11_good();");
CWE563_Unused_Variable__unused_init_variable_char_11_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_11_good();");
CWE563_Unused_Variable__unused_init_variable_struct_11_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_07_good();");
CWE563_Unused_Variable__unused_init_variable_char_07_good();
printLine("Calling CWE563_Unused_Variable__unused_parameter_variable_01_good();");
CWE563_Unused_Variable__unused_parameter_variable_01_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_05_good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_05_good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_01_good();");
CWE563_Unused_Variable__unused_value_wchar_t_01_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_01_good();");
CWE563_Unused_Variable__unused_init_variable_int_01_good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_16_good();");
CWE563_Unused_Variable__unused_value_struct_16_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_02_good();");
CWE563_Unused_Variable__unused_uninit_variable_long_02_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_18_good();");
CWE563_Unused_Variable__unused_init_variable_long_18_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_21_good();");
CWE563_Unused_Variable__unused_init_variable_long_21_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_15_good();");
CWE563_Unused_Variable__unused_value_int_15_good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_02_good();");
CWE563_Unused_Variable__unused_value_struct_02_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_03_good();");
CWE563_Unused_Variable__unused_uninit_variable_int_03_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_22_good();");
CWE563_Unused_Variable__unused_init_variable_long_22_good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_11_good();");
CWE563_Unused_Variable__unused_value_char_11_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_13_good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_13_good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_10_good();");
CWE563_Unused_Variable__unused_value_char_10_good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_17_good();");
CWE563_Unused_Variable__unused_value_char_17_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_04_good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_04_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_02_good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_02_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_18_good();");
CWE563_Unused_Variable__unused_uninit_variable_long_18_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_15_good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_15_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_06_good();");
CWE563_Unused_Variable__unused_value_int_06_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_18_good();");
CWE563_Unused_Variable__unused_init_variable_char_18_good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_05_good();");
CWE563_Unused_Variable__unused_value_wchar_t_05_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_18_good();");
CWE563_Unused_Variable__unused_value_int64_t_18_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_10_good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_10_good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_05_good();");
CWE563_Unused_Variable__unused_value_long_05_good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_17_good();");
CWE563_Unused_Variable__unused_value_struct_17_good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_01_good();");
CWE563_Unused_Variable__unused_value_long_01_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_17_good();");
CWE563_Unused_Variable__unused_uninit_variable_long_17_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_14_good();");
CWE563_Unused_Variable__unused_init_variable_long_14_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_07_good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_07_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_15_good();");
CWE563_Unused_Variable__unused_uninit_variable_int_15_good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_07_good();");
CWE563_Unused_Variable__unused_value_long_07_good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_01_good();");
CWE563_Unused_Variable__unused_value_struct_01_good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_04_good();");
CWE563_Unused_Variable__unused_value_struct_04_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_04_good();");
CWE563_Unused_Variable__unused_uninit_variable_int_04_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_05_good();");
CWE563_Unused_Variable__unused_init_variable_struct_05_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_15_good();");
CWE563_Unused_Variable__unused_init_variable_char_15_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_05_good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_05_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_22_good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_22_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_03_good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_03_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_21_good();");
CWE563_Unused_Variable__unused_init_variable_int_21_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_10_good();");
CWE563_Unused_Variable__unused_init_variable_char_10_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_01_good();");
CWE563_Unused_Variable__unused_uninit_variable_long_01_good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_03_good();");
CWE563_Unused_Variable__unused_value_wchar_t_03_good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_04_good();");
CWE563_Unused_Variable__unused_value_char_04_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_13_good();");
CWE563_Unused_Variable__unused_init_variable_struct_13_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_04_good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_04_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_06_good();");
CWE563_Unused_Variable__unused_value_int64_t_06_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_07_good();");
CWE563_Unused_Variable__unused_init_variable_struct_07_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_16_good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_16_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_17_good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_17_good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_16_good();");
CWE563_Unused_Variable__unused_value_char_16_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_05_good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_05_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_11_good();");
CWE563_Unused_Variable__unused_uninit_variable_char_11_good();
printLine("Calling CWE563_Unused_Variable__unused_global_value_01_good();");
CWE563_Unused_Variable__unused_global_value_01_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_16_good();");
CWE563_Unused_Variable__unused_value_int64_t_16_good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_06_good();");
CWE563_Unused_Variable__unused_value_char_06_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_06_good();");
CWE563_Unused_Variable__unused_init_variable_long_06_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_15_good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_15_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_15_good();");
CWE563_Unused_Variable__unused_init_variable_struct_15_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_11_good();");
CWE563_Unused_Variable__unused_init_variable_long_11_good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_14_good();");
CWE563_Unused_Variable__unused_value_struct_14_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_04_good();");
CWE563_Unused_Variable__unused_init_variable_char_04_good();
printLine("Calling CWE563_Unused_Variable__unused_global_variable_01_good();");
CWE563_Unused_Variable__unused_global_variable_01_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_06_good();");
CWE563_Unused_Variable__unused_uninit_variable_long_06_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_11_good();");
CWE563_Unused_Variable__unused_init_variable_int_11_good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_01_good();");
CWE563_Unused_Variable__unused_value_char_01_good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_13_good();");
CWE563_Unused_Variable__unused_value_struct_13_good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_02_good();");
CWE563_Unused_Variable__unused_value_char_02_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_11_good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_11_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_08_good();");
CWE563_Unused_Variable__unused_value_int_08_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_21_good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_21_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_02_good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_02_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_04_good();");
CWE563_Unused_Variable__unused_uninit_variable_char_04_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_01_good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_01_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_02_good();");
CWE563_Unused_Variable__unused_value_int_02_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_09_good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_09_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_02_good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_02_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_16_good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_16_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_06_good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_06_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_13_good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_13_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_16_good();");
CWE563_Unused_Variable__unused_init_variable_int_16_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_04_good();");
CWE563_Unused_Variable__unused_init_variable_struct_04_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_09_good();");
CWE563_Unused_Variable__unused_value_int64_t_09_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_14_good();");
CWE563_Unused_Variable__unused_init_variable_char_14_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_14_good();");
CWE563_Unused_Variable__unused_uninit_variable_long_14_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_09_good();");
CWE563_Unused_Variable__unused_uninit_variable_long_09_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_08_good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_08_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_08_good();");
CWE563_Unused_Variable__unused_uninit_variable_long_08_good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_17_good();");
CWE563_Unused_Variable__unused_value_long_17_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_10_good();");
CWE563_Unused_Variable__unused_value_int64_t_10_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_01_good();");
CWE563_Unused_Variable__unused_uninit_variable_char_01_good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_07_good();");
CWE563_Unused_Variable__unused_value_wchar_t_07_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_21_good();");
CWE563_Unused_Variable__unused_init_variable_char_21_good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_22_good();");
CWE563_Unused_Variable__unused_value_char_22_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_22_good();");
CWE563_Unused_Variable__unused_init_variable_struct_22_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_08_good();");
CWE563_Unused_Variable__unused_uninit_variable_char_08_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_03_good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_03_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_03_good();");
CWE563_Unused_Variable__unused_value_int64_t_03_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_03_good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_03_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_17_good();");
CWE563_Unused_Variable__unused_init_variable_struct_17_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_21_good();");
CWE563_Unused_Variable__unused_value_int64_t_21_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_10_good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_10_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_05_good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_05_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_18_good();");
CWE563_Unused_Variable__unused_uninit_variable_int_18_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_05_good();");
CWE563_Unused_Variable__unused_value_int64_t_05_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_21_good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_21_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_21_good();");
CWE563_Unused_Variable__unused_uninit_variable_long_21_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_22_good();");
CWE563_Unused_Variable__unused_value_int_22_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_15_good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_15_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_18_good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_18_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_10_good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_10_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_14_good();");
CWE563_Unused_Variable__unused_uninit_variable_int_14_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_08_good();");
CWE563_Unused_Variable__unused_value_int64_t_08_good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_15_good();");
CWE563_Unused_Variable__unused_value_long_15_good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_18_good();");
CWE563_Unused_Variable__unused_value_long_18_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_16_good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_16_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_02_good();");
CWE563_Unused_Variable__unused_init_variable_int_02_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_07_good();");
CWE563_Unused_Variable__unused_init_variable_int_07_good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_13_good();");
CWE563_Unused_Variable__unused_value_char_13_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_13_good();");
CWE563_Unused_Variable__unused_uninit_variable_long_13_good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_18_good();");
CWE563_Unused_Variable__unused_value_char_18_good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_10_good();");
CWE563_Unused_Variable__unused_value_struct_10_good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_09_good();");
CWE563_Unused_Variable__unused_value_wchar_t_09_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_04_good();");
CWE563_Unused_Variable__unused_init_variable_int_04_good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_13_good();");
CWE563_Unused_Variable__unused_value_wchar_t_13_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_22_good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_22_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_09_good();");
CWE563_Unused_Variable__unused_value_int_09_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_02_good();");
CWE563_Unused_Variable__unused_init_variable_struct_02_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_07_good();");
CWE563_Unused_Variable__unused_uninit_variable_int_07_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_01_good();");
CWE563_Unused_Variable__unused_init_variable_struct_01_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_01_good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_01_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_13_good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_13_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_18_good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_18_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_13_good();");
CWE563_Unused_Variable__unused_value_int64_t_13_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_03_good();");
CWE563_Unused_Variable__unused_uninit_variable_long_03_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_05_good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_05_good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_13_good();");
CWE563_Unused_Variable__unused_value_long_13_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_07_good();");
CWE563_Unused_Variable__unused_uninit_variable_char_07_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_07_good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_07_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_16_good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_16_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_08_good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_08_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_08_good();");
CWE563_Unused_Variable__unused_init_variable_char_08_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_09_good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_09_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_13_good();");
CWE563_Unused_Variable__unused_init_variable_char_13_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_11_good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_11_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_11_good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_11_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_11_good();");
CWE563_Unused_Variable__unused_value_int_11_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_07_good();");
CWE563_Unused_Variable__unused_uninit_variable_long_07_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_14_good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_14_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_07_good();");
CWE563_Unused_Variable__unused_init_variable_long_07_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_21_good();");
CWE563_Unused_Variable__unused_init_variable_struct_21_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_01_good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_01_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_08_good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_08_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_17_good();");
CWE563_Unused_Variable__unused_value_int64_t_17_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_01_good();");
CWE563_Unused_Variable__unused_value_int_01_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_16_good();");
CWE563_Unused_Variable__unused_uninit_variable_int_16_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_08_good();");
CWE563_Unused_Variable__unused_uninit_variable_int_08_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_07_good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_07_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_05_good();");
CWE563_Unused_Variable__unused_value_int_05_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_09_good();");
CWE563_Unused_Variable__unused_uninit_variable_int_09_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_08_good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_08_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_01_good();");
CWE563_Unused_Variable__unused_init_variable_char_01_good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_11_good();");
CWE563_Unused_Variable__unused_value_struct_11_good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_09_good();");
CWE563_Unused_Variable__unused_value_long_09_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_14_good();");
CWE563_Unused_Variable__unused_init_variable_struct_14_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_02_good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_02_good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_04_good();");
CWE563_Unused_Variable__unused_value_int64_t_04_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_09_good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_09_good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_14_good();");
CWE563_Unused_Variable__unused_value_char_14_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_18_good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_18_good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_22_good();");
CWE563_Unused_Variable__unused_init_variable_char_22_good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_18_good();");
CWE563_Unused_Variable__unused_uninit_variable_char_18_good();
/* END-AUTOGENERATED-C-GOOD-FUNCTION-CALLS */
#ifdef __cplusplus
/* Calling C++ good functions */
/* BEGIN-AUTOGENERATED-CPP-GOOD-FUNCTION-CALLS */
printLine("Calling CWE563_Unused_Variable__unused_value_char_84::good();");
CWE563_Unused_Variable__unused_value_char_84::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_74::good();");
CWE563_Unused_Variable__unused_uninit_variable_long_74::good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_83::good();");
CWE563_Unused_Variable__unused_value_int_83::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_43::good();");
CWE563_Unused_Variable__unused_uninit_variable_int_43::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_84::good();");
CWE563_Unused_Variable__unused_init_variable_long_84::good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_81::good();");
CWE563_Unused_Variable__unused_value_int64_t_81::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_82::good();");
CWE563_Unused_Variable__unused_uninit_variable_int_82::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_83::good();");
CWE563_Unused_Variable__unused_init_variable_struct_83::good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_82::good();");
CWE563_Unused_Variable__unused_value_struct_82::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_83::good();");
CWE563_Unused_Variable__unused_uninit_variable_char_83::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_73::good();");
CWE563_Unused_Variable__unused_uninit_variable_char_73::good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_33::good();");
CWE563_Unused_Variable__unused_value_wchar_t_33::good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_73::good();");
CWE563_Unused_Variable__unused_value_int_73::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_73::good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_73::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_33::good();");
CWE563_Unused_Variable__unused_uninit_variable_int_33::good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_83::good();");
CWE563_Unused_Variable__unused_value_int_83::good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_33::good();");
CWE563_Unused_Variable__unused_value_struct_33::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_43::good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_43::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_83::good();");
CWE563_Unused_Variable__unused_init_variable_int_83::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_82::good();");
CWE563_Unused_Variable__unused_init_variable_int_82::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_83::good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_83::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_84::good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_84::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_43::good();");
CWE563_Unused_Variable__unused_init_variable_int_43::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_33::good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_33::good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_74::good();");
CWE563_Unused_Variable__unused_value_int_74::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_81::good();");
CWE563_Unused_Variable__unused_init_variable_int_81::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_43::good();");
CWE563_Unused_Variable__unused_init_variable_struct_43::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_83::good();");
CWE563_Unused_Variable__unused_init_variable_long_83::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_84::good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_84::good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_81::good();");
CWE563_Unused_Variable__unused_value_wchar_t_81::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_33::good();");
CWE563_Unused_Variable__unused_uninit_variable_long_33::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_82::good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_82::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_82::good();");
CWE563_Unused_Variable__unused_init_variable_long_82::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_81::good();");
CWE563_Unused_Variable__unused_uninit_variable_long_81::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_83::good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_83::good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_83::good();");
CWE563_Unused_Variable__unused_value_int64_t_83::good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_84::good();");
CWE563_Unused_Variable__unused_value_wchar_t_84::good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_84::good();");
CWE563_Unused_Variable__unused_value_char_84::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_74::good();");
CWE563_Unused_Variable__unused_init_variable_long_74::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_74::good();");
CWE563_Unused_Variable__unused_uninit_variable_char_74::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_81::good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_81::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_43::good();");
CWE563_Unused_Variable__unused_init_variable_long_43::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_81::good();");
CWE563_Unused_Variable__unused_init_variable_long_81::good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_82::good();");
CWE563_Unused_Variable__unused_value_char_82::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_83::good();");
CWE563_Unused_Variable__unused_uninit_variable_char_83::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_81::good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_81::good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_73::good();");
CWE563_Unused_Variable__unused_value_wchar_t_73::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_43::good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_43::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_74::good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_74::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_74::good();");
CWE563_Unused_Variable__unused_uninit_variable_int_74::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_72::good();");
CWE563_Unused_Variable__unused_init_variable_struct_72::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_81::good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_81::good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_74::good();");
CWE563_Unused_Variable__unused_value_long_74::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_84::good();");
CWE563_Unused_Variable__unused_init_variable_int_84::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_73::good();");
CWE563_Unused_Variable__unused_init_variable_long_73::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_82::good();");
CWE563_Unused_Variable__unused_uninit_variable_long_82::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_83::good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_83::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_33::good();");
CWE563_Unused_Variable__unused_init_variable_char_33::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_43::good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_43::good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_82::good();");
CWE563_Unused_Variable__unused_value_long_82::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_84::good();");
CWE563_Unused_Variable__unused_uninit_variable_long_84::good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_82::good();");
CWE563_Unused_Variable__unused_value_int_82::good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_84::good();");
CWE563_Unused_Variable__unused_value_struct_84::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_81::good();");
CWE563_Unused_Variable__unused_uninit_variable_char_81::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_84::good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_84::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_33::good();");
CWE563_Unused_Variable__unused_init_variable_struct_33::good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_43::good();");
CWE563_Unused_Variable__unused_value_struct_43::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_82::good();");
CWE563_Unused_Variable__unused_init_variable_struct_82::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_73::good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_73::good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_83::good();");
CWE563_Unused_Variable__unused_value_char_83::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_84::good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_84::good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_43::good();");
CWE563_Unused_Variable__unused_value_wchar_t_43::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_82::good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_82::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_74::good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_74::good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_74::good();");
CWE563_Unused_Variable__unused_value_char_74::good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_82::good();");
CWE563_Unused_Variable__unused_value_wchar_t_82::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_33::good();");
CWE563_Unused_Variable__unused_init_variable_long_33::good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_33::good();");
CWE563_Unused_Variable__unused_value_int_33::good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_43::good();");
CWE563_Unused_Variable__unused_value_int64_t_43::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_72::good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_72::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_73::good();");
CWE563_Unused_Variable__unused_uninit_variable_long_73::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_83::good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_83::good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_74::good();");
CWE563_Unused_Variable__unused_value_int64_t_74::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_72::good();");
CWE563_Unused_Variable__unused_uninit_variable_int_72::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_74::good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_74::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_74::good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_74::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_83::good();");
CWE563_Unused_Variable__unused_init_variable_char_83::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_73::good();");
CWE563_Unused_Variable__unused_init_variable_char_73::good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_83::good();");
CWE563_Unused_Variable__unused_value_wchar_t_83::good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_72::good();");
CWE563_Unused_Variable__unused_value_int64_t_72::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_72::good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_72::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_84::good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_84::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_83::good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_83::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_83::good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_83::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_83::good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_83::good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_83::good();");
CWE563_Unused_Variable__unused_value_int64_t_83::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_84::good();");
CWE563_Unused_Variable__unused_init_variable_int_84::good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_84::good();");
CWE563_Unused_Variable__unused_value_int_84::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_84::good();");
CWE563_Unused_Variable__unused_init_variable_struct_84::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_43::good();");
CWE563_Unused_Variable__unused_init_variable_char_43::good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_83::good();");
CWE563_Unused_Variable__unused_value_long_83::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_82::good();");
CWE563_Unused_Variable__unused_uninit_variable_char_82::good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_73::good();");
CWE563_Unused_Variable__unused_value_struct_73::good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_82::good();");
CWE563_Unused_Variable__unused_value_int64_t_82::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_84::good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_84::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_84::good();");
CWE563_Unused_Variable__unused_init_variable_long_84::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_82::good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_82::good();
printLine("Calling CWE563_Unused_Variable__unused_class_member_value_01::good();");
CWE563_Unused_Variable__unused_class_member_value_01::good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_84::good();");
CWE563_Unused_Variable__unused_value_long_84::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_43::good();");
CWE563_Unused_Variable__unused_uninit_variable_long_43::good();
printLine("Calling CWE563_Unused_Variable__unused_class_member_variable_01::good();");
CWE563_Unused_Variable__unused_class_member_variable_01::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_74::good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_74::good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_43::good();");
CWE563_Unused_Variable__unused_value_int_43::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_82::good();");
CWE563_Unused_Variable__unused_init_variable_char_82::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_84::good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_84::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_81::good();");
CWE563_Unused_Variable__unused_init_variable_char_81::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_81::good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_81::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_83::good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_83::good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_73::good();");
CWE563_Unused_Variable__unused_value_int64_t_73::good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_72::good();");
CWE563_Unused_Variable__unused_value_long_72::good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_83::good();");
CWE563_Unused_Variable__unused_value_struct_83::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_82::good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_82::good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_74::good();");
CWE563_Unused_Variable__unused_value_struct_74::good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_81::good();");
CWE563_Unused_Variable__unused_value_struct_81::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_84::good();");
CWE563_Unused_Variable__unused_uninit_variable_long_84::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_73::good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_73::good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_84::good();");
CWE563_Unused_Variable__unused_value_struct_84::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_84::good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_84::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_72::good();");
CWE563_Unused_Variable__unused_init_variable_int_72::good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_33::good();");
CWE563_Unused_Variable__unused_value_int64_t_33::good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_83::good();");
CWE563_Unused_Variable__unused_value_wchar_t_83::good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_73::good();");
CWE563_Unused_Variable__unused_value_long_73::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_73::good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_73::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_83::good();");
CWE563_Unused_Variable__unused_uninit_variable_long_83::good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_84::good();");
CWE563_Unused_Variable__unused_value_long_84::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_84::good();");
CWE563_Unused_Variable__unused_uninit_variable_int_84::good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_83::good();");
CWE563_Unused_Variable__unused_value_long_83::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_72::good();");
CWE563_Unused_Variable__unused_uninit_variable_char_72::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_84::good();");
CWE563_Unused_Variable__unused_init_variable_char_84::good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_43::good();");
CWE563_Unused_Variable__unused_value_long_43::good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_72::good();");
CWE563_Unused_Variable__unused_value_wchar_t_72::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_83::good();");
CWE563_Unused_Variable__unused_uninit_variable_int_83::good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_81::good();");
CWE563_Unused_Variable__unused_value_long_81::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_43::good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_43::good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_72::good();");
CWE563_Unused_Variable__unused_value_int_72::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_72::good();");
CWE563_Unused_Variable__unused_init_variable_char_72::good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_84::good();");
CWE563_Unused_Variable__unused_value_int_84::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_33::good();");
CWE563_Unused_Variable__unused_uninit_variable_char_33::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_72::good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_72::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_73::good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_73::good();
printLine("Calling CWE563_Unused_Variable__unused_value_long_33::good();");
CWE563_Unused_Variable__unused_value_long_33::good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_72::good();");
CWE563_Unused_Variable__unused_value_char_72::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_83::good();");
CWE563_Unused_Variable__unused_uninit_variable_int_83::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_33::good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_33::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_83::good();");
CWE563_Unused_Variable__unused_init_variable_int_83::good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_74::good();");
CWE563_Unused_Variable__unused_value_wchar_t_74::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_84::good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_84::good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_43::good();");
CWE563_Unused_Variable__unused_value_char_43::good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_84::good();");
CWE563_Unused_Variable__unused_value_int64_t_84::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_72::good();");
CWE563_Unused_Variable__unused_uninit_variable_long_72::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_72::good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_72::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_82::good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_82::good();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_84::good();");
CWE563_Unused_Variable__unused_value_wchar_t_84::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_74::good();");
CWE563_Unused_Variable__unused_init_variable_struct_74::good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_33::good();");
CWE563_Unused_Variable__unused_value_char_33::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_84::good();");
CWE563_Unused_Variable__unused_init_variable_struct_84::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_84::good();");
CWE563_Unused_Variable__unused_init_variable_int64_t_84::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_43::good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_43::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_83::good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_83::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_74::good();");
CWE563_Unused_Variable__unused_init_variable_char_74::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_33::good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_33::good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_81::good();");
CWE563_Unused_Variable__unused_value_char_81::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_72::good();");
CWE563_Unused_Variable__unused_init_variable_long_72::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_84::good();");
CWE563_Unused_Variable__unused_uninit_variable_char_84::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_83::good();");
CWE563_Unused_Variable__unused_uninit_variable_long_83::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_83::good();");
CWE563_Unused_Variable__unused_init_variable_char_83::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_74::good();");
CWE563_Unused_Variable__unused_init_variable_int_74::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_83::good();");
CWE563_Unused_Variable__unused_init_variable_long_83::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_43::good();");
CWE563_Unused_Variable__unused_uninit_variable_char_43::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_83::good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_83::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_73::good();");
CWE563_Unused_Variable__unused_uninit_variable_int_73::good();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_84::good();");
CWE563_Unused_Variable__unused_value_int64_t_84::good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_73::good();");
CWE563_Unused_Variable__unused_value_char_73::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_81::good();");
CWE563_Unused_Variable__unused_init_variable_struct_81::good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_83::good();");
CWE563_Unused_Variable__unused_value_struct_83::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_81::good();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_81::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_84::good();");
CWE563_Unused_Variable__unused_init_variable_char_84::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_33::good();");
CWE563_Unused_Variable__unused_uninit_variable_struct_33::good();
printLine("Calling CWE563_Unused_Variable__unused_value_int_81::good();");
CWE563_Unused_Variable__unused_value_int_81::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_33::good();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_33::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_83::good();");
CWE563_Unused_Variable__unused_init_variable_struct_83::good();
printLine("Calling CWE563_Unused_Variable__unused_value_char_83::good();");
CWE563_Unused_Variable__unused_value_char_83::good();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_72::good();");
CWE563_Unused_Variable__unused_value_struct_72::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_81::good();");
CWE563_Unused_Variable__unused_uninit_variable_int_81::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_73::good();");
CWE563_Unused_Variable__unused_init_variable_int_73::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_84::good();");
CWE563_Unused_Variable__unused_uninit_variable_char_84::good();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_84::good();");
CWE563_Unused_Variable__unused_uninit_variable_int_84::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_72::good();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_72::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_33::good();");
CWE563_Unused_Variable__unused_init_variable_int_33::good();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_73::good();");
CWE563_Unused_Variable__unused_init_variable_struct_73::good();
/* END-AUTOGENERATED-CPP-GOOD-FUNCTION-CALLS */
#endif /* __cplusplus */
#endif /* OMITGOOD */
#ifndef OMITBAD
/* Calling C bad functions */
/* BEGIN-AUTOGENERATED-C-BAD-FUNCTION-CALLS */
printLine("Calling CWE563_Unused_Variable__unused_value_struct_22_bad();");
CWE563_Unused_Variable__unused_value_struct_22_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_09_bad();");
CWE563_Unused_Variable__unused_value_struct_09_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_03_bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_03_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_16_bad();");
CWE563_Unused_Variable__unused_init_variable_long_16_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_13_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_13_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_11_bad();");
CWE563_Unused_Variable__unused_value_long_11_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_02_bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_02_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_14_bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_14_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_01_bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_04_bad();");
CWE563_Unused_Variable__unused_value_long_04_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_02_bad();");
CWE563_Unused_Variable__unused_init_variable_char_02_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_10_bad();");
CWE563_Unused_Variable__unused_init_variable_int_10_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_17_bad();");
CWE563_Unused_Variable__unused_value_wchar_t_17_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_10_bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_10_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_16_bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_16_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_01_bad();");
CWE563_Unused_Variable__unused_init_variable_long_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_06_bad();");
CWE563_Unused_Variable__unused_value_long_06_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_15_bad();");
CWE563_Unused_Variable__unused_init_variable_int_15_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_15_bad();");
CWE563_Unused_Variable__unused_init_variable_long_15_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_06_bad();");
CWE563_Unused_Variable__unused_value_struct_06_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_10_bad();");
CWE563_Unused_Variable__unused_init_variable_struct_10_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_03_bad();");
CWE563_Unused_Variable__unused_init_variable_char_03_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_09_bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_09_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_06_bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_06_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_02_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_02_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_05_bad();");
CWE563_Unused_Variable__unused_value_struct_05_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_16_bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_16_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_09_bad();");
CWE563_Unused_Variable__unused_init_variable_struct_09_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_17_bad();");
CWE563_Unused_Variable__unused_value_int_17_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_14_bad();");
CWE563_Unused_Variable__unused_value_wchar_t_14_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_15_bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_15_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_04_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_04_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_16_bad();");
CWE563_Unused_Variable__unused_init_variable_char_16_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_08_bad();");
CWE563_Unused_Variable__unused_value_wchar_t_08_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_02_bad();");
CWE563_Unused_Variable__unused_value_wchar_t_02_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_17_bad();");
CWE563_Unused_Variable__unused_init_variable_int_17_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_04_bad();");
CWE563_Unused_Variable__unused_value_int_04_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_03_bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_03_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_01_bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_09_bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_09_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_04_bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_04_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_10_bad();");
CWE563_Unused_Variable__unused_value_long_10_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_17_bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_17_bad();
printLine("Calling CWE563_Unused_Variable__unused_static_global_variable_01_bad();");
CWE563_Unused_Variable__unused_static_global_variable_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_14_bad();");
CWE563_Unused_Variable__unused_init_variable_int_14_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_21_bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_21_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_17_bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_17_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_21_bad();");
CWE563_Unused_Variable__unused_value_long_21_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_22_bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_22_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_02_bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_02_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_06_bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_06_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_06_bad();");
CWE563_Unused_Variable__unused_init_variable_int_06_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_06_bad();");
CWE563_Unused_Variable__unused_init_variable_char_06_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_10_bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_10_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_08_bad();");
CWE563_Unused_Variable__unused_value_char_08_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_11_bad();");
CWE563_Unused_Variable__unused_value_int64_t_11_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_17_bad();");
CWE563_Unused_Variable__unused_init_variable_long_17_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_08_bad();");
CWE563_Unused_Variable__unused_init_variable_long_08_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_14_bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_14_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_13_bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_13_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_14_bad();");
CWE563_Unused_Variable__unused_value_int_14_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_07_bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_07_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_04_bad();");
CWE563_Unused_Variable__unused_init_variable_long_04_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_06_bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_06_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_22_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_22_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_09_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_09_bad();
printLine("Calling CWE563_Unused_Variable__unused_parameter_value_01_bad();");
CWE563_Unused_Variable__unused_parameter_value_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_14_bad();");
CWE563_Unused_Variable__unused_value_int64_t_14_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_14_bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_14_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_04_bad();");
CWE563_Unused_Variable__unused_value_wchar_t_04_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_13_bad();");
CWE563_Unused_Variable__unused_value_int_13_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_15_bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_15_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_21_bad();");
CWE563_Unused_Variable__unused_value_struct_21_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_22_bad();");
CWE563_Unused_Variable__unused_init_variable_int_22_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_09_bad();");
CWE563_Unused_Variable__unused_value_char_09_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_17_bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_17_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_05_bad();");
CWE563_Unused_Variable__unused_init_variable_long_05_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_17_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_17_bad();
printLine("Calling CWE563_Unused_Variable__unused_static_global_value_01_bad();");
CWE563_Unused_Variable__unused_static_global_value_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_16_bad();");
CWE563_Unused_Variable__unused_value_int_16_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_07_bad();");
CWE563_Unused_Variable__unused_value_int64_t_07_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_03_bad();");
CWE563_Unused_Variable__unused_value_struct_03_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_22_bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_22_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_14_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_14_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_18_bad();");
CWE563_Unused_Variable__unused_value_struct_18_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_22_bad();");
CWE563_Unused_Variable__unused_value_wchar_t_22_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_10_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_10_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_03_bad();");
CWE563_Unused_Variable__unused_value_long_03_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_06_bad();");
CWE563_Unused_Variable__unused_init_variable_struct_06_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_18_bad();");
CWE563_Unused_Variable__unused_init_variable_int_18_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_17_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_17_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_07_bad();");
CWE563_Unused_Variable__unused_value_struct_07_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_16_bad();");
CWE563_Unused_Variable__unused_value_wchar_t_16_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_05_bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_05_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_07_bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_07_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_03_bad();");
CWE563_Unused_Variable__unused_init_variable_struct_03_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_18_bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_18_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_15_bad();");
CWE563_Unused_Variable__unused_value_wchar_t_15_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_13_bad();");
CWE563_Unused_Variable__unused_init_variable_int_13_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_16_bad();");
CWE563_Unused_Variable__unused_init_variable_struct_16_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_21_bad();");
CWE563_Unused_Variable__unused_value_char_21_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_06_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_06_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_21_bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_21_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_14_bad();");
CWE563_Unused_Variable__unused_value_long_14_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_08_bad();");
CWE563_Unused_Variable__unused_init_variable_struct_08_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_02_bad();");
CWE563_Unused_Variable__unused_init_variable_long_02_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_13_bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_13_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_05_bad();");
CWE563_Unused_Variable__unused_init_variable_char_05_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_22_bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_22_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_10_bad();");
CWE563_Unused_Variable__unused_value_wchar_t_10_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_10_bad();");
CWE563_Unused_Variable__unused_value_int_10_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_11_bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_11_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_03_bad();");
CWE563_Unused_Variable__unused_init_variable_long_03_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_15_bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_15_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_14_bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_14_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_11_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_11_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_01_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_15_bad();");
CWE563_Unused_Variable__unused_value_int64_t_15_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_15_bad();");
CWE563_Unused_Variable__unused_value_char_15_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_21_bad();");
CWE563_Unused_Variable__unused_value_int_21_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_03_bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_03_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_22_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_22_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_22_bad();");
CWE563_Unused_Variable__unused_value_long_22_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_21_bad();");
CWE563_Unused_Variable__unused_value_wchar_t_21_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_05_bad();");
CWE563_Unused_Variable__unused_value_char_05_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_02_bad();");
CWE563_Unused_Variable__unused_value_long_02_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_22_bad();");
CWE563_Unused_Variable__unused_value_int64_t_22_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_01_bad();");
CWE563_Unused_Variable__unused_value_int64_t_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_07_bad();");
CWE563_Unused_Variable__unused_value_int_07_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_03_bad();");
CWE563_Unused_Variable__unused_value_int_03_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_17_bad();");
CWE563_Unused_Variable__unused_init_variable_char_17_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_04_bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_04_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_11_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_11_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_08_bad();");
CWE563_Unused_Variable__unused_value_long_08_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_08_bad();");
CWE563_Unused_Variable__unused_value_struct_08_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_10_bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_10_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_09_bad();");
CWE563_Unused_Variable__unused_init_variable_int_09_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_06_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_06_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_10_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_10_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_06_bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_06_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_05_bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_05_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_16_bad();");
CWE563_Unused_Variable__unused_value_long_16_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_13_bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_13_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_04_bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_04_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_07_bad();");
CWE563_Unused_Variable__unused_value_char_07_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_18_bad();");
CWE563_Unused_Variable__unused_value_wchar_t_18_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_10_bad();");
CWE563_Unused_Variable__unused_init_variable_long_10_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_21_bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_21_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_15_bad();");
CWE563_Unused_Variable__unused_value_struct_15_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_05_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_05_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_13_bad();");
CWE563_Unused_Variable__unused_init_variable_long_13_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_08_bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_08_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_11_bad();");
CWE563_Unused_Variable__unused_value_wchar_t_11_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_11_bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_11_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_03_bad();");
CWE563_Unused_Variable__unused_init_variable_int_03_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_16_bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_16_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_09_bad();");
CWE563_Unused_Variable__unused_init_variable_char_09_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_15_bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_15_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_02_bad();");
CWE563_Unused_Variable__unused_value_int64_t_02_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_22_bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_22_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_18_bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_18_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_09_bad();");
CWE563_Unused_Variable__unused_init_variable_long_09_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_06_bad();");
CWE563_Unused_Variable__unused_value_wchar_t_06_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_08_bad();");
CWE563_Unused_Variable__unused_init_variable_int_08_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_21_bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_21_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_17_bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_17_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_18_bad();");
CWE563_Unused_Variable__unused_init_variable_struct_18_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_03_bad();");
CWE563_Unused_Variable__unused_value_char_03_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_21_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_21_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_05_bad();");
CWE563_Unused_Variable__unused_init_variable_int_05_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_18_bad();");
CWE563_Unused_Variable__unused_value_int_18_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_11_bad();");
CWE563_Unused_Variable__unused_init_variable_char_11_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_11_bad();");
CWE563_Unused_Variable__unused_init_variable_struct_11_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_07_bad();");
CWE563_Unused_Variable__unused_init_variable_char_07_bad();
printLine("Calling CWE563_Unused_Variable__unused_parameter_variable_01_bad();");
CWE563_Unused_Variable__unused_parameter_variable_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_05_bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_05_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_01_bad();");
CWE563_Unused_Variable__unused_value_wchar_t_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_01_bad();");
CWE563_Unused_Variable__unused_init_variable_int_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_16_bad();");
CWE563_Unused_Variable__unused_value_struct_16_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_02_bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_02_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_18_bad();");
CWE563_Unused_Variable__unused_init_variable_long_18_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_21_bad();");
CWE563_Unused_Variable__unused_init_variable_long_21_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_15_bad();");
CWE563_Unused_Variable__unused_value_int_15_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_02_bad();");
CWE563_Unused_Variable__unused_value_struct_02_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_03_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_03_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_22_bad();");
CWE563_Unused_Variable__unused_init_variable_long_22_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_11_bad();");
CWE563_Unused_Variable__unused_value_char_11_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_13_bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_13_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_10_bad();");
CWE563_Unused_Variable__unused_value_char_10_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_17_bad();");
CWE563_Unused_Variable__unused_value_char_17_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_04_bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_04_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_02_bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_02_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_18_bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_18_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_15_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_15_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_06_bad();");
CWE563_Unused_Variable__unused_value_int_06_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_18_bad();");
CWE563_Unused_Variable__unused_init_variable_char_18_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_05_bad();");
CWE563_Unused_Variable__unused_value_wchar_t_05_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_18_bad();");
CWE563_Unused_Variable__unused_value_int64_t_18_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_10_bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_10_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_05_bad();");
CWE563_Unused_Variable__unused_value_long_05_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_17_bad();");
CWE563_Unused_Variable__unused_value_struct_17_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_01_bad();");
CWE563_Unused_Variable__unused_value_long_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_17_bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_17_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_14_bad();");
CWE563_Unused_Variable__unused_init_variable_long_14_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_07_bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_07_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_15_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_15_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_07_bad();");
CWE563_Unused_Variable__unused_value_long_07_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_01_bad();");
CWE563_Unused_Variable__unused_value_struct_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_04_bad();");
CWE563_Unused_Variable__unused_value_struct_04_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_04_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_04_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_05_bad();");
CWE563_Unused_Variable__unused_init_variable_struct_05_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_15_bad();");
CWE563_Unused_Variable__unused_init_variable_char_15_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_05_bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_05_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_22_bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_22_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_03_bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_03_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_21_bad();");
CWE563_Unused_Variable__unused_init_variable_int_21_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_10_bad();");
CWE563_Unused_Variable__unused_init_variable_char_10_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_01_bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_03_bad();");
CWE563_Unused_Variable__unused_value_wchar_t_03_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_04_bad();");
CWE563_Unused_Variable__unused_value_char_04_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_13_bad();");
CWE563_Unused_Variable__unused_init_variable_struct_13_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_04_bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_04_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_06_bad();");
CWE563_Unused_Variable__unused_value_int64_t_06_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_07_bad();");
CWE563_Unused_Variable__unused_init_variable_struct_07_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_16_bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_16_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_17_bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_17_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_16_bad();");
CWE563_Unused_Variable__unused_value_char_16_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_05_bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_05_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_11_bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_11_bad();
printLine("Calling CWE563_Unused_Variable__unused_global_value_01_bad();");
CWE563_Unused_Variable__unused_global_value_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_16_bad();");
CWE563_Unused_Variable__unused_value_int64_t_16_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_06_bad();");
CWE563_Unused_Variable__unused_value_char_06_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_06_bad();");
CWE563_Unused_Variable__unused_init_variable_long_06_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_15_bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_15_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_15_bad();");
CWE563_Unused_Variable__unused_init_variable_struct_15_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_11_bad();");
CWE563_Unused_Variable__unused_init_variable_long_11_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_14_bad();");
CWE563_Unused_Variable__unused_value_struct_14_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_04_bad();");
CWE563_Unused_Variable__unused_init_variable_char_04_bad();
printLine("Calling CWE563_Unused_Variable__unused_global_variable_01_bad();");
CWE563_Unused_Variable__unused_global_variable_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_06_bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_06_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_11_bad();");
CWE563_Unused_Variable__unused_init_variable_int_11_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_01_bad();");
CWE563_Unused_Variable__unused_value_char_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_13_bad();");
CWE563_Unused_Variable__unused_value_struct_13_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_02_bad();");
CWE563_Unused_Variable__unused_value_char_02_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_11_bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_11_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_08_bad();");
CWE563_Unused_Variable__unused_value_int_08_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_21_bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_21_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_02_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_02_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_04_bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_04_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_01_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_02_bad();");
CWE563_Unused_Variable__unused_value_int_02_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_09_bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_09_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_02_bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_02_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_16_bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_16_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_06_bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_06_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_13_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_13_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_16_bad();");
CWE563_Unused_Variable__unused_init_variable_int_16_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_04_bad();");
CWE563_Unused_Variable__unused_init_variable_struct_04_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_09_bad();");
CWE563_Unused_Variable__unused_value_int64_t_09_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_14_bad();");
CWE563_Unused_Variable__unused_init_variable_char_14_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_14_bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_14_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_09_bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_09_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_08_bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_08_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_08_bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_08_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_17_bad();");
CWE563_Unused_Variable__unused_value_long_17_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_10_bad();");
CWE563_Unused_Variable__unused_value_int64_t_10_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_01_bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_07_bad();");
CWE563_Unused_Variable__unused_value_wchar_t_07_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_21_bad();");
CWE563_Unused_Variable__unused_init_variable_char_21_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_22_bad();");
CWE563_Unused_Variable__unused_value_char_22_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_22_bad();");
CWE563_Unused_Variable__unused_init_variable_struct_22_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_08_bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_08_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_03_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_03_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_03_bad();");
CWE563_Unused_Variable__unused_value_int64_t_03_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_03_bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_03_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_17_bad();");
CWE563_Unused_Variable__unused_init_variable_struct_17_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_21_bad();");
CWE563_Unused_Variable__unused_value_int64_t_21_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_10_bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_10_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_05_bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_05_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_18_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_18_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_05_bad();");
CWE563_Unused_Variable__unused_value_int64_t_05_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_21_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_21_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_21_bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_21_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_22_bad();");
CWE563_Unused_Variable__unused_value_int_22_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_15_bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_15_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_18_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_18_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_10_bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_10_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_14_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_14_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_08_bad();");
CWE563_Unused_Variable__unused_value_int64_t_08_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_15_bad();");
CWE563_Unused_Variable__unused_value_long_15_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_18_bad();");
CWE563_Unused_Variable__unused_value_long_18_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_16_bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_16_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_02_bad();");
CWE563_Unused_Variable__unused_init_variable_int_02_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_07_bad();");
CWE563_Unused_Variable__unused_init_variable_int_07_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_13_bad();");
CWE563_Unused_Variable__unused_value_char_13_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_13_bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_13_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_18_bad();");
CWE563_Unused_Variable__unused_value_char_18_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_10_bad();");
CWE563_Unused_Variable__unused_value_struct_10_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_09_bad();");
CWE563_Unused_Variable__unused_value_wchar_t_09_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_04_bad();");
CWE563_Unused_Variable__unused_init_variable_int_04_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_13_bad();");
CWE563_Unused_Variable__unused_value_wchar_t_13_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_22_bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_22_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_09_bad();");
CWE563_Unused_Variable__unused_value_int_09_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_02_bad();");
CWE563_Unused_Variable__unused_init_variable_struct_02_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_07_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_07_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_01_bad();");
CWE563_Unused_Variable__unused_init_variable_struct_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_01_bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_13_bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_13_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_18_bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_18_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_13_bad();");
CWE563_Unused_Variable__unused_value_int64_t_13_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_03_bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_03_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_05_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_05_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_13_bad();");
CWE563_Unused_Variable__unused_value_long_13_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_07_bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_07_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_07_bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_07_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_16_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_16_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_08_bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_08_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_08_bad();");
CWE563_Unused_Variable__unused_init_variable_char_08_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_09_bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_09_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_13_bad();");
CWE563_Unused_Variable__unused_init_variable_char_13_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_11_bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_11_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_11_bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_11_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_11_bad();");
CWE563_Unused_Variable__unused_value_int_11_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_07_bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_07_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_14_bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_14_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_07_bad();");
CWE563_Unused_Variable__unused_init_variable_long_07_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_21_bad();");
CWE563_Unused_Variable__unused_init_variable_struct_21_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_01_bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_08_bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_08_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_17_bad();");
CWE563_Unused_Variable__unused_value_int64_t_17_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_01_bad();");
CWE563_Unused_Variable__unused_value_int_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_16_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_16_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_08_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_08_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_07_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_07_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_05_bad();");
CWE563_Unused_Variable__unused_value_int_05_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_09_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_09_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_08_bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_08_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_01_bad();");
CWE563_Unused_Variable__unused_init_variable_char_01_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_11_bad();");
CWE563_Unused_Variable__unused_value_struct_11_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_09_bad();");
CWE563_Unused_Variable__unused_value_long_09_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_14_bad();");
CWE563_Unused_Variable__unused_init_variable_struct_14_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_02_bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_02_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_04_bad();");
CWE563_Unused_Variable__unused_value_int64_t_04_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_09_bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_09_bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_14_bad();");
CWE563_Unused_Variable__unused_value_char_14_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_18_bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_18_bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_22_bad();");
CWE563_Unused_Variable__unused_init_variable_char_22_bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_18_bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_18_bad();
/* END-AUTOGENERATED-C-BAD-FUNCTION-CALLS */
#ifdef __cplusplus
/* Calling C++ bad functions */
/* BEGIN-AUTOGENERATED-CPP-BAD-FUNCTION-CALLS */
printLine("Calling CWE563_Unused_Variable__unused_value_char_84::bad();");
CWE563_Unused_Variable__unused_value_char_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_74::bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_74::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_83::bad();");
CWE563_Unused_Variable__unused_value_int_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_43::bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_43::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_84::bad();");
CWE563_Unused_Variable__unused_init_variable_long_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_81::bad();");
CWE563_Unused_Variable__unused_value_int64_t_81::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_82::bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_82::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_83::bad();");
CWE563_Unused_Variable__unused_init_variable_struct_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_82::bad();");
CWE563_Unused_Variable__unused_value_struct_82::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_83::bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_73::bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_73::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_33::bad();");
CWE563_Unused_Variable__unused_value_wchar_t_33::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_73::bad();");
CWE563_Unused_Variable__unused_value_int_73::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_73::bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_73::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_33::bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_33::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_83::bad();");
CWE563_Unused_Variable__unused_value_int_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_33::bad();");
CWE563_Unused_Variable__unused_value_struct_33::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_43::bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_43::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_83::bad();");
CWE563_Unused_Variable__unused_init_variable_int_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_82::bad();");
CWE563_Unused_Variable__unused_init_variable_int_82::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_83::bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_84::bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_43::bad();");
CWE563_Unused_Variable__unused_init_variable_int_43::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_33::bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_33::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_74::bad();");
CWE563_Unused_Variable__unused_value_int_74::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_81::bad();");
CWE563_Unused_Variable__unused_init_variable_int_81::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_43::bad();");
CWE563_Unused_Variable__unused_init_variable_struct_43::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_83::bad();");
CWE563_Unused_Variable__unused_init_variable_long_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_84::bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_81::bad();");
CWE563_Unused_Variable__unused_value_wchar_t_81::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_33::bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_33::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_82::bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_82::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_82::bad();");
CWE563_Unused_Variable__unused_init_variable_long_82::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_81::bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_81::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_83::bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_83::bad();");
CWE563_Unused_Variable__unused_value_int64_t_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_84::bad();");
CWE563_Unused_Variable__unused_value_wchar_t_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_84::bad();");
CWE563_Unused_Variable__unused_value_char_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_74::bad();");
CWE563_Unused_Variable__unused_init_variable_long_74::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_74::bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_74::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_81::bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_81::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_43::bad();");
CWE563_Unused_Variable__unused_init_variable_long_43::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_81::bad();");
CWE563_Unused_Variable__unused_init_variable_long_81::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_82::bad();");
CWE563_Unused_Variable__unused_value_char_82::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_83::bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_81::bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_81::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_73::bad();");
CWE563_Unused_Variable__unused_value_wchar_t_73::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_43::bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_43::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_74::bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_74::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_74::bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_74::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_72::bad();");
CWE563_Unused_Variable__unused_init_variable_struct_72::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_81::bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_81::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_74::bad();");
CWE563_Unused_Variable__unused_value_long_74::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_84::bad();");
CWE563_Unused_Variable__unused_init_variable_int_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_73::bad();");
CWE563_Unused_Variable__unused_init_variable_long_73::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_82::bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_82::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_83::bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_33::bad();");
CWE563_Unused_Variable__unused_init_variable_char_33::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_43::bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_43::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_82::bad();");
CWE563_Unused_Variable__unused_value_long_82::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_84::bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_82::bad();");
CWE563_Unused_Variable__unused_value_int_82::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_84::bad();");
CWE563_Unused_Variable__unused_value_struct_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_81::bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_81::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_84::bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_33::bad();");
CWE563_Unused_Variable__unused_init_variable_struct_33::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_43::bad();");
CWE563_Unused_Variable__unused_value_struct_43::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_82::bad();");
CWE563_Unused_Variable__unused_init_variable_struct_82::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_73::bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_73::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_83::bad();");
CWE563_Unused_Variable__unused_value_char_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_84::bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_43::bad();");
CWE563_Unused_Variable__unused_value_wchar_t_43::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_82::bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_82::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_74::bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_74::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_74::bad();");
CWE563_Unused_Variable__unused_value_char_74::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_82::bad();");
CWE563_Unused_Variable__unused_value_wchar_t_82::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_33::bad();");
CWE563_Unused_Variable__unused_init_variable_long_33::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_33::bad();");
CWE563_Unused_Variable__unused_value_int_33::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_43::bad();");
CWE563_Unused_Variable__unused_value_int64_t_43::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_72::bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_72::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_73::bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_73::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_83::bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_74::bad();");
CWE563_Unused_Variable__unused_value_int64_t_74::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_72::bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_72::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_74::bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_74::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_74::bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_74::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_83::bad();");
CWE563_Unused_Variable__unused_init_variable_char_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_73::bad();");
CWE563_Unused_Variable__unused_init_variable_char_73::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_83::bad();");
CWE563_Unused_Variable__unused_value_wchar_t_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_72::bad();");
CWE563_Unused_Variable__unused_value_int64_t_72::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_72::bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_72::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_84::bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_83::bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_83::bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_83::bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_83::bad();");
CWE563_Unused_Variable__unused_value_int64_t_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_84::bad();");
CWE563_Unused_Variable__unused_init_variable_int_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_84::bad();");
CWE563_Unused_Variable__unused_value_int_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_84::bad();");
CWE563_Unused_Variable__unused_init_variable_struct_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_43::bad();");
CWE563_Unused_Variable__unused_init_variable_char_43::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_83::bad();");
CWE563_Unused_Variable__unused_value_long_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_82::bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_82::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_73::bad();");
CWE563_Unused_Variable__unused_value_struct_73::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_82::bad();");
CWE563_Unused_Variable__unused_value_int64_t_82::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_84::bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_84::bad();");
CWE563_Unused_Variable__unused_init_variable_long_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_82::bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_82::bad();
printLine("Calling CWE563_Unused_Variable__unused_class_member_value_01::bad();");
CWE563_Unused_Variable__unused_class_member_value_01::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_84::bad();");
CWE563_Unused_Variable__unused_value_long_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_43::bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_43::bad();
printLine("Calling CWE563_Unused_Variable__unused_class_member_variable_01::bad();");
CWE563_Unused_Variable__unused_class_member_variable_01::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_74::bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_74::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_43::bad();");
CWE563_Unused_Variable__unused_value_int_43::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_82::bad();");
CWE563_Unused_Variable__unused_init_variable_char_82::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_84::bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_81::bad();");
CWE563_Unused_Variable__unused_init_variable_char_81::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_81::bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_81::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_83::bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_73::bad();");
CWE563_Unused_Variable__unused_value_int64_t_73::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_72::bad();");
CWE563_Unused_Variable__unused_value_long_72::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_83::bad();");
CWE563_Unused_Variable__unused_value_struct_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_82::bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_82::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_74::bad();");
CWE563_Unused_Variable__unused_value_struct_74::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_81::bad();");
CWE563_Unused_Variable__unused_value_struct_81::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_84::bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_73::bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_73::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_84::bad();");
CWE563_Unused_Variable__unused_value_struct_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_84::bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_72::bad();");
CWE563_Unused_Variable__unused_init_variable_int_72::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_33::bad();");
CWE563_Unused_Variable__unused_value_int64_t_33::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_83::bad();");
CWE563_Unused_Variable__unused_value_wchar_t_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_73::bad();");
CWE563_Unused_Variable__unused_value_long_73::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_73::bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_73::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_83::bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_84::bad();");
CWE563_Unused_Variable__unused_value_long_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_84::bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_83::bad();");
CWE563_Unused_Variable__unused_value_long_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_72::bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_72::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_84::bad();");
CWE563_Unused_Variable__unused_init_variable_char_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_43::bad();");
CWE563_Unused_Variable__unused_value_long_43::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_72::bad();");
CWE563_Unused_Variable__unused_value_wchar_t_72::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_83::bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_81::bad();");
CWE563_Unused_Variable__unused_value_long_81::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_43::bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_43::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_72::bad();");
CWE563_Unused_Variable__unused_value_int_72::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_72::bad();");
CWE563_Unused_Variable__unused_init_variable_char_72::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_84::bad();");
CWE563_Unused_Variable__unused_value_int_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_33::bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_33::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_72::bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_72::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_73::bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_73::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_long_33::bad();");
CWE563_Unused_Variable__unused_value_long_33::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_72::bad();");
CWE563_Unused_Variable__unused_value_char_72::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_83::bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_33::bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_33::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_83::bad();");
CWE563_Unused_Variable__unused_init_variable_int_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_74::bad();");
CWE563_Unused_Variable__unused_value_wchar_t_74::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_84::bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_43::bad();");
CWE563_Unused_Variable__unused_value_char_43::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_84::bad();");
CWE563_Unused_Variable__unused_value_int64_t_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_72::bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_72::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_72::bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_72::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_82::bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_82::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_wchar_t_84::bad();");
CWE563_Unused_Variable__unused_value_wchar_t_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_74::bad();");
CWE563_Unused_Variable__unused_init_variable_struct_74::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_33::bad();");
CWE563_Unused_Variable__unused_value_char_33::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_84::bad();");
CWE563_Unused_Variable__unused_init_variable_struct_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int64_t_84::bad();");
CWE563_Unused_Variable__unused_init_variable_int64_t_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_43::bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_43::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_83::bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_74::bad();");
CWE563_Unused_Variable__unused_init_variable_char_74::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_33::bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_33::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_81::bad();");
CWE563_Unused_Variable__unused_value_char_81::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_72::bad();");
CWE563_Unused_Variable__unused_init_variable_long_72::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_84::bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_long_83::bad();");
CWE563_Unused_Variable__unused_uninit_variable_long_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_83::bad();");
CWE563_Unused_Variable__unused_init_variable_char_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_74::bad();");
CWE563_Unused_Variable__unused_init_variable_int_74::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_long_83::bad();");
CWE563_Unused_Variable__unused_init_variable_long_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_43::bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_43::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_83::bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_73::bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_73::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int64_t_84::bad();");
CWE563_Unused_Variable__unused_value_int64_t_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_73::bad();");
CWE563_Unused_Variable__unused_value_char_73::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_81::bad();");
CWE563_Unused_Variable__unused_init_variable_struct_81::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_83::bad();");
CWE563_Unused_Variable__unused_value_struct_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_wchar_t_81::bad();");
CWE563_Unused_Variable__unused_uninit_variable_wchar_t_81::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_char_84::bad();");
CWE563_Unused_Variable__unused_init_variable_char_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_struct_33::bad();");
CWE563_Unused_Variable__unused_uninit_variable_struct_33::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_int_81::bad();");
CWE563_Unused_Variable__unused_value_int_81::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int64_t_33::bad();");
CWE563_Unused_Variable__unused_uninit_variable_int64_t_33::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_83::bad();");
CWE563_Unused_Variable__unused_init_variable_struct_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_char_83::bad();");
CWE563_Unused_Variable__unused_value_char_83::bad();
printLine("Calling CWE563_Unused_Variable__unused_value_struct_72::bad();");
CWE563_Unused_Variable__unused_value_struct_72::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_81::bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_81::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_73::bad();");
CWE563_Unused_Variable__unused_init_variable_int_73::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_char_84::bad();");
CWE563_Unused_Variable__unused_uninit_variable_char_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_uninit_variable_int_84::bad();");
CWE563_Unused_Variable__unused_uninit_variable_int_84::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_wchar_t_72::bad();");
CWE563_Unused_Variable__unused_init_variable_wchar_t_72::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_int_33::bad();");
CWE563_Unused_Variable__unused_init_variable_int_33::bad();
printLine("Calling CWE563_Unused_Variable__unused_init_variable_struct_73::bad();");
CWE563_Unused_Variable__unused_init_variable_struct_73::bad();
/* END-AUTOGENERATED-CPP-BAD-FUNCTION-CALLS */
#endif /* __cplusplus */
#endif /* OMITBAD */
return 0;
}
| bsd-3-clause |
Letargie/pggi | examples/cairo/lineJoin.php | 720 | <?php
namespace PGGI\Cairo;
chdir(__DIR__);
$surface = new ImageSurface(ImageSurface::FORMAT_ARGB32, 300, 300);
$context = new Context($surface);
$context->lineWidth = 40.96;
$context->moveTo(76.8, 84.48)
->relLineTo(51.2, -51.2)
->relLineTo(51.2, 51.2)
->lineJoin = Context::LINE_JOIN_MITER; // default one
$context->stroke()
->moveTo(76.8, 161.28)
->relLineTo(51.2, -51.2)
->relLineTo(51.2, 51.2)
->lineJoin = Context::LINE_JOIN_BEVEL;
$context->stroke()
->moveTo(76.8, 238.08)
->relLineTo(51.2, -51.2)
->relLineTo(51.2, 51.2)
->lineJoin = Context::LINE_JOIN_ROUND;
$context->stroke();
$surface->writeToPNG("lineJoin.png");
| bsd-3-clause |
NCIP/edct-analytics | lib/yuicompressor-2.4.6/src/org/mozilla/javascript/TokenStream.java | 49640 | /*L
* Copyright HealthCare IT, Inc.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/edct-analytics/LICENSE.txt for details.
*/
/* ***** BEGIN LICENSE BLOCK *****
*
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License
* at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* See the License for the specific language governing rights and
* limitations under the License.
*
* The Original Code is org/mozilla/javascript/TokenStream.java,
* a component of the Rhino Library ( http://www.mozilla.org/rhino/ )
* This file is a modification of the Original Code developed
* for YUI Compressor.
*
* The Initial Developer of the Original Code is Mozilla Foundation
*
* Copyright (c) 2009 Mozilla Foundation. All Rights Reserved.
*
* Contributor(s): Yahoo! Inc. 2009
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript;
import java.io.*;
/**
* This class implements the JavaScript scanner.
*
* It is based on the C source files jsscan.c and jsscan.h
* in the jsref package.
*
* @see org.mozilla.javascript.Parser
*
* @author Mike McCabe
* @author Brendan Eich
*/
class TokenStream
{
/*
* For chars - because we need something out-of-range
* to check. (And checking EOF by exception is annoying.)
* Note distinction from EOF token type!
*/
private final static int
EOF_CHAR = -1;
TokenStream(Parser parser, Reader sourceReader, String sourceString,
int lineno)
{
this.parser = parser;
this.lineno = lineno;
if (sourceReader != null) {
if (sourceString != null) Kit.codeBug();
this.sourceReader = sourceReader;
this.sourceBuffer = new char[512];
this.sourceEnd = 0;
} else {
if (sourceString == null) Kit.codeBug();
this.sourceString = sourceString;
this.sourceEnd = sourceString.length();
}
this.sourceCursor = 0;
}
/* This function uses the cached op, string and number fields in
* TokenStream; if getToken has been called since the passed token
* was scanned, the op or string printed may be incorrect.
*/
String tokenToString(int token)
{
if (Token.printTrees) {
String name = Token.name(token);
switch (token) {
case Token.STRING:
case Token.REGEXP:
case Token.NAME:
return name + " `" + this.string + "'";
case Token.NUMBER:
return "NUMBER " + this.number;
}
return name;
}
return "";
}
static boolean isKeyword(String s)
{
return Token.EOF != stringToKeyword(s);
}
private static int stringToKeyword(String name)
{
// #string_id_map#
// The following assumes that Token.EOF == 0
final int
Id_break = Token.BREAK,
Id_case = Token.CASE,
Id_continue = Token.CONTINUE,
Id_default = Token.DEFAULT,
Id_delete = Token.DELPROP,
Id_do = Token.DO,
Id_else = Token.ELSE,
Id_export = Token.EXPORT,
Id_false = Token.FALSE,
Id_for = Token.FOR,
Id_function = Token.FUNCTION,
Id_if = Token.IF,
Id_in = Token.IN,
Id_new = Token.NEW,
Id_null = Token.NULL,
Id_return = Token.RETURN,
Id_switch = Token.SWITCH,
Id_this = Token.THIS,
Id_true = Token.TRUE,
Id_typeof = Token.TYPEOF,
Id_var = Token.VAR,
Id_void = Token.VOID,
Id_while = Token.WHILE,
Id_with = Token.WITH,
// the following are #ifdef RESERVE_JAVA_KEYWORDS in jsscan.c
Id_abstract = Token.RESERVED,
Id_boolean = Token.RESERVED,
Id_byte = Token.RESERVED,
Id_catch = Token.CATCH,
Id_char = Token.RESERVED,
Id_class = Token.RESERVED,
Id_const = Token.CONST,
Id_debugger = Token.RESERVED,
Id_double = Token.RESERVED,
Id_enum = Token.RESERVED,
Id_extends = Token.RESERVED,
Id_final = Token.RESERVED,
Id_finally = Token.FINALLY,
Id_float = Token.RESERVED,
Id_goto = Token.RESERVED,
Id_implements = Token.RESERVED,
Id_import = Token.IMPORT,
Id_instanceof = Token.INSTANCEOF,
Id_int = Token.RESERVED,
Id_interface = Token.RESERVED,
Id_long = Token.RESERVED,
Id_native = Token.RESERVED,
Id_package = Token.RESERVED,
Id_private = Token.RESERVED,
Id_protected = Token.RESERVED,
Id_public = Token.RESERVED,
Id_short = Token.RESERVED,
Id_static = Token.RESERVED,
Id_super = Token.RESERVED,
Id_synchronized = Token.RESERVED,
Id_throw = Token.THROW,
Id_throws = Token.RESERVED,
Id_transient = Token.RESERVED,
Id_try = Token.TRY,
Id_volatile = Token.RESERVED;
int id;
String s = name;
// #generated# Last update: 2001-06-01 17:45:01 CEST
L0: { id = 0; String X = null; int c;
L: switch (s.length()) {
case 2: c=s.charAt(1);
if (c=='f') { if (s.charAt(0)=='i') {id=Id_if; break L0;} }
else if (c=='n') { if (s.charAt(0)=='i') {id=Id_in; break L0;} }
else if (c=='o') { if (s.charAt(0)=='d') {id=Id_do; break L0;} }
break L;
case 3: switch (s.charAt(0)) {
case 'f': if (s.charAt(2)=='r' && s.charAt(1)=='o') {id=Id_for; break L0;} break L;
case 'i': if (s.charAt(2)=='t' && s.charAt(1)=='n') {id=Id_int; break L0;} break L;
case 'n': if (s.charAt(2)=='w' && s.charAt(1)=='e') {id=Id_new; break L0;} break L;
case 't': if (s.charAt(2)=='y' && s.charAt(1)=='r') {id=Id_try; break L0;} break L;
case 'v': if (s.charAt(2)=='r' && s.charAt(1)=='a') {id=Id_var; break L0;} break L;
} break L;
case 4: switch (s.charAt(0)) {
case 'b': X="byte";id=Id_byte; break L;
case 'c': c=s.charAt(3);
if (c=='e') { if (s.charAt(2)=='s' && s.charAt(1)=='a') {id=Id_case; break L0;} }
else if (c=='r') { if (s.charAt(2)=='a' && s.charAt(1)=='h') {id=Id_char; break L0;} }
break L;
case 'e': c=s.charAt(3);
if (c=='e') { if (s.charAt(2)=='s' && s.charAt(1)=='l') {id=Id_else; break L0;} }
else if (c=='m') { if (s.charAt(2)=='u' && s.charAt(1)=='n') {id=Id_enum; break L0;} }
break L;
case 'g': X="goto";id=Id_goto; break L;
case 'l': X="long";id=Id_long; break L;
case 'n': X="null";id=Id_null; break L;
case 't': c=s.charAt(3);
if (c=='e') { if (s.charAt(2)=='u' && s.charAt(1)=='r') {id=Id_true; break L0;} }
else if (c=='s') { if (s.charAt(2)=='i' && s.charAt(1)=='h') {id=Id_this; break L0;} }
break L;
case 'v': X="void";id=Id_void; break L;
case 'w': X="with";id=Id_with; break L;
} break L;
case 5: switch (s.charAt(2)) {
case 'a': X="class";id=Id_class; break L;
case 'e': X="break";id=Id_break; break L;
case 'i': X="while";id=Id_while; break L;
case 'l': X="false";id=Id_false; break L;
case 'n': c=s.charAt(0);
if (c=='c') { X="const";id=Id_const; }
else if (c=='f') { X="final";id=Id_final; }
break L;
case 'o': c=s.charAt(0);
if (c=='f') { X="float";id=Id_float; }
else if (c=='s') { X="short";id=Id_short; }
break L;
case 'p': X="super";id=Id_super; break L;
case 'r': X="throw";id=Id_throw; break L;
case 't': X="catch";id=Id_catch; break L;
} break L;
case 6: switch (s.charAt(1)) {
case 'a': X="native";id=Id_native; break L;
case 'e': c=s.charAt(0);
if (c=='d') { X="delete";id=Id_delete; }
else if (c=='r') { X="return";id=Id_return; }
break L;
case 'h': X="throws";id=Id_throws; break L;
case 'm': X="import";id=Id_import; break L;
case 'o': X="double";id=Id_double; break L;
case 't': X="static";id=Id_static; break L;
case 'u': X="public";id=Id_public; break L;
case 'w': X="switch";id=Id_switch; break L;
case 'x': X="export";id=Id_export; break L;
case 'y': X="typeof";id=Id_typeof; break L;
} break L;
case 7: switch (s.charAt(1)) {
case 'a': X="package";id=Id_package; break L;
case 'e': X="default";id=Id_default; break L;
case 'i': X="finally";id=Id_finally; break L;
case 'o': X="boolean";id=Id_boolean; break L;
case 'r': X="private";id=Id_private; break L;
case 'x': X="extends";id=Id_extends; break L;
} break L;
case 8: switch (s.charAt(0)) {
case 'a': X="abstract";id=Id_abstract; break L;
case 'c': X="continue";id=Id_continue; break L;
case 'd': X="debugger";id=Id_debugger; break L;
case 'f': X="function";id=Id_function; break L;
case 'v': X="volatile";id=Id_volatile; break L;
} break L;
case 9: c=s.charAt(0);
if (c=='i') { X="interface";id=Id_interface; }
else if (c=='p') { X="protected";id=Id_protected; }
else if (c=='t') { X="transient";id=Id_transient; }
break L;
case 10: c=s.charAt(1);
if (c=='m') { X="implements";id=Id_implements; }
else if (c=='n') { X="instanceof";id=Id_instanceof; }
break L;
case 12: X="synchronized";id=Id_synchronized; break L;
}
if (X!=null && X!=s && !X.equals(s)) id = 0;
}
// #/generated#
// #/string_id_map#
if (id == 0) { return Token.EOF; }
return id & 0xff;
}
final int getLineno() { return lineno; }
final String getString() { return string; }
final double getNumber() { return number; }
final boolean eof() { return hitEOF; }
final int getToken() throws IOException
{
int c;
retry:
for (;;) {
// Eat whitespace, possibly sensitive to newlines.
for (;;) {
c = getChar();
if (c == EOF_CHAR) {
return Token.EOF;
} else if (c == '\n') {
dirtyLine = false;
return Token.EOL;
} else if (!isJSSpace(c)) {
if (c != '-') {
dirtyLine = true;
}
break;
}
}
if (c == '@') return Token.XMLATTR;
// identifier/keyword/instanceof?
// watch out for starting with a <backslash>
boolean identifierStart;
boolean isUnicodeEscapeStart = false;
if (c == '\\') {
c = getChar();
if (c == 'u') {
identifierStart = true;
isUnicodeEscapeStart = true;
stringBufferTop = 0;
} else {
identifierStart = false;
ungetChar(c);
c = '\\';
}
} else {
identifierStart = Character.isJavaIdentifierStart((char)c);
if (identifierStart) {
stringBufferTop = 0;
addToString(c);
}
}
if (identifierStart) {
boolean containsEscape = isUnicodeEscapeStart;
for (;;) {
if (isUnicodeEscapeStart) {
// strictly speaking we should probably push-back
// all the bad characters if the <backslash>uXXXX
// sequence is malformed. But since there isn't a
// correct context(is there?) for a bad Unicode
// escape sequence in an identifier, we can report
// an error here.
int escapeVal = 0;
for (int i = 0; i != 4; ++i) {
c = getChar();
escapeVal = Kit.xDigitToInt(c, escapeVal);
// Next check takes care about c < 0 and bad escape
if (escapeVal < 0) { break; }
}
if (escapeVal < 0) {
parser.addError("msg.invalid.escape");
return Token.ERROR;
}
addToString(escapeVal);
isUnicodeEscapeStart = false;
} else {
c = getChar();
if (c == '\\') {
c = getChar();
if (c == 'u') {
isUnicodeEscapeStart = true;
containsEscape = true;
} else {
parser.addError("msg.illegal.character");
return Token.ERROR;
}
} else {
if (c == EOF_CHAR
|| !Character.isJavaIdentifierPart((char)c))
{
break;
}
addToString(c);
}
}
}
ungetChar(c);
String str = getStringFromBuffer();
if (!containsEscape) {
// OPT we shouldn't have to make a string (object!) to
// check if it's a keyword.
// Return the corresponding token if it's a keyword
int result = stringToKeyword(str);
if (result != Token.EOF) {
if (result != Token.RESERVED) {
return result;
} else if (!parser.compilerEnv.
isReservedKeywordAsIdentifier())
{
return result;
} else {
// If implementation permits to use future reserved
// keywords in violation with the EcmaScript,
// treat it as name but issue warning
parser.addWarning("msg.reserved.keyword", str);
}
}
}
this.string = (String)allStrings.intern(str);
return Token.NAME;
}
// is it a number?
if (isDigit(c) || (c == '.' && isDigit(peekChar()))) {
stringBufferTop = 0;
int base = 10;
if (c == '0') {
c = getChar();
if (c == 'x' || c == 'X') {
base = 16;
c = getChar();
} else if (isDigit(c)) {
base = 8;
} else {
addToString('0');
}
}
if (base == 16) {
while (0 <= Kit.xDigitToInt(c, 0)) {
addToString(c);
c = getChar();
}
} else {
while ('0' <= c && c <= '9') {
/*
* We permit 08 and 09 as decimal numbers, which
* makes our behavior a superset of the ECMA
* numeric grammar. We might not always be so
* permissive, so we warn about it.
*/
if (base == 8 && c >= '8') {
parser.addWarning("msg.bad.octal.literal",
c == '8' ? "8" : "9");
base = 10;
}
addToString(c);
c = getChar();
}
}
boolean isInteger = true;
if (base == 10 && (c == '.' || c == 'e' || c == 'E')) {
isInteger = false;
if (c == '.') {
do {
addToString(c);
c = getChar();
} while (isDigit(c));
}
if (c == 'e' || c == 'E') {
addToString(c);
c = getChar();
if (c == '+' || c == '-') {
addToString(c);
c = getChar();
}
if (!isDigit(c)) {
parser.addError("msg.missing.exponent");
return Token.ERROR;
}
do {
addToString(c);
c = getChar();
} while (isDigit(c));
}
}
ungetChar(c);
String numString = getStringFromBuffer();
double dval;
if (base == 10 && !isInteger) {
try {
// Use Java conversion to number from string...
dval = Double.valueOf(numString).doubleValue();
}
catch (NumberFormatException ex) {
parser.addError("msg.caught.nfe");
return Token.ERROR;
}
} else {
dval = ScriptRuntime.stringToNumber(numString, 0, base);
}
this.number = dval;
return Token.NUMBER;
}
// is it a string?
if (c == '"' || c == '\'') {
// We attempt to accumulate a string the fast way, by
// building it directly out of the reader. But if there
// are any escaped characters in the string, we revert to
// building it out of a StringBuffer.
int quoteChar = c;
stringBufferTop = 0;
c = getChar();
while (c != quoteChar) {
if (c == '\n' || c == EOF_CHAR) {
ungetChar(c);
parser.addError("msg.unterminated.string.lit");
return Token.ERROR;
}
if (c == '\\') {
// We've hit an escaped character
c = getChar();
switch (c) {
case '\\': // backslash
case 'b': // backspace
case 'f': // form feed
case 'n': // line feed
case 'r': // carriage return
case 't': // horizontal tab
case 'v': // vertical tab
case 'd': // octal sequence
case 'u': // unicode sequence
case 'x': // hexadecimal sequence
// Only keep the '\' character for those
// characters that need to be escaped...
// Don't escape quoting characters...
addToString('\\');
addToString(c);
break;
case '\n':
// Remove line terminator after escape
break;
default:
if (isDigit(c)) {
// Octal representation of a character.
// Preserve the escaping (see Y! bug #1637286)
addToString('\\');
}
addToString(c);
break;
}
} else {
addToString(c);
}
c = getChar();
}
String str = getStringFromBuffer();
this.string = (String)allStrings.intern(str);
return Token.STRING;
}
switch (c) {
case ';': return Token.SEMI;
case '[': return Token.LB;
case ']': return Token.RB;
case '{': return Token.LC;
case '}': return Token.RC;
case '(': return Token.LP;
case ')': return Token.RP;
case ',': return Token.COMMA;
case '?': return Token.HOOK;
case ':':
if (matchChar(':')) {
return Token.COLONCOLON;
} else {
return Token.COLON;
}
case '.':
if (matchChar('.')) {
return Token.DOTDOT;
} else if (matchChar('(')) {
return Token.DOTQUERY;
} else {
return Token.DOT;
}
case '|':
if (matchChar('|')) {
return Token.OR;
} else if (matchChar('=')) {
return Token.ASSIGN_BITOR;
} else {
return Token.BITOR;
}
case '^':
if (matchChar('=')) {
return Token.ASSIGN_BITXOR;
} else {
return Token.BITXOR;
}
case '&':
if (matchChar('&')) {
return Token.AND;
} else if (matchChar('=')) {
return Token.ASSIGN_BITAND;
} else {
return Token.BITAND;
}
case '=':
if (matchChar('=')) {
if (matchChar('='))
return Token.SHEQ;
else
return Token.EQ;
} else {
return Token.ASSIGN;
}
case '!':
if (matchChar('=')) {
if (matchChar('='))
return Token.SHNE;
else
return Token.NE;
} else {
return Token.NOT;
}
case '<':
/* NB:treat HTML begin-comment as comment-till-eol */
if (matchChar('!')) {
if (matchChar('-')) {
if (matchChar('-')) {
skipLine();
continue retry;
}
ungetChar('-');
}
ungetChar('!');
}
if (matchChar('<')) {
if (matchChar('=')) {
return Token.ASSIGN_LSH;
} else {
return Token.LSH;
}
} else {
if (matchChar('=')) {
return Token.LE;
} else {
return Token.LT;
}
}
case '>':
if (matchChar('>')) {
if (matchChar('>')) {
if (matchChar('=')) {
return Token.ASSIGN_URSH;
} else {
return Token.URSH;
}
} else {
if (matchChar('=')) {
return Token.ASSIGN_RSH;
} else {
return Token.RSH;
}
}
} else {
if (matchChar('=')) {
return Token.GE;
} else {
return Token.GT;
}
}
case '*':
if (matchChar('=')) {
return Token.ASSIGN_MUL;
} else {
return Token.MUL;
}
case '/':
// is it a // comment?
if (matchChar('/')) {
skipLine();
continue retry;
}
if (matchChar('*')) {
boolean lookForSlash = false;
StringBuffer sb = new StringBuffer();
for (;;) {
c = getChar();
if (c == EOF_CHAR) {
parser.addError("msg.unterminated.comment");
return Token.ERROR;
}
sb.append((char) c);
if (c == '*') {
lookForSlash = true;
} else if (c == '/') {
if (lookForSlash) {
sb.delete(sb.length()-2, sb.length());
String s1 = sb.toString();
String s2 = s1.trim();
if (s1.startsWith("!")) {
// Remove the leading '!' ** EDIT actually don't remove it:
// http://yuilibrary.com/projects/yuicompressor/ticket/2528008
// this.string = s1.substring(1);
this.string = s1;
return Token.KEEPCOMMENT;
} else if (s2.startsWith("@cc_on") ||
s2.startsWith("@if") ||
s2.startsWith("@elif") ||
s2.startsWith("@else") ||
s2.startsWith("@end")) {
this.string = s1;
return Token.CONDCOMMENT;
} else {
continue retry;
}
}
} else {
lookForSlash = false;
}
}
}
if (matchChar('=')) {
return Token.ASSIGN_DIV;
} else {
return Token.DIV;
}
case '%':
if (matchChar('=')) {
return Token.ASSIGN_MOD;
} else {
return Token.MOD;
}
case '~':
return Token.BITNOT;
case '+':
if (matchChar('=')) {
return Token.ASSIGN_ADD;
} else if (matchChar('+')) {
return Token.INC;
} else {
return Token.ADD;
}
case '-':
if (matchChar('=')) {
c = Token.ASSIGN_SUB;
} else if (matchChar('-')) {
if (!dirtyLine) {
// treat HTML end-comment after possible whitespace
// after line start as comment-utill-eol
if (matchChar('>')) {
skipLine();
continue retry;
}
}
c = Token.DEC;
} else {
c = Token.SUB;
}
dirtyLine = true;
return c;
default:
parser.addError("msg.illegal.character");
return Token.ERROR;
}
}
}
private static boolean isAlpha(int c)
{
// Use 'Z' < 'a'
if (c <= 'Z') {
return 'A' <= c;
} else {
return 'a' <= c && c <= 'z';
}
}
static boolean isDigit(int c)
{
return '0' <= c && c <= '9';
}
/* As defined in ECMA. jsscan.c uses C isspace() (which allows
* \v, I think.) note that code in getChar() implicitly accepts
* '\r' == \u000D as well.
*/
static boolean isJSSpace(int c)
{
if (c <= 127) {
return c == 0x20 || c == 0x9 || c == 0xC || c == 0xB;
} else {
return c == 0xA0
|| Character.getType((char)c) == Character.SPACE_SEPARATOR;
}
}
private static boolean isJSFormatChar(int c)
{
return c > 127 && Character.getType((char)c) == Character.FORMAT;
}
/**
* Parser calls the method when it gets / or /= in literal context.
*/
void readRegExp(int startToken)
throws IOException
{
stringBufferTop = 0;
if (startToken == Token.ASSIGN_DIV) {
// Miss-scanned /=
addToString('=');
} else {
if (startToken != Token.DIV) Kit.codeBug();
}
int c;
boolean inClass = false;
while ((c = getChar()) != '/' || inClass) {
if (c == '\n' || c == EOF_CHAR) {
ungetChar(c);
throw parser.reportError("msg.unterminated.re.lit");
}
if (c == '\\') {
addToString(c);
c = getChar();
} else if (c == '[') {
inClass = true;
} else if (c == ']') {
inClass = false;
}
addToString(c);
}
int reEnd = stringBufferTop;
while (true) {
if (matchChar('g'))
addToString('g');
else if (matchChar('i'))
addToString('i');
else if (matchChar('m'))
addToString('m');
else
break;
}
if (isAlpha(peekChar())) {
throw parser.reportError("msg.invalid.re.flag");
}
this.string = new String(stringBuffer, 0, reEnd);
this.regExpFlags = new String(stringBuffer, reEnd,
stringBufferTop - reEnd);
}
boolean isXMLAttribute()
{
return xmlIsAttribute;
}
int getFirstXMLToken() throws IOException
{
xmlOpenTagsCount = 0;
xmlIsAttribute = false;
xmlIsTagContent = false;
ungetChar('<');
return getNextXMLToken();
}
int getNextXMLToken() throws IOException
{
stringBufferTop = 0; // remember the XML
for (int c = getChar(); c != EOF_CHAR; c = getChar()) {
if (xmlIsTagContent) {
switch (c) {
case '>':
addToString(c);
xmlIsTagContent = false;
xmlIsAttribute = false;
break;
case '/':
addToString(c);
if (peekChar() == '>') {
c = getChar();
addToString(c);
xmlIsTagContent = false;
xmlOpenTagsCount--;
}
break;
case '{':
ungetChar(c);
this.string = getStringFromBuffer();
return Token.XML;
case '\'':
case '"':
addToString(c);
if (!readQuotedString(c)) return Token.ERROR;
break;
case '=':
addToString(c);
xmlIsAttribute = true;
break;
case ' ':
case '\t':
case '\r':
case '\n':
addToString(c);
break;
default:
addToString(c);
xmlIsAttribute = false;
break;
}
if (!xmlIsTagContent && xmlOpenTagsCount == 0) {
this.string = getStringFromBuffer();
return Token.XMLEND;
}
} else {
switch (c) {
case '<':
addToString(c);
c = peekChar();
switch (c) {
case '!':
c = getChar(); // Skip !
addToString(c);
c = peekChar();
switch (c) {
case '-':
c = getChar(); // Skip -
addToString(c);
c = getChar();
if (c == '-') {
addToString(c);
if(!readXmlComment()) return Token.ERROR;
} else {
// throw away the string in progress
stringBufferTop = 0;
this.string = null;
parser.addError("msg.XML.bad.form");
return Token.ERROR;
}
break;
case '[':
c = getChar(); // Skip [
addToString(c);
if (getChar() == 'C' &&
getChar() == 'D' &&
getChar() == 'A' &&
getChar() == 'T' &&
getChar() == 'A' &&
getChar() == '[')
{
addToString('C');
addToString('D');
addToString('A');
addToString('T');
addToString('A');
addToString('[');
if (!readCDATA()) return Token.ERROR;
} else {
// throw away the string in progress
stringBufferTop = 0;
this.string = null;
parser.addError("msg.XML.bad.form");
return Token.ERROR;
}
break;
default:
if(!readEntity()) return Token.ERROR;
break;
}
break;
case '?':
c = getChar(); // Skip ?
addToString(c);
if (!readPI()) return Token.ERROR;
break;
case '/':
// End tag
c = getChar(); // Skip /
addToString(c);
if (xmlOpenTagsCount == 0) {
// throw away the string in progress
stringBufferTop = 0;
this.string = null;
parser.addError("msg.XML.bad.form");
return Token.ERROR;
}
xmlIsTagContent = true;
xmlOpenTagsCount--;
break;
default:
// Start tag
xmlIsTagContent = true;
xmlOpenTagsCount++;
break;
}
break;
case '{':
ungetChar(c);
this.string = getStringFromBuffer();
return Token.XML;
default:
addToString(c);
break;
}
}
}
stringBufferTop = 0; // throw away the string in progress
this.string = null;
parser.addError("msg.XML.bad.form");
return Token.ERROR;
}
/**
*
*/
private boolean readQuotedString(int quote) throws IOException
{
for (int c = getChar(); c != EOF_CHAR; c = getChar()) {
addToString(c);
if (c == quote) return true;
}
stringBufferTop = 0; // throw away the string in progress
this.string = null;
parser.addError("msg.XML.bad.form");
return false;
}
/**
*
*/
private boolean readXmlComment() throws IOException
{
for (int c = getChar(); c != EOF_CHAR;) {
addToString(c);
if (c == '-' && peekChar() == '-') {
c = getChar();
addToString(c);
if (peekChar() == '>') {
c = getChar(); // Skip >
addToString(c);
return true;
} else {
continue;
}
}
c = getChar();
}
stringBufferTop = 0; // throw away the string in progress
this.string = null;
parser.addError("msg.XML.bad.form");
return false;
}
/**
*
*/
private boolean readCDATA() throws IOException
{
for (int c = getChar(); c != EOF_CHAR;) {
addToString(c);
if (c == ']' && peekChar() == ']') {
c = getChar();
addToString(c);
if (peekChar() == '>') {
c = getChar(); // Skip >
addToString(c);
return true;
} else {
continue;
}
}
c = getChar();
}
stringBufferTop = 0; // throw away the string in progress
this.string = null;
parser.addError("msg.XML.bad.form");
return false;
}
/**
*
*/
private boolean readEntity() throws IOException
{
int declTags = 1;
for (int c = getChar(); c != EOF_CHAR; c = getChar()) {
addToString(c);
switch (c) {
case '<':
declTags++;
break;
case '>':
declTags--;
if (declTags == 0) return true;
break;
}
}
stringBufferTop = 0; // throw away the string in progress
this.string = null;
parser.addError("msg.XML.bad.form");
return false;
}
/**
*
*/
private boolean readPI() throws IOException
{
for (int c = getChar(); c != EOF_CHAR; c = getChar()) {
addToString(c);
if (c == '?' && peekChar() == '>') {
c = getChar(); // Skip >
addToString(c);
return true;
}
}
stringBufferTop = 0; // throw away the string in progress
this.string = null;
parser.addError("msg.XML.bad.form");
return false;
}
private String getStringFromBuffer()
{
return new String(stringBuffer, 0, stringBufferTop);
}
private void addToString(int c)
{
int N = stringBufferTop;
if (N == stringBuffer.length) {
char[] tmp = new char[stringBuffer.length * 2];
System.arraycopy(stringBuffer, 0, tmp, 0, N);
stringBuffer = tmp;
}
stringBuffer[N] = (char)c;
stringBufferTop = N + 1;
}
private void ungetChar(int c)
{
// can not unread past across line boundary
if (ungetCursor != 0 && ungetBuffer[ungetCursor - 1] == '\n')
Kit.codeBug();
ungetBuffer[ungetCursor++] = c;
}
private boolean matchChar(int test) throws IOException
{
int c = getChar();
if (c == test) {
return true;
} else {
ungetChar(c);
return false;
}
}
private int peekChar() throws IOException
{
int c = getChar();
ungetChar(c);
return c;
}
private int getChar() throws IOException
{
if (ungetCursor != 0) {
return ungetBuffer[--ungetCursor];
}
for(;;) {
int c;
if (sourceString != null) {
if (sourceCursor == sourceEnd) {
hitEOF = true;
return EOF_CHAR;
}
c = sourceString.charAt(sourceCursor++);
} else {
if (sourceCursor == sourceEnd) {
if (!fillSourceBuffer()) {
hitEOF = true;
return EOF_CHAR;
}
}
c = sourceBuffer[sourceCursor++];
}
if (lineEndChar >= 0) {
if (lineEndChar == '\r' && c == '\n') {
lineEndChar = '\n';
continue;
}
lineEndChar = -1;
lineStart = sourceCursor - 1;
lineno++;
}
if (c <= 127) {
if (c == '\n' || c == '\r') {
lineEndChar = c;
c = '\n';
}
} else {
if (isJSFormatChar(c)) {
continue;
}
if (ScriptRuntime.isJSLineTerminator(c)) {
lineEndChar = c;
c = '\n';
}
}
return c;
}
}
private void skipLine() throws IOException
{
// skip to end of line
int c;
while ((c = getChar()) != EOF_CHAR && c != '\n') { }
ungetChar(c);
}
final int getOffset()
{
int n = sourceCursor - lineStart;
if (lineEndChar >= 0) { --n; }
return n;
}
final String getLine()
{
if (sourceString != null) {
// String case
int lineEnd = sourceCursor;
if (lineEndChar >= 0) {
--lineEnd;
} else {
for (; lineEnd != sourceEnd; ++lineEnd) {
int c = sourceString.charAt(lineEnd);
if (ScriptRuntime.isJSLineTerminator(c)) {
break;
}
}
}
return sourceString.substring(lineStart, lineEnd);
} else {
// Reader case
int lineLength = sourceCursor - lineStart;
if (lineEndChar >= 0) {
--lineLength;
} else {
// Read until the end of line
for (;; ++lineLength) {
int i = lineStart + lineLength;
if (i == sourceEnd) {
try {
if (!fillSourceBuffer()) { break; }
} catch (IOException ioe) {
// ignore it, we're already displaying an error...
break;
}
// i recalculuation as fillSourceBuffer can move saved
// line buffer and change lineStart
i = lineStart + lineLength;
}
int c = sourceBuffer[i];
if (ScriptRuntime.isJSLineTerminator(c)) {
break;
}
}
}
return new String(sourceBuffer, lineStart, lineLength);
}
}
private boolean fillSourceBuffer() throws IOException
{
if (sourceString != null) Kit.codeBug();
if (sourceEnd == sourceBuffer.length) {
if (lineStart != 0) {
System.arraycopy(sourceBuffer, lineStart, sourceBuffer, 0,
sourceEnd - lineStart);
sourceEnd -= lineStart;
sourceCursor -= lineStart;
lineStart = 0;
} else {
char[] tmp = new char[sourceBuffer.length * 2];
System.arraycopy(sourceBuffer, 0, tmp, 0, sourceEnd);
sourceBuffer = tmp;
}
}
int n = sourceReader.read(sourceBuffer, sourceEnd,
sourceBuffer.length - sourceEnd);
if (n < 0) {
return false;
}
sourceEnd += n;
return true;
}
// stuff other than whitespace since start of line
private boolean dirtyLine;
String regExpFlags;
// Set this to an inital non-null value so that the Parser has
// something to retrieve even if an error has occured and no
// string is found. Fosters one class of error, but saves lots of
// code.
private String string = "";
private double number;
private char[] stringBuffer = new char[128];
private int stringBufferTop;
private ObjToIntMap allStrings = new ObjToIntMap(50);
// Room to backtrace from to < on failed match of the last - in <!--
private final int[] ungetBuffer = new int[3];
private int ungetCursor;
private boolean hitEOF = false;
private int lineStart = 0;
private int lineno;
private int lineEndChar = -1;
private String sourceString;
private Reader sourceReader;
private char[] sourceBuffer;
private int sourceEnd;
private int sourceCursor;
// for xml tokenizer
private boolean xmlIsAttribute;
private boolean xmlIsTagContent;
private int xmlOpenTagsCount;
private Parser parser;
}
| bsd-3-clause |
PolymerLabs/arcs-live | concrete-storage/node_modules/pouchdb-binary-utils/lib/index.es.js | 3075 | import bufferFrom from 'buffer-from';
function thisAtob(str) {
var base64 = new Buffer(str, 'base64');
// Node.js will just skip the characters it can't decode instead of
// throwing an exception
if (base64.toString('base64') !== str) {
throw new Error("attachment is not a valid base64 string");
}
return base64.toString('binary');
}
function thisBtoa(str) {
return bufferFrom(str, 'binary').toString('base64');
}
function typedBuffer(binString, buffType, type) {
// buffType is either 'binary' or 'base64'
var buff = bufferFrom(binString, buffType);
buff.type = type; // non-standard, but used for consistency with the browser
return buff;
}
function b64ToBluffer(b64, type) {
return typedBuffer(b64, 'base64', type);
}
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
function binaryStringToArrayBuffer(bin) {
var length = bin.length;
var buf = new ArrayBuffer(length);
var arr = new Uint8Array(buf);
for (var i = 0; i < length; i++) {
arr[i] = bin.charCodeAt(i);
}
return buf;
}
function binStringToBluffer(binString, type) {
return typedBuffer(binString, 'binary', type);
}
// This function is unused in Node
/* istanbul ignore next */
function createBlob() {
}
function blobToBase64(blobOrBuffer, callback) {
callback(blobOrBuffer.toString('base64'));
}
// not used in Node, but here for completeness
function blobToBase64$1(blobOrBuffer, callback) {
callback(blobOrBuffer.toString('binary'));
}
// simplified API. universal browser support is assumed
function readAsArrayBuffer(blob, callback) {
var reader = new FileReader();
reader.onloadend = function (e) {
var result = e.target.result || new ArrayBuffer(0);
callback(result);
};
reader.readAsArrayBuffer(blob);
}
//Can't find original post, but this is close
//http://stackoverflow.com/questions/6965107/ (continues on next line)
//converting-between-strings-and-arraybuffers
function arrayBufferToBinaryString(buffer) {
var binary = '';
var bytes = new Uint8Array(buffer);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}
return binary;
}
// shim for browsers that don't support it
function readAsBinaryString(blob, callback) {
var reader = new FileReader();
var hasBinaryString = typeof reader.readAsBinaryString === 'function';
reader.onloadend = function (e) {
var result = e.target.result || '';
if (hasBinaryString) {
return callback(result);
}
callback(arrayBufferToBinaryString(result));
};
if (hasBinaryString) {
reader.readAsBinaryString(blob);
} else {
reader.readAsArrayBuffer(blob);
}
}
export { thisAtob as atob, thisBtoa as btoa, b64ToBluffer as base64StringToBlobOrBuffer, binaryStringToArrayBuffer, binStringToBluffer as binaryStringToBlobOrBuffer, createBlob as blob, blobToBase64 as blobOrBufferToBase64, blobToBase64$1 as blobOrBufferToBinaryString, readAsArrayBuffer, readAsBinaryString, typedBuffer };
| bsd-3-clause |
01vadim10/slot_automat | socketserver/lib/module/game.php | 3911 | <?php
class ModuleGame extends Errors{
/**
* @var gameServerClient
*/
private $_client;
/**
* @var SlotSlot
*/
private $_game = null;
private $_lines_count;
private $_bet;
private $_denomination;
// private $_dual_rate = false;
private $_won = null;
private $_bonus_won = null;
public function __construct(gameServerClient $client)
{
$this->_client = $client;
}
/**
* Start new game
*
* @param array $params = array('id'=>(int))
* @return bool
*
*/
public function start($params)
{
//game already started?
if($this->_game && $this->_game->getId() == $params['id'])
return true;
switch ($params['id'])
{
case 1:
$this->_game = new GameBook_Of_Ra();
break;
default:
$this->_game = null;
break;
}
$balance = 0;
if ($this->_client->get_user()->getAPI() !== null)
$balance = $this->_client->get_user()->getAPI()->get_balance();
$res = array('started'=>$this->_checkGame(), 'balance'=>$balance);
return $res;
}
/**
* Spin slot
*
* @param array $params = array('bet'=>int, 'denomination'=>float, 'lines'=>int)
* @return array | FALSE
*/
public function spin($params)
{
if(!$this->_checkGame()) return false;
if ($this->_game->getBonusCount() <= 0)
{
$this->_game->setBonusGame(false);
}
if (!$this->_game->getIsBonus())
{
$this->_lines_count = intval($params['lines']);
$this->_bet = $params['bet'];
$this->_denomination = $params['denomination'];
}
$lines_count = $this->_lines_count;
$bet = $this->_bet;
$denomination = $this->_denomination;
if($this->_game->checkBet($bet, $denomination, $lines_count))
{
$bet = new ItemBet($this->_client->get_user()->getAPI(), $this->_game, $denomination, $bet, $lines_count);
if($bet->save())
{
$this->_game->spin($lines_count);
if(!$bet->won($this->_game->getWins()))
$this->pushError($bet);
if ($this->_game->getIsBonus())
if(!$bet->won($this->_game->getBonusWins(), true))
$this->pushError($bet);
}
}
$this->pushError($bet);
if(!$this->hasErrors())
{
$res = $this->_game->getScreenArray();
if ($this->_game->getIsBonus())
{
$res['bonus_won'] = $bet->getBonusWinningAmount();
$this->_bonus_won = $res['bonus_won'];
}
$res['won'] = $bet->getWinningAmount();
$this->_won = $res['won'];
$res['balance'] = $this->_client->get_user()->getAPI()->get_balance();
return $res;
}
return false;
}
/**
* Returns list of lines
*
* @param array $params
* @return array | FALSE
*/
public function getLines($params)
{
if(!$this->_checkGame()) return false;
return $this->_game->getLinesArray();
}
/**
* @return bool
*/
private function _checkGame()
{
if($this->_game == null)
{
$this->pushError('game_not_found');
return false;
}
return true;
}
public function getDenominations()
{
if(!$this->_checkGame()) return false;
$res = array();
$res['list'] = $this->_game->getParams()->getDenominations();
$res['max_bet'] = $this->_game->getParams()->getMaxBet();
return $res;
}
/* public function setDualRate($dual_rate = true)
{
$this->_dual_rate = $dual_rate;
}
*/
// Бонус-игра с удвоением выигрыша
// $expectation - количество успешных выигрышей (в процентах)
// $dual_rate_expectation - вероятность выигрыша(ставиться модератором)
public function DualRateSpin($params)
{
$won = $this->_won+$this->_bonus_won;
echo 'Won_amount:';
var_dump($won);
if ($won > 0)
{
$res = array();
$foo = rand(0, 1);
if ($foo == $params['rate'])
{
if ($params['expectation'] <= $params['dual_rate_expectation'])
{
$res['dual_rate'] = $won*2;
return $res['dual_rate'];
}
else $this->DualRateSpin($params);
}
}
return false;
}
} | bsd-3-clause |
nickschot/jmonkeyengine | jme3-core/src/main/java/com/jme3/renderer/RenderManager.java | 41489 | /*
* Copyright (c) 2009-2012 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.renderer;
import com.jme3.light.DefaultLightFilter;
import com.jme3.light.LightFilter;
import com.jme3.light.LightList;
import com.jme3.material.*;
import com.jme3.math.Matrix4f;
import com.jme3.post.SceneProcessor;
import com.jme3.profile.AppProfiler;
import com.jme3.profile.AppStep;
import com.jme3.profile.VpStep;
import com.jme3.renderer.queue.GeometryList;
import com.jme3.renderer.queue.RenderQueue;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.renderer.queue.RenderQueue.ShadowMode;
import com.jme3.scene.*;
import com.jme3.shader.Uniform;
import com.jme3.shader.UniformBinding;
import com.jme3.shader.UniformBindingManager;
import com.jme3.system.NullRenderer;
import com.jme3.system.Timer;
import com.jme3.util.SafeArrayList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
/**
* <code>RenderManager</code> is a high-level rendering interface that is
* above the Renderer implementation. RenderManager takes care
* of rendering the scene graphs attached to each viewport and
* handling SceneProcessors.
*
* @see SceneProcessor
* @see ViewPort
* @see Spatial
*/
public class RenderManager {
private static final Logger logger = Logger.getLogger(RenderManager.class.getName());
private Renderer renderer;
private UniformBindingManager uniformBindingManager = new UniformBindingManager();
private ArrayList<ViewPort> preViewPorts = new ArrayList<ViewPort>();
private ArrayList<ViewPort> viewPorts = new ArrayList<ViewPort>();
private ArrayList<ViewPort> postViewPorts = new ArrayList<ViewPort>();
private Camera prevCam = null;
private Material forcedMaterial = null;
private String forcedTechnique = null;
private RenderState forcedRenderState = null;
private int viewX, viewY, viewWidth, viewHeight;
private Matrix4f orthoMatrix = new Matrix4f();
private LightList filteredLightList = new LightList(null);
private String tmpTech;
private boolean handleTranlucentBucket = true;
private AppProfiler prof;
private LightFilter lightFilter = new DefaultLightFilter();
private TechniqueDef.LightMode preferredLightMode = TechniqueDef.LightMode.MultiPass;
private int singlePassLightBatchSize = 1;
/**
* Create a high-level rendering interface over the
* low-level rendering interface.
* @param renderer
*/
public RenderManager(Renderer renderer) {
this.renderer = renderer;
}
/**
* Returns the pre ViewPort with the given name.
*
* @param viewName The name of the pre ViewPort to look up
* @return The ViewPort, or null if not found.
*
* @see #createPreView(java.lang.String, com.jme3.renderer.Camera)
*/
public ViewPort getPreView(String viewName) {
for (int i = 0; i < preViewPorts.size(); i++) {
if (preViewPorts.get(i).getName().equals(viewName)) {
return preViewPorts.get(i);
}
}
return null;
}
/**
* Removes the pre ViewPort with the specified name.
*
* @param viewName The name of the pre ViewPort to remove
* @return True if the ViewPort was removed successfully.
*
* @see #createPreView(java.lang.String, com.jme3.renderer.Camera)
*/
public boolean removePreView(String viewName) {
for (int i = 0; i < preViewPorts.size(); i++) {
if (preViewPorts.get(i).getName().equals(viewName)) {
preViewPorts.remove(i);
return true;
}
}
return false;
}
/**
* Removes the specified pre ViewPort.
*
* @param view The pre ViewPort to remove
* @return True if the ViewPort was removed successfully.
*
* @see #createPreView(java.lang.String, com.jme3.renderer.Camera)
*/
public boolean removePreView(ViewPort view) {
return preViewPorts.remove(view);
}
/**
* Returns the main ViewPort with the given name.
*
* @param viewName The name of the main ViewPort to look up
* @return The ViewPort, or null if not found.
*
* @see #createMainView(java.lang.String, com.jme3.renderer.Camera)
*/
public ViewPort getMainView(String viewName) {
for (int i = 0; i < viewPorts.size(); i++) {
if (viewPorts.get(i).getName().equals(viewName)) {
return viewPorts.get(i);
}
}
return null;
}
/**
* Removes the main ViewPort with the specified name.
*
* @param viewName The main ViewPort name to remove
* @return True if the ViewPort was removed successfully.
*
* @see #createMainView(java.lang.String, com.jme3.renderer.Camera)
*/
public boolean removeMainView(String viewName) {
for (int i = 0; i < viewPorts.size(); i++) {
if (viewPorts.get(i).getName().equals(viewName)) {
viewPorts.remove(i);
return true;
}
}
return false;
}
/**
* Removes the specified main ViewPort.
*
* @param view The main ViewPort to remove
* @return True if the ViewPort was removed successfully.
*
* @see #createMainView(java.lang.String, com.jme3.renderer.Camera)
*/
public boolean removeMainView(ViewPort view) {
return viewPorts.remove(view);
}
/**
* Returns the post ViewPort with the given name.
*
* @param viewName The name of the post ViewPort to look up
* @return The ViewPort, or null if not found.
*
* @see #createPostView(java.lang.String, com.jme3.renderer.Camera)
*/
public ViewPort getPostView(String viewName) {
for (int i = 0; i < postViewPorts.size(); i++) {
if (postViewPorts.get(i).getName().equals(viewName)) {
return postViewPorts.get(i);
}
}
return null;
}
/**
* Removes the post ViewPort with the specified name.
*
* @param viewName The post ViewPort name to remove
* @return True if the ViewPort was removed successfully.
*
* @see #createPostView(java.lang.String, com.jme3.renderer.Camera)
*/
public boolean removePostView(String viewName) {
for (int i = 0; i < postViewPorts.size(); i++) {
if (postViewPorts.get(i).getName().equals(viewName)) {
postViewPorts.remove(i);
return true;
}
}
return false;
}
/**
* Removes the specified post ViewPort.
*
* @param view The post ViewPort to remove
* @return True if the ViewPort was removed successfully.
*
* @see #createPostView(java.lang.String, com.jme3.renderer.Camera)
*/
public boolean removePostView(ViewPort view) {
return postViewPorts.remove(view);
}
/**
* Returns a read-only list of all pre ViewPorts
* @return a read-only list of all pre ViewPorts
* @see #createPreView(java.lang.String, com.jme3.renderer.Camera)
*/
public List<ViewPort> getPreViews() {
return Collections.unmodifiableList(preViewPorts);
}
/**
* Returns a read-only list of all main ViewPorts
* @return a read-only list of all main ViewPorts
* @see #createMainView(java.lang.String, com.jme3.renderer.Camera)
*/
public List<ViewPort> getMainViews() {
return Collections.unmodifiableList(viewPorts);
}
/**
* Returns a read-only list of all post ViewPorts
* @return a read-only list of all post ViewPorts
* @see #createPostView(java.lang.String, com.jme3.renderer.Camera)
*/
public List<ViewPort> getPostViews() {
return Collections.unmodifiableList(postViewPorts);
}
/**
* Creates a new pre ViewPort, to display the given camera's content.
* <p>
* The view will be processed before the main and post viewports.
*/
public ViewPort createPreView(String viewName, Camera cam) {
ViewPort vp = new ViewPort(viewName, cam);
preViewPorts.add(vp);
return vp;
}
/**
* Creates a new main ViewPort, to display the given camera's content.
* <p>
* The view will be processed before the post viewports but after
* the pre viewports.
*/
public ViewPort createMainView(String viewName, Camera cam) {
ViewPort vp = new ViewPort(viewName, cam);
viewPorts.add(vp);
return vp;
}
/**
* Creates a new post ViewPort, to display the given camera's content.
* <p>
* The view will be processed after the pre and main viewports.
*/
public ViewPort createPostView(String viewName, Camera cam) {
ViewPort vp = new ViewPort(viewName, cam);
postViewPorts.add(vp);
return vp;
}
private void notifyReshape(ViewPort vp, int w, int h) {
List<SceneProcessor> processors = vp.getProcessors();
for (SceneProcessor proc : processors) {
if (!proc.isInitialized()) {
proc.initialize(this, vp);
} else {
proc.reshape(vp, w, h);
}
}
}
/**
* Internal use only.
* Updates the resolution of all on-screen cameras to match
* the given width and height.
*/
public void notifyReshape(int w, int h) {
for (ViewPort vp : preViewPorts) {
if (vp.getOutputFrameBuffer() == null) {
Camera cam = vp.getCamera();
cam.resize(w, h, true);
}
notifyReshape(vp, w, h);
}
for (ViewPort vp : viewPorts) {
if (vp.getOutputFrameBuffer() == null) {
Camera cam = vp.getCamera();
cam.resize(w, h, true);
}
notifyReshape(vp, w, h);
}
for (ViewPort vp : postViewPorts) {
if (vp.getOutputFrameBuffer() == null) {
Camera cam = vp.getCamera();
cam.resize(w, h, true);
}
notifyReshape(vp, w, h);
}
}
/**
* Set the material to use to render all future objects.
* This overrides the material set on the geometry and renders
* with the provided material instead.
* Use null to clear the material and return renderer to normal
* functionality.
* @param mat The forced material to set, or null to return to normal
*/
public void setForcedMaterial(Material mat) {
forcedMaterial = mat;
}
/**
* Returns the material that is forced for the next render pass
* @return the forced material
*/
public Material getForcedMaterial() {
return this.forcedMaterial;
}
public LightList getFilteredLightList() {
return this.filteredLightList;
}
/**
* Returns the Light Filter used on the lights that will be rendered.
* @return the lightlist
*/
public LightFilter getLightFilter() {
return this.lightFilter;
}
/**
* Returns the forced render state previously set with
* {@link #setForcedRenderState(com.jme3.material.RenderState) }.
* @return the forced render state
*/
public RenderState getForcedRenderState() {
return forcedRenderState;
}
/**
* Set the render state to use for all future objects.
* This overrides the render state set on the material and instead
* forces this render state to be applied for all future materials
* rendered. Set to null to return to normal functionality.
*
* @param forcedRenderState The forced render state to set, or null
* to return to normal
*/
public void setForcedRenderState(RenderState forcedRenderState) {
this.forcedRenderState = forcedRenderState;
}
/**
* Set the timer that should be used to query the time based
* {@link UniformBinding}s for material world parameters.
*
* @param timer The timer to query time world parameters
*/
public void setTimer(Timer timer) {
uniformBindingManager.setTimer(timer);
}
/**
* Sets an AppProfiler hook that will be called back for
* specific steps within a single update frame. Value defaults
* to null.
*/
public void setAppProfiler(AppProfiler prof) {
this.prof = prof;
}
/**
* Returns the forced technique name set.
*
* @return the forced technique name set.
*
* @see #setForcedTechnique(java.lang.String)
*/
public String getForcedTechnique() {
return forcedTechnique;
}
/**
* Sets the forced technique to use when rendering geometries.
* <p>
* If the specified technique name is available on the geometry's
* material, then it is used, otherwise, the
* {@link #setForcedMaterial(com.jme3.material.Material) forced material} is used.
* If a forced material is not set and the forced technique name cannot
* be found on the material, the geometry will <em>not</em> be rendered.
*
* @param forcedTechnique The forced technique name to use, set to null
* to return to normal functionality.
*
* @see #renderGeometry(com.jme3.scene.Geometry)
*/
public void setForcedTechnique(String forcedTechnique) {
this.forcedTechnique = forcedTechnique;
}
/**
* Enable or disable alpha-to-coverage.
* <p>
* When alpha to coverage is enabled and the renderer implementation
* supports it, then alpha blending will be replaced with alpha dissolve
* if multi-sampling is also set on the renderer.
* This feature allows avoiding of alpha blending artifacts due to
* lack of triangle-level back-to-front sorting.
*
* @param value True to enable alpha-to-coverage, false otherwise.
*/
public void setAlphaToCoverage(boolean value) {
renderer.setAlphaToCoverage(value);
}
/**
* True if the translucent bucket should automatically be rendered
* by the RenderManager.
*
* @return Whether or not the translucent bucket is rendered.
*
* @see #setHandleTranslucentBucket(boolean)
*/
public boolean isHandleTranslucentBucket() {
return handleTranlucentBucket;
}
/**
* Enable or disable rendering of the
* {@link Bucket#Translucent translucent bucket}
* by the RenderManager. The default is enabled.
*
* @param handleTranslucentBucket Whether or not the translucent bucket should
* be rendered.
*/
public void setHandleTranslucentBucket(boolean handleTranslucentBucket) {
this.handleTranlucentBucket = handleTranslucentBucket;
}
/**
* Internal use only. Sets the world matrix to use for future
* rendering. This has no effect unless objects are rendered manually
* using {@link Material#render(com.jme3.scene.Geometry, com.jme3.renderer.RenderManager) }.
* Using {@link #renderGeometry(com.jme3.scene.Geometry) } will
* override this value.
*
* @param mat The world matrix to set
*/
public void setWorldMatrix(Matrix4f mat) {
uniformBindingManager.setWorldMatrix(mat);
}
/**
* Internal use only.
* Updates the given list of uniforms with {@link UniformBinding uniform bindings}
* based on the current world state.
*/
public void updateUniformBindings(List<Uniform> params) {
uniformBindingManager.updateUniformBindings(params);
}
/**
* Renders the given geometry.
* <p>
* First the proper world matrix is set, if
* the geometry's {@link Geometry#setIgnoreTransform(boolean) ignore transform}
* feature is enabled, the identity world matrix is used, otherwise, the
* geometry's {@link Geometry#getWorldMatrix() world transform matrix} is used.
* <p>
* Once the world matrix is applied, the proper material is chosen for rendering.
* If a {@link #setForcedMaterial(com.jme3.material.Material) forced material} is
* set on this RenderManager, then it is used for rendering the geometry,
* otherwise, the {@link Geometry#getMaterial() geometry's material} is used.
* <p>
* If a {@link #setForcedTechnique(java.lang.String) forced technique} is
* set on this RenderManager, then it is selected automatically
* on the geometry's material and is used for rendering. Otherwise, one
* of the {@link MaterialDef#getDefaultTechniques() default techniques} is
* used.
* <p>
* If a {@link #setForcedRenderState(com.jme3.material.RenderState) forced
* render state} is set on this RenderManager, then it is used
* for rendering the material, and the material's own render state is ignored.
* Otherwise, the material's render state is used as intended.
*
* @param g The geometry to render
*
* @see Technique
* @see RenderState
* @see Material#selectTechnique(java.lang.String, com.jme3.renderer.RenderManager)
* @see Material#render(com.jme3.scene.Geometry, com.jme3.renderer.RenderManager)
*/
public void renderGeometry(Geometry g) {
g.render(this);
}
/**
* Renders the given GeometryList.
* <p>
* For every geometry in the list, the
* {@link #renderGeometry(com.jme3.scene.Geometry) } method is called.
*
* @param gl The geometry list to render.
*
* @see GeometryList
* @see #renderGeometry(com.jme3.scene.Geometry)
*/
public void renderGeometryList(GeometryList gl) {
for (int i = 0; i < gl.size(); i++) {
renderGeometry(gl.get(i));
}
}
/**
* Preloads a scene for rendering.
* <p>
* After invocation of this method, the underlying
* renderer would have uploaded any textures, shaders and meshes
* used by the given scene to the video driver.
* Using this method is useful when wishing to avoid the initial pause
* when rendering a scene for the first time. Note that it is not
* guaranteed that the underlying renderer will actually choose to upload
* the data to the GPU so some pause is still to be expected.
*
* @param scene The scene to preload
*/
public void preloadScene(Spatial scene) {
if (scene instanceof Node) {
// recurse for all children
Node n = (Node) scene;
List<Spatial> children = n.getChildren();
for (int i = 0; i < children.size(); i++) {
preloadScene(children.get(i));
}
} else if (scene instanceof Geometry) {
// add to the render queue
Geometry gm = (Geometry) scene;
if (gm.getMaterial() == null) {
throw new IllegalStateException("No material is set for Geometry: " + gm.getName());
}
gm.preload(this);
Mesh mesh = gm.getMesh();
if (mesh != null) {
for (VertexBuffer vb : mesh.getBufferList().getArray()) {
if (vb.getData() != null && vb.getUsage() != VertexBuffer.Usage.CpuOnly) {
renderer.updateBufferData(vb);
}
}
}
}
}
/**
* Flattens the given scene graph into the ViewPort's RenderQueue,
* checking for culling as the call goes down the graph recursively.
* <p>
* First, the scene is checked for culling based on the <code>Spatial</code>s
* {@link Spatial#setCullHint(com.jme3.scene.Spatial.CullHint) cull hint},
* if the camera frustum contains the scene, then this method is recursively
* called on its children.
* <p>
* When the scene's leaves or {@link Geometry geometries} are reached,
* they are each enqueued into the
* {@link ViewPort#getQueue() ViewPort's render queue}.
* <p>
* In addition to enqueuing the visible geometries, this method
* also scenes which cast or receive shadows, by putting them into the
* RenderQueue's {@link RenderQueue#renderShadowQueue(GeometryList, RenderManager, Camera, boolean) shadow queue}.
* Each Spatial which has its {@link Spatial#setShadowMode(com.jme3.renderer.queue.RenderQueue.ShadowMode) shadow mode}
* set to not off, will be put into the appropriate shadow queue, note that
* this process does not check for frustum culling on any
* {@link ShadowMode#Cast shadow casters}, as they don't have to be
* in the eye camera frustum to cast shadows on objects that are inside it.
*
* @param scene The scene to flatten into the queue
* @param vp The ViewPort provides the {@link ViewPort#getCamera() camera}
* used for culling and the {@link ViewPort#getQueue() queue} used to
* contain the flattened scene graph.
*/
public void renderScene(Spatial scene, ViewPort vp) {
//reset of the camera plane state for proper culling (must be 0 for the first note of the scene to be rendered)
vp.getCamera().setPlaneState(0);
//rendering the scene
renderSubScene(scene, vp);
}
// recursively renders the scene
private void renderSubScene(Spatial scene, ViewPort vp) {
// check culling first.
if (!scene.checkCulling(vp.getCamera())) {
return;
}
scene.runControlRender(this, vp);
if (scene instanceof Node) {
// Recurse for all children
Node n = (Node) scene;
List<Spatial> children = n.getChildren();
// Saving cam state for culling
int camState = vp.getCamera().getPlaneState();
for (int i = 0; i < children.size(); i++) {
// Restoring cam state before proceeding children recusively
vp.getCamera().setPlaneState(camState);
renderSubScene(children.get(i), vp);
}
} else if (scene instanceof Geometry) {
// add to the render queue
Geometry gm = (Geometry) scene;
if (gm.getMaterial() == null) {
throw new IllegalStateException("No material is set for Geometry: " + gm.getName());
}
vp.getQueue().addToQueue(gm, scene.getQueueBucket());
}
}
/**
* Returns the camera currently used for rendering.
* <p>
* The camera can be set with {@link #setCamera(com.jme3.renderer.Camera, boolean) }.
*
* @return the camera currently used for rendering.
*/
public Camera getCurrentCamera() {
return prevCam;
}
/**
* The renderer implementation used for rendering operations.
*
* @return The renderer implementation
*
* @see #RenderManager(com.jme3.renderer.Renderer)
* @see Renderer
*/
public Renderer getRenderer() {
return renderer;
}
/**
* Flushes the ViewPort's {@link ViewPort#getQueue() render queue}
* by rendering each of its visible buckets.
* By default the queues will automatically be cleared after rendering,
* so there's no need to clear them manually.
*
* @param vp The ViewPort of which the queue will be flushed
*
* @see RenderQueue#renderQueue(com.jme3.renderer.queue.RenderQueue.Bucket, com.jme3.renderer.RenderManager, com.jme3.renderer.Camera)
* @see #renderGeometryList(com.jme3.renderer.queue.GeometryList)
*/
public void flushQueue(ViewPort vp) {
renderViewPortQueues(vp, true);
}
/**
* Clears the queue of the given ViewPort.
* Simply calls {@link RenderQueue#clear() } on the ViewPort's
* {@link ViewPort#getQueue() render queue}.
*
* @param vp The ViewPort of which the queue will be cleared.
*
* @see RenderQueue#clear()
* @see ViewPort#getQueue()
*/
public void clearQueue(ViewPort vp) {
vp.getQueue().clear();
}
/**
* Sets the light filter to use when rendering lit Geometries.
*
* @see LightFilter
* @param lightFilter The light filter. Set it to null if you want all lights to be rendered.
*/
public void setLightFilter(LightFilter lightFilter) {
this.lightFilter = lightFilter;
}
/**
* Defines what light mode will be selected when a technique offers several light modes.
* @param preferredLightMode The light mode to use.
*/
public void setPreferredLightMode(TechniqueDef.LightMode preferredLightMode) {
this.preferredLightMode = preferredLightMode;
}
/**
* returns the preferred light mode.
* @return the light mode.
*/
public TechniqueDef.LightMode getPreferredLightMode() {
return preferredLightMode;
}
/**
* returns the number of lights used for each pass when the light mode is single pass.
* @return the number of lights.
*/
public int getSinglePassLightBatchSize() {
return singlePassLightBatchSize;
}
/**
* Sets the number of lights to use for each pass when the light mode is single pass.
* @param singlePassLightBatchSize the number of lights.
*/
public void setSinglePassLightBatchSize(int singlePassLightBatchSize) {
// Ensure the batch size is no less than 1
this.singlePassLightBatchSize = singlePassLightBatchSize < 1 ? 1 : singlePassLightBatchSize;
}
/**
* Render the given viewport queues.
* <p>
* Changes the {@link Renderer#setDepthRange(float, float) depth range}
* appropriately as expected by each queue and then calls
* {@link RenderQueue#renderQueue(com.jme3.renderer.queue.RenderQueue.Bucket, com.jme3.renderer.RenderManager, com.jme3.renderer.Camera, boolean) }
* on the queue. Makes sure to restore the depth range to [0, 1]
* at the end of the call.
* Note that the {@link Bucket#Translucent translucent bucket} is NOT
* rendered by this method. Instead the user should call
* {@link #renderTranslucentQueue(com.jme3.renderer.ViewPort) }
* after this call.
*
* @param vp the viewport of which queue should be rendered
* @param flush If true, the queues will be cleared after
* rendering.
*
* @see RenderQueue
* @see #renderTranslucentQueue(com.jme3.renderer.ViewPort)
*/
public void renderViewPortQueues(ViewPort vp, boolean flush) {
RenderQueue rq = vp.getQueue();
Camera cam = vp.getCamera();
boolean depthRangeChanged = false;
// render opaque objects with default depth range
// opaque objects are sorted front-to-back, reducing overdraw
if (prof!=null) prof.vpStep(VpStep.RenderBucket, vp, Bucket.Opaque);
rq.renderQueue(Bucket.Opaque, this, cam, flush);
// render the sky, with depth range set to the farthest
if (!rq.isQueueEmpty(Bucket.Sky)) {
if (prof!=null) prof.vpStep(VpStep.RenderBucket, vp, Bucket.Sky);
renderer.setDepthRange(1, 1);
rq.renderQueue(Bucket.Sky, this, cam, flush);
depthRangeChanged = true;
}
// transparent objects are last because they require blending with the
// rest of the scene's objects. Consequently, they are sorted
// back-to-front.
if (!rq.isQueueEmpty(Bucket.Transparent)) {
if (prof!=null) prof.vpStep(VpStep.RenderBucket, vp, Bucket.Transparent);
if (depthRangeChanged) {
renderer.setDepthRange(0, 1);
depthRangeChanged = false;
}
rq.renderQueue(Bucket.Transparent, this, cam, flush);
}
if (!rq.isQueueEmpty(Bucket.Gui)) {
if (prof!=null) prof.vpStep(VpStep.RenderBucket, vp, Bucket.Gui);
renderer.setDepthRange(0, 0);
setCamera(cam, true);
rq.renderQueue(Bucket.Gui, this, cam, flush);
setCamera(cam, false);
depthRangeChanged = true;
}
// restore range to default
if (depthRangeChanged) {
renderer.setDepthRange(0, 1);
}
}
/**
* Renders the {@link Bucket#Translucent translucent queue} on the viewPort.
* <p>
* This call does nothing unless {@link #setHandleTranslucentBucket(boolean) }
* is set to true. This method clears the translucent queue after rendering
* it.
*
* @param vp The viewport of which the translucent queue should be rendered.
*
* @see #renderViewPortQueues(com.jme3.renderer.ViewPort, boolean)
* @see #setHandleTranslucentBucket(boolean)
*/
public void renderTranslucentQueue(ViewPort vp) {
if (prof!=null) prof.vpStep(VpStep.RenderBucket, vp, Bucket.Translucent);
RenderQueue rq = vp.getQueue();
if (!rq.isQueueEmpty(Bucket.Translucent) && handleTranlucentBucket) {
rq.renderQueue(Bucket.Translucent, this, vp.getCamera(), true);
}
}
private void setViewPort(Camera cam) {
// this will make sure to update viewport only if needed
if (cam != prevCam || cam.isViewportChanged()) {
viewX = (int) (cam.getViewPortLeft() * cam.getWidth());
viewY = (int) (cam.getViewPortBottom() * cam.getHeight());
int viewX2 = (int) (cam.getViewPortRight() * cam.getWidth());
int viewY2 = (int) (cam.getViewPortTop() * cam.getHeight());
viewWidth = viewX2 - viewX;
viewHeight = viewY2 - viewY;
uniformBindingManager.setViewPort(viewX, viewY, viewWidth, viewHeight);
renderer.setViewPort(viewX, viewY, viewWidth, viewHeight);
renderer.setClipRect(viewX, viewY, viewWidth, viewHeight);
cam.clearViewportChanged();
prevCam = cam;
// float translateX = viewWidth == viewX ? 0 : -(viewWidth + viewX) / (viewWidth - viewX);
// float translateY = viewHeight == viewY ? 0 : -(viewHeight + viewY) / (viewHeight - viewY);
// float scaleX = viewWidth == viewX ? 1f : 2f / (viewWidth - viewX);
// float scaleY = viewHeight == viewY ? 1f : 2f / (viewHeight - viewY);
//
// orthoMatrix.loadIdentity();
// orthoMatrix.setTranslation(translateX, translateY, 0);
// orthoMatrix.setScale(scaleX, scaleY, 0);
orthoMatrix.loadIdentity();
orthoMatrix.setTranslation(-1f, -1f, 0f);
orthoMatrix.setScale(2f / cam.getWidth(), 2f / cam.getHeight(), 0f);
}
}
private void setViewProjection(Camera cam, boolean ortho) {
if (ortho) {
uniformBindingManager.setCamera(cam, Matrix4f.IDENTITY, orthoMatrix, orthoMatrix);
} else {
uniformBindingManager.setCamera(cam, cam.getViewMatrix(), cam.getProjectionMatrix(), cam.getViewProjectionMatrix());
}
}
/**
* Set the camera to use for rendering.
* <p>
* First, the camera's
* {@link Camera#setViewPort(float, float, float, float) view port parameters}
* are applied. Then, the camera's {@link Camera#getViewMatrix() view} and
* {@link Camera#getProjectionMatrix() projection} matrices are set
* on the renderer. If <code>ortho</code> is <code>true</code>, then
* instead of using the camera's view and projection matrices, an ortho
* matrix is computed and used instead of the view projection matrix.
* The ortho matrix converts from the range (0 ~ Width, 0 ~ Height, -1 ~ +1)
* to the clip range (-1 ~ +1, -1 ~ +1, -1 ~ +1).
*
* @param cam The camera to set
* @param ortho True if to use orthographic projection (for GUI rendering),
* false if to use the camera's view and projection matrices.
*/
public void setCamera(Camera cam, boolean ortho) {
// Tell the light filter which camera to use for filtering.
if (lightFilter != null) {
lightFilter.setCamera(cam);
}
setViewPort(cam);
setViewProjection(cam, ortho);
}
/**
* Draws the viewport but without notifying {@link SceneProcessor scene
* processors} of any rendering events.
*
* @param vp The ViewPort to render
*
* @see #renderViewPort(com.jme3.renderer.ViewPort, float)
*/
public void renderViewPortRaw(ViewPort vp) {
setCamera(vp.getCamera(), false);
List<Spatial> scenes = vp.getScenes();
for (int i = scenes.size() - 1; i >= 0; i--) {
renderScene(scenes.get(i), vp);
}
flushQueue(vp);
}
/**
* Renders the {@link ViewPort}.
* <p>
* If the ViewPort is {@link ViewPort#isEnabled() disabled}, this method
* returns immediately. Otherwise, the ViewPort is rendered by
* the following process:<br>
* <ul>
* <li>All {@link SceneProcessor scene processors} that are attached
* to the ViewPort are {@link SceneProcessor#initialize(com.jme3.renderer.RenderManager, com.jme3.renderer.ViewPort) initialized}.
* </li>
* <li>The SceneProcessors' {@link SceneProcessor#preFrame(float) } method
* is called.</li>
* <li>The ViewPort's {@link ViewPort#getOutputFrameBuffer() output framebuffer}
* is set on the Renderer</li>
* <li>The camera is set on the renderer, including its view port parameters.
* (see {@link #setCamera(com.jme3.renderer.Camera, boolean) })</li>
* <li>Any buffers that the ViewPort requests to be cleared are cleared
* and the {@link ViewPort#getBackgroundColor() background color} is set</li>
* <li>Every scene that is attached to the ViewPort is flattened into
* the ViewPort's render queue
* (see {@link #renderViewPortQueues(com.jme3.renderer.ViewPort, boolean) })
* </li>
* <li>The SceneProcessors' {@link SceneProcessor#postQueue(com.jme3.renderer.queue.RenderQueue) }
* method is called.</li>
* <li>The render queue is sorted and then flushed, sending
* rendering commands to the underlying Renderer implementation.
* (see {@link #flushQueue(com.jme3.renderer.ViewPort) })</li>
* <li>The SceneProcessors' {@link SceneProcessor#postFrame(com.jme3.texture.FrameBuffer) }
* method is called.</li>
* <li>The translucent queue of the ViewPort is sorted and then flushed
* (see {@link #renderTranslucentQueue(com.jme3.renderer.ViewPort) })</li>
* <li>If any objects remained in the render queue, they are removed
* from the queue. This is generally objects added to the
* {@link RenderQueue#renderShadowQueue(GeometryList, RenderManager, Camera, boolean) shadow queue}
* which were not rendered because of a missing shadow renderer.</li>
* </ul>
*
* @param vp View port to render
* @param tpf Time per frame value
*/
public void renderViewPort(ViewPort vp, float tpf) {
if (!vp.isEnabled()) {
return;
}
if (prof!=null) prof.vpStep(VpStep.BeginRender, vp, null);
SafeArrayList<SceneProcessor> processors = vp.getProcessors();
if (processors.isEmpty()) {
processors = null;
}
if (processors != null) {
for (SceneProcessor proc : processors.getArray()) {
if (!proc.isInitialized()) {
proc.initialize(this, vp);
}
proc.preFrame(tpf);
}
}
renderer.setFrameBuffer(vp.getOutputFrameBuffer());
setCamera(vp.getCamera(), false);
if (vp.isClearDepth() || vp.isClearColor() || vp.isClearStencil()) {
if (vp.isClearColor()) {
renderer.setBackgroundColor(vp.getBackgroundColor());
}
renderer.clearBuffers(vp.isClearColor(),
vp.isClearDepth(),
vp.isClearStencil());
}
if (prof!=null) prof.vpStep(VpStep.RenderScene, vp, null);
List<Spatial> scenes = vp.getScenes();
for (int i = scenes.size() - 1; i >= 0; i--) {
renderScene(scenes.get(i), vp);
}
if (processors != null) {
if (prof!=null) prof.vpStep(VpStep.PostQueue, vp, null);
for (SceneProcessor proc : processors.getArray()) {
proc.postQueue(vp.getQueue());
}
}
if (prof!=null) prof.vpStep(VpStep.FlushQueue, vp, null);
flushQueue(vp);
if (processors != null) {
if (prof!=null) prof.vpStep(VpStep.PostFrame, vp, null);
for (SceneProcessor proc : processors.getArray()) {
proc.postFrame(vp.getOutputFrameBuffer());
}
}
//renders the translucent objects queue after processors have been rendered
renderTranslucentQueue(vp);
// clear any remaining spatials that were not rendered.
clearQueue(vp);
if (prof!=null) prof.vpStep(VpStep.EndRender, vp, null);
}
/**
* Called by the application to render any ViewPorts
* added to this RenderManager.
* <p>
* Renders any viewports that were added using the following methods:
* <ul>
* <li>{@link #createPreView(java.lang.String, com.jme3.renderer.Camera) }</li>
* <li>{@link #createMainView(java.lang.String, com.jme3.renderer.Camera) }</li>
* <li>{@link #createPostView(java.lang.String, com.jme3.renderer.Camera) }</li>
* </ul>
*
* @param tpf Time per frame value
*/
public void render(float tpf, boolean mainFrameBufferActive) {
if (renderer instanceof NullRenderer) {
return;
}
uniformBindingManager.newFrame();
if (prof!=null) prof.appStep(AppStep.RenderPreviewViewPorts);
for (int i = 0; i < preViewPorts.size(); i++) {
ViewPort vp = preViewPorts.get(i);
if (vp.getOutputFrameBuffer() != null || mainFrameBufferActive) {
renderViewPort(vp, tpf);
}
}
if (prof!=null) prof.appStep(AppStep.RenderMainViewPorts);
for (int i = 0; i < viewPorts.size(); i++) {
ViewPort vp = viewPorts.get(i);
if (vp.getOutputFrameBuffer() != null || mainFrameBufferActive) {
renderViewPort(vp, tpf);
}
}
if (prof!=null) prof.appStep(AppStep.RenderPostViewPorts);
for (int i = 0; i < postViewPorts.size(); i++) {
ViewPort vp = postViewPorts.get(i);
if (vp.getOutputFrameBuffer() != null || mainFrameBufferActive) {
renderViewPort(vp, tpf);
}
}
}
}
| bsd-3-clause |
amyvmiwei/skia | src/effects/SkAlphaThresholdFilter.cpp | 15533 | /*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkAlphaThresholdFilter.h"
#include "SkBitmap.h"
#include "SkReadBuffer.h"
#include "SkWriteBuffer.h"
#include "SkRegion.h"
class SK_API SkAlphaThresholdFilterImpl : public SkImageFilter {
public:
SkAlphaThresholdFilterImpl(const SkRegion& region, SkScalar innerThreshold,
SkScalar outerThreshold, SkImageFilter* input);
SK_TO_STRING_OVERRIDE()
SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkAlphaThresholdFilterImpl)
protected:
void flatten(SkWriteBuffer&) const override;
virtual bool onFilterImage(Proxy*, const SkBitmap& src, const Context&,
SkBitmap* result, SkIPoint* offset) const override;
#if SK_SUPPORT_GPU
virtual bool asFragmentProcessor(GrFragmentProcessor**, GrTexture*, const SkMatrix&,
const SkIRect& bounds) const override;
#endif
private:
SkRegion fRegion;
SkScalar fInnerThreshold;
SkScalar fOuterThreshold;
typedef SkImageFilter INHERITED;
};
SkImageFilter* SkAlphaThresholdFilter::Create(const SkRegion& region,
SkScalar innerThreshold,
SkScalar outerThreshold,
SkImageFilter* input) {
return SkNEW_ARGS(SkAlphaThresholdFilterImpl, (region, innerThreshold, outerThreshold, input));
}
#if SK_SUPPORT_GPU
#include "GrContext.h"
#include "GrCoordTransform.h"
#include "GrFragmentProcessor.h"
#include "GrInvariantOutput.h"
#include "GrTextureAccess.h"
#include "effects/GrPorterDuffXferProcessor.h"
#include "SkGr.h"
#include "gl/GrGLProcessor.h"
#include "gl/builders/GrGLProgramBuilder.h"
class AlphaThresholdEffect : public GrFragmentProcessor {
public:
static GrFragmentProcessor* Create(GrTexture* texture,
GrTexture* maskTexture,
float innerThreshold,
float outerThreshold) {
return SkNEW_ARGS(AlphaThresholdEffect, (texture,
maskTexture,
innerThreshold,
outerThreshold));
}
virtual ~AlphaThresholdEffect() {};
const char* name() const override { return "Alpha Threshold"; }
float innerThreshold() const { return fInnerThreshold; }
float outerThreshold() const { return fOuterThreshold; }
void getGLProcessorKey(const GrGLSLCaps&, GrProcessorKeyBuilder*) const override;
GrGLFragmentProcessor* createGLInstance() const override;
private:
AlphaThresholdEffect(GrTexture* texture,
GrTexture* maskTexture,
float innerThreshold,
float outerThreshold)
: fInnerThreshold(innerThreshold)
, fOuterThreshold(outerThreshold)
, fImageCoordTransform(kLocal_GrCoordSet,
GrCoordTransform::MakeDivByTextureWHMatrix(texture), texture,
GrTextureParams::kNone_FilterMode)
, fImageTextureAccess(texture)
, fMaskCoordTransform(kLocal_GrCoordSet,
GrCoordTransform::MakeDivByTextureWHMatrix(maskTexture), maskTexture,
GrTextureParams::kNone_FilterMode)
, fMaskTextureAccess(maskTexture) {
this->initClassID<AlphaThresholdEffect>();
this->addCoordTransform(&fImageCoordTransform);
this->addTextureAccess(&fImageTextureAccess);
this->addCoordTransform(&fMaskCoordTransform);
this->addTextureAccess(&fMaskTextureAccess);
}
bool onIsEqual(const GrFragmentProcessor&) const override;
void onComputeInvariantOutput(GrInvariantOutput* inout) const override;
GR_DECLARE_FRAGMENT_PROCESSOR_TEST;
float fInnerThreshold;
float fOuterThreshold;
GrCoordTransform fImageCoordTransform;
GrTextureAccess fImageTextureAccess;
GrCoordTransform fMaskCoordTransform;
GrTextureAccess fMaskTextureAccess;
typedef GrFragmentProcessor INHERITED;
};
class GrGLAlphaThresholdEffect : public GrGLFragmentProcessor {
public:
GrGLAlphaThresholdEffect(const GrFragmentProcessor&) {}
virtual void emitCode(GrGLFPBuilder*,
const GrFragmentProcessor&,
const char* outputColor,
const char* inputColor,
const TransformedCoordsArray&,
const TextureSamplerArray&) override;
void setData(const GrGLProgramDataManager&, const GrProcessor&) override;
private:
GrGLProgramDataManager::UniformHandle fInnerThresholdVar;
GrGLProgramDataManager::UniformHandle fOuterThresholdVar;
typedef GrGLFragmentProcessor INHERITED;
};
void GrGLAlphaThresholdEffect::emitCode(GrGLFPBuilder* builder,
const GrFragmentProcessor&,
const char* outputColor,
const char* inputColor,
const TransformedCoordsArray& coords,
const TextureSamplerArray& samplers) {
fInnerThresholdVar = builder->addUniform(
GrGLProgramBuilder::kFragment_Visibility,
kFloat_GrSLType, kDefault_GrSLPrecision,
"inner_threshold");
fOuterThresholdVar = builder->addUniform(
GrGLProgramBuilder::kFragment_Visibility,
kFloat_GrSLType, kDefault_GrSLPrecision,
"outer_threshold");
GrGLFragmentBuilder* fsBuilder = builder->getFragmentShaderBuilder();
SkString coords2D = fsBuilder->ensureFSCoords2D(coords, 0);
SkString maskCoords2D = fsBuilder->ensureFSCoords2D(coords, 1);
fsBuilder->codeAppendf("\t\tvec2 coord = %s;\n", coords2D.c_str());
fsBuilder->codeAppendf("\t\tvec2 mask_coord = %s;\n", maskCoords2D.c_str());
fsBuilder->codeAppend("\t\tvec4 input_color = ");
fsBuilder->appendTextureLookup(samplers[0], "coord");
fsBuilder->codeAppend(";\n");
fsBuilder->codeAppend("\t\tvec4 mask_color = ");
fsBuilder->appendTextureLookup(samplers[1], "mask_coord");
fsBuilder->codeAppend(";\n");
fsBuilder->codeAppendf("\t\tfloat inner_thresh = %s;\n",
builder->getUniformCStr(fInnerThresholdVar));
fsBuilder->codeAppendf("\t\tfloat outer_thresh = %s;\n",
builder->getUniformCStr(fOuterThresholdVar));
fsBuilder->codeAppend("\t\tfloat mask = mask_color.a;\n");
fsBuilder->codeAppend("vec4 color = input_color;\n");
fsBuilder->codeAppend("\t\tif (mask < 0.5) {\n"
"\t\t\tif (color.a > outer_thresh) {\n"
"\t\t\t\tfloat scale = outer_thresh / color.a;\n"
"\t\t\t\tcolor.rgb *= scale;\n"
"\t\t\t\tcolor.a = outer_thresh;\n"
"\t\t\t}\n"
"\t\t} else if (color.a < inner_thresh) {\n"
"\t\t\tfloat scale = inner_thresh / max(0.001, color.a);\n"
"\t\t\tcolor.rgb *= scale;\n"
"\t\t\tcolor.a = inner_thresh;\n"
"\t\t}\n");
fsBuilder->codeAppendf("%s = %s;\n", outputColor,
(GrGLSLExpr4(inputColor) * GrGLSLExpr4("color")).c_str());
}
void GrGLAlphaThresholdEffect::setData(const GrGLProgramDataManager& pdman,
const GrProcessor& proc) {
const AlphaThresholdEffect& alpha_threshold = proc.cast<AlphaThresholdEffect>();
pdman.set1f(fInnerThresholdVar, alpha_threshold.innerThreshold());
pdman.set1f(fOuterThresholdVar, alpha_threshold.outerThreshold());
}
/////////////////////////////////////////////////////////////////////
GR_DEFINE_FRAGMENT_PROCESSOR_TEST(AlphaThresholdEffect);
GrFragmentProcessor* AlphaThresholdEffect::TestCreate(SkRandom* random,
GrContext* context,
const GrDrawTargetCaps&,
GrTexture** textures) {
GrTexture* bmpTex = textures[GrProcessorUnitTest::kSkiaPMTextureIdx];
GrTexture* maskTex = textures[GrProcessorUnitTest::kAlphaTextureIdx];
float inner_thresh = random->nextUScalar1();
float outer_thresh = random->nextUScalar1();
return AlphaThresholdEffect::Create(bmpTex, maskTex, inner_thresh, outer_thresh);
}
///////////////////////////////////////////////////////////////////////////////
void AlphaThresholdEffect::getGLProcessorKey(const GrGLSLCaps& caps,
GrProcessorKeyBuilder* b) const {
GrGLAlphaThresholdEffect::GenKey(*this, caps, b);
}
GrGLFragmentProcessor* AlphaThresholdEffect::createGLInstance() const {
return SkNEW_ARGS(GrGLAlphaThresholdEffect, (*this));
}
bool AlphaThresholdEffect::onIsEqual(const GrFragmentProcessor& sBase) const {
const AlphaThresholdEffect& s = sBase.cast<AlphaThresholdEffect>();
return (this->fInnerThreshold == s.fInnerThreshold &&
this->fOuterThreshold == s.fOuterThreshold);
}
void AlphaThresholdEffect::onComputeInvariantOutput(GrInvariantOutput* inout) const {
if (GrPixelConfigIsAlphaOnly(this->texture(0)->config())) {
inout->mulByUnknownSingleComponent();
} else if (GrPixelConfigIsOpaque(this->texture(0)->config()) && fOuterThreshold >= 1.f) {
inout->mulByUnknownOpaqueFourComponents();
} else {
inout->mulByUnknownFourComponents();
}
}
#endif
SkFlattenable* SkAlphaThresholdFilterImpl::CreateProc(SkReadBuffer& buffer) {
SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 1);
SkScalar inner = buffer.readScalar();
SkScalar outer = buffer.readScalar();
SkRegion rgn;
buffer.readRegion(&rgn);
return SkAlphaThresholdFilter::Create(rgn, inner, outer, common.getInput(0));
}
SkAlphaThresholdFilterImpl::SkAlphaThresholdFilterImpl(const SkRegion& region,
SkScalar innerThreshold,
SkScalar outerThreshold,
SkImageFilter* input)
: INHERITED(1, &input)
, fRegion(region)
, fInnerThreshold(innerThreshold)
, fOuterThreshold(outerThreshold) {
}
#if SK_SUPPORT_GPU
bool SkAlphaThresholdFilterImpl::asFragmentProcessor(GrFragmentProcessor** fp,
GrTexture* texture,
const SkMatrix& in_matrix,
const SkIRect&) const {
if (fp) {
GrContext* context = texture->getContext();
GrSurfaceDesc maskDesc;
if (context->isConfigRenderable(kAlpha_8_GrPixelConfig, false)) {
maskDesc.fConfig = kAlpha_8_GrPixelConfig;
} else {
maskDesc.fConfig = kRGBA_8888_GrPixelConfig;
}
maskDesc.fFlags = kRenderTarget_GrSurfaceFlag;
// Add one pixel of border to ensure that clamp mode will be all zeros
// the outside.
maskDesc.fWidth = texture->width();
maskDesc.fHeight = texture->height();
SkAutoTUnref<GrTexture> maskTexture(
context->refScratchTexture(maskDesc, GrContext::kApprox_ScratchTexMatch));
if (!maskTexture) {
return false;
}
{
GrPaint grPaint;
grPaint.setPorterDuffXPFactory(SkXfermode::kSrc_Mode);
SkRegion::Iterator iter(fRegion);
context->clear(NULL, 0x0, true, maskTexture->asRenderTarget());
while (!iter.done()) {
SkRect rect = SkRect::Make(iter.rect());
context->drawRect(maskTexture->asRenderTarget(), GrClip::WideOpen(), grPaint,
in_matrix, rect);
iter.next();
}
}
*fp = AlphaThresholdEffect::Create(texture,
maskTexture,
fInnerThreshold,
fOuterThreshold);
}
return true;
}
#endif
void SkAlphaThresholdFilterImpl::flatten(SkWriteBuffer& buffer) const {
this->INHERITED::flatten(buffer);
buffer.writeScalar(fInnerThreshold);
buffer.writeScalar(fOuterThreshold);
buffer.writeRegion(fRegion);
}
bool SkAlphaThresholdFilterImpl::onFilterImage(Proxy*, const SkBitmap& src,
const Context& ctx, SkBitmap* dst,
SkIPoint* offset) const {
SkASSERT(src.colorType() == kN32_SkColorType);
if (src.colorType() != kN32_SkColorType) {
return false;
}
SkMatrix localInverse;
if (!ctx.ctm().invert(&localInverse)) {
return false;
}
SkAutoLockPixels alp(src);
SkASSERT(src.getPixels());
if (!src.getPixels() || src.width() <= 0 || src.height() <= 0) {
return false;
}
if (!dst->tryAllocPixels(src.info())) {
return false;
}
U8CPU innerThreshold = (U8CPU)(fInnerThreshold * 0xFF);
U8CPU outerThreshold = (U8CPU)(fOuterThreshold * 0xFF);
SkColor* sptr = src.getAddr32(0, 0);
SkColor* dptr = dst->getAddr32(0, 0);
int width = src.width(), height = src.height();
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
const SkColor& source = sptr[y * width + x];
SkColor output_color(source);
SkPoint position;
localInverse.mapXY((SkScalar)x, (SkScalar)y, &position);
if (fRegion.contains((int32_t)position.x(), (int32_t)position.y())) {
if (SkColorGetA(source) < innerThreshold) {
U8CPU alpha = SkColorGetA(source);
if (alpha == 0)
alpha = 1;
float scale = (float)innerThreshold / alpha;
output_color = SkColorSetARGB(innerThreshold,
(U8CPU)(SkColorGetR(source) * scale),
(U8CPU)(SkColorGetG(source) * scale),
(U8CPU)(SkColorGetB(source) * scale));
}
} else {
if (SkColorGetA(source) > outerThreshold) {
float scale = (float)outerThreshold / SkColorGetA(source);
output_color = SkColorSetARGB(outerThreshold,
(U8CPU)(SkColorGetR(source) * scale),
(U8CPU)(SkColorGetG(source) * scale),
(U8CPU)(SkColorGetB(source) * scale));
}
}
dptr[y * dst->width() + x] = output_color;
}
}
return true;
}
#ifndef SK_IGNORE_TO_STRING
void SkAlphaThresholdFilterImpl::toString(SkString* str) const {
str->appendf("SkAlphaThresholdImageFilter: (");
str->appendf("inner: %f outer: %f", fInnerThreshold, fOuterThreshold);
str->append(")");
}
#endif
| bsd-3-clause |
wrboyce/py-gtranslate | gtrans.py | 1626 | import re
import urllib
import simplejson as json
class UrlOpener(urllib.FancyURLopener):
version = "py-gtranslate/1.0"
class InvalidLanguage(Exception): pass
class UnableToDetectLanguage(Exception): pass
base_uri = "http://ajax.googleapis.com/ajax/services/language/translate"
detect_uri = "http://ajax.googleapis.com/ajax/services/language/detect"
default_params = {'v': '1.0'}
langs = json.load(file('langs.json', 'r'))
class TranslatedString(unicode):
lang = "auto"
def to(self, to):
t = translate(u'%s' % self, to=to, src=self.lang)
t.lang = to
return t
def _build_args(dict):
args = default_params.copy()
args.update(dict)
return '&'.join(['%s=%s' % (k,v) for (k,v) in args.iteritems()])
def detect_lang(phrase):
args = {'q': urllib.quote_plus(phrase.encode('utf-8'))}
resp = json.load(UrlOpener().open('%s?%s' % (detect_uri, _build_args(args))))
try:
return resp['responseData']['language']
except:
raise UnableToDetectLanguage()
def translate(phrase, to, src="auto"):
if src == "auto":
src = detect_lang(phrase)
src = langs.get(src, src)
to = langs.get(to, to)
if not src in langs.values() or not to in langs.values():
raise InvalidLanguage("%s=>%s is not a valid translation" % (src, to))
args = {
'langpair': '%s%%7C%s' % (src, to),
'q': urllib.quote_plus(phrase.encode('utf-8')),
}
resp = json.load(UrlOpener().open('%s?%s' % (base_uri, _build_args(args))))
try:
t = TranslatedString(resp['responseData']['translatedText'])
t.lang = to
return t
except:
# should probably warn about failed translation
t = TranslatedString(phrase)
t.lang = src
return t
| bsd-3-clause |
getdnsapi/getdns-java-bindings | src/test/java/com/verisign/getdns/asyncwithcallback/test/GeneralASyncWithCallbackTest.java | 5276 | package com.verisign.getdns.asyncwithcallback.test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.verisign.getdns.GetDNSException;
import com.verisign.getdns.GetDNSFactory;
import com.verisign.getdns.IGetDNSCallback;
import com.verisign.getdns.IGetDNSContextAsyncWithCallback;
import com.verisign.getdns.RRType;
import com.verisign.getdns.test.ErrorCodeMatcher;
public class GeneralASyncWithCallbackTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testGetDNSAsyncWithCallback() throws ExecutionException, TimeoutException, InterruptedException {
final IGetDNSContextAsyncWithCallback context = GetDNSFactory.createAsyncWithCallback(1, null);
final long a = System.currentTimeMillis();
try {
final String domain = "getdnsapi.net";
context.generalAsync(domain, RRType.valueOf("A"), null, new IGetDNSCallback() {
@Override
public void handleResponse(HashMap<String, Object> response, RuntimeException exception) {
try {
Thread.sleep(5000);
assertNotNull(response);
System.out.println("Completed processing for: " + domain);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
context.run();
Thread.sleep(10000);
} finally {
System.out.println("total wating time: " + (System.currentTimeMillis() - a));
context.close();
}
}
@Test
public void testGetDNSAsyncCancelWithCallback() throws ExecutionException, TimeoutException, InterruptedException {
final IGetDNSContextAsyncWithCallback context = GetDNSFactory.createAsyncWithCallback(1, null);
final long a = System.currentTimeMillis();
try {
final String domain = "getdnsapi.net";
long transactionId = context.generalAsync(domain, RRType.valueOf("A"), null, new IGetDNSCallback() {
@Override
public void handleResponse(HashMap<String, Object> response, RuntimeException exception) {
try {
Thread.sleep(5000);
fail("After cancelling the request,this block shouldn't executed");
System.out.println("Completed processing for: " + domain);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
context.cancelRequest(transactionId);
context.run();
Thread.sleep(10000);
} finally {
System.out.println("total waiting time: " + (System.currentTimeMillis() - a));
context.close();
}
}
@Test
public void testGetDNSAsyncCancelWithCallback1() throws ExecutionException, TimeoutException, InterruptedException {
final IGetDNSContextAsyncWithCallback context = GetDNSFactory.createAsyncWithCallback(1, null);
final long a = System.currentTimeMillis();
try {
thrown.expect(GetDNSException.class);
thrown.expect(new ErrorCodeMatcher("GETDNS_RETURN_UNKNOWN_TRANSACTION"));
final String domain = "getdnsapi.net";
long transactionId = context.generalAsync(domain, RRType.valueOf("A"), null, new IGetDNSCallback() {
@Override
public void handleResponse(HashMap<String, Object> response, RuntimeException exception) {
try {
Thread.sleep(5000);
fail("After cancelling the request,this block shouldn't executed");
System.out.println("Completed processing for: " + domain);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
context.cancelRequest(transactionId);
context.run();
context.cancelRequest(transactionId);
Thread.sleep(10000);
} finally {
System.out.println("total waiting time: " + (System.currentTimeMillis() - a));
context.close();
}
}
@Test
public void testGetDNSAsyncCancelWithCallback2() throws ExecutionException, TimeoutException, InterruptedException {
final IGetDNSContextAsyncWithCallback context = GetDNSFactory.createAsyncWithCallback(1, null);
final long a = System.currentTimeMillis();
try {
final String domain1 = "getdnsapi.net";
final String domain2 = "verisigninc.com";
long transactionId = context.generalAsync(domain1, RRType.valueOf("A"), null, new IGetDNSCallback() {
@Override
public void handleResponse(HashMap<String, Object> response, RuntimeException exception) {
try {
Thread.sleep(5000);
fail("After cancelling the request,this block shouldn't executed");
System.out.println("Completed processing for: " + domain1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
context.cancelRequest(transactionId);
context.run();
context.generalAsync(domain2, RRType.valueOf("A"), null, new IGetDNSCallback() {
@Override
public void handleResponse(HashMap<String, Object> response, RuntimeException exception) {
try {
Thread.sleep(5000);
assertNotNull(response);
System.out.println("Completed processing for: " + domain2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
context.run();
Thread.sleep(10000);
} finally {
System.out.println("total waiting time: " + (System.currentTimeMillis() - a));
context.close();
}
}
}
| bsd-3-clause |
nwjs/chromium.src | chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_unittest.cc | 41970 | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <tuple>
#include "base/files/file_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/enterprise/signals/device_info_fetcher.h"
#include "chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.h"
#include "base/command_line.h"
#include "base/files/scoped_temp_dir.h"
#include "base/macros.h"
#include "build/build_config.h"
#include "chrome/browser/enterprise/signals/signals_common.h"
#include "chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.h"
#include "chrome/browser/extensions/extension_api_unittest.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/net/stub_resolver_config_reader.h"
#include "chrome/browser/policy/dm_token_utils.h"
#include "chrome/common/pref_names.h"
#include "components/component_updater/pref_names.h"
#include "components/enterprise/browser/controller/fake_browser_dm_token_storage.h"
#include "components/policy/core/common/policy_pref_names.h"
#include "components/policy/core/common/policy_types.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "components/version_info/version_info.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(OS_WIN)
#include <netfw.h>
#include <windows.h>
#include <wrl/client.h>
#include "base/test/test_reg_util_win.h"
#endif
#if defined(OS_LINUX) || defined(OS_CHROMEOS)
#include "base/nix/xdg_util.h"
#endif
namespace enterprise_reporting_private =
::extensions::api::enterprise_reporting_private;
using SettingValue = enterprise_signals::SettingValue;
namespace extensions {
#if !defined(OS_CHROMEOS)
namespace {
const char kFakeClientId[] = "fake-client-id";
} // namespace
// Test for API enterprise.reportingPrivate.getDeviceId
class EnterpriseReportingPrivateGetDeviceIdTest : public ExtensionApiUnittest {
public:
EnterpriseReportingPrivateGetDeviceIdTest() = default;
EnterpriseReportingPrivateGetDeviceIdTest(
const EnterpriseReportingPrivateGetDeviceIdTest&) = delete;
EnterpriseReportingPrivateGetDeviceIdTest& operator=(
const EnterpriseReportingPrivateGetDeviceIdTest&) = delete;
void SetClientId(const std::string& client_id) {
storage_.SetClientId(client_id);
}
private:
policy::FakeBrowserDMTokenStorage storage_;
};
TEST_F(EnterpriseReportingPrivateGetDeviceIdTest, GetDeviceId) {
auto function =
base::MakeRefCounted<EnterpriseReportingPrivateGetDeviceIdFunction>();
SetClientId(kFakeClientId);
std::unique_ptr<base::Value> id =
RunFunctionAndReturnValue(function.get(), "[]");
ASSERT_TRUE(id);
ASSERT_TRUE(id->is_string());
EXPECT_EQ(kFakeClientId, id->GetString());
}
TEST_F(EnterpriseReportingPrivateGetDeviceIdTest, DeviceIdNotExist) {
auto function =
base::MakeRefCounted<EnterpriseReportingPrivateGetDeviceIdFunction>();
SetClientId("");
ASSERT_EQ(enterprise_reporting::kDeviceIdNotFound,
RunFunctionAndReturnError(function.get(), "[]"));
}
// Test for API enterprise.reportingPrivate.getDeviceId
class EnterpriseReportingPrivateDeviceDataFunctionsTest
: public ExtensionApiUnittest {
public:
EnterpriseReportingPrivateDeviceDataFunctionsTest() = default;
EnterpriseReportingPrivateDeviceDataFunctionsTest(
const EnterpriseReportingPrivateDeviceDataFunctionsTest&) = delete;
EnterpriseReportingPrivateDeviceDataFunctionsTest& operator=(
const EnterpriseReportingPrivateDeviceDataFunctionsTest&) = delete;
void SetUp() override {
ExtensionApiUnittest::SetUp();
ASSERT_TRUE(fake_appdata_dir_.CreateUniqueTempDir());
OverrideEndpointVerificationDirForTesting(fake_appdata_dir_.GetPath());
}
private:
base::ScopedTempDir fake_appdata_dir_;
};
TEST_F(EnterpriseReportingPrivateDeviceDataFunctionsTest, StoreDeviceData) {
auto function =
base::MakeRefCounted<EnterpriseReportingPrivateSetDeviceDataFunction>();
std::unique_ptr<base::ListValue> values = std::make_unique<base::ListValue>();
values->Append("a");
values->Append(
std::make_unique<base::Value>(base::Value::BlobStorage({1, 2, 3})));
extension_function_test_utils::RunFunction(function.get(), std::move(values),
browser(),
extensions::api_test_utils::NONE);
ASSERT_TRUE(function->GetResultList());
EXPECT_EQ(0u, function->GetResultList()->GetList().size());
EXPECT_TRUE(function->GetError().empty());
}
TEST_F(EnterpriseReportingPrivateDeviceDataFunctionsTest, DeviceDataMissing) {
auto function =
base::MakeRefCounted<EnterpriseReportingPrivateGetDeviceDataFunction>();
std::unique_ptr<base::ListValue> values = std::make_unique<base::ListValue>();
values->Append("b");
extension_function_test_utils::RunFunction(function.get(), std::move(values),
browser(),
extensions::api_test_utils::NONE);
ASSERT_TRUE(function->GetResultList());
EXPECT_EQ(1u, function->GetResultList()->GetList().size());
EXPECT_TRUE(function->GetError().empty());
const base::Value* single_result = nullptr;
EXPECT_TRUE(function->GetResultList()->Get(0, &single_result));
ASSERT_TRUE(single_result);
ASSERT_TRUE(single_result->is_blob());
EXPECT_EQ(base::Value::BlobStorage(), single_result->GetBlob());
}
TEST_F(EnterpriseReportingPrivateDeviceDataFunctionsTest, DeviceBadId) {
auto set_function =
base::MakeRefCounted<EnterpriseReportingPrivateSetDeviceDataFunction>();
std::unique_ptr<base::ListValue> set_values =
std::make_unique<base::ListValue>();
set_values->Append("a/b");
set_values->Append(
std::make_unique<base::Value>(base::Value::BlobStorage({1, 2, 3})));
extension_function_test_utils::RunFunction(set_function.get(),
std::move(set_values), browser(),
extensions::api_test_utils::NONE);
ASSERT_TRUE(set_function->GetError().empty());
// Try to read the directory as a file and should fail.
auto function =
base::MakeRefCounted<EnterpriseReportingPrivateGetDeviceDataFunction>();
std::unique_ptr<base::ListValue> values = std::make_unique<base::ListValue>();
values->Append("a");
extension_function_test_utils::RunFunction(function.get(), std::move(values),
browser(),
extensions::api_test_utils::NONE);
ASSERT_TRUE(function->GetResultList());
EXPECT_EQ(0u, function->GetResultList()->GetList().size());
EXPECT_FALSE(function->GetError().empty());
}
TEST_F(EnterpriseReportingPrivateDeviceDataFunctionsTest, RetrieveDeviceData) {
auto set_function =
base::MakeRefCounted<EnterpriseReportingPrivateSetDeviceDataFunction>();
std::unique_ptr<base::ListValue> set_values =
std::make_unique<base::ListValue>();
set_values->Append("c");
set_values->Append(
std::make_unique<base::Value>(base::Value::BlobStorage({1, 2, 3})));
extension_function_test_utils::RunFunction(set_function.get(),
std::move(set_values), browser(),
extensions::api_test_utils::NONE);
ASSERT_TRUE(set_function->GetError().empty());
auto get_function =
base::MakeRefCounted<EnterpriseReportingPrivateGetDeviceDataFunction>();
std::unique_ptr<base::ListValue> values = std::make_unique<base::ListValue>();
values->Append("c");
extension_function_test_utils::RunFunction(get_function.get(),
std::move(values), browser(),
extensions::api_test_utils::NONE);
const base::Value* single_result = nullptr;
ASSERT_TRUE(get_function->GetResultList());
EXPECT_TRUE(get_function->GetResultList()->Get(0, &single_result));
EXPECT_TRUE(get_function->GetError().empty());
ASSERT_TRUE(single_result);
ASSERT_TRUE(single_result->is_blob());
EXPECT_EQ(base::Value::BlobStorage({1, 2, 3}), single_result->GetBlob());
// Clear the data and check that it is gone.
auto set_function2 =
base::MakeRefCounted<EnterpriseReportingPrivateSetDeviceDataFunction>();
std::unique_ptr<base::ListValue> reset_values =
std::make_unique<base::ListValue>();
reset_values->Append("c");
extension_function_test_utils::RunFunction(set_function2.get(),
std::move(reset_values), browser(),
extensions::api_test_utils::NONE);
ASSERT_TRUE(set_function2->GetError().empty());
auto get_function2 =
base::MakeRefCounted<EnterpriseReportingPrivateGetDeviceDataFunction>();
std::unique_ptr<base::ListValue> values2 =
std::make_unique<base::ListValue>();
values2->Append("c");
extension_function_test_utils::RunFunction(get_function2.get(),
std::move(values2), browser(),
extensions::api_test_utils::NONE);
ASSERT_TRUE(get_function2->GetResultList());
EXPECT_EQ(1u, get_function2->GetResultList()->GetList().size());
EXPECT_TRUE(get_function2->GetError().empty());
EXPECT_TRUE(get_function2->GetResultList()->Get(0, &single_result));
ASSERT_TRUE(single_result);
ASSERT_TRUE(single_result->is_blob());
EXPECT_EQ(base::Value::BlobStorage(), single_result->GetBlob());
}
// TODO(pastarmovj): Remove once implementation for the other platform exists.
#if defined(OS_WIN)
// Test for API enterprise.reportingPrivate.getDeviceId
class EnterpriseReportingPrivateGetPersistentSecretFunctionTest
: public ExtensionApiUnittest {
public:
EnterpriseReportingPrivateGetPersistentSecretFunctionTest() = default;
EnterpriseReportingPrivateGetPersistentSecretFunctionTest(
const EnterpriseReportingPrivateGetPersistentSecretFunctionTest&) =
delete;
EnterpriseReportingPrivateGetPersistentSecretFunctionTest& operator=(
const EnterpriseReportingPrivateGetPersistentSecretFunctionTest&) =
delete;
void SetUp() override {
ExtensionApiUnittest::SetUp();
#if defined(OS_WIN)
ASSERT_NO_FATAL_FAILURE(
registry_override_manager_.OverrideRegistry(HKEY_CURRENT_USER));
#endif
}
private:
#if defined(OS_WIN)
registry_util::RegistryOverrideManager registry_override_manager_;
#endif
};
TEST_F(EnterpriseReportingPrivateGetPersistentSecretFunctionTest, GetSecret) {
auto function = base::MakeRefCounted<
EnterpriseReportingPrivateGetPersistentSecretFunction>();
std::unique_ptr<base::Value> result1 =
RunFunctionAndReturnValue(function.get(), "[]");
ASSERT_TRUE(result1);
ASSERT_TRUE(result1->is_blob());
auto generated_blob = result1->GetBlob();
// Re-running should not change the secret.
auto function2 = base::MakeRefCounted<
EnterpriseReportingPrivateGetPersistentSecretFunction>();
std::unique_ptr<base::Value> result2 =
RunFunctionAndReturnValue(function2.get(), "[]");
ASSERT_TRUE(result2);
ASSERT_TRUE(result2->is_blob());
ASSERT_EQ(generated_blob, result2->GetBlob());
// Re-running should not change the secret even when force recreate is set.
auto function3 = base::MakeRefCounted<
EnterpriseReportingPrivateGetPersistentSecretFunction>();
std::unique_ptr<base::Value> result3 =
RunFunctionAndReturnValue(function3.get(), "[true]");
ASSERT_TRUE(result3);
ASSERT_TRUE(result3->is_blob());
ASSERT_EQ(generated_blob, result3->GetBlob());
const wchar_t kDefaultRegistryPath[] =
L"SOFTWARE\\Google\\Endpoint Verification";
const wchar_t kValueName[] = L"Safe Storage";
base::win::RegKey key;
ASSERT_EQ(ERROR_SUCCESS,
key.Create(HKEY_CURRENT_USER, kDefaultRegistryPath, KEY_WRITE));
// Mess up with the value.
ASSERT_EQ(ERROR_SUCCESS, key.WriteValue(kValueName, 1337));
// Re-running with no recreate enforcement should return an error.
auto function4 = base::MakeRefCounted<
EnterpriseReportingPrivateGetPersistentSecretFunction>();
std::string error = RunFunctionAndReturnError(function4.get(), "[]");
ASSERT_FALSE(error.empty());
// Re=running should not change the secret even when force recreate is set.
auto function5 = base::MakeRefCounted<
EnterpriseReportingPrivateGetPersistentSecretFunction>();
std::unique_ptr<base::Value> result5 =
RunFunctionAndReturnValue(function5.get(), "[true]");
ASSERT_TRUE(result5);
ASSERT_TRUE(result5->is_blob());
ASSERT_NE(generated_blob, result5->GetBlob());
}
#endif // defined(OS_WIN)
using EnterpriseReportingPrivateGetDeviceInfoTest = ExtensionApiUnittest;
TEST_F(EnterpriseReportingPrivateGetDeviceInfoTest, GetDeviceInfo) {
auto function =
base::MakeRefCounted<EnterpriseReportingPrivateGetDeviceInfoFunction>();
std::unique_ptr<base::Value> device_info_value =
RunFunctionAndReturnValue(function.get(), "[]");
ASSERT_TRUE(device_info_value.get());
enterprise_reporting_private::DeviceInfo info;
ASSERT_TRUE(enterprise_reporting_private::DeviceInfo::Populate(
*device_info_value, &info));
#if defined(OS_MAC)
EXPECT_EQ("macOS", info.os_name);
#elif defined(OS_WIN)
EXPECT_EQ("windows", info.os_name);
EXPECT_FALSE(info.device_model.empty());
#elif defined(OS_LINUX) || defined(OS_CHROMEOS)
std::unique_ptr<base::Environment> env(base::Environment::Create());
env->SetVar(base::nix::kXdgCurrentDesktopEnvVar, "XFCE");
EXPECT_EQ("linux", info.os_name);
#else
// Verify a stub implementation.
EXPECT_EQ("stubOS", info.os_name);
EXPECT_EQ("0.0.0.0", info.os_version);
EXPECT_EQ("midnightshift", info.device_host_name);
EXPECT_EQ("topshot", info.device_model);
EXPECT_EQ("twirlchange", info.serial_number);
EXPECT_EQ(enterprise_reporting_private::SETTING_VALUE_ENABLED,
info.screen_lock_secured);
EXPECT_EQ(enterprise_reporting_private::SETTING_VALUE_DISABLED,
info.disk_encrypted);
ASSERT_EQ(1u, info.mac_addresses.size());
EXPECT_EQ("00:00:00:00:00:00", info.mac_addresses[0]);
EXPECT_EQ(*info.windows_machine_domain, "MACHINE_DOMAIN");
EXPECT_EQ(*info.windows_user_domain, "USER_DOMAIN");
#endif
}
TEST_F(EnterpriseReportingPrivateGetDeviceInfoTest, GetDeviceInfoConversion) {
// Verify that the conversion from a DeviceInfoFetcher result works,
// regardless of platform.
auto device_info_fetcher =
enterprise_signals::DeviceInfoFetcher::CreateStubInstanceForTesting();
enterprise_reporting_private::DeviceInfo info =
EnterpriseReportingPrivateGetDeviceInfoFunction::ToDeviceInfo(
device_info_fetcher->Fetch());
EXPECT_EQ("stubOS", info.os_name);
EXPECT_EQ("0.0.0.0", info.os_version);
EXPECT_EQ("midnightshift", info.device_host_name);
EXPECT_EQ("topshot", info.device_model);
EXPECT_EQ("twirlchange", info.serial_number);
EXPECT_EQ(enterprise_reporting_private::SETTING_VALUE_ENABLED,
info.screen_lock_secured);
EXPECT_EQ(enterprise_reporting_private::SETTING_VALUE_DISABLED,
info.disk_encrypted);
ASSERT_EQ(1u, info.mac_addresses.size());
EXPECT_EQ("00:00:00:00:00:00", info.mac_addresses[0]);
EXPECT_EQ(*info.windows_machine_domain, "MACHINE_DOMAIN");
EXPECT_EQ(*info.windows_user_domain, "USER_DOMAIN");
}
#endif // !defined(OS_CHROMEOS)
class EnterpriseReportingPrivateGetContextInfoTest
: public ExtensionApiUnittest {
public:
void SetUp() override {
ExtensionApiUnittest::SetUp();
// Only used to set the right default BuiltInDnsClientEnabled preference
// value according to the OS. DnsClient and DoH default preferences are
// updated when the object is created, making the object unnecessary outside
// this scope.
StubResolverConfigReader stub_resolver_config_reader(
g_browser_process->local_state());
}
enterprise_reporting_private::ContextInfo GetContextInfo() {
auto function = base::MakeRefCounted<
EnterpriseReportingPrivateGetContextInfoFunction>();
std::unique_ptr<base::Value> context_info_value =
RunFunctionAndReturnValue(function.get(), "[]");
EXPECT_TRUE(context_info_value.get());
enterprise_reporting_private::ContextInfo info;
EXPECT_TRUE(enterprise_reporting_private::ContextInfo::Populate(
*context_info_value, &info));
return info;
}
bool BuiltInDnsClientPlatformDefault() {
#if defined(OS_CHROMEOS) || defined(OS_MAC) || defined(OS_ANDROID)
return true;
#else
return false;
#endif
}
void ExpectDefaultChromeCleanupEnabled(
const enterprise_reporting_private::ContextInfo& info) {
#if defined(OS_WIN)
EXPECT_TRUE(*info.chrome_cleanup_enabled);
#else
EXPECT_EQ(nullptr, info.chrome_cleanup_enabled.get());
#endif
}
void ExpectDefaultThirdPartyBlockingEnabled(
const enterprise_reporting_private::ContextInfo& info) {
#if defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING)
EXPECT_TRUE(*info.third_party_blocking_enabled);
#else
EXPECT_EQ(info.third_party_blocking_enabled, nullptr);
#endif
}
};
TEST_F(EnterpriseReportingPrivateGetContextInfoTest, NoSpecialContext) {
// This tests the data returned by the API is correct when no special context
// is present, ie no policies are set, the browser is unamanaged, etc.
enterprise_reporting_private::ContextInfo info = GetContextInfo();
EXPECT_TRUE(info.browser_affiliation_ids.empty());
EXPECT_TRUE(info.profile_affiliation_ids.empty());
EXPECT_TRUE(info.on_file_attached_providers.empty());
EXPECT_TRUE(info.on_file_downloaded_providers.empty());
EXPECT_TRUE(info.on_bulk_data_entry_providers.empty());
EXPECT_EQ(enterprise_reporting_private::REALTIME_URL_CHECK_MODE_DISABLED,
info.realtime_url_check_mode);
EXPECT_TRUE(info.on_security_event_providers.empty());
EXPECT_EQ(version_info::GetVersionNumber(), info.browser_version);
EXPECT_EQ(enterprise_reporting_private::SAFE_BROWSING_LEVEL_STANDARD,
info.safe_browsing_protection_level);
EXPECT_EQ(BuiltInDnsClientPlatformDefault(),
info.built_in_dns_client_enabled);
EXPECT_EQ(
enterprise_reporting_private::PASSWORD_PROTECTION_TRIGGER_POLICY_UNSET,
info.password_protection_warning_trigger);
ExpectDefaultChromeCleanupEnabled(info);
EXPECT_FALSE(info.chrome_remote_desktop_app_blocked);
ExpectDefaultThirdPartyBlockingEnabled(info);
}
#if defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING)
class EnterpriseReportingPrivateGetContextInfoThirdPartyBlockingTest
: public EnterpriseReportingPrivateGetContextInfoTest,
public testing::WithParamInterface<bool> {};
TEST_P(EnterpriseReportingPrivateGetContextInfoThirdPartyBlockingTest, Test) {
bool policyValue = GetParam();
g_browser_process->local_state()->SetBoolean(
prefs::kThirdPartyBlockingEnabled, policyValue);
enterprise_reporting_private::ContextInfo info = GetContextInfo();
EXPECT_TRUE(info.browser_affiliation_ids.empty());
EXPECT_TRUE(info.profile_affiliation_ids.empty());
EXPECT_TRUE(info.on_file_attached_providers.empty());
EXPECT_TRUE(info.on_file_downloaded_providers.empty());
EXPECT_TRUE(info.on_bulk_data_entry_providers.empty());
EXPECT_EQ(enterprise_reporting_private::REALTIME_URL_CHECK_MODE_DISABLED,
info.realtime_url_check_mode);
EXPECT_TRUE(info.on_security_event_providers.empty());
EXPECT_EQ(version_info::GetVersionNumber(), info.browser_version);
EXPECT_EQ(enterprise_reporting_private::SAFE_BROWSING_LEVEL_STANDARD,
info.safe_browsing_protection_level);
EXPECT_EQ(BuiltInDnsClientPlatformDefault(),
info.built_in_dns_client_enabled);
ExpectDefaultChromeCleanupEnabled(info);
EXPECT_FALSE(info.chrome_remote_desktop_app_blocked);
EXPECT_EQ(policyValue, *info.third_party_blocking_enabled);
}
INSTANTIATE_TEST_SUITE_P(
,
EnterpriseReportingPrivateGetContextInfoThirdPartyBlockingTest,
testing::Bool());
#endif // defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING)
class EnterpriseReportingPrivateGetContextInfoSafeBrowsingTest
: public EnterpriseReportingPrivateGetContextInfoTest,
public testing::WithParamInterface<std::tuple<bool, bool>> {};
TEST_P(EnterpriseReportingPrivateGetContextInfoSafeBrowsingTest, Test) {
std::tuple<bool, bool> params = GetParam();
bool safe_browsing_enabled = std::get<0>(params);
bool safe_browsing_enhanced_enabled = std::get<1>(params);
profile()->GetPrefs()->SetBoolean(prefs::kSafeBrowsingEnabled,
safe_browsing_enabled);
profile()->GetPrefs()->SetBoolean(prefs::kSafeBrowsingEnhanced,
safe_browsing_enhanced_enabled);
enterprise_reporting_private::ContextInfo info = GetContextInfo();
EXPECT_TRUE(info.browser_affiliation_ids.empty());
EXPECT_TRUE(info.profile_affiliation_ids.empty());
EXPECT_TRUE(info.on_file_attached_providers.empty());
EXPECT_TRUE(info.on_file_downloaded_providers.empty());
EXPECT_TRUE(info.on_bulk_data_entry_providers.empty());
EXPECT_EQ(enterprise_reporting_private::REALTIME_URL_CHECK_MODE_DISABLED,
info.realtime_url_check_mode);
EXPECT_TRUE(info.on_security_event_providers.empty());
EXPECT_EQ(version_info::GetVersionNumber(), info.browser_version);
if (safe_browsing_enabled) {
if (safe_browsing_enhanced_enabled)
EXPECT_EQ(enterprise_reporting_private::SAFE_BROWSING_LEVEL_ENHANCED,
info.safe_browsing_protection_level);
else
EXPECT_EQ(enterprise_reporting_private::SAFE_BROWSING_LEVEL_STANDARD,
info.safe_browsing_protection_level);
} else {
EXPECT_EQ(enterprise_reporting_private::SAFE_BROWSING_LEVEL_DISABLED,
info.safe_browsing_protection_level);
}
EXPECT_EQ(BuiltInDnsClientPlatformDefault(),
info.built_in_dns_client_enabled);
EXPECT_EQ(
enterprise_reporting_private::PASSWORD_PROTECTION_TRIGGER_POLICY_UNSET,
info.password_protection_warning_trigger);
ExpectDefaultThirdPartyBlockingEnabled(info);
}
INSTANTIATE_TEST_SUITE_P(
,
EnterpriseReportingPrivateGetContextInfoSafeBrowsingTest,
testing::Values(std::make_tuple(false, false),
std::make_tuple(true, false),
std::make_tuple(true, true)));
class EnterpriseReportingPrivateGetContextInfoBuiltInDnsClientTest
: public EnterpriseReportingPrivateGetContextInfoTest,
public testing::WithParamInterface<bool> {};
TEST_P(EnterpriseReportingPrivateGetContextInfoBuiltInDnsClientTest, Test) {
bool policyValue = GetParam();
g_browser_process->local_state()->SetBoolean(prefs::kBuiltInDnsClientEnabled,
policyValue);
enterprise_reporting_private::ContextInfo info = GetContextInfo();
EXPECT_TRUE(info.browser_affiliation_ids.empty());
EXPECT_TRUE(info.profile_affiliation_ids.empty());
EXPECT_TRUE(info.on_file_attached_providers.empty());
EXPECT_TRUE(info.on_file_downloaded_providers.empty());
EXPECT_TRUE(info.on_bulk_data_entry_providers.empty());
EXPECT_EQ(enterprise_reporting_private::REALTIME_URL_CHECK_MODE_DISABLED,
info.realtime_url_check_mode);
EXPECT_TRUE(info.on_security_event_providers.empty());
EXPECT_EQ(version_info::GetVersionNumber(), info.browser_version);
EXPECT_EQ(enterprise_reporting_private::SAFE_BROWSING_LEVEL_STANDARD,
info.safe_browsing_protection_level);
EXPECT_EQ(policyValue, info.built_in_dns_client_enabled);
EXPECT_EQ(
enterprise_reporting_private::PASSWORD_PROTECTION_TRIGGER_POLICY_UNSET,
info.password_protection_warning_trigger);
ExpectDefaultThirdPartyBlockingEnabled(info);
}
INSTANTIATE_TEST_SUITE_P(
,
EnterpriseReportingPrivateGetContextInfoBuiltInDnsClientTest,
testing::Bool());
class EnterpriseReportingPrivateGetContextPasswordProtectionWarningTrigger
: public EnterpriseReportingPrivateGetContextInfoTest,
public testing::WithParamInterface<
enterprise_reporting_private::PasswordProtectionTrigger> {
public:
safe_browsing::PasswordProtectionTrigger MapPasswordProtectionTriggerToPolicy(
enterprise_reporting_private::PasswordProtectionTrigger enumValue) {
switch (enumValue) {
case enterprise_reporting_private::
PASSWORD_PROTECTION_TRIGGER_PASSWORD_PROTECTION_OFF:
return safe_browsing::PASSWORD_PROTECTION_OFF;
case enterprise_reporting_private::
PASSWORD_PROTECTION_TRIGGER_PASSWORD_REUSE:
return safe_browsing::PASSWORD_REUSE;
case enterprise_reporting_private::
PASSWORD_PROTECTION_TRIGGER_PHISHING_REUSE:
return safe_browsing::PHISHING_REUSE;
default:
NOTREACHED();
return safe_browsing::PASSWORD_PROTECTION_TRIGGER_MAX;
}
}
};
TEST_P(EnterpriseReportingPrivateGetContextPasswordProtectionWarningTrigger,
Test) {
enterprise_reporting_private::PasswordProtectionTrigger passwordTriggerValue =
GetParam();
profile()->GetPrefs()->SetInteger(
prefs::kPasswordProtectionWarningTrigger,
MapPasswordProtectionTriggerToPolicy(passwordTriggerValue));
enterprise_reporting_private::ContextInfo info = GetContextInfo();
EXPECT_TRUE(info.browser_affiliation_ids.empty());
EXPECT_TRUE(info.profile_affiliation_ids.empty());
EXPECT_TRUE(info.on_file_attached_providers.empty());
EXPECT_TRUE(info.on_file_downloaded_providers.empty());
EXPECT_TRUE(info.on_bulk_data_entry_providers.empty());
EXPECT_EQ(enterprise_reporting_private::REALTIME_URL_CHECK_MODE_DISABLED,
info.realtime_url_check_mode);
EXPECT_TRUE(info.on_security_event_providers.empty());
EXPECT_EQ(version_info::GetVersionNumber(), info.browser_version);
EXPECT_EQ(enterprise_reporting_private::SAFE_BROWSING_LEVEL_STANDARD,
info.safe_browsing_protection_level);
EXPECT_EQ(BuiltInDnsClientPlatformDefault(),
info.built_in_dns_client_enabled);
ExpectDefaultThirdPartyBlockingEnabled(info);
EXPECT_EQ(passwordTriggerValue, info.password_protection_warning_trigger);
}
INSTANTIATE_TEST_SUITE_P(
,
EnterpriseReportingPrivateGetContextPasswordProtectionWarningTrigger,
testing::Values(enterprise_reporting_private::
PASSWORD_PROTECTION_TRIGGER_PASSWORD_PROTECTION_OFF,
enterprise_reporting_private::
PASSWORD_PROTECTION_TRIGGER_PASSWORD_REUSE,
enterprise_reporting_private::
PASSWORD_PROTECTION_TRIGGER_PHISHING_REUSE));
#if defined(OS_LINUX)
class EnterpriseReportingPrivateGetContextOSFirewallLinuxTest
: public EnterpriseReportingPrivateGetContextInfoTest,
public testing::WithParamInterface<
enterprise_reporting_private::SettingValue> {
public:
void SetUp() override {
ExtensionApiUnittest::SetUp();
ASSERT_TRUE(fake_appdata_dir_.CreateUniqueTempDir());
file_path_ = fake_appdata_dir_.GetPath().Append("ufw.conf");
}
void ExpectDefaultPolicies(
const enterprise_reporting_private::ContextInfo& info) {
EXPECT_TRUE(info.browser_affiliation_ids.empty());
EXPECT_TRUE(info.profile_affiliation_ids.empty());
EXPECT_TRUE(info.on_file_attached_providers.empty());
EXPECT_TRUE(info.on_file_downloaded_providers.empty());
EXPECT_TRUE(info.on_bulk_data_entry_providers.empty());
EXPECT_EQ(enterprise_reporting_private::REALTIME_URL_CHECK_MODE_DISABLED,
info.realtime_url_check_mode);
EXPECT_TRUE(info.on_security_event_providers.empty());
EXPECT_EQ(version_info::GetVersionNumber(), info.browser_version);
EXPECT_EQ(enterprise_reporting_private::SAFE_BROWSING_LEVEL_STANDARD,
info.safe_browsing_protection_level);
EXPECT_EQ(BuiltInDnsClientPlatformDefault(),
info.built_in_dns_client_enabled);
EXPECT_EQ(
enterprise_reporting_private::PASSWORD_PROTECTION_TRIGGER_POLICY_UNSET,
info.password_protection_warning_trigger);
ExpectDefaultChromeCleanupEnabled(info);
EXPECT_FALSE(info.chrome_remote_desktop_app_blocked);
ExpectDefaultThirdPartyBlockingEnabled(info);
}
protected:
base::ScopedTempDir fake_appdata_dir_;
base::FilePath file_path_;
};
TEST_F(EnterpriseReportingPrivateGetContextOSFirewallLinuxTest,
NoFirewallFile) {
// Refer to a non existent firewall config file
enterprise_signals::ScopedUfwConfigPathForTesting scoped_path(
file_path_.value().c_str());
enterprise_reporting_private::ContextInfo info = GetContextInfo();
ExpectDefaultPolicies(info);
EXPECT_EQ(info.os_firewall,
enterprise_reporting_private::SETTING_VALUE_UNKNOWN);
}
TEST_F(EnterpriseReportingPrivateGetContextOSFirewallLinuxTest, NoEnabledKey) {
// Refer to a config file without the ENABLED=value key-value pair
base::WriteFile(file_path_,
"#comment1\n#comment2\nLOGLEVEL=yes\nTESTKEY=yes\n");
enterprise_signals::ScopedUfwConfigPathForTesting scoped_path(
file_path_.value().c_str());
enterprise_reporting_private::ContextInfo info = GetContextInfo();
ExpectDefaultPolicies(info);
EXPECT_EQ(info.os_firewall,
enterprise_reporting_private::SETTING_VALUE_UNKNOWN);
}
TEST_P(EnterpriseReportingPrivateGetContextOSFirewallLinuxTest, Test) {
enterprise_reporting_private::SettingValue os_firewall_value = GetParam();
switch (os_firewall_value) {
case enterprise_reporting_private::SETTING_VALUE_ENABLED:
// File format to test if comments, empty lines and strings containing the
// key are ignored
base::WriteFile(file_path_,
"#ENABLED=no\nrandomtextENABLED=no\n \nENABLED=yes\n");
break;
case enterprise_reporting_private::SETTING_VALUE_DISABLED:
base::WriteFile(file_path_,
"#ENABLED=yes\nENABLEDrandomtext=yes\n \nENABLED=no\n");
break;
case enterprise_reporting_private::SETTING_VALUE_UNKNOWN:
// File content to test a value that isn't yes or no
base::WriteFile(file_path_,
"#ENABLED=yes\nLOGLEVEL=yes\nENABLED=yesno\n");
break;
default:
NOTREACHED();
}
enterprise_signals::ScopedUfwConfigPathForTesting scoped_path(
file_path_.value().c_str());
enterprise_reporting_private::ContextInfo info = GetContextInfo();
ExpectDefaultPolicies(info);
EXPECT_EQ(info.os_firewall, os_firewall_value);
}
INSTANTIATE_TEST_SUITE_P(
,
EnterpriseReportingPrivateGetContextOSFirewallLinuxTest,
testing::Values(enterprise_reporting_private::SETTING_VALUE_ENABLED,
enterprise_reporting_private::SETTING_VALUE_DISABLED,
enterprise_reporting_private::SETTING_VALUE_UNKNOWN));
#endif // defined(OS_LINUX)
#if defined(OS_WIN)
class EnterpriseReportingPrivateGetContextInfoChromeCleanupTest
: public EnterpriseReportingPrivateGetContextInfoTest,
public testing::WithParamInterface<bool> {};
TEST_P(EnterpriseReportingPrivateGetContextInfoChromeCleanupTest, Test) {
bool policy_value = GetParam();
g_browser_process->local_state()->SetBoolean(prefs::kSwReporterEnabled,
policy_value);
enterprise_reporting_private::ContextInfo info = GetContextInfo();
EXPECT_TRUE(info.browser_affiliation_ids.empty());
EXPECT_TRUE(info.profile_affiliation_ids.empty());
EXPECT_TRUE(info.on_file_attached_providers.empty());
EXPECT_TRUE(info.on_file_downloaded_providers.empty());
EXPECT_TRUE(info.on_bulk_data_entry_providers.empty());
EXPECT_EQ(enterprise_reporting_private::REALTIME_URL_CHECK_MODE_DISABLED,
info.realtime_url_check_mode);
EXPECT_TRUE(info.on_security_event_providers.empty());
EXPECT_EQ(version_info::GetVersionNumber(), info.browser_version);
EXPECT_EQ(enterprise_reporting_private::SAFE_BROWSING_LEVEL_STANDARD,
info.safe_browsing_protection_level);
EXPECT_EQ(BuiltInDnsClientPlatformDefault(),
info.built_in_dns_client_enabled);
EXPECT_EQ(
enterprise_reporting_private::PASSWORD_PROTECTION_TRIGGER_POLICY_UNSET,
info.password_protection_warning_trigger);
ExpectDefaultThirdPartyBlockingEnabled(info);
EXPECT_EQ(policy_value, *info.chrome_cleanup_enabled);
}
INSTANTIATE_TEST_SUITE_P(
,
EnterpriseReportingPrivateGetContextInfoChromeCleanupTest,
testing::Bool());
#endif // defined(OS_WIN)
class EnterpriseReportingPrivateGetContextInfoChromeRemoteDesktopAppBlockedTest
: public EnterpriseReportingPrivateGetContextInfoTest,
public testing::WithParamInterface<const char*> {
public:
void SetURLBlockedPolicy(const std::string& url) {
base::Value blockList(base::Value::Type::LIST);
blockList.Append(base::Value(url));
profile()->GetPrefs()->Set(policy::policy_prefs::kUrlBlocklist,
std::move(blockList));
}
void SetURLAllowedPolicy(const std::string& url) {
base::Value allowList(base::Value::Type::LIST);
allowList.Append(base::Value(url));
profile()->GetPrefs()->Set(policy::policy_prefs::kUrlAllowlist,
std::move(allowList));
}
void ExpectDefaultPolicies(enterprise_reporting_private::ContextInfo& info) {
EXPECT_TRUE(info.browser_affiliation_ids.empty());
EXPECT_TRUE(info.profile_affiliation_ids.empty());
EXPECT_TRUE(info.on_file_attached_providers.empty());
EXPECT_TRUE(info.on_file_downloaded_providers.empty());
EXPECT_TRUE(info.on_bulk_data_entry_providers.empty());
EXPECT_EQ(enterprise_reporting_private::REALTIME_URL_CHECK_MODE_DISABLED,
info.realtime_url_check_mode);
EXPECT_TRUE(info.on_security_event_providers.empty());
EXPECT_EQ(version_info::GetVersionNumber(), info.browser_version);
EXPECT_EQ(enterprise_reporting_private::SAFE_BROWSING_LEVEL_STANDARD,
info.safe_browsing_protection_level);
EXPECT_EQ(BuiltInDnsClientPlatformDefault(),
info.built_in_dns_client_enabled);
EXPECT_EQ(
enterprise_reporting_private::PASSWORD_PROTECTION_TRIGGER_POLICY_UNSET,
info.password_protection_warning_trigger);
ExpectDefaultChromeCleanupEnabled(info);
ExpectDefaultThirdPartyBlockingEnabled(info);
}
};
TEST_P(
EnterpriseReportingPrivateGetContextInfoChromeRemoteDesktopAppBlockedTest,
BlockedURL) {
SetURLBlockedPolicy(GetParam());
enterprise_reporting_private::ContextInfo info = GetContextInfo();
ExpectDefaultPolicies(info);
EXPECT_TRUE(info.chrome_remote_desktop_app_blocked);
}
TEST_P(
EnterpriseReportingPrivateGetContextInfoChromeRemoteDesktopAppBlockedTest,
AllowedURL) {
SetURLAllowedPolicy(GetParam());
enterprise_reporting_private::ContextInfo info = GetContextInfo();
ExpectDefaultPolicies(info);
EXPECT_FALSE(info.chrome_remote_desktop_app_blocked);
}
TEST_P(
EnterpriseReportingPrivateGetContextInfoChromeRemoteDesktopAppBlockedTest,
BlockedAndAllowedURL) {
SetURLBlockedPolicy(GetParam());
SetURLAllowedPolicy(GetParam());
enterprise_reporting_private::ContextInfo info = GetContextInfo();
ExpectDefaultPolicies(info);
EXPECT_FALSE(info.chrome_remote_desktop_app_blocked);
}
INSTANTIATE_TEST_SUITE_P(
,
EnterpriseReportingPrivateGetContextInfoChromeRemoteDesktopAppBlockedTest,
testing::Values("https://remotedesktop.google.com",
"https://remotedesktop.corp.google.com",
"corp.google.com",
"google.com",
"https://*"));
#if defined(OS_WIN)
class EnterpriseReportingPrivateGetContextInfoOSFirewallTest
: public EnterpriseReportingPrivateGetContextInfoTest,
public testing::WithParamInterface<SettingValue> {
public:
EnterpriseReportingPrivateGetContextInfoOSFirewallTest()
: enabled_(VARIANT_TRUE) {}
protected:
void SetUp() override {
ExtensionApiUnittest::SetUp();
HRESULT hr = CoCreateInstance(CLSID_NetFwPolicy2, nullptr, CLSCTX_ALL,
IID_PPV_ARGS(&firewall_policy_));
EXPECT_FALSE(FAILED(hr));
long profile_types = 0;
hr = firewall_policy_->get_CurrentProfileTypes(&profile_types);
EXPECT_FALSE(FAILED(hr));
// Setting the firewall for each active profile
const NET_FW_PROFILE_TYPE2 kProfileTypes[] = {NET_FW_PROFILE2_PUBLIC,
NET_FW_PROFILE2_PRIVATE,
NET_FW_PROFILE2_DOMAIN};
for (size_t i = 0; i < base::size(kProfileTypes); ++i) {
if ((profile_types & kProfileTypes[i]) != 0) {
hr = firewall_policy_->get_FirewallEnabled(kProfileTypes[i], &enabled_);
EXPECT_FALSE(FAILED(hr));
active_profile_ = kProfileTypes[i];
hr = firewall_policy_->put_FirewallEnabled(
kProfileTypes[i], firewall_value_ == SettingValue::ENABLED
? VARIANT_TRUE
: VARIANT_FALSE);
EXPECT_FALSE(FAILED(hr));
break;
}
}
}
void TearDown() override {
// Resetting the firewall to its initial state
HRESULT hr =
firewall_policy_->put_FirewallEnabled(active_profile_, enabled_);
EXPECT_FALSE(FAILED(hr));
}
extensions::api::enterprise_reporting_private::SettingValue
ToInfoSettingValue(enterprise_signals::SettingValue value) {
switch (value) {
case SettingValue::DISABLED:
return extensions::api::enterprise_reporting_private::
SETTING_VALUE_DISABLED;
case SettingValue::ENABLED:
return extensions::api::enterprise_reporting_private::
SETTING_VALUE_ENABLED;
default:
NOTREACHED();
return extensions::api::enterprise_reporting_private::
SETTING_VALUE_UNKNOWN;
}
}
Microsoft::WRL::ComPtr<INetFwPolicy2> firewall_policy_;
SettingValue firewall_value_ = GetParam();
VARIANT_BOOL enabled_;
NET_FW_PROFILE_TYPE2 active_profile_;
};
TEST_P(EnterpriseReportingPrivateGetContextInfoOSFirewallTest, Test) {
enterprise_reporting_private::ContextInfo info = GetContextInfo();
EXPECT_TRUE(info.browser_affiliation_ids.empty());
EXPECT_TRUE(info.profile_affiliation_ids.empty());
EXPECT_TRUE(info.on_file_attached_providers.empty());
EXPECT_TRUE(info.on_file_downloaded_providers.empty());
EXPECT_TRUE(info.on_bulk_data_entry_providers.empty());
EXPECT_EQ(enterprise_reporting_private::REALTIME_URL_CHECK_MODE_DISABLED,
info.realtime_url_check_mode);
EXPECT_TRUE(info.on_security_event_providers.empty());
EXPECT_EQ(version_info::GetVersionNumber(), info.browser_version);
EXPECT_EQ(enterprise_reporting_private::SAFE_BROWSING_LEVEL_STANDARD,
info.safe_browsing_protection_level);
EXPECT_EQ(BuiltInDnsClientPlatformDefault(),
info.built_in_dns_client_enabled);
EXPECT_EQ(
enterprise_reporting_private::PASSWORD_PROTECTION_TRIGGER_POLICY_UNSET,
info.password_protection_warning_trigger);
ExpectDefaultChromeCleanupEnabled(info);
EXPECT_FALSE(info.chrome_remote_desktop_app_blocked);
ExpectDefaultThirdPartyBlockingEnabled(info);
EXPECT_EQ(ToInfoSettingValue(firewall_value_), info.os_firewall);
}
INSTANTIATE_TEST_SUITE_P(,
EnterpriseReportingPrivateGetContextInfoOSFirewallTest,
testing::Values(SettingValue::DISABLED,
SettingValue::ENABLED));
#endif // defined(OS_WIN)
class EnterpriseReportingPrivateGetContextInfoRealTimeURLCheckTest
: public EnterpriseReportingPrivateGetContextInfoTest,
public testing::WithParamInterface<bool> {
public:
EnterpriseReportingPrivateGetContextInfoRealTimeURLCheckTest() {
policy::SetDMTokenForTesting(
policy::DMToken::CreateValidTokenForTesting("fake-token"));
}
bool url_check_enabled() const { return GetParam(); }
};
INSTANTIATE_TEST_SUITE_P(
,
EnterpriseReportingPrivateGetContextInfoRealTimeURLCheckTest,
testing::Bool());
TEST_P(EnterpriseReportingPrivateGetContextInfoRealTimeURLCheckTest, Test) {
profile()->GetPrefs()->SetInteger(
prefs::kSafeBrowsingEnterpriseRealTimeUrlCheckMode,
url_check_enabled() ? safe_browsing::REAL_TIME_CHECK_FOR_MAINFRAME_ENABLED
: safe_browsing::REAL_TIME_CHECK_DISABLED);
profile()->GetPrefs()->SetInteger(
prefs::kSafeBrowsingEnterpriseRealTimeUrlCheckScope,
policy::POLICY_SCOPE_MACHINE);
enterprise_reporting_private::ContextInfo info = GetContextInfo();
if (url_check_enabled()) {
EXPECT_EQ(enterprise_reporting_private::
REALTIME_URL_CHECK_MODE_ENABLED_MAIN_FRAME,
info.realtime_url_check_mode);
} else {
EXPECT_EQ(enterprise_reporting_private::REALTIME_URL_CHECK_MODE_DISABLED,
info.realtime_url_check_mode);
}
EXPECT_TRUE(info.browser_affiliation_ids.empty());
EXPECT_TRUE(info.profile_affiliation_ids.empty());
EXPECT_TRUE(info.on_file_attached_providers.empty());
EXPECT_TRUE(info.on_file_downloaded_providers.empty());
EXPECT_TRUE(info.on_bulk_data_entry_providers.empty());
EXPECT_TRUE(info.on_security_event_providers.empty());
EXPECT_EQ(version_info::GetVersionNumber(), info.browser_version);
EXPECT_EQ(enterprise_reporting_private::SAFE_BROWSING_LEVEL_STANDARD,
info.safe_browsing_protection_level);
EXPECT_EQ(BuiltInDnsClientPlatformDefault(),
info.built_in_dns_client_enabled);
EXPECT_EQ(
enterprise_reporting_private::PASSWORD_PROTECTION_TRIGGER_POLICY_UNSET,
info.password_protection_warning_trigger);
ExpectDefaultThirdPartyBlockingEnabled(info);
}
} // namespace extensions
| bsd-3-clause |
suzlab/Autoware | ros/src/computing/planning/common/lib/openplanner/op_simu/src/glm.cpp | 67057 | /*
glm.c
Nate Robins, 1997, 2000
nate@pobox.com, http://www.pobox.com/~nate
Wavefront OBJ model file format reader/writer/manipulator.
Includes routines for generating smooth normals with
preservation of edges, welding redundant vertices & texture
coordinate generation (spheremap and planar projections) + more.
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "op_simu/glm.h"
namespace Graphics
{
#define T(x) (model->triangles[(x)])
/* _GLMnode: general purpose node */
typedef struct _GLMnode {
GLuint index;
GLboolean averaged;
struct _GLMnode* next;
} GLMnode;
/* glmMax: returns the maximum of two floats */
static GLfloat
glmMax(GLfloat a, GLfloat b)
{
if (b > a)
return b;
return a;
}
/* glmAbs: returns the absolute value of a float */
static GLfloat
glmAbs(GLfloat f)
{
if (f < 0)
return -f;
return f;
}
/* glmDot: compute the dot product of two vectors
*
* u - array of 3 GLfloats (GLfloat u[3])
* v - array of 3 GLfloats (GLfloat v[3])
*/
static GLfloat
glmDot(GLfloat* u, GLfloat* v)
{
assert(u); assert(v);
return u[0]*v[0] + u[1]*v[1] + u[2]*v[2];
}
/* glmCross: compute the cross product of two vectors
*
* u - array of 3 GLfloats (GLfloat u[3])
* v - array of 3 GLfloats (GLfloat v[3])
* n - array of 3 GLfloats (GLfloat n[3]) to return the cross product in
*/
static GLvoid
glmCross(GLfloat* u, GLfloat* v, GLfloat* n)
{
assert(u); assert(v); assert(n);
n[0] = u[1]*v[2] - u[2]*v[1];
n[1] = u[2]*v[0] - u[0]*v[2];
n[2] = u[0]*v[1] - u[1]*v[0];
}
/* glmNormalize: normalize a vector
*
* v - array of 3 GLfloats (GLfloat v[3]) to be normalized
*/
static GLvoid
glmNormalize(GLfloat* v)
{
GLfloat l;
assert(v);
l = (GLfloat)sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v[0] /= l;
v[1] /= l;
v[2] /= l;
}
/* glmEqual: compares two vectors and returns GL_TRUE if they are
* equal (within a certain threshold) or GL_FALSE if not. An epsilon
* that works fairly well is 0.000001.
*
* u - array of 3 GLfloats (GLfloat u[3])
* v - array of 3 GLfloats (GLfloat v[3])
*/
static GLboolean
glmEqual(GLfloat* u, GLfloat* v, GLfloat epsilon)
{
if (glmAbs(u[0] - v[0]) < epsilon &&
glmAbs(u[1] - v[1]) < epsilon &&
glmAbs(u[2] - v[2]) < epsilon)
{
return GL_TRUE;
}
return GL_FALSE;
}
/* glmWeldVectors: eliminate (weld) vectors that are within an
* epsilon of each other.
*
* vectors - array of GLfloat[3]'s to be welded
* numvectors - number of GLfloat[3]'s in vectors
* epsilon - maximum difference between vectors
*
*/
GLfloat*
glmWeldVectors(GLfloat* vectors, GLuint* numvectors, GLfloat epsilon)
{
GLfloat* copies;
GLuint copied;
GLuint i, j;
copies = (GLfloat*)malloc(sizeof(GLfloat) * 3 * (*numvectors + 1));
memcpy(copies, vectors, (sizeof(GLfloat) * 3 * (*numvectors + 1)));
copied = 1;
for (i = 1; i <= *numvectors; i++) {
for (j = 1; j <= copied; j++) {
if (glmEqual(&vectors[3 * i], &copies[3 * j], epsilon)) {
goto duplicate;
}
}
/* must not be any duplicates -- add to the copies array */
copies[3 * copied + 0] = vectors[3 * i + 0];
copies[3 * copied + 1] = vectors[3 * i + 1];
copies[3 * copied + 2] = vectors[3 * i + 2];
j = copied; /* pass this along for below */
copied++;
duplicate:
/* set the first component of this vector to point at the correct
index into the new copies array */
vectors[3 * i + 0] = (GLfloat)j;
}
*numvectors = copied-1;
return copies;
}
/* glmFindGroup: Find a group in the model */
GLMgroup*
glmFindGroup(GLMmodel* model, char* name)
{
GLMgroup* group;
assert(model);
group = model->groups;
while(group) {
if (!strcmp(name, group->name))
break;
group = group->next;
}
return group;
}
/* glmAddGroup: Add a group to the model */
GLMgroup*
glmAddGroup(GLMmodel* model, char* name)
{
GLMgroup* group;
group = glmFindGroup(model, name);
if (!group) {
group = (GLMgroup*)malloc(sizeof(GLMgroup));
group->name = strdup(name);
group->material = 0;
group->numtriangles = 0;
group->triangles = NULL;
group->next = model->groups;
model->groups = group;
model->numgroups++;
}
return group;
}
/* glmFindGroup: Find a material in the model */
GLuint
glmFindMaterial(GLMmodel* model, char* name)
{
GLuint i;
/* XXX doing a linear search on a string key'd list is pretty lame,
but it works and is fast enough for now. */
for (i = 0; i < model->nummaterials; i++) {
if (!strcmp(model->materials[i].name, name))
goto found;
}
/* didn't find the name, so print a warning and return the default
material (0). */
printf("glmFindMaterial(): can't find material \"%s\".\n", name);
i = 0;
found:
return i;
}
/* glmDirName: return the directory given a path
*
* path - filesystem path
*
* NOTE: the return value should be free'd.
*/
static char*
glmDirName(char* path)
{
char* dir;
char* s;
dir = strdup(path);
s = strrchr(dir, '/');
if (s)
s[1] = '\0';
else
dir[0] = '\0';
return dir;
}
/* glmReadMTL: read a wavefront material library file
*
* model - properly initialized GLMmodel structure
* name - name of the material library
*/
static GLvoid
glmReadMTL(GLMmodel* model, char* name)
{
FILE* file;
char* dir;
char* filename;
char buf[128];
GLuint nummaterials, i;
dir = glmDirName(model->pathname);
filename = (char*)malloc(sizeof(char) * (strlen(dir) + strlen(name) + 1));
strcpy(filename, dir);
strcat(filename, name);
free(dir);
file = fopen(filename, "r");
if (!file) {
fprintf(stderr, "glmReadMTL() failed: can't open material file \"%s\".\n",
filename);
exit(1);
}
free(filename);
/* count the number of materials in the file */
nummaterials = 1;
while(fscanf(file, "%s", buf) != EOF) {
switch(buf[0]) {
case '#': /* comment */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
case 'n': /* newmtl */
fgets(buf, sizeof(buf), file);
nummaterials++;
sscanf(buf, "%s %s", buf, buf);
break;
default:
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
}
}
rewind(file);
model->materials = (GLMmaterial*)malloc(sizeof(GLMmaterial) * nummaterials);
model->nummaterials = nummaterials;
/* set the default material */
for (i = 0; i < nummaterials; i++) {
model->materials[i].name = NULL;
model->materials[i].shininess = 65.0;
model->materials[i].diffuse[0] = 0.8;
model->materials[i].diffuse[1] = 0.8;
model->materials[i].diffuse[2] = 0.8;
model->materials[i].diffuse[3] = 1.0;
model->materials[i].ambient[0] = 0.2;
model->materials[i].ambient[1] = 0.2;
model->materials[i].ambient[2] = 0.2;
model->materials[i].ambient[3] = 1.0;
model->materials[i].specular[0] = 0.0;
model->materials[i].specular[1] = 0.0;
model->materials[i].specular[2] = 0.0;
model->materials[i].specular[3] = 1.0;
}
model->materials[0].name = strdup("default");
/* now, read in the data */
nummaterials = 0;
while(fscanf(file, "%s", buf) != EOF) {
switch(buf[0]) {
case '#': /* comment */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
case 'n': /* newmtl */
fgets(buf, sizeof(buf), file);
sscanf(buf, "%s %s", buf, buf);
nummaterials++;
model->materials[nummaterials].name = strdup(buf);
break;
case 'N':
fscanf(file, "%f", &model->materials[nummaterials].shininess);
/* wavefront shininess is from [0, 1000], so scale for OpenGL */
model->materials[nummaterials].shininess /= 1000.0;
model->materials[nummaterials].shininess *= 128.0;
break;
case 'K':
switch(buf[1]) {
case 'd':
fscanf(file, "%f %f %f",
&model->materials[nummaterials].diffuse[0],
&model->materials[nummaterials].diffuse[1],
&model->materials[nummaterials].diffuse[2]);
break;
case 's':
fscanf(file, "%f %f %f",
&model->materials[nummaterials].specular[0],
&model->materials[nummaterials].specular[1],
&model->materials[nummaterials].specular[2]);
break;
case 'a':
fscanf(file, "%f %f %f",
&model->materials[nummaterials].ambient[0],
&model->materials[nummaterials].ambient[1],
&model->materials[nummaterials].ambient[2]);
break;
default:
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
}
break;
default:
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
}
}
}
/* glmWriteMTL: write a wavefront material library file
*
* model - properly initialized GLMmodel structure
* modelpath - pathname of the model being written
* mtllibname - name of the material library to be written
*/
static GLvoid glmWriteMTL(GLMmodel* model, char* modelpath, char* mtllibname)
{
FILE* file;
char* dir;
char* filename;
GLMmaterial* material;
GLuint i;
dir = glmDirName(modelpath);
filename = (char*)malloc(sizeof(char) * (strlen(dir)+strlen(mtllibname)));
strcpy(filename, dir);
strcat(filename, mtllibname);
free(dir);
/* open the file */
file = fopen(filename, "w");
if (!file) {
fprintf(stderr, "glmWriteMTL() failed: can't open file \"%s\".\n",
filename);
exit(1);
}
// free(filename);
/* spit out a header */
fprintf(file, "# \n");
fprintf(file, "# Wavefront MTL generated by GLM library\n");
fprintf(file, "# \n");
fprintf(file, "# GLM library\n");
fprintf(file, "# Nate Robins\n");
fprintf(file, "# ndr@pobox.com\n");
fprintf(file, "# http://www.pobox.com/~ndr\n");
fprintf(file, "# \n\n");
for (i = 0; i < model->nummaterials; i++) {
material = &model->materials[i];
fprintf(file, "newmtl %s\n", material->name);
fprintf(file, "Ka %f %f %f\n",
material->ambient[0], material->ambient[1], material->ambient[2]);
fprintf(file, "Kd %f %f %f\n",
material->diffuse[0], material->diffuse[1], material->diffuse[2]);
fprintf(file, "Ks %f %f %f\n",
material->specular[0],material->specular[1],material->specular[2]);
fprintf(file, "Ns %f\n", material->shininess / 128.0 * 1000.0);
fprintf(file, "\n");
}
}
/* glmFirstPass: first pass at a Wavefront OBJ file that gets all the
* statistics of the model (such as #vertices, #normals, etc)
*
* model - properly initialized GLMmodel structure
* file - (fopen'd) file descriptor
*/
static GLvoid glmFirstPass(GLMmodel* model, FILE* file)
{
GLuint numvertices; /* number of vertices in model */
GLuint numnormals; /* number of normals in model */
GLuint numtexcoords; /* number of texcoords in model */
GLuint numtriangles; /* number of triangles in model */
GLMgroup* group; /* current group */
int v, n, t;
char buf[128];
/* make a default group */
group = glmAddGroup(model, (char*) "default");
numvertices = numnormals = numtexcoords = numtriangles = 0;
while(fscanf(file, "%s", buf) != EOF) {
switch(buf[0]) {
case '#': /* comment */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
case 'v': /* v, vn, vt */
switch(buf[1]) {
case '\0': /* vertex */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
numvertices++;
break;
case 'n': /* normal */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
numnormals++;
break;
case 't': /* texcoord */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
numtexcoords++;
break;
default:
printf("glmFirstPass(): Unknown token \"%s\".\n", buf);
exit(1);
break;
}
break;
case 'm':
fgets(buf, sizeof(buf), file);
sscanf(buf, "%s %s", buf, buf);
model->mtllibname = strdup(buf);
glmReadMTL(model, buf);
break;
case 'u':
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
case 'g': /* group */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
#if SINGLE_STRING_GROUP_NAMES
sscanf(buf, "%s", buf);
#else
buf[strlen(buf)-1] = '\0'; /* nuke '\n' */
#endif
group = glmAddGroup(model, buf);
break;
case 'f': /* face */
v = n = t = 0;
fscanf(file, "%s", buf);
/* can be one of %d, %d//%d, %d/%d, %d/%d/%d %d//%d */
if (strstr(buf, "//")) {
/* v//n */
sscanf(buf, "%d//%d", &v, &n);
fscanf(file, "%d//%d", &v, &n);
fscanf(file, "%d//%d", &v, &n);
numtriangles++;
group->numtriangles++;
while(fscanf(file, "%d//%d", &v, &n) > 0) {
numtriangles++;
group->numtriangles++;
}
} else if (sscanf(buf, "%d/%d/%d", &v, &t, &n) == 3) {
/* v/t/n */
fscanf(file, "%d/%d/%d", &v, &t, &n);
fscanf(file, "%d/%d/%d", &v, &t, &n);
numtriangles++;
group->numtriangles++;
while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0) {
numtriangles++;
group->numtriangles++;
}
} else if (sscanf(buf, "%d/%d", &v, &t) == 2) {
/* v/t */
fscanf(file, "%d/%d", &v, &t);
fscanf(file, "%d/%d", &v, &t);
numtriangles++;
group->numtriangles++;
while(fscanf(file, "%d/%d", &v, &t) > 0) {
numtriangles++;
group->numtriangles++;
}
} else {
/* v */
fscanf(file, "%d", &v);
fscanf(file, "%d", &v);
numtriangles++;
group->numtriangles++;
while(fscanf(file, "%d", &v) > 0) {
numtriangles++;
group->numtriangles++;
}
}
break;
default:
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
}
}
/* set the stats in the model structure */
model->numvertices = numvertices;
model->numnormals = numnormals;
model->numtexcoords = numtexcoords;
model->numtriangles = numtriangles;
/* allocate memory for the triangles in each group */
group = model->groups;
while(group) {
group->triangles = (GLuint*)malloc(sizeof(GLuint) * group->numtriangles);
group->numtriangles = 0;
group = group->next;
}
}
/* glmSecondPass: second pass at a Wavefront OBJ file that gets all
* the data.
*
* model - properly initialized GLMmodel structure
* file - (fopen'd) file descriptor
*/
static GLvoid
glmSecondPass(GLMmodel* model, FILE* file)
{
GLuint numvertices; /* number of vertices in model */
GLuint numnormals; /* number of normals in model */
GLuint numtexcoords; /* number of texcoords in model */
GLuint numtriangles; /* number of triangles in model */
GLfloat* vertices; /* array of vertices */
GLfloat* normals; /* array of normals */
GLfloat* texcoords; /* array of texture coordinates */
GLMgroup* group; /* current group pointer */
GLuint material; /* current material */
int v, n, t;
char buf[128];
/* set the pointer shortcuts */
vertices = model->vertices;
normals = model->normals;
texcoords = model->texcoords;
group = model->groups;
/* on the second pass through the file, read all the data into the
allocated arrays */
numvertices = numnormals = numtexcoords = 1;
numtriangles = 0;
material = 0;
while(fscanf(file, "%s", buf) != EOF) {
switch(buf[0]) {
case '#': /* comment */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
case 'v': /* v, vn, vt */
switch(buf[1]) {
case '\0': /* vertex */
fscanf(file, "%f %f %f",
&vertices[3 * numvertices + 0],
&vertices[3 * numvertices + 1],
&vertices[3 * numvertices + 2]);
numvertices++;
break;
case 'n': /* normal */
fscanf(file, "%f %f %f",
&normals[3 * numnormals + 0],
&normals[3 * numnormals + 1],
&normals[3 * numnormals + 2]);
numnormals++;
break;
case 't': /* texcoord */
fscanf(file, "%f %f",
&texcoords[2 * numtexcoords + 0],
&texcoords[2 * numtexcoords + 1]);
numtexcoords++;
break;
}
break;
case 'u':
fgets(buf, sizeof(buf), file);
sscanf(buf, "%s %s", buf, buf);
group->material = material = glmFindMaterial(model, buf);
break;
case 'g': /* group */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
#if SINGLE_STRING_GROUP_NAMES
sscanf(buf, "%s", buf);
#else
buf[strlen(buf)-1] = '\0'; /* nuke '\n' */
#endif
group = glmFindGroup(model, buf);
group->material = material;
break;
case 'f': /* face */
v = n = t = 0;
fscanf(file, "%s", buf);
/* can be one of %d, %d//%d, %d/%d, %d/%d/%d %d//%d */
if (strstr(buf, "//")) {
/* v//n */
sscanf(buf, "%d//%d", &v, &n);
T(numtriangles).vindices[0] = v < 0 ? v + numvertices : v;
T(numtriangles).nindices[0] = n < 0 ? n + numnormals : n;
fscanf(file, "%d//%d", &v, &n);
T(numtriangles).vindices[1] = v < 0 ? v + numvertices : v;
T(numtriangles).nindices[1] = n < 0 ? n + numnormals : n;
fscanf(file, "%d//%d", &v, &n);
T(numtriangles).vindices[2] = v < 0 ? v + numvertices : v;
T(numtriangles).nindices[2] = n < 0 ? n + numnormals : n;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
while(fscanf(file, "%d//%d", &v, &n) > 0) {
T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
T(numtriangles).nindices[0] = T(numtriangles-1).nindices[0];
T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
T(numtriangles).nindices[1] = T(numtriangles-1).nindices[2];
T(numtriangles).vindices[2] = v < 0 ? v + numvertices : v;
T(numtriangles).nindices[2] = n < 0 ? n + numnormals : n;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
}
} else if (sscanf(buf, "%d/%d/%d", &v, &t, &n) == 3) {
/* v/t/n */
T(numtriangles).vindices[0] = v < 0 ? v + numvertices : v;
T(numtriangles).tindices[0] = t < 0 ? t + numtexcoords : t;
T(numtriangles).nindices[0] = n < 0 ? n + numnormals : n;
fscanf(file, "%d/%d/%d", &v, &t, &n);
T(numtriangles).vindices[1] = v < 0 ? v + numvertices : v;
T(numtriangles).tindices[1] = t < 0 ? t + numtexcoords : t;
T(numtriangles).nindices[1] = n < 0 ? n + numnormals : n;
fscanf(file, "%d/%d/%d", &v, &t, &n);
T(numtriangles).vindices[2] = v < 0 ? v + numvertices : v;
T(numtriangles).tindices[2] = t < 0 ? t + numtexcoords : t;
T(numtriangles).nindices[2] = n < 0 ? n + numnormals : n;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0) {
T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
T(numtriangles).tindices[0] = T(numtriangles-1).tindices[0];
T(numtriangles).nindices[0] = T(numtriangles-1).nindices[0];
T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
T(numtriangles).tindices[1] = T(numtriangles-1).tindices[2];
T(numtriangles).nindices[1] = T(numtriangles-1).nindices[2];
T(numtriangles).vindices[2] = v < 0 ? v + numvertices : v;
T(numtriangles).tindices[2] = t < 0 ? t + numtexcoords : t;
T(numtriangles).nindices[2] = n < 0 ? n + numnormals : n;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
}
} else if (sscanf(buf, "%d/%d", &v, &t) == 2) {
/* v/t */
T(numtriangles).vindices[0] = v < 0 ? v + numvertices : v;
T(numtriangles).tindices[0] = t < 0 ? t + numtexcoords : t;
fscanf(file, "%d/%d", &v, &t);
T(numtriangles).vindices[1] = v < 0 ? v + numvertices : v;
T(numtriangles).tindices[1] = t < 0 ? t + numtexcoords : t;
fscanf(file, "%d/%d", &v, &t);
T(numtriangles).vindices[2] = v < 0 ? v + numvertices : v;
T(numtriangles).tindices[2] = t < 0 ? t + numtexcoords : t;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
while(fscanf(file, "%d/%d", &v, &t) > 0) {
T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
T(numtriangles).tindices[0] = T(numtriangles-1).tindices[0];
T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
T(numtriangles).tindices[1] = T(numtriangles-1).tindices[2];
T(numtriangles).vindices[2] = v < 0 ? v + numvertices : v;
T(numtriangles).tindices[2] = t < 0 ? t + numtexcoords : t;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
}
} else {
/* v */
sscanf(buf, "%d", &v);
T(numtriangles).vindices[0] = v < 0 ? v + numvertices : v;
fscanf(file, "%d", &v);
T(numtriangles).vindices[1] = v < 0 ? v + numvertices : v;
fscanf(file, "%d", &v);
T(numtriangles).vindices[2] = v < 0 ? v + numvertices : v;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
while(fscanf(file, "%d", &v) > 0) {
T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
T(numtriangles).vindices[2] = v < 0 ? v + numvertices : v;
group->triangles[group->numtriangles++] = numtriangles;
numtriangles++;
}
}
break;
default:
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
}
}
#if 0
/* announce the memory requirements */
printf(" Memory: %d bytes\n",
numvertices * 3*sizeof(GLfloat) +
numnormals * 3*sizeof(GLfloat) * (numnormals ? 1 : 0) +
numtexcoords * 3*sizeof(GLfloat) * (numtexcoords ? 1 : 0) +
numtriangles * sizeof(GLMtriangle));
#endif
}
/* public functions */
/* glmUnitize: "unitize" a model by translating it to the origin and
* scaling it to fit in a unit cube around the origin. Returns the
* scalefactor used.
*
* model - properly initialized GLMmodel structure
*/
GLfloat
glmUnitize(GLMmodel* model)
{
GLuint i;
GLfloat maxx, minx, maxy, miny, maxz, minz;
GLfloat cx, cy, cz, w, h, d;
GLfloat scale;
assert(model);
assert(model->vertices);
/* get the max/mins */
maxx = minx = model->vertices[3 + 0];
maxy = miny = model->vertices[3 + 1];
maxz = minz = model->vertices[3 + 2];
for (i = 1; i <= model->numvertices; i++) {
if (maxx < model->vertices[3 * i + 0])
maxx = model->vertices[3 * i + 0];
if (minx > model->vertices[3 * i + 0])
minx = model->vertices[3 * i + 0];
if (maxy < model->vertices[3 * i + 1])
maxy = model->vertices[3 * i + 1];
if (miny > model->vertices[3 * i + 1])
miny = model->vertices[3 * i + 1];
if (maxz < model->vertices[3 * i + 2])
maxz = model->vertices[3 * i + 2];
if (minz > model->vertices[3 * i + 2])
minz = model->vertices[3 * i + 2];
}
/* calculate model width, height, and depth */
w = glmAbs(maxx) + glmAbs(minx);
h = glmAbs(maxy) + glmAbs(miny);
d = glmAbs(maxz) + glmAbs(minz);
/* calculate center of the model */
cx = (maxx + minx) / 2.0;
cy = (maxy + miny) / 2.0;
cz = (maxz + minz) / 2.0;
/* calculate unitizing scale factor */
scale = 2.0 / glmMax(glmMax(w, h), d);
/* translate around center then scale */
for (i = 1; i <= model->numvertices; i++) {
model->vertices[3 * i + 0] -= cx;
model->vertices[3 * i + 1] -= cy;
model->vertices[3 * i + 2] -= cz;
model->vertices[3 * i + 0] *= scale;
model->vertices[3 * i + 1] *= scale;
model->vertices[3 * i + 2] *= scale;
}
return scale;
}
/* glmDimensions: Calculates the dimensions (width, height, depth) of
* a model.
*
* model - initialized GLMmodel structure
* dimensions - array of 3 GLfloats (GLfloat dimensions[3])
*/
GLvoid
glmDimensions(GLMmodel* model, GLfloat* dimensions)
{
GLuint i;
GLfloat maxx, minx, maxy, miny, maxz, minz;
assert(model);
assert(model->vertices);
assert(dimensions);
/* get the max/mins */
maxx = minx = model->vertices[3 + 0];
maxy = miny = model->vertices[3 + 1];
maxz = minz = model->vertices[3 + 2];
for (i = 1; i <= model->numvertices; i++) {
if (maxx < model->vertices[3 * i + 0])
maxx = model->vertices[3 * i + 0];
if (minx > model->vertices[3 * i + 0])
minx = model->vertices[3 * i + 0];
if (maxy < model->vertices[3 * i + 1])
maxy = model->vertices[3 * i + 1];
if (miny > model->vertices[3 * i + 1])
miny = model->vertices[3 * i + 1];
if (maxz < model->vertices[3 * i + 2])
maxz = model->vertices[3 * i + 2];
if (minz > model->vertices[3 * i + 2])
minz = model->vertices[3 * i + 2];
}
/* calculate model width, height, and depth */
dimensions[0] = glmAbs(maxx) + glmAbs(minx);
dimensions[1] = glmAbs(maxy) + glmAbs(miny);
dimensions[2] = glmAbs(maxz) + glmAbs(minz);
}
/* glmScale: Scales a model by a given amount.
*
* model - properly initialized GLMmodel structure
* scale - scalefactor (0.5 = half as large, 2.0 = twice as large)
*/
GLvoid
glmScale(GLMmodel* model, GLfloat scale)
{
GLuint i;
for (i = 1; i <= model->numvertices; i++) {
model->vertices[3 * i + 0] *= scale;
model->vertices[3 * i + 1] *= scale;
model->vertices[3 * i + 2] *= scale;
}
}
/* glmReverseWinding: Reverse the polygon winding for all polygons in
* this model. Default winding is counter-clockwise. Also changes
* the direction of the normals.
*
* model - properly initialized GLMmodel structure
*/
GLvoid
glmReverseWinding(GLMmodel* model)
{
GLuint i, swap;
assert(model);
for (i = 0; i < model->numtriangles; i++) {
swap = T(i).vindices[0];
T(i).vindices[0] = T(i).vindices[2];
T(i).vindices[2] = swap;
if (model->numnormals) {
swap = T(i).nindices[0];
T(i).nindices[0] = T(i).nindices[2];
T(i).nindices[2] = swap;
}
if (model->numtexcoords) {
swap = T(i).tindices[0];
T(i).tindices[0] = T(i).tindices[2];
T(i).tindices[2] = swap;
}
}
/* reverse facet normals */
for (i = 1; i <= model->numfacetnorms; i++) {
model->facetnorms[3 * i + 0] = -model->facetnorms[3 * i + 0];
model->facetnorms[3 * i + 1] = -model->facetnorms[3 * i + 1];
model->facetnorms[3 * i + 2] = -model->facetnorms[3 * i + 2];
}
/* reverse vertex normals */
for (i = 1; i <= model->numnormals; i++) {
model->normals[3 * i + 0] = -model->normals[3 * i + 0];
model->normals[3 * i + 1] = -model->normals[3 * i + 1];
model->normals[3 * i + 2] = -model->normals[3 * i + 2];
}
}
/* glmFacetNormals: Generates facet normals for a model (by taking the
* cross product of the two vectors derived from the sides of each
* triangle). Assumes a counter-clockwise winding.
*
* model - initialized GLMmodel structure
*/
GLvoid
glmFacetNormals(GLMmodel* model)
{
GLuint i;
GLfloat u[3];
GLfloat v[3];
assert(model);
assert(model->vertices);
/* clobber any old facetnormals */
if (model->facetnorms)
free(model->facetnorms);
/* allocate memory for the new facet normals */
model->numfacetnorms = model->numtriangles;
model->facetnorms = (GLfloat*)malloc(sizeof(GLfloat) *
3 * (model->numfacetnorms + 1));
for (i = 0; i < model->numtriangles; i++) {
model->triangles[i].findex = i+1;
u[0] = model->vertices[3 * T(i).vindices[1] + 0] -
model->vertices[3 * T(i).vindices[0] + 0];
u[1] = model->vertices[3 * T(i).vindices[1] + 1] -
model->vertices[3 * T(i).vindices[0] + 1];
u[2] = model->vertices[3 * T(i).vindices[1] + 2] -
model->vertices[3 * T(i).vindices[0] + 2];
v[0] = model->vertices[3 * T(i).vindices[2] + 0] -
model->vertices[3 * T(i).vindices[0] + 0];
v[1] = model->vertices[3 * T(i).vindices[2] + 1] -
model->vertices[3 * T(i).vindices[0] + 1];
v[2] = model->vertices[3 * T(i).vindices[2] + 2] -
model->vertices[3 * T(i).vindices[0] + 2];
glmCross(u, v, &model->facetnorms[3 * (i+1)]);
glmNormalize(&model->facetnorms[3 * (i+1)]);
}
}
/* glmVertexNormals: Generates smooth vertex normals for a model.
* First builds a list of all the triangles each vertex is in. Then
* loops through each vertex in the the list averaging all the facet
* normals of the triangles each vertex is in. Finally, sets the
* normal index in the triangle for the vertex to the generated smooth
* normal. If the dot product of a facet normal and the facet normal
* associated with the first triangle in the list of triangles the
* current vertex is in is greater than the cosine of the angle
* parameter to the function, that facet normal is not added into the
* average normal calculation and the corresponding vertex is given
* the facet normal. This tends to preserve hard edges. The angle to
* use depends on the model, but 90 degrees is usually a good start.
*
* model - initialized GLMmodel structure
* angle - maximum angle (in degrees) to smooth across
*/
GLvoid
glmVertexNormals(GLMmodel* model, GLfloat angle)
{
GLMnode* node;
GLMnode* tail;
GLMnode** members;
GLfloat* normals;
GLuint numnormals;
GLfloat average[3];
GLfloat dot, cos_angle;
GLuint i, avg;
assert(model);
assert(model->facetnorms);
/* calculate the cosine of the angle (in degrees) */
cos_angle = cos(angle * M_PI / 180.0);
/* nuke any previous normals */
if (model->normals)
free(model->normals);
/* allocate space for new normals */
model->numnormals = model->numtriangles * 3; /* 3 normals per triangle */
model->normals = (GLfloat*)malloc(sizeof(GLfloat)* 3* (model->numnormals+1));
/* allocate a structure that will hold a linked list of triangle
indices for each vertex */
members = (GLMnode**)malloc(sizeof(GLMnode*) * (model->numvertices + 1));
for (i = 1; i <= model->numvertices; i++)
members[i] = NULL;
/* for every triangle, create a node for each vertex in it */
for (i = 0; i < model->numtriangles; i++) {
node = (GLMnode*)malloc(sizeof(GLMnode));
node->index = i;
node->next = members[T(i).vindices[0]];
members[T(i).vindices[0]] = node;
node = (GLMnode*)malloc(sizeof(GLMnode));
node->index = i;
node->next = members[T(i).vindices[1]];
members[T(i).vindices[1]] = node;
node = (GLMnode*)malloc(sizeof(GLMnode));
node->index = i;
node->next = members[T(i).vindices[2]];
members[T(i).vindices[2]] = node;
}
/* calculate the average normal for each vertex */
numnormals = 1;
for (i = 1; i <= model->numvertices; i++) {
/* calculate an average normal for this vertex by averaging the
facet normal of every triangle this vertex is in */
node = members[i];
if (!node)
fprintf(stderr, "glmVertexNormals(): vertex w/o a triangle\n");
average[0] = 0.0; average[1] = 0.0; average[2] = 0.0;
avg = 0;
while (node) {
/* only average if the dot product of the angle between the two
facet normals is greater than the cosine of the threshold
angle -- or, said another way, the angle between the two
facet normals is less than (or equal to) the threshold angle */
dot = glmDot(&model->facetnorms[3 * T(node->index).findex],
&model->facetnorms[3 * T(members[i]->index).findex]);
if (dot > cos_angle) {
node->averaged = GL_TRUE;
average[0] += model->facetnorms[3 * T(node->index).findex + 0];
average[1] += model->facetnorms[3 * T(node->index).findex + 1];
average[2] += model->facetnorms[3 * T(node->index).findex + 2];
avg = 1; /* we averaged at least one normal! */
} else {
node->averaged = GL_FALSE;
}
node = node->next;
}
if (avg) {
/* normalize the averaged normal */
glmNormalize(average);
/* add the normal to the vertex normals list */
model->normals[3 * numnormals + 0] = average[0];
model->normals[3 * numnormals + 1] = average[1];
model->normals[3 * numnormals + 2] = average[2];
avg = numnormals;
numnormals++;
}
/* set the normal of this vertex in each triangle it is in */
node = members[i];
while (node) {
if (node->averaged) {
/* if this node was averaged, use the average normal */
if (T(node->index).vindices[0] == i)
T(node->index).nindices[0] = avg;
else if (T(node->index).vindices[1] == i)
T(node->index).nindices[1] = avg;
else if (T(node->index).vindices[2] == i)
T(node->index).nindices[2] = avg;
} else {
/* if this node wasn't averaged, use the facet normal */
model->normals[3 * numnormals + 0] =
model->facetnorms[3 * T(node->index).findex + 0];
model->normals[3 * numnormals + 1] =
model->facetnorms[3 * T(node->index).findex + 1];
model->normals[3 * numnormals + 2] =
model->facetnorms[3 * T(node->index).findex + 2];
if (T(node->index).vindices[0] == i)
T(node->index).nindices[0] = numnormals;
else if (T(node->index).vindices[1] == i)
T(node->index).nindices[1] = numnormals;
else if (T(node->index).vindices[2] == i)
T(node->index).nindices[2] = numnormals;
numnormals++;
}
node = node->next;
}
}
model->numnormals = numnormals - 1;
/* free the member information */
for (i = 1; i <= model->numvertices; i++) {
node = members[i];
while (node) {
tail = node;
node = node->next;
free(tail);
}
}
free(members);
/* pack the normals array (we previously allocated the maximum
number of normals that could possibly be created (numtriangles *
3), so get rid of some of them (usually alot unless none of the
facet normals were averaged)) */
normals = model->normals;
model->normals = (GLfloat*)malloc(sizeof(GLfloat)* 3* (model->numnormals+1));
for (i = 1; i <= model->numnormals; i++) {
model->normals[3 * i + 0] = normals[3 * i + 0];
model->normals[3 * i + 1] = normals[3 * i + 1];
model->normals[3 * i + 2] = normals[3 * i + 2];
}
free(normals);
}
/* glmLinearTexture: Generates texture coordinates according to a
* linear projection of the texture map. It generates these by
* linearly mapping the vertices onto a square.
*
* model - pointer to initialized GLMmodel structure
*/
GLvoid
glmLinearTexture(GLMmodel* model)
{
GLMgroup *group;
GLfloat dimensions[3];
GLfloat x, y, scalefactor;
GLuint i;
assert(model);
if (model->texcoords)
free(model->texcoords);
model->numtexcoords = model->numvertices;
model->texcoords=(GLfloat*)malloc(sizeof(GLfloat)*2*(model->numtexcoords+1));
glmDimensions(model, dimensions);
scalefactor = 2.0 /
glmAbs(glmMax(glmMax(dimensions[0], dimensions[1]), dimensions[2]));
/* do the calculations */
for(i = 1; i <= model->numvertices; i++) {
x = model->vertices[3 * i + 0] * scalefactor;
y = model->vertices[3 * i + 2] * scalefactor;
model->texcoords[2 * i + 0] = (x + 1.0) / 2.0;
model->texcoords[2 * i + 1] = (y + 1.0) / 2.0;
}
/* go through and put texture coordinate indices in all the triangles */
group = model->groups;
while(group) {
for(i = 0; i < group->numtriangles; i++) {
T(group->triangles[i]).tindices[0] = T(group->triangles[i]).vindices[0];
T(group->triangles[i]).tindices[1] = T(group->triangles[i]).vindices[1];
T(group->triangles[i]).tindices[2] = T(group->triangles[i]).vindices[2];
}
group = group->next;
}
#if 0
printf("glmLinearTexture(): generated %d linear texture coordinates\n",
model->numtexcoords);
#endif
}
/* glmSpheremapTexture: Generates texture coordinates according to a
* spherical projection of the texture map. Sometimes referred to as
* spheremap, or reflection map texture coordinates. It generates
* these by using the normal to calculate where that vertex would map
* onto a sphere. Since it is impossible to map something flat
* perfectly onto something spherical, there is distortion at the
* poles. This particular implementation causes the poles along the X
* axis to be distorted.
*
* model - pointer to initialized GLMmodel structure
*/
GLvoid
glmSpheremapTexture(GLMmodel* model)
{
GLMgroup* group;
GLfloat theta, phi, rho, x, y, z, r;
GLuint i;
assert(model);
assert(model->normals);
if (model->texcoords)
free(model->texcoords);
model->numtexcoords = model->numnormals;
model->texcoords=(GLfloat*)malloc(sizeof(GLfloat)*2*(model->numtexcoords+1));
for (i = 1; i <= model->numnormals; i++) {
z = model->normals[3 * i + 0]; /* re-arrange for pole distortion */
y = model->normals[3 * i + 1];
x = model->normals[3 * i + 2];
r = sqrt((x * x) + (y * y));
rho = sqrt((r * r) + (z * z));
if(r == 0.0) {
theta = 0.0;
phi = 0.0;
} else {
if(z == 0.0)
phi = 3.14159265 / 2.0;
else
phi = acos(z / rho);
if(y == 0.0)
theta = 3.141592365 / 2.0;
else
theta = asin(y / r) + (3.14159265 / 2.0);
}
model->texcoords[2 * i + 0] = theta / 3.14159265;
model->texcoords[2 * i + 1] = phi / 3.14159265;
}
/* go through and put texcoord indices in all the triangles */
group = model->groups;
while(group) {
for (i = 0; i < group->numtriangles; i++) {
T(group->triangles[i]).tindices[0] = T(group->triangles[i]).nindices[0];
T(group->triangles[i]).tindices[1] = T(group->triangles[i]).nindices[1];
T(group->triangles[i]).tindices[2] = T(group->triangles[i]).nindices[2];
}
group = group->next;
}
}
/* glmDelete: Deletes a GLMmodel structure.
*
* model - initialized GLMmodel structure
*/
GLvoid
glmDelete(GLMmodel* model)
{
GLMgroup* group;
GLuint i;
assert(model);
if (model->pathname) free(model->pathname);
if (model->mtllibname) free(model->mtllibname);
if (model->vertices) free(model->vertices);
if (model->normals) free(model->normals);
if (model->texcoords) free(model->texcoords);
if (model->facetnorms) free(model->facetnorms);
if (model->triangles) free(model->triangles);
if (model->materials) {
for (i = 0; i < model->nummaterials; i++)
free(model->materials[i].name);
}
free(model->materials);
while(model->groups) {
group = model->groups;
model->groups = model->groups->next;
free(group->name);
free(group->triangles);
free(group);
}
free(model);
}
/* glmReadOBJ: Reads a model description from a Wavefront .OBJ file.
* Returns a pointer to the created object which should be free'd with
* glmDelete().
*
* filename - name of the file containing the Wavefront .OBJ format data.
*/
GLMmodel*
glmReadOBJ(char* filename)
{
GLMmodel* model;
FILE* file;
/* open the file */
file = fopen(filename, "r");
if (!file) {
fprintf(stderr, "glmReadOBJ() failed: can't open data file \"%s\".\n",
filename);
exit(1);
}
/* allocate a new model */
model = (GLMmodel*)malloc(sizeof(GLMmodel));
model->pathname = strdup(filename);
model->mtllibname = NULL;
model->numvertices = 0;
model->vertices = NULL;
model->numnormals = 0;
model->normals = NULL;
model->numtexcoords = 0;
model->texcoords = NULL;
model->numfacetnorms = 0;
model->facetnorms = NULL;
model->numtriangles = 0;
model->triangles = NULL;
model->nummaterials = 0;
model->materials = NULL;
model->numgroups = 0;
model->groups = NULL;
model->position[0] = 0.0;
model->position[1] = 0.0;
model->position[2] = 0.0;
/* make a first pass through the file to get a count of the number
of vertices, normals, texcoords & triangles */
glmFirstPass(model, file);
/* allocate memory */
model->vertices = (GLfloat*)malloc(sizeof(GLfloat) *
3 * (model->numvertices + 1));
model->triangles = (GLMtriangle*)malloc(sizeof(GLMtriangle) *
model->numtriangles);
if (model->numnormals) {
model->normals = (GLfloat*)malloc(sizeof(GLfloat) *
3 * (model->numnormals + 1));
}
if (model->numtexcoords) {
model->texcoords = (GLfloat*)malloc(sizeof(GLfloat) *
2 * (model->numtexcoords + 1));
}
/* rewind to beginning of file and read in the data this pass */
rewind(file);
glmSecondPass(model, file);
/* close the file */
fclose(file);
// model->mtllibname = new char[strlen("HV_TestObj.mtl")];
// strcpy(model->mtllibname, "HV_TestObj.mtl");
// glmWriteOBJ(model, "HV_TestObj.obj", GLM_SMOOTH | GLM_MATERIAL);
return model;
}
/* glmWriteOBJ: Writes a model description in Wavefront .OBJ format to
* a file.
*
* model - initialized GLMmodel structure
* filename - name of the file to write the Wavefront .OBJ format data to
* mode - a bitwise or of values describing what is written to the file
* GLM_NONE - render with only vertices
* GLM_FLAT - render with facet normals
* GLM_SMOOTH - render with vertex normals
* GLM_TEXTURE - render with texture coords
* GLM_COLOR - render with colors (color material)
* GLM_MATERIAL - render with materials
* GLM_COLOR and GLM_MATERIAL should not both be specified.
* GLM_FLAT and GLM_SMOOTH should not both be specified.
*/
GLvoid
glmWriteOBJ(GLMmodel* model, char* filename, GLuint mode)
{
GLuint i;
FILE* file;
GLMgroup* group;
assert(model);
/* do a bit of warning */
if ((mode & GLM_FLAT) && !model->facetnorms) {
printf("glmWriteOBJ() warning: flat normal output requested "
"with no facet normals defined.\n");
mode &= ~GLM_FLAT;
}
if ((mode & GLM_SMOOTH) && !model->normals) {
printf("glmWriteOBJ() warning: smooth normal output requested "
"with no normals defined.\n");
mode &= ~GLM_SMOOTH;
}
if ((mode & GLM_TEXTURE) && !model->texcoords) {
printf("glmWriteOBJ() warning: texture coordinate output requested "
"with no texture coordinates defined.\n");
mode &= ~GLM_TEXTURE;
}
if ((mode & GLM_FLAT) && (mode & GLM_SMOOTH)) {
printf("glmWriteOBJ() warning: flat normal output requested "
"and smooth normal output requested (using smooth).\n");
mode &= ~GLM_FLAT;
}
if ((mode & GLM_COLOR) && !model->materials) {
printf("glmWriteOBJ() warning: color output requested "
"with no colors (materials) defined.\n");
mode &= ~GLM_COLOR;
}
if ((mode & GLM_MATERIAL) && !model->materials) {
printf("glmWriteOBJ() warning: material output requested "
"with no materials defined.\n");
mode &= ~GLM_MATERIAL;
}
if ((mode & GLM_COLOR) && (mode & GLM_MATERIAL)) {
printf("glmWriteOBJ() warning: color and material output requested "
"outputting only materials.\n");
mode &= ~GLM_COLOR;
}
/* open the file */
file = fopen(filename, "w");
if (!file) {
fprintf(stderr, "glmWriteOBJ() failed: can't open file \"%s\" to write.\n",
filename);
exit(1);
}
/* spit out a header */
fprintf(file, "# \n");
fprintf(file, "# Wavefront OBJ generated by GLM library\n");
fprintf(file, "# \n");
fprintf(file, "# GLM library\n");
fprintf(file, "# Nate Robins\n");
fprintf(file, "# ndr@pobox.com\n");
fprintf(file, "# http://www.pobox.com/~ndr\n");
fprintf(file, "# \n");
if ((mode & GLM_MATERIAL) && model->mtllibname) {
fprintf(file, "\nmtllib %s\n\n", model->mtllibname);
glmWriteMTL(model, filename, model->mtllibname);
}
/* spit out the vertices */
fprintf(file, "\n");
fprintf(file, "# %d vertices\n", model->numvertices);
for (i = 1; i <= model->numvertices; i++) {
fprintf(file, "v %f %f %f\n",
model->vertices[3 * i + 0],
model->vertices[3 * i + 1],
model->vertices[3 * i + 2]);
}
/* spit out the smooth/flat normals */
if (mode & GLM_SMOOTH) {
fprintf(file, "\n");
fprintf(file, "# %d normals\n", model->numnormals);
for (i = 1; i <= model->numnormals; i++) {
fprintf(file, "vn %f %f %f\n",
model->normals[3 * i + 0],
model->normals[3 * i + 1],
model->normals[3 * i + 2]);
}
} else if (mode & GLM_FLAT) {
fprintf(file, "\n");
fprintf(file, "# %d normals\n", model->numfacetnorms);
for (i = 1; i <= model->numnormals; i++) {
fprintf(file, "vn %f %f %f\n",
model->facetnorms[3 * i + 0],
model->facetnorms[3 * i + 1],
model->facetnorms[3 * i + 2]);
}
}
/* spit out the texture coordinates */
if (mode & GLM_TEXTURE) {
fprintf(file, "\n");
fprintf(file, "# %d texcoords\n", model->numtexcoords);
for (i = 1; i <= model->numtexcoords; i++) {
fprintf(file, "vt %f %f\n",
model->texcoords[2 * i + 0],
model->texcoords[2 * i + 1]);
}
}
fprintf(file, "\n");
fprintf(file, "# %d groups\n", model->numgroups);
fprintf(file, "# %d faces (triangles)\n", model->numtriangles);
fprintf(file, "\n");
group = model->groups;
while(group) {
fprintf(file, "g %s\n", group->name);
if (mode & GLM_MATERIAL)
fprintf(file, "usemtl %s\n", model->materials[group->material].name);
for (i = 0; i < group->numtriangles; i++) {
if ((mode & GLM_SMOOTH) && (mode & GLM_TEXTURE)) {
fprintf(file, "f %d/%d/%d %d/%d/%d %d/%d/%d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).tindices[0],
T(group->triangles[i]).nindices[0],
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).tindices[1],
T(group->triangles[i]).nindices[1],
T(group->triangles[i]).vindices[2],
T(group->triangles[i]).tindices[2],
T(group->triangles[i]).nindices[2]);
} else if ((mode & GLM_FLAT) && (mode & GLM_TEXTURE)) {
fprintf(file, "f %d/%d %d/%d %d/%d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).findex,
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).findex,
T(group->triangles[i]).vindices[2],
T(group->triangles[i]).findex);
} else if (mode & GLM_TEXTURE) {
fprintf(file, "f %d/%d %d/%d %d/%d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).tindices[0],
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).tindices[1],
T(group->triangles[i]).vindices[2],
T(group->triangles[i]).tindices[2]);
} else if (mode & GLM_SMOOTH) {
fprintf(file, "f %d//%d %d//%d %d//%d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).nindices[0],
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).nindices[1],
T(group->triangles[i]).vindices[2],
T(group->triangles[i]).nindices[2]);
} else if (mode & GLM_FLAT) {
fprintf(file, "f %d//%d %d//%d %d//%d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).findex,
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).findex,
T(group->triangles[i]).vindices[2],
T(group->triangles[i]).findex);
} else {
fprintf(file, "f %d %d %d\n",
T(group->triangles[i]).vindices[0],
T(group->triangles[i]).vindices[1],
T(group->triangles[i]).vindices[2]);
}
}
fprintf(file, "\n");
group = group->next;
}
fclose(file);
}
/* glmDraw: Renders the model to the current OpenGL context using the
* mode specified.
*
* model - initialized GLMmodel structure
* mode - a bitwise OR of values describing what is to be rendered.
* GLM_NONE - render with only vertices
* GLM_FLAT - render with facet normals
* GLM_SMOOTH - render with vertex normals
* GLM_TEXTURE - render with texture coords
* GLM_COLOR - render with colors (color material)
* GLM_MATERIAL - render with materials
* GLM_COLOR and GLM_MATERIAL should not both be specified.
* GLM_FLAT and GLM_SMOOTH should not both be specified.
*/
GLvoid
glmDraw(GLMmodel* model, GLuint mode)
{
static GLuint i;
static GLMgroup* group;
static GLMtriangle* triangle;
static GLMmaterial* material;
assert(model);
assert(model->vertices);
/* do a bit of warning */
if ((mode & GLM_FLAT) && !model->facetnorms) {
printf("glmDraw() warning: flat render mode requested "
"with no facet normals defined.\n");
mode &= ~GLM_FLAT;
}
if ((mode & GLM_SMOOTH) && !model->normals) {
printf("glmDraw() warning: smooth render mode requested "
"with no normals defined.\n");
mode &= ~GLM_SMOOTH;
}
if ((mode & GLM_TEXTURE) && !model->texcoords) {
printf("glmDraw() warning: texture render mode requested "
"with no texture coordinates defined.\n");
mode &= ~GLM_TEXTURE;
}
if ((mode & GLM_FLAT) && (mode & GLM_SMOOTH)) {
printf("glmDraw() warning: flat render mode requested "
"and smooth render mode requested (using smooth).\n");
mode &= ~GLM_FLAT;
}
if ((mode & GLM_COLOR) && !model->materials) {
printf("glmDraw() warning: color render mode requested "
"with no materials defined.\n");
mode &= ~GLM_COLOR;
}
if ((mode & GLM_MATERIAL) && !model->materials) {
printf("glmDraw() warning: material render mode requested "
"with no materials defined.\n");
mode &= ~GLM_MATERIAL;
}
if ((mode & GLM_COLOR) && (mode & GLM_MATERIAL)) {
printf("glmDraw() warning: color and material render mode requested "
"using only material mode.\n");
mode &= ~GLM_COLOR;
}
if (mode & GLM_COLOR)
glEnable(GL_COLOR_MATERIAL);
else if (mode & GLM_MATERIAL)
glDisable(GL_COLOR_MATERIAL);
/* perhaps this loop should be unrolled into material, color, flat,
smooth, etc. loops? since most cpu's have good branch prediction
schemes (and these branches will always go one way), probably
wouldn't gain too much? */
glRotatef(90,0.0, 0.0, 1.0);
glRotatef(90,1.0, 0.0, 0.0);
group = model->groups;
while (group) {
if (mode & GLM_MATERIAL) {
material = &model->materials[group->material];
material->ambient[0] = material->ambient[0]/2.0;
material->ambient[1] = material->ambient[1]/2.0;
material->ambient[2] = material->ambient[2]/2.0;
material->ambient[3] = material->ambient[3]/2.0;
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, material->ambient);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, material->diffuse);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, material->specular);
material->shininess = 0.75 * material->shininess;
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, material->shininess);
}
if (mode & GLM_COLOR) {
glColor3fv(material->diffuse);
}
glBegin(GL_TRIANGLES);
for (i = 0; i < group->numtriangles; i++) {
triangle = &T(group->triangles[i]);
if (mode & GLM_FLAT)
glNormal3fv(&model->facetnorms[3 * triangle->findex]);
if (mode & GLM_SMOOTH)
glNormal3fv(&model->normals[3 * triangle->nindices[0]]);
if (mode & GLM_TEXTURE)
glTexCoord2fv(&model->texcoords[2 * triangle->tindices[0]]);
glVertex3fv(&model->vertices[3 * triangle->vindices[0]]);
if (mode & GLM_SMOOTH)
glNormal3fv(&model->normals[3 * triangle->nindices[1]]);
if (mode & GLM_TEXTURE)
glTexCoord2fv(&model->texcoords[2 * triangle->tindices[1]]);
glVertex3fv(&model->vertices[3 * triangle->vindices[1]]);
if (mode & GLM_SMOOTH)
glNormal3fv(&model->normals[3 * triangle->nindices[2]]);
if (mode & GLM_TEXTURE)
glTexCoord2fv(&model->texcoords[2 * triangle->tindices[2]]);
glVertex3fv(&model->vertices[3 * triangle->vindices[2]]);
}
glEnd();
group = group->next;
}
}
/* glmList: Generates and returns a display list for the model using
* the mode specified.
*
* model - initialized GLMmodel structure
* mode - a bitwise OR of values describing what is to be rendered.
* GLM_NONE - render with only vertices
* GLM_FLAT - render with facet normals
* GLM_SMOOTH - render with vertex normals
* GLM_TEXTURE - render with texture coords
* GLM_COLOR - render with colors (color material)
* GLM_MATERIAL - render with materials
* GLM_COLOR and GLM_MATERIAL should not both be specified.
* GLM_FLAT and GLM_SMOOTH should not both be specified.
*/
GLuint
glmList(GLMmodel* model, GLuint mode)
{
GLuint list;
list = glGenLists(1);
glNewList(list, GL_COMPILE);
glmDraw(model, mode);
glEndList();
return list;
}
/* glmWeld: eliminate (weld) vectors that are within an epsilon of
* each other.
*
* model - initialized GLMmodel structure
* epsilon - maximum difference between vertices
* ( 0.00001 is a good start for a unitized model)
*
*/
GLvoid
glmWeld(GLMmodel* model, GLfloat epsilon)
{
GLfloat* vectors;
GLfloat* copies;
GLuint numvectors;
GLuint i;
/* vertices */
numvectors = model->numvertices;
vectors = model->vertices;
copies = glmWeldVectors(vectors, &numvectors, epsilon);
#if 0
printf("glmWeld(): %d redundant vertices.\n",
model->numvertices - numvectors - 1);
#endif
for (i = 0; i < model->numtriangles; i++) {
T(i).vindices[0] = (GLuint)vectors[3 * T(i).vindices[0] + 0];
T(i).vindices[1] = (GLuint)vectors[3 * T(i).vindices[1] + 0];
T(i).vindices[2] = (GLuint)vectors[3 * T(i).vindices[2] + 0];
}
/* free space for old vertices */
free(vectors);
/* allocate space for the new vertices */
model->numvertices = numvectors;
model->vertices = (GLfloat*)malloc(sizeof(GLfloat) *
3 * (model->numvertices + 1));
/* copy the optimized vertices into the actual vertex list */
for (i = 1; i <= model->numvertices; i++) {
model->vertices[3 * i + 0] = copies[3 * i + 0];
model->vertices[3 * i + 1] = copies[3 * i + 1];
model->vertices[3 * i + 2] = copies[3 * i + 2];
}
free(copies);
}
/* glmReadPPM: read a PPM raw (type P6) file. The PPM file has a header
* that should look something like:
*
* P6
* # comment
* width height max_value
* rgbrgbrgb...
*
* where "P6" is the magic cookie which identifies the file type and
* should be the only characters on the first line followed by a
* carriage return. Any line starting with a # mark will be treated
* as a comment and discarded. After the magic cookie, three integer
* values are expected: width, height of the image and the maximum
* value for a pixel (max_value must be < 256 for PPM raw files). The
* data section consists of width*height rgb triplets (one byte each)
* in binary format (i.e., such as that written with fwrite() or
* equivalent).
*
* The rgb data is returned as an array of unsigned chars (packed
* rgb). The malloc()'d memory should be free()'d by the caller. If
* an error occurs, an error message is sent to stderr and NULL is
* returned.
*
* filename - name of the .ppm file.
* width - will contain the width of the image on return.
* height - will contain the height of the image on return.
*
*/
GLubyte*
glmReadPPM(char* filename, int* width, int* height)
{
FILE* fp;
int i, w, h, d;
unsigned char* image;
char head[70]; /* max line <= 70 in PPM (per spec). */
fp = fopen(filename, "rb");
if (!fp) {
perror(filename);
return NULL;
}
/* grab first two chars of the file and make sure that it has the
correct magic cookie for a raw PPM file. */
fgets(head, 70, fp);
if (strncmp(head, "P6", 2)) {
fprintf(stderr, "%s: Not a raw PPM file\n", filename);
return NULL;
}
/* grab the three elements in the header (width, height, maxval). */
i = 0;
while(i < 3) {
fgets(head, 70, fp);
if (head[0] == '#') /* skip comments. */
continue;
if (i == 0)
i += sscanf(head, "%d %d %d", &w, &h, &d);
else if (i == 1)
i += sscanf(head, "%d %d", &h, &d);
else if (i == 2)
i += sscanf(head, "%d", &d);
}
/* grab all the image data in one fell swoop. */
image = (unsigned char*)malloc(sizeof(unsigned char)*w*h*3);
fread(image, sizeof(unsigned char), w*h*3, fp);
fclose(fp);
*width = w;
*height = h;
return image;
}
#if 0
/* normals */
if (model->numnormals) {
numvectors = model->numnormals;
vectors = model->normals;
copies = glmOptimizeVectors(vectors, &numvectors);
printf("glmOptimize(): %d redundant normals.\n",
model->numnormals - numvectors);
for (i = 0; i < model->numtriangles; i++) {
T(i).nindices[0] = (GLuint)vectors[3 * T(i).nindices[0] + 0];
T(i).nindices[1] = (GLuint)vectors[3 * T(i).nindices[1] + 0];
T(i).nindices[2] = (GLuint)vectors[3 * T(i).nindices[2] + 0];
}
/* free space for old normals */
free(vectors);
/* allocate space for the new normals */
model->numnormals = numvectors;
model->normals = (GLfloat*)malloc(sizeof(GLfloat) *
3 * (model->numnormals + 1));
/* copy the optimized vertices into the actual vertex list */
for (i = 1; i <= model->numnormals; i++) {
model->normals[3 * i + 0] = copies[3 * i + 0];
model->normals[3 * i + 1] = copies[3 * i + 1];
model->normals[3 * i + 2] = copies[3 * i + 2];
}
free(copies);
}
/* texcoords */
if (model->numtexcoords) {
numvectors = model->numtexcoords;
vectors = model->texcoords;
copies = glmOptimizeVectors(vectors, &numvectors);
printf("glmOptimize(): %d redundant texcoords.\n",
model->numtexcoords - numvectors);
for (i = 0; i < model->numtriangles; i++) {
for (j = 0; j < 3; j++) {
T(i).tindices[j] = (GLuint)vectors[3 * T(i).tindices[j] + 0];
}
}
/* free space for old texcoords */
free(vectors);
/* allocate space for the new texcoords */
model->numtexcoords = numvectors;
model->texcoords = (GLfloat*)malloc(sizeof(GLfloat) *
2 * (model->numtexcoords + 1));
/* copy the optimized vertices into the actual vertex list */
for (i = 1; i <= model->numtexcoords; i++) {
model->texcoords[2 * i + 0] = copies[2 * i + 0];
model->texcoords[2 * i + 1] = copies[2 * i + 1];
}
free(copies);
}
#endif
#if 0
/* look for unused vertices */
/* look for unused normals */
/* look for unused texcoords */
for (i = 1; i <= model->numvertices; i++) {
for (j = 0; j < model->numtriangles; i++) {
if (T(j).vindices[0] == i ||
T(j).vindices[1] == i ||
T(j).vindices[1] == i)
break;
}
}
#endif
}
| bsd-3-clause |
tbjohns/BlitzML | test/cpp/test_dataset.cpp | 6241 | #include "catch.hpp"
#include <blitzml/base/common.h>
#include <blitzml/dataset/sparse_dataset.h>
#include <blitzml/dataset/dense_dataset.h>
#include <blitzml/dataset/sparse_binary_dataset.h>
using std::vector;
using namespace BlitzML;
TEST_CASE( "test_sparse_dataset", "[dataset]" ) {
vector<index_t> indices;
vector<float> data;
vector<size_t> indptr;
indptr.push_back(0);
// Column 1
indptr.push_back(0);
// Column 2
indices.push_back(2); data.push_back(2.5);
indices.push_back(4); data.push_back(-0.5);
indptr.push_back(2);
// Column 3
indptr.push_back(2);
// Column 4
indices.push_back(0); data.push_back(-0.5);
indices.push_back(4); data.push_back(0.3);
indptr.push_back(4);
// Column 5
indptr.push_back(4);
// Column 6
indices.push_back(1); data.push_back(2.0);
indices.push_back(2); data.push_back(2.0);
indices.push_back(3); data.push_back(2.0);
indptr.push_back(7);
vector<value_t> b(5, 0.);
b[0] = 1.0;
b[2] = 2.0;
b[4] = -0.5;
SparseDataset<float> ds(&indices[0], &indptr[0], &data[0],
5, 6, data.size(), &b[0], 5);
vector<value_t> v(5, 0.);
v[0] = 2.0;
v[3] = 1.0;
v[4] = 0.2;
value_t val = ds.column(3)->inner_product(v);
REQUIRE( val == Approx( -0.94 ) );
val = ds.column(0)->inner_product(v);
REQUIRE( val == 0. );
val = ds.column(1)->inner_product(v);
REQUIRE( val == Approx( -0.1 ) );
REQUIRE( ds.any_columns_overlapping_in_submatrix(0, 4) == true );
REQUIRE( ds.any_columns_overlapping_in_submatrix(2, 4) == false );
REQUIRE( ds.any_columns_overlapping_in_submatrix(0, 3) == false );
REQUIRE( ds.b_value(0) == 1.0 );
REQUIRE( ds.b_value(1) == 0.0 );
REQUIRE( ds.b_value(4) == -0.5 );
REQUIRE( ds.num_rows() == 5 );
REQUIRE( ds.num_cols() == 6 );
REQUIRE( ds.nnz() == 7 );
}
TEST_CASE( "test_sparse_dataset_types", "[dataset]" ) {
vector<double> data_double(2, 1.0);
vector<float> data_float(2, 1.0);
vector<int> data_int(2, 1);
bool data_bool[2] = {true, true};
vector<index_t> indices;
indices.push_back(0); indices.push_back(1);
vector<size_t> indptr;
indptr.push_back(0); indptr.push_back(2);
vector<value_t> b(2, 0.);
SparseDataset<double> ds_double(&indices[0], &indptr[0], &data_double[0],
2, 1, 2, &b[0], 2);
SparseDataset<float> ds_float(&indices[0], &indptr[0], &data_float[0],
2, 1, 2, &b[0], 2);
SparseDataset<int> ds_int(&indices[0], &indptr[0], &data_int[0],
2, 1, 2, &b[0], 2);
SparseDataset<bool> ds_bool(&indices[0], &indptr[0], &data_bool[0],
2, 1, 2, &b[0], 2);
vector<value_t> v;
v.push_back(-2.0);
v.push_back(2.6);
REQUIRE( ds_double.column(0)->inner_product(v) == Approx( 0.6 ) );
REQUIRE( ds_float.column(0)->inner_product(v) == Approx( 0.6 ) );
REQUIRE( ds_int.column(0)->inner_product(v) == Approx( 0.6 ) );
REQUIRE( ds_bool.column(0)->inner_product(v) == Approx( 0.6 ) );
}
TEST_CASE( "test_dense_dataset", "[datset]" ) {
double data[12] = {1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.};
value_t b[4] = {1., 1., -3., 1.};
DenseDataset<double> ds(data, 4, 3, b, 4);
value_t val = ds.column(0)->l2_norm_sq();
REQUIRE( ds.column(0)->l2_norm_sq() == Approx( 30. ) );
vector<value_t> vec(4, 0.0);
vec[3] = -1.0;
vec[1] = -0.5;
REQUIRE( ds.column(2)->inner_product(vec) == Approx( -17. ) );
REQUIRE( ds.any_columns_overlapping_in_submatrix(0, 2) == true );
REQUIRE( ds.any_columns_overlapping_in_submatrix(0, 3) == true );
REQUIRE( ds.any_columns_overlapping_in_submatrix(0, 1) == false );
REQUIRE( ds.any_columns_overlapping_in_submatrix(1, 2) == false );
REQUIRE( ds.b_value(2) == -3. );
REQUIRE( ds.b_value(0) == 1. );
REQUIRE( ds.b_value(3) == 1. );
REQUIRE( ds.num_rows() == 4 );
REQUIRE( ds.num_cols() == 3 );
REQUIRE( ds.nnz() == 12 );
}
TEST_CASE( "test_dense_dataset_types", "[dataset]" ) {
double data_double[2] = {1., 1.};
float data_float[2] = {1., 1.};
int data_int[2] = {1., 1.};
bool data_bool[2] = {true, true};
DenseDataset<double> ds_double(data_double, 2, 1, NULL, 0);
DenseDataset<float> ds_float(data_float, 2, 1, NULL, 0);
DenseDataset<int> ds_int(data_int, 2, 1, NULL, 0);
DenseDataset<bool> ds_bool(data_bool, 2, 1, NULL, 0);
vector<value_t> vec;
vec.push_back(-2.6); vec.push_back(0.3);
REQUIRE( ds_double.column(0)->inner_product(vec) == Approx(-2.3) );
REQUIRE( ds_float.column(0)->inner_product(vec) == Approx(-2.3) );
REQUIRE( ds_int.column(0)->inner_product(vec) == Approx(-2.3) );
REQUIRE( ds_bool.column(0)->inner_product(vec) == Approx(-2.3) );
}
TEST_CASE( "test_binary_dataset", "[datset]" ) {
index_t indices[8] = {0, 2, 3, 0, 3, 1, 2, 4};
size_t indptr[5] = {0, 0, 3, 5, 8};
value_t b[5] = {0., 1.0, 0., -2.5, 3.0};
SparseBinaryDataset ds(indices, indptr, 5, 4, 8, b, 5);
vector<value_t> vec;
vec.push_back(0.1); vec.push_back(0.2); vec.push_back(-0.3);
vec.push_back(-0.4); vec.push_back(0.5);
REQUIRE( ds.column(0)->inner_product(vec) == 0. );
REQUIRE( ds.column(3)->inner_product(vec) == Approx(0.4) );
REQUIRE( ds.any_columns_overlapping_in_submatrix(2, 4) == false );
REQUIRE( ds.any_columns_overlapping_in_submatrix(3, 4) == false );
REQUIRE( ds.any_columns_overlapping_in_submatrix(1, 4) == true );
REQUIRE( ds.any_columns_overlapping_in_submatrix(0, 2) == false );
REQUIRE( ds.any_columns_overlapping_in_submatrix(0, 3) == true );
REQUIRE( ds.b_value(0) == 0. );
REQUIRE( ds.b_value(4) == 3. );
REQUIRE( ds.b_value(3) == -2.5 );
REQUIRE( ds.num_rows() == 5 );
REQUIRE( ds.num_cols() == 4 );
REQUIRE( ds.nnz() == 8 );
}
TEST_CASE( "test_dataset_general", "[dataset]" ) {
double data[12] = {1., -0.3, 0., 2.1, 5., 1.0, 7., 8., 9., 0., -1., 12.};
value_t b[4] = {1., 1., -3., 1.};
DenseDataset<double> ds(data, 4, 3, b, 4);
vector<value_t> vec(4, 0.);
vec[0] = -1.1;
vec[1] = -2.1;
vec[2] = 1.8;
vec[3] = 10.1;
vector<value_t> result(2, 0.);
ds.contiguous_submatrix_multiply(vec, &result[0], 1, 3);
REQUIRE( result[0] == Approx(85.8) );
REQUIRE( result[1] == Approx(109.5) );
}
| bsd-3-clause |
rawjam/dj-stripe | djstripe/models.py | 36799 | """
Beging porting from django-stripe-payments
"""
from __future__ import unicode_literals
import datetime
import decimal
import json
import traceback
from django.conf import settings
from django.core.mail import EmailMessage
from django.db import models
from django.utils import timezone
from django.template.loader import render_to_string
from django.contrib.sites.models import Site
from jsonfield.fields import JSONField
from model_utils.models import TimeStampedModel
import stripe
from . import exceptions
from .managers import CustomerManager, ChargeManager, TransferManager
from .settings import PAYMENTS_PLANS, INVOICE_FROM_EMAIL
from .settings import plan_from_stripe_id
from .signals import WEBHOOK_SIGNALS
from .signals import subscription_made, cancelled, card_changed
from .signals import webhook_processing_error
from .settings import TRIAL_PERIOD_FOR_USER_CALLBACK
from .settings import DEFAULT_PLAN
stripe.api_key = settings.STRIPE_SECRET_KEY
stripe.api_version = getattr(settings, "STRIPE_API_VERSION", "2012-11-07")
def convert_tstamp(response, field_name=None):
try:
if field_name and response[field_name]:
if settings.USE_TZ:
return datetime.datetime.fromtimestamp(
response[field_name],
timezone.utc
)
else:
return datetime.datetime.fromtimestamp(response[field_name])
if not field_name:
if settings.USE_TZ:
return datetime.datetime.fromtimestamp(
response,
timezone.utc
)
else:
return datetime.datetime.fromtimestamp(response)
except KeyError:
pass
return None
class StripeObject(TimeStampedModel):
stripe_id = models.CharField(max_length=50, unique=True)
class Meta:
abstract = True
class EventProcessingException(TimeStampedModel):
event = models.ForeignKey("Event", null=True)
data = models.TextField()
message = models.CharField(max_length=500)
traceback = models.TextField()
@classmethod
def log(cls, data, exception, event):
cls.objects.create(
event=event,
data=data or "",
message=str(exception),
traceback=traceback.format_exc()
)
def __unicode__(self):
return u"<%s, pk=%s, Event=%s>" % (self.message, self.pk, self.event)
class Event(StripeObject):
kind = models.CharField(max_length=250)
livemode = models.BooleanField(default=False)
customer = models.ForeignKey("Customer", null=True)
webhook_message = JSONField()
validated_message = JSONField(null=True)
valid = models.NullBooleanField(null=True)
processed = models.BooleanField(default=False)
@property
def message(self):
return self.validated_message
def __unicode__(self):
return "%s - %s" % (self.kind, self.stripe_id)
def link_customer(self):
cus_id = None
customer_crud_events = [
"customer.created",
"customer.updated",
"customer.deleted"
]
if self.kind in customer_crud_events:
cus_id = self.message["data"]["object"]["id"]
else:
cus_id = self.message["data"]["object"].get("customer", None)
if cus_id is not None:
try:
self.customer = Customer.objects.get(stripe_id=cus_id)
self.save()
except Customer.DoesNotExist:
pass
def validate(self):
evt = stripe.Event.retrieve(self.stripe_id)
self.validated_message = json.loads(
json.dumps(
evt.to_dict(),
sort_keys=True,
cls=stripe.StripeObjectEncoder
)
)
if self.webhook_message["data"] == self.validated_message["data"]:
self.valid = True
else:
self.valid = False
self.save()
def process(self):
"""
"account.updated",
"account.application.deauthorized",
"charge.succeeded",
"charge.failed",
"charge.refunded",
"charge.dispute.created",
"charge.dispute.updated",
"chagne.dispute.closed",
"customer.created",
"customer.updated",
"customer.deleted",
"customer.subscription.created",
"customer.subscription.updated",
"customer.subscription.deleted",
"customer.subscription.trial_will_end",
"customer.discount.created",
"customer.discount.updated",
"customer.discount.deleted",
"invoice.created",
"invoice.updated",
"invoice.payment_succeeded",
"invoice.payment_failed",
"invoiceitem.created",
"invoiceitem.updated",
"invoiceitem.deleted",
"plan.created",
"plan.updated",
"plan.deleted",
"coupon.created",
"coupon.updated",
"coupon.deleted",
"transfer.created",
"transfer.updated",
"transfer.failed",
"ping"
"""
if self.valid and not self.processed:
try:
if not self.kind.startswith("plan.") and \
not self.kind.startswith("transfer."):
self.link_customer()
if self.kind.startswith("invoice."):
Invoice.handle_event(self)
elif self.kind.startswith("charge."):
if not self.customer:
self.link_customer()
self.customer.record_charge(
self.message["data"]["object"]["id"]
)
elif self.kind.startswith("transfer."):
Transfer.process_transfer(
self,
self.message["data"]["object"]
)
elif self.kind.startswith("customer.subscription."):
if not self.customer:
self.link_customer()
if self.customer:
self.customer.sync_current_subscription()
elif self.kind == "customer.deleted":
if not self.customer:
self.link_customer()
self.customer.purge()
self.send_signal()
self.processed = True
self.save()
except stripe.StripeError as e:
EventProcessingException.log(
data=e.http_body,
exception=e,
event=self
)
webhook_processing_error.send(
sender=Event,
data=e.http_body,
exception=e
)
def send_signal(self):
signal = WEBHOOK_SIGNALS.get(self.kind)
if signal:
return signal.send(sender=Event, event=self)
class Transfer(StripeObject):
event = models.ForeignKey(Event, related_name="transfers")
amount = models.DecimalField(decimal_places=2, max_digits=7)
status = models.CharField(max_length=25)
date = models.DateTimeField()
description = models.TextField(null=True, blank=True)
adjustment_count = models.IntegerField()
adjustment_fees = models.DecimalField(decimal_places=2, max_digits=7)
adjustment_gross = models.DecimalField(decimal_places=2, max_digits=7)
charge_count = models.IntegerField()
charge_fees = models.DecimalField(decimal_places=2, max_digits=7)
charge_gross = models.DecimalField(decimal_places=2, max_digits=7)
collected_fee_count = models.IntegerField()
collected_fee_gross = models.DecimalField(decimal_places=2, max_digits=7)
net = models.DecimalField(decimal_places=2, max_digits=7)
refund_count = models.IntegerField()
refund_fees = models.DecimalField(decimal_places=2, max_digits=7)
refund_gross = models.DecimalField(decimal_places=2, max_digits=7)
validation_count = models.IntegerField()
validation_fees = models.DecimalField(decimal_places=2, max_digits=7)
objects = TransferManager()
def update_status(self):
self.status = stripe.Transfer.retrieve(self.stripe_id).status
self.save()
@classmethod
def process_transfer(cls, event, transfer):
defaults = {
"amount": transfer["amount"] / decimal.Decimal("100"),
"status": transfer["status"],
"date": convert_tstamp(transfer, "date"),
"description": transfer.get("description", ""),
"adjustment_count": transfer["summary"]["adjustment_count"],
"adjustment_fees": transfer["summary"]["adjustment_fees"],
"adjustment_gross": transfer["summary"]["adjustment_gross"],
"charge_count": transfer["summary"]["charge_count"],
"charge_fees": transfer["summary"]["charge_fees"],
"charge_gross": transfer["summary"]["charge_gross"],
"collected_fee_count": transfer["summary"]["collected_fee_count"],
"collected_fee_gross": transfer["summary"]["collected_fee_gross"],
"net": transfer["summary"]["net"] / decimal.Decimal("100"),
"refund_count": transfer["summary"]["refund_count"],
"refund_fees": transfer["summary"]["refund_fees"],
"refund_gross": transfer["summary"]["refund_gross"],
"validation_count": transfer["summary"]["validation_count"],
"validation_fees": transfer["summary"]["validation_fees"],
}
for field in defaults:
if field.endswith("fees") or field.endswith("gross"):
defaults[field] = defaults[field] / decimal.Decimal("100")
if event.kind == "transfer.paid":
defaults.update({"event": event})
obj, created = Transfer.objects.get_or_create(
stripe_id=transfer["id"],
defaults=defaults
)
else:
obj, created = Transfer.objects.get_or_create(
stripe_id=transfer["id"],
event=event,
defaults=defaults
)
if created:
for fee in transfer["summary"]["charge_fee_details"]:
obj.charge_fee_details.create(
amount=fee["amount"] / decimal.Decimal("100"),
application=fee.get("application", ""),
description=fee.get("description", ""),
kind=fee["type"]
)
else:
obj.status = transfer["status"]
obj.save()
if event.kind == "transfer.updated":
obj.update_status()
class TransferChargeFee(TimeStampedModel):
transfer = models.ForeignKey(Transfer, related_name="charge_fee_details")
amount = models.DecimalField(decimal_places=2, max_digits=7)
application = models.TextField(null=True, blank=True)
description = models.TextField(null=True, blank=True)
kind = models.CharField(max_length=150)
class Customer(StripeObject):
user = models.OneToOneField(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), null=True)
card_fingerprint = models.CharField(max_length=200, blank=True)
card_last_4 = models.CharField(max_length=4, blank=True)
card_kind = models.CharField(max_length=50, blank=True)
date_purged = models.DateTimeField(null=True, editable=False)
objects = CustomerManager()
def __unicode__(self):
return unicode(self.user)
@property
def stripe_customer(self):
return stripe.Customer.retrieve(self.stripe_id)
def apply_coupon(self, coupon_to_apply):
cu = self.stripe_customer
cu.coupon = coupon_to_apply
cu.save()
#stripe_customer = stripe.Customer.create(
# email=user.email
#)
#self.sync(cu=cu)
def purge(self):
try:
self.stripe_customer.delete()
except stripe.InvalidRequestError as e:
if e.message.startswith("No such customer:"):
# The exception was thrown because the customer was already
# deleted on the stripe side, ignore the exception
pass
else:
# The exception was raised for another reason, re-raise it
raise
self.user = None
self.card_fingerprint = ""
self.card_last_4 = ""
self.card_kind = ""
self.date_purged = timezone.now()
self.save()
def delete(self, using=None):
# Only way to delete a customer is to use SQL
self.purge()
def can_charge(self):
return self.card_fingerprint and \
self.card_last_4 and \
self.card_kind and \
self.date_purged is None
def has_active_subscription(self):
try:
return self.current_subscription.is_valid()
except CurrentSubscription.DoesNotExist:
return False
def cancel_subscription(self, at_period_end=True):
try:
current_subscription = self.current_subscription
except CurrentSubscription.DoesNotExist:
raise exceptions.SubscriptionCancellationFailure(
"Customer does not have current subscription"
)
try:
"""
If plan has trial days and customer cancels before trial period ends,
then end subscription now, i.e. at_period_end=False
"""
if self.current_subscription.trial_end and self.current_subscription.trial_end > timezone.now():
at_period_end = False
sub = self.stripe_customer.cancel_subscription(at_period_end=at_period_end)
except stripe.InvalidRequestError as e:
raise exceptions.SubscriptionCancellationFailure(
"Customer's information is not current with Stripe.\n{}".format(
e.message
)
)
current_subscription.status = sub.status
current_subscription.cancel_at_period_end = sub.cancel_at_period_end
current_subscription.period_end = convert_tstamp(sub, "current_period_end")
current_subscription.canceled_at = timezone.now()
current_subscription.save()
cancelled.send(sender=self, stripe_response=sub)
return current_subscription
def cancel(self, at_period_end=True):
""" Utility method to preserve usage of previous API """
return self.cancel_subscription(at_period_end=at_period_end)
@classmethod
def get_or_create(cls, user):
try:
return Customer.objects.get(user=user), False
except Customer.DoesNotExist:
return cls.create(user), True
@classmethod
def create(cls, user):
trial_days = None
if TRIAL_PERIOD_FOR_USER_CALLBACK:
trial_days = TRIAL_PERIOD_FOR_USER_CALLBACK(user)
stripe_customer = stripe.Customer.create(
email=user.email
)
cus = Customer.objects.create(
user=user,
stripe_id=stripe_customer.id
)
if DEFAULT_PLAN and trial_days:
cus.subscribe(plan=DEFAULT_PLAN, trial_days=trial_days)
return cus
def update_card(self, token):
cu = self.stripe_customer
cu.card = token
cu.save()
self.card_fingerprint = cu.active_card.fingerprint
self.card_last_4 = cu.active_card.last4
self.card_kind = cu.active_card.type
self.save()
card_changed.send(sender=self, stripe_response=cu)
def retry_unpaid_invoices(self):
self.sync_invoices()
for inv in self.invoices.filter(paid=False, closed=False):
try:
inv.retry() # Always retry unpaid invoices
except stripe.InvalidRequestError as error:
if error.message != "Invoice is already paid":
raise error
def send_invoice(self):
try:
invoice = stripe.Invoice.create(customer=self.stripe_id)
invoice.pay()
return True
except stripe.InvalidRequestError:
return False # There was nothing to invoice
def sync(self, cu=None):
cu = cu or self.stripe_customer
if cu.active_card:
self.card_fingerprint = cu.active_card.fingerprint
self.card_last_4 = cu.active_card.last4
self.card_kind = cu.active_card.type
self.save()
def sync_invoices(self, cu=None, **kwargs):
cu = cu or self.stripe_customer
for invoice in cu.invoices(**kwargs).data:
Invoice.sync_from_stripe_data(invoice, send_receipt=False)
def sync_charges(self, cu=None, **kwargs):
cu = cu or self.stripe_customer
for charge in cu.charges(**kwargs).data:
self.record_charge(charge.id)
def sync_current_subscription(self, cu=None):
cu = cu or self.stripe_customer
sub = cu.subscription
if sub:
try:
sub_obj = self.current_subscription
sub_obj.plan = plan_from_stripe_id(sub.plan.id)
# Its possible theyre on a plan that has since been removed
if sub_obj.plan:
sub_obj.current_period_start = convert_tstamp(
sub.current_period_start
)
sub_obj.current_period_end = convert_tstamp(
sub.current_period_end
)
sub_obj.amount = (sub.plan.amount / decimal.Decimal("100"))
sub_obj.status = sub.status
sub_obj.cancel_at_period_end = sub.cancel_at_period_end
sub_obj.start = convert_tstamp(sub.start)
sub_obj.quantity = sub.quantity
sub_obj.save()
else:
sub_obj = None
except CurrentSubscription.DoesNotExist:
sub_obj = CurrentSubscription.objects.create(
customer=self,
plan=plan_from_stripe_id(sub.plan.id),
current_period_start=convert_tstamp(
sub.current_period_start
),
current_period_end=convert_tstamp(
sub.current_period_end
),
amount=(sub.plan.amount / decimal.Decimal("100")),
status=sub.status,
cancel_at_period_end=sub.cancel_at_period_end,
start=convert_tstamp(sub.start),
quantity=sub.quantity
)
# Its possible theyre on a plan that has since been removed
if sub_obj and sub_obj.plan:
if sub.trial_start and sub.trial_end:
sub_obj.trial_start = convert_tstamp(sub.trial_start)
sub_obj.trial_end = convert_tstamp(sub.trial_end)
else:
"""
Avoids keeping old values for trial_start and trial_end
for cases where customer had a subscription with trial days
then one without that (s)he cancels.
"""
sub_obj.trial_start = None
sub_obj.trial_end = None
# Are there any discounts active on this account?
if sub.discount:
coupon = sub.discount.coupon
if coupon.valid:
sub_obj.discount_amount = coupon.amount_off
sub_obj.discount_percentage = coupon.percent_off
else:
sub_obj.discount_amount = None
sub_obj.discount_percentage = None
sub_obj.save()
# Just in case, trigger the sub updated signal
signal = WEBHOOK_SIGNALS.get('customer.subscription.updated')
signal.send(sender=Customer, event=self)
return sub_obj
def update_plan_quantity(self, quantity, charge_immediately=False):
self.subscribe(
plan=plan_from_stripe_id(
self.stripe_customer.subscription.plan.id
),
quantity=quantity,
charge_immediately=charge_immediately
)
def subscribe(self, plan, quantity=1, trial_days=None,
charge_immediately=True, always_allow_trial=False):
cu = self.stripe_customer
"""
Trial_days corresponds to the value specified by the selected plan
for the key trial_period_days.
"""
if not trial_days and "trial_period_days" in PAYMENTS_PLANS[plan]:
trial_days = PAYMENTS_PLANS[plan]["trial_period_days"]
"""
The subscription is defined with prorate=False to make the subscription
end behavior of Change plan consistent with the one of Cancel subscription (which is
defined with at_period_end=True).
"""
if trial_days:
# Obviously if this person is upgrading or downgrading to another plan
# we don't want to let them take out another 30 day trial or they could
# simply upgrade / downgrade indefinitely without leaving a trial. So
# let's check for this situation!
try:
current_sub = self.current_subscription
current_sub_is_active = current_sub.status == CurrentSubscription.STATUS_ACTIVE
except CurrentSubscription.DoesNotExist:
current_sub = None
current_sub_is_active = False
if current_sub and not current_sub_is_active and current_sub.trial_end and current_sub.trial_end > timezone.now() and not always_allow_trial:
# Let the trial end carry over!
trial_end = current_sub.trial_end
elif not current_sub or always_allow_trial:
# This is their first subscription so let the trial_end be dictated by the
# plans default trial days value
trial_end = timezone.now() + datetime.timedelta(days=trial_days)
else:
# This is not the users first subscription and they have no trial days left
# so don't let any new trial days be set!
trial_end = None
resp = cu.update_subscription(
plan=PAYMENTS_PLANS[plan]["stripe_plan_id"],
trial_end=trial_end,
prorate=False,
quantity=quantity
)
else:
resp = cu.update_subscription(
plan=PAYMENTS_PLANS[plan]["stripe_plan_id"],
prorate=False,
quantity=quantity
)
self.sync_current_subscription()
if charge_immediately:
self.send_invoice()
subscription_made.send(sender=self, plan=plan, stripe_response=resp)
def charge(self, amount, currency="usd", description=None, send_receipt=True):
"""
This method expects `amount` to be a Decimal type representing a
dollar amount. It will be converted to cents so any decimals beyond
two will be ignored.
"""
if not isinstance(amount, decimal.Decimal):
raise ValueError(
"You must supply a decimal value representing dollars."
)
resp = stripe.Charge.create(
amount=int(amount * 100), # Convert dollars into cents
currency=currency,
customer=self.stripe_id,
description=description,
)
obj = self.record_charge(resp["id"])
if send_receipt:
obj.send_receipt()
return obj
def record_charge(self, charge_id):
data = stripe.Charge.retrieve(charge_id)
return Charge.sync_from_stripe_data(data)
class CurrentSubscription(TimeStampedModel):
STATUS_TRIALING = "trialing"
STATUS_ACTIVE = "active"
STATUS_PAST_DUE = "past_due"
STATUS_CANCELLED = "canceled"
STATUS_UNPAID = "unpaid"
customer = models.OneToOneField(
Customer,
related_name="current_subscription",
null=True
)
plan = models.CharField(max_length=100)
quantity = models.IntegerField()
start = models.DateTimeField()
# trialing, active, past_due, canceled, or unpaid
# In progress of moving it to choices field
status = models.CharField(max_length=25)
cancel_at_period_end = models.BooleanField(default=False)
canceled_at = models.DateTimeField(null=True, blank=True)
current_period_end = models.DateTimeField(null=True)
current_period_start = models.DateTimeField(null=True)
ended_at = models.DateTimeField(null=True, blank=True)
trial_end = models.DateTimeField(null=True, blank=True)
trial_start = models.DateTimeField(null=True, blank=True)
amount = models.DecimalField(decimal_places=2, max_digits=7)
discount_amount = models.DecimalField(decimal_places=2, max_digits=7, null=True, blank=True)
discount_percentage = models.IntegerField(null=True, blank=True)
def has_discount(self):
if self.discount_amount or self.discount_percentage:
return True
else:
return False
def discounted_amount(self):
_amount = (self.amount * self.quantity)
if self.has_discount():
if self.discount_amount:
return _amount - (self.discount_amount/100)
elif self.discount_percentage:
amount_to_discount = (_amount*self.discount_percentage)/100
return _amount - amount_to_discount
return _amount
def plan_display(self):
try:
return PAYMENTS_PLANS[self.plan]["name"]
except KeyError:
return None
def status_display(self):
return self.status.replace("_", " ").title()
def is_period_current(self):
if self.current_period_end is None:
return False
return self.current_period_end > timezone.now()
def is_status_current(self):
return self.status in [self.STATUS_TRIALING, self.STATUS_ACTIVE]
"""
Status when customer canceled their latest subscription, one that does not prorate,
and therefore has a temporary active subscription until period end.
"""
def is_status_temporarily_current(self):
return self.canceled_at and self.start < self.canceled_at and self.cancel_at_period_end
def is_valid(self):
if not self.is_status_current():
return False
if self.cancel_at_period_end and not self.is_period_current():
return False
return True
class Invoice(TimeStampedModel):
stripe_id = models.CharField(max_length=50)
customer = models.ForeignKey(Customer, related_name="invoices")
attempted = models.NullBooleanField()
attempts = models.PositiveIntegerField(null=True)
closed = models.BooleanField(default=False)
paid = models.BooleanField(default=False)
period_end = models.DateTimeField()
period_start = models.DateTimeField()
subtotal = models.DecimalField(decimal_places=2, max_digits=7)
total = models.DecimalField(decimal_places=2, max_digits=7)
date = models.DateTimeField()
charge = models.CharField(max_length=50, blank=True)
class Meta:
ordering = ["-date"]
def retry(self):
if not self.paid and not self.closed:
inv = stripe.Invoice.retrieve(self.stripe_id)
inv.pay()
return True
return False
def status(self):
if self.paid:
return "Paid"
if self.closed:
return "Closed"
return "Open"
@classmethod
def sync_from_stripe_data(cls, stripe_invoice, send_receipt=True):
try:
c = Customer.objects.get(stripe_id=stripe_invoice["customer"])
except Customer.DoesNotExist:
c = None
if c:
period_end = convert_tstamp(stripe_invoice, "period_end")
period_start = convert_tstamp(stripe_invoice, "period_start")
date = convert_tstamp(stripe_invoice, "date")
invoice, created = cls.objects.get_or_create(
stripe_id=stripe_invoice["id"],
defaults=dict(
customer=c,
attempted=stripe_invoice["attempted"],
closed=stripe_invoice["closed"],
paid=stripe_invoice["paid"],
period_end=period_end,
period_start=period_start,
subtotal=stripe_invoice["subtotal"] / decimal.Decimal("100"),
total=stripe_invoice["total"] / decimal.Decimal("100"),
date=date,
charge=stripe_invoice.get("charge") or ""
)
)
if not created:
# pylint: disable=C0301
invoice.attempted = stripe_invoice["attempted"]
invoice.closed = stripe_invoice["closed"]
invoice.paid = stripe_invoice["paid"]
invoice.period_end = period_end
invoice.period_start = period_start
invoice.subtotal = stripe_invoice["subtotal"] / decimal.Decimal("100")
invoice.total = stripe_invoice["total"] / decimal.Decimal("100")
invoice.date = date
invoice.charge = stripe_invoice.get("charge") or ""
invoice.save()
for item in stripe_invoice["lines"].get("data", []):
period_end = convert_tstamp(item["period"], "end")
period_start = convert_tstamp(item["period"], "start")
"""
Period end of invoice is the period end of the latest invoiceitem.
"""
invoice.period_end = period_end
if item.get("plan"):
plan = plan_from_stripe_id(item["plan"]["id"])
if not plan:
plan = ""
else:
plan = ""
inv_item, inv_item_created = invoice.items.get_or_create(
stripe_id=item["id"],
defaults=dict(
amount=(item["amount"] / decimal.Decimal("100")),
currency=item["currency"],
proration=item["proration"],
description=item.get("description") or "",
line_type=item["type"],
plan=plan,
period_start=period_start,
period_end=period_end,
quantity=item.get("quantity")
)
)
if not inv_item_created:
inv_item.amount = (item["amount"] / decimal.Decimal("100"))
inv_item.currency = item["currency"]
inv_item.proration = item["proration"]
inv_item.description = item.get("description") or ""
inv_item.line_type = item["type"]
inv_item.plan = plan
inv_item.period_start = period_start
inv_item.period_end = period_end
inv_item.quantity = item.get("quantity")
inv_item.save()
"""
Save invoice period end assignment.
"""
invoice.save()
if stripe_invoice.get("charge"):
obj = c.record_charge(stripe_invoice["charge"])
obj.invoice = invoice
obj.save()
if send_receipt:
obj.send_receipt()
return invoice
@classmethod
def handle_event(cls, event):
valid_events = ["invoice.payment_failed", "invoice.payment_succeeded"]
if event.kind in valid_events:
invoice_data = event.message["data"]["object"]
stripe_invoice = stripe.Invoice.retrieve(invoice_data["id"])
cls.sync_from_stripe_data(stripe_invoice)
class InvoiceItem(TimeStampedModel):
""" Not inherited from StripeObject because there can be multiple invoice
items for a single stripe_id.
"""
stripe_id = models.CharField(max_length=50)
invoice = models.ForeignKey(Invoice, related_name="items")
amount = models.DecimalField(decimal_places=2, max_digits=7)
currency = models.CharField(max_length=10)
period_start = models.DateTimeField()
period_end = models.DateTimeField()
proration = models.BooleanField(default=False)
line_type = models.CharField(max_length=50)
description = models.CharField(max_length=200, blank=True)
plan = models.CharField(max_length=100, blank=True)
quantity = models.IntegerField(null=True)
def plan_display(self):
return PAYMENTS_PLANS[self.plan]["name"]
class Charge(StripeObject):
customer = models.ForeignKey(Customer, related_name="charges")
invoice = models.ForeignKey(Invoice, null=True, related_name="charges")
card_last_4 = models.CharField(max_length=4, blank=True)
card_kind = models.CharField(max_length=50, blank=True)
amount = models.DecimalField(decimal_places=2, max_digits=7, null=True)
amount_refunded = models.DecimalField(
decimal_places=2,
max_digits=7,
null=True
)
description = models.TextField(blank=True)
paid = models.NullBooleanField(null=True)
disputed = models.NullBooleanField(null=True)
refunded = models.NullBooleanField(null=True)
fee = models.DecimalField(decimal_places=2, max_digits=7, null=True)
receipt_sent = models.BooleanField(default=False)
charge_created = models.DateTimeField(null=True, blank=True)
objects = ChargeManager()
def calculate_refund_amount(self, amount=None):
eligible_to_refund = self.amount - (self.amount_refunded or 0)
if amount:
amount_to_refund = min(eligible_to_refund, amount)
else:
amount_to_refund = eligible_to_refund
return int(amount_to_refund * 100)
def refund(self, amount=None):
charge_obj = stripe.Charge.retrieve(
self.stripe_id
).refund(
amount=self.calculate_refund_amount(amount=amount)
)
Charge.sync_from_stripe_data(charge_obj)
@classmethod
def sync_from_stripe_data(cls, data):
customer = Customer.objects.get(stripe_id=data["customer"])
obj, _ = customer.charges.get_or_create(
stripe_id=data["id"]
)
invoice_id = data.get("invoice", None)
if obj.customer.invoices.filter(stripe_id=invoice_id).exists():
obj.invoice = obj.customer.invoices.get(stripe_id=invoice_id)
obj.card_last_4 = data["card"]["last4"]
obj.card_kind = data["card"]["type"]
obj.amount = (data["amount"] / decimal.Decimal("100"))
obj.paid = data["paid"]
obj.refunded = data["refunded"]
obj.fee = (data["fee"] / decimal.Decimal("100"))
obj.disputed = data["dispute"] is not None
obj.charge_created = convert_tstamp(data, "created")
if data.get("description"):
obj.description = data["description"]
if data.get("amount_refunded"):
# pylint: disable=C0301
obj.amount_refunded = (data["amount_refunded"] / decimal.Decimal("100"))
if data["refunded"]:
obj.amount_refunded = (data["amount"] / decimal.Decimal("100"))
obj.save()
return obj
def send_receipt(self):
if not self.receipt_sent and getattr(settings, "DJSTRIPE_SEND_RECEIPTS", False):
site = Site.objects.get_current()
protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
ctx = {
"charge": self,
"site": site,
"protocol": protocol,
}
subject = render_to_string("djstripe/email/subject.txt", ctx)
subject = subject.strip()
message = render_to_string("djstripe/email/body.txt", ctx)
num_sent = EmailMessage(
subject,
message,
to=[self.customer.user.email],
from_email=INVOICE_FROM_EMAIL
).send()
self.receipt_sent = num_sent > 0
self.save()
| bsd-3-clause |
lm-tools/situational | situational/apps/travel_report/tests/test_feature.py | 1052 | from django.core.urlresolvers import reverse
from django.core import mail
from splinter import Browser
from situational.testing import BaseCase
class TestTravelReport(BaseCase):
def test_happy_path(self):
with Browser("django") as b:
b.visit(reverse("travel_report:start"))
b.fill("postcode", "SW1A 1AA")
b.find_by_text("Start").first.click()
self.assertTrue(
b.is_text_present(
"Your map is loading")
)
b.reload()
self.assertTrue(
b.is_text_present(
"This map shows where you can get to from SW1A1AA")
)
self.assertTrue(
b.find_by_css('.travel-map')
)
b.fill("email", "test@example.org")
b.find_by_value("Send").first.click()
self.assertTrue(
b.is_text_present(
"Sent to test@example.org")
)
self.assertEqual(len(mail.outbox), 1)
| bsd-3-clause |
corner82/codebase | public/jsinline/admin_aclroleprivilege.js | 35612 | $(document).ready(function () {
/**
* easyui tree extend for 'unselect' event
* @author Mustafa Zeynel Dağlı
* @since 04/04/2016
*/
$.extend($.fn.tree.methods,{
unselect:function(jq,target){
return jq.each(function(){
var opts = $(this).tree('options');
$(target).removeClass('tree-node-selected');
if (opts.onUnselect){
opts.onUnselect.call(this, $(this).tree('getNode',target));
}
});
}
});
/**
* multilanguage plugin
* @type Lang
*/
var lang = new Lang();
lang.dynamic($('#ln').val(), '/plugins/jquery-lang-js-master/langpack/'+$('#ln').val()+'.json');
lang.init({
defaultLang: 'en'
});
lang.change($('#ln').val());
/**
* loader image for resource and rol tree loading process
* @type @call;$@call;loadImager
* @author Mustafa Zeynel Dağlı
* @since 15/07/2016
*/
var loader_resource = $("#loading-image-resource").loadImager();
loader_resource.loadImager('appendImage');
var sm = $(window).successMessage();
var dm = $(window).dangerMessage();
var wm = $(window).warningMessage();
var wcm = $(window).warningComplexMessage({ denyButtonLabel : 'Vazgeç' ,
actionButtonLabel : 'İşleme devam et'});
/*
*
* ACL resource and rol tree
* Mustafa Zeynel Dağlı
* 15/07/2016
*/
$('#tt_tree_menu2').tree({
url: 'https://proxy.trf.com/SlimProxyBoot.php?url=pkFillResourceGroups_sysAclResources&pk=' + $("#pk").val()+ '&language_code='+$("#langCode").val(),
method: 'get',
animate: true,
checkbox: false,
cascadeCheck: false,
lines: true,
onLoadSuccess: function (node, data) {
loader_resource.loadImager('removeLoadImage');
},
onClick: function (node) {
selectedRoot = $(this).tree('getRoot', node.target);
selectedItem = $(this).tree('getData', node.target);
},
onSelect : function(node) {
var self = $(this);
var tagBuilderNot;
var tagBuilder = $('#test-cabin').tagCabin({
tagCopy : false,
tagDeletable : true,
tagDeletableAll : false,
tagBox : $('.tag-container').find('ul'),
dataMapper : {attributes : Array('role_id', 'resource_id', 'privilege_id')}
});
tagBuilder.tagCabin({
onTagRemoved : function(event, data) {
var self = $(this);
var elementData = data.element;
//console.log(elementData);
var id = data.id;
//self.tagCabin()
window.deleteRolePrivilege(id, elementData, tagBuilderNot);
}
});
tagBuilderNot = $('#test-cabin-not').tagCabin({
tagCopy : true,
tagDeletable : false,
tagDeletableAll : false,
tagBox : $('.tag-container-not').find('ul'),
dataMapper : {attributes : Array('role_id', 'resource_id', 'privilege_id')}
});
tagBuilderNot.tagCabin({
onTagCopied : function(event, data) {
var self = $(this);
window.assignRolePrivilege(data.id, data.element, tagBuilder);
}
});
if(!self.tree('isLeaf', node.target)) {
wm.warningMessage( {
onShown : function (event ,data ) {
self.tree('uncheck', node.target);
}
});
wm.warningMessage('show','ACL Rol Seçiniz',
'ACL resource (kaynak) seçtiniz, Lütfen rol seçiniz...');
} else {
window.clearRolePrivilege(node, tagBuilder);
window.getRolePrivileges(node, self, tagBuilder);
window.clearRolePrivilege(node, tagBuilderNot);
window.getRolePrivilegesNotAssigned(node, self, tagBuilderNot);
}
},
});
/**
* assign privilege to role
* @param {type} nodeID
* @param {type} nodeName
* @returns {undefined}
* @author Mustafa Zeynel Dağlı
* @since 15/07/2016
*/
window.assignRolePrivilege = function (property_id, tag, tagBuilder) {
var tag = tag;
var tagBuilder = tagBuilder;
var loader = $("#rolePrivilegeBlock").loadImager();
loader.loadImager('appendImage');
console.log(tag.attr('data-attribute'));
console.log(tag.text());
console.log(tag.attr('data-resource_id'));
console.log(tag.attr('data-privilege_id'));
console.log(tag.attr('data-role_id'));
var role_id = tag.attr('data-role_id');
var privilege_id = tag.attr('data-privilege_id');
var resource_id = tag.attr('data-resource_id');
var aj = $(window).ajaxCall({
proxy : 'https://proxy.trf.com/SlimProxyBoot.php',
data : {
url:'pkTransferRolesPrivilege_sysAclRrp' ,
role_id : role_id,
resource_id : resource_id,
privilege_id : privilege_id,
pk : $("#pk").val()
}
})
aj.ajaxCall ({
onError : function (event, textStatus, errorThrown) {
dm.dangerMessage('resetOnShown');
dm.dangerMessage('show', 'Yetki Ekleme İşlemi Başarısız...',
'Yetki ekleme işlemi başarısız, sistem yöneticisi ile temasa geçiniz... ')
console.error('"pkTransferRolesPrivilege_sysAclRrp" servis hatası->'+textStatus);
},
onSuccess : function (event, data) {
var data = data;
var id = data.lastInsertId;
tagBuilder.tagCabin('addTagManuallyDataAttr', id,
tag.text(),
{role_id : role_id,
resource_id : resource_id,
privilege_id : privilege_id });
tag.remove();
loader.loadImager('removeLoadImage');
sm.successMessage('show', 'Yetki Ekleme İşlemi Başarılı...',
'Yetki ekleme İşlemini gerçekleştirdiniz... ',
data);
},
onErrorDataNull : function (event, data) {
dm.dangerMessage('resetOnShown');
dm.dangerMessage('show', 'Yetki Ekleme İşlemi Başarısız...',
'Yetki Eekleme işlemi başarısız, sistem yöneticisi ile temasa geçiniz... ');
console.error('"pkTransferRolesPrivilege_sysAclRrp" servis datası boştur!!');
},
onErrorMessage : function (event, data) {
dm.dangerMessage('resetOnShown');
dm.dangerMessage('show', 'Yetki Ekleme İşlemi Başarısız...',
'Yetki ekleme işlemi başarısız, sistem yöneticisi ile temasa geçiniz... ');
console.error('"pkTransferRolesPrivilege_sysAclRrp" servis hatası->'+textStatus);
},
onError23503 : function (event, data) {
},
onError23505 : function (event, data) {
dm.dangerMessage({
onShown : function(event, data) {
//$('#machPropFormInsertPopup')[0].reset();
loader.loadImager('removeLoadImage');
}
});
dm.dangerMessage('show', 'Yetki Ekleme İşlemi Başarısız...',
'Yetki daha önce eklenmiştir, yeni bir yetki deneyiniz... ');
}
})
aj.ajaxCall('call');
}
/**
* delete privilege from a specific role
* @param {type} id
* @param {type} element
* @param {type} machine_group_id
* @returns {undefined}
* @since 15/07/2016
*/
window.deleteRolePrivilege = function(id, tag, tagBuilder) {
var tag = tag;
var tagBuilder = tagBuilder;
var id = id;
var loader = $("#rolePrivilegeBlock").loadImager();
loader.loadImager('appendImage');
console.log(tag.attr('data-attribute'));
console.log(tag.text());
console.log(tag.attr('data-resource_id'));
console.log(tag.attr('data-privilege_id'));
console.log(tag.attr('data-role_id'));
var role_id = tag.attr('data-role_id');
var privilege_id = tag.attr('data-privilege_id');
var resource_id = tag.attr('data-resource_id');
var ajPopUpDelete = $(window).ajaxCall({
proxy : 'https://proxy.trf.com/SlimProxyBoot.php',
data : {
url:'pkDelete_sysAclRrp' ,
id : id,
pk : $("#pk").val()
}
});
ajPopUpDelete.ajaxCall ({
onError : function (event, textStatus, errorThrown) {
dm.dangerMessage('resetOnShown');
dm.dangerMessage('show', 'Rol Yetki Silme İşlemi Başarısız...',
'Rol yetkisi silinememiştir, sistem yöneticisi ile temasa geçiniz...');
console.error('"pkDelete_sysAclRrp" servis hatası->'+textStatus);
},
onSuccess : function (event, data) {
tagBuilder.tagCabin('addTagManuallyDataAttr', 0,
tag.text(),
{role_id : role_id,
resource_id : resource_id,
privilege_id : privilege_id });
tag.remove();
loader.loadImager('removeLoadImage');
sm.successMessage('show', 'Rol Yetki Silme İşleminiz Başarılı...',
'Rol yetki silme işleminiz başarılı...')
},
});
ajPopUpDelete.ajaxCall('call');
}
/**
* clear role privileges from interface
* @param {type} node
* @param {type} tagBuilder
* @returns {undefined}
* @since 15/07/2016
*/
window.clearRolePrivilege = function(node, tagBuilder) {
var nodeID = node.id;
/*$('#mach-prop-box').loadImager();
$('#mach-prop-box').loadImager('appendImage');*/
tagBuilder.tagCabin({
onSpecificTagsRemoved : function(event) {
//$('#mach-prop-box').loadImager('removeLoadImage');
}
});
tagBuilder.tagCabin('removeAllTags');
}
/**
* clear role privileges not assigned from interface
* @param {type} node
* @param {type} tagBuilder
* @returns {undefined}
* @since 28/07/2016
*/
window.clearRolePrivilegeNotAssigned = function(node, tagBuilderNot) {
var nodeID = node.id;
tagBuilderNot.tagCabin({
onSpecificTagsRemoved : function(event) {
}
});
tagBuilderNot.tagCabin('removeAllTags');
}
/**
* set ACL role privileges tags
* @param {type} node
* @param {type} treeObj
* @param {type} tagBuilder
* @returns {undefined}
* @since 15/07/2016
*/
window.getRolePrivileges = function(node, treeObj, tagBuilder) {
var nodeID = node.id;
$('#mach-prop-box').loadImager();
$('#mach-prop-box').loadImager('appendImage');
var resourceNode = $('#tt_tree_menu2').tree('getParent', node.target);
var resource_id = resourceNode.id;
//console.log(resourceNode);
if(tagBuilder.tagCabin('findSpecificTags', nodeID, 'data-role_id')) {
var ajaxMacProp = $('#test-cabin').ajaxCallWidget({
proxy : 'https://proxy.trf.com/SlimProxyBoot.php',
data : {
url:'pkFillPrivilegesOfRoles_sysAclPrivilege' ,
language_code : $('#langCode').val(),
role_id : nodeID,
resource_id : resource_id,
pk : $("#pk").val()
}
})
ajaxMacProp.ajaxCallWidget ({
onError : function (event, textStatus,errorThrown) {
dm.dangerMessage({
onShown : function() {
$('#mach-prop-box').loadImager('removeLoadImage');
//treeObj.tree('uncheck', node.target);
}
});
dm.dangerMessage('show', 'Rol Yetkileri Yüklenememiştir...',
'Rol Yetkileri yüklenememiştir, sistem yöneticiniz ile temasa geçiniz...');
},
onSuccess : function (event, data) {
tagBuilder.tagCabin(
{tagsFound :function(event, item) {
}
});
tagBuilder.tagCabin(
{onTagRemovedUltimately :function(event, data) {
var element = data.element;
var id = data.id;
var role_id = element.attr('data-role_id');
window.deleteRolePrivilegeUltimatelyDialog(id, element, role_id);
return false;
}
});
//console.log(data);
tagBuilder.tagCabin('addTags', data);
$('#mach-prop-box').loadImager('removeLoadImage');
},
onErrorDataNull : function (event, data) {
dm.dangerMessage({
onShown : function() {
$('#mach-prop-box').loadImager('removeLoadImage');
//treeObj.tree('uncheck', node.target);
}
});
dm.dangerMessage('show', 'Role Bağlı Yetki Bulunamamıştır...',
'Seçtiğiniz role bağlı yetki kaydı bulunamamıştır...');
$('#mach-prop-box').loadImager('removeLoadImage');
},
})
ajaxMacProp.ajaxCallWidget('call');
} else {
wm.warningMessage('resetOnShown');
wm.warningMessage('show', 'Yetkiler Seçilmiştir!!!'
, 'Seçili rol yetkileri yüklenmiş durumdadır...');
$('#mach-prop-box').loadImager('removeLoadImage');
}
}
/**
* set ACL resource privileges tags not assigned to role
* @param {type} node
* @param {type} treeObj
* @param {type} tagBuilder
* @returns {undefined}
* @since 15/07/2016
*/
window.getRolePrivilegesNotAssigned = function(node, treeObj, tagBuilder) {
var nodeID = node.id;
$('#mach-prop-box-not').loadImager();
$('#mach-prop-box-not').loadImager('appendImage');
var resourceNode = $('#tt_tree_menu2').tree('getParent', node.target);
var resource_id = resourceNode.id;
if(tagBuilder.tagCabin('findSpecificTags', nodeID, 'data-role_id')) {
var ajaxMacPropNot = $('#test-cabin-not').ajaxCallWidget({
proxy : 'https://proxy.trf.com/SlimProxyBoot.php',
data : {
url:'pkFillNotInPrivilegesOfRoles_sysAclPrivilege' ,
language_code : $('#langCode').val(),
role_id : nodeID,
resource_id : resource_id,
pk : $("#pk").val()
}
})
ajaxMacPropNot.ajaxCallWidget ({
onError : function (event, textStatus,errorThrown) {
dm.dangerMessage({
onShown : function() {
$('#mach-prop-box-not').loadImager('removeLoadImage');
//treeObj.tree('uncheck', node.target);
}
});
dm.dangerMessage('show', 'Resource Yetkileri Yüklenememiştir...',
'Resource Yetkileri yüklenememiştir, sistem yöneticiniz ile temasa geçiniz...');
},
onSuccess : function (event, data) {
$('#mach-prop-box-not').loadImager('removeLoadImage');
tagBuilder.tagCabin(
{tagsFound :function(event, item) {
//console.log($(item).attr('data-attribute'));
//console.log($(item).attr('data-tree-item'));
}
});
//console.log(data);
tagBuilder.tagCabin('addTags', data);
},
onErrorDataNull : function (event, data) {
dm.dangerMessage({
onShown : function() {
$('#mach-prop-box-not').loadImager('removeLoadImage');
//treeObj.tree('uncheck', node.target);
}
});
dm.dangerMessage('show', 'Resource (Kaynak) Bağlı Yetki Bulunamamıştır...',
'Seçtiğiniz rol için atanmamış yetki kaydı bulunamamıştır...');
$('#mach-prop-box-not').loadImager('removeLoadImage');
},
})
ajaxMacPropNot.ajaxCallWidget('call');
} else {
wm.warningMessage('resetOnShown');
wm.warningMessage('show', 'Yetkiler Seçilmiştir!!!'
, 'Seçili resource (kaynak) yetkileri yüklenmiş durumdadır...');
$('#mach-prop-box-not').loadImager('removeLoadImage');
}
}
// Left menuyu oluşturmak için çağırılan fonksiyon...
//$.fn.leftMenuFunction();
/**
* wrapper class for pop up and delete privilege from
* specific role
* @param {integer} nodeID
* @returns {null}
* @author Mustafa Zeynel Dağlı
* @since 15/07/2016
*/
window.deleteRolePrivilegeDialog= function(id, tag, tagBuilder){
var nodeID = nodeID;
wcm.warningComplexMessage({onConfirm : function(event, data) {
deleteRolePrivilege(id, tag, tagBuilder);
}
});
wcm.warningComplexMessage('show', 'Rol Yetkisi Silme İşlemi Gerçekleştirmek Üzeresiniz!',
'Rol yetkisini silmek üzeresiniz, yetki silme işlemi geri alınamaz!! ');
}
/**
* wrapper for machine property insert process
* @param {type} nodeID
* @param {type} nodeName
* @returns {Boolean}
* @author Mustafa Zeynel Dağlı
* @since 19/04/2016
*/
window.insertMachPropDialog = function (nodeID, nodeName) {
var nodeID = nodeID;
var nodeName = nodeName;
BootstrapDialog.show({
title: '"'+ nodeName + '" makina katmanına yeni özellik eklemektesiniz...',
message: function (dialogRef) {
var dialogRef = dialogRef;
var $message = $(' <div class="row">\n\
<div class="col-md-12">\n\
<div id="loading-image-crud-popup" class="box box-primary">\n\
<form id="machPropFormInsertPopup" method="get" class="form-horizontal">\n\
<div class="hr-line-dashed"></div>\n\
<div class="form-group" style="padding-top: 10px;" >\n\
<label class="col-sm-2 control-label">Birim Sistemi</label>\n\
<div class="col-sm-10">\n\
<div class="input-group">\n\
<div class="input-group-addon">\n\
<i class="fa fa-hand-o-right"></i>\n\
</div>\n\
<ul id="tt_tree_menu_popup" class="easyui-tree" ></ul>\n\
</div>\n\
</div>\n\
</div>\n\
<div class="form-group">\n\
<label class="col-sm-2 control-label">Mevcut Kategori Özellikleri</label>\n\
<div class="col-sm-10">\n\
<div class="input-group">\n\
<div class="input-group-addon">\n\
<i class="fa fa-hand-o-right"></i>\n\
</div>\n\
<div style="margin-bottom: -10px;" class="tag-container-popup">\n\
<ul id="test-cabin-popup" class="tag-box"></ul>\n\
</div>\n\
</div>\n\
</div>\n\
</div>\n\
<div class="form-group">\n\
<label class="col-sm-2 control-label">Kategoride Olmayan Özellikler</label>\n\
<div class="col-sm-10">\n\
<div class="input-group">\n\
<div class="input-group-addon">\n\
<i class="fa fa-hand-o-right"></i>\n\
</div>\n\
<div style="margin-bottom: -10px;" class="tag-container-popup-not">\n\
<ul id="test-cabin-popup-not" class="tag-box"></ul>\n\
</div>\n\
</div>\n\
</div>\n\
</div>\n\
<div class="form-group">\n\
<label class="col-sm-2 control-label">Makina Özelliği</label>\n\
<div class="col-sm-10">\n\
<div class="input-group">\n\
<div class="input-group-addon">\n\
<i class="fa fa-hand-o-right"></i>\n\
</div>\n\
<input data-prompt-position="topLeft:70" class="form-control validate[required]" type="text" name="property_name_popup" id="property_name_popup" />\n\
</div>\n\
</div>\n\
</div>\n\
<div class="form-group">\n\
<label class="col-sm-2 control-label">İngilizce Makina Özelliği</label>\n\
<div class="col-sm-10">\n\
<div class="input-group">\n\
<div class="input-group-addon">\n\
<i class="fa fa-hand-o-right"></i>\n\
</div>\n\
<input data-prompt-position="topLeft:70" class="form-control validate[required]" type="text" name="property_name_eng_popup" id="property_name_eng_popup" />\n\
</div>\n\
</div>\n\
</div>\n\
<div class="hr-line-dashed"></div>\n\
<div class="form-group">\n\
<div class="col-sm-10 col-sm-offset-2">\n\
<button id="insertUnitPopUp" class="btn btn-primary" type="submit" onclick="return insertMachPropWrapper(event, '+nodeID+', \''+nodeName+'\');">\n\
<i class="fa fa-save"></i> Kaydet </button>\n\
<button id="resetForm" onclick="regulateButtonsPopupInsert();" class="btn btn-flat" type="reset" " >\n\
<i class="fa fa-remove"></i> Reset </button>\n\
</div>\n\
</div>\n\
</form>\n\
</div>\n\
</div>\n\
</div>');
return $message;
},
type: BootstrapDialog.TYPE_PRIMARY,
onshown : function () {
$("#machPropFormInsertPopup").validationEngine();
var ajPopUpMachProp = $('#test-cabin-popup').ajaxCallWidget({
proxy : 'https://proxy.trf.com/SlimProxyBoot.php',
data : {
url:'pkFillMachineGroupPropertyDefinitions_sysMachineToolPropertyDefinition' ,
language_code : $('#langCode').val(),
role_id : nodeID,
pk : $("#pk").val()
}
})
ajPopUpMachProp.ajaxCallWidget ({
onError : function (event, textStatus, errorThrown) {
dm.dangerMessage({
onShown : function () {
var loader = $("#loading-image-crud-popup").loadImager();
loader.loadImager('appendImage');
}
});
dm.dangerMessage('show', 'Kategoriye Ait Makina Özellikleri Yüklenememiştir...',
'Kategoriye ait makina özellikleri yüklenememiştir,msistem yöneticisi ile temasa geçiniz...');
},
onSuccess : function (event, data) {
//alert('on success');
window.tagBuilderPopup = $('#test-cabin-popup').tagCabin({
tagCopy : false,
tagDeletable : true,
tagBox : $('.tag-container-popup').find('ul'),
dataMapper : {attributes : Array('role_id')}
});
tagBuilderPopup.tagCabin({
onTagRemoved : function(event, data) {
var elementData = data.element;
var id = data.id;
window.deleteRolePrivilegeDialog(id, nodeID, elementData);
}
});
tagBuilderPopup.tagCabin('addTags', data);
},
})
ajPopUpMachProp.ajaxCallWidget('call');
var ajPopUpMachPropNot = $("#loading-image-crud-popup").ajaxCallWidget({
proxy : 'https://proxy.trf.com/SlimProxyBoot.php',
data : {
url:'pkFillMachineGroupNotInPropertyDefinitions_sysMachineToolPropertyDefinition' ,
language_code : $('#langCode').val(),
role_id : nodeID,
pk : $("#pk").val()
}
})
ajPopUpMachPropNot.ajaxCallWidget ({
onError : function (event, textStatus, errorThrown) {
dm.dangerMessage({
onShown : function () {
var loader = $("#loading-image-crud-popup").loadImager();
loader.loadImager('appendImage');
}
});
dm.dangerMessage('show', 'Kategoriye Ait Makina Özellikleri Yüklenememiştir...',
'Kategoriye ait makina özellikleri yüklenememiştir,msistem yöneticisi ile temasa geçiniz...');
},
onSuccess : function (event, data) {
//alert('on success');
window.tagBuilderPopupNot = $('#test-cabin-popup-not').tagCabin({
tagCopy : true,
tagDeletable : false,
tagBox : $('.tag-container-popup-not').find('ul'),
dataMapper : {attributes : Array('role_id')}
});
tagBuilderPopupNot.tagCabin({
onTagCopied : function(event, data) {
var elementData = data.element;
var id = data.id;
console.warn(elementData.text());
var tagText = elementData.text();
window.addRolePrivilege(id, nodeID, elementData);
//window.deleteRolePrivilegeDialog(id, elementData);
}
});
tagBuilderPopupNot.tagCabin('addTags', data);
},
})
ajPopUpMachPropNot.ajaxCallWidget('call');
$('#tt_tree_menu_popup').tree({
url: 'https://proxy.trf.com/SlimProxyBoot.php?url=pkFillUnitsTree_sysUnits&pk=' + $("#pk").val()+ '&language_code='+$("#langCode").val(),
method: 'get',
animate: true,
checkbox: false,
cascadeCheck: false,
lines: true,
onLoadSuccess: function (node, data) {
loader.loadImager('removeLoadImage');
},
onSelect: function(node) {
var self = $(this);
if(self.tree('isLeaf', node.target)) {
wm.warningMessage( {
onShown : function (event ,data ) {
var parent = self.tree('getParent', node.target);
self.tree('select', parent.target);
}
});
wm.warningMessage('show','Ana Kategori Seçiniz',
'Lütfen ana kategori seçiniz...');
}
},
formatter: function (node) {
if(node.attributes.system != null) {
var s = node.text+' ('+node.attributes.system+')';
} else {
var s = node.text;
}
return s;
}
});
},
onhide : function() {
},
});
return false;
}
/**
* add privilege to role
* @param {type} nodeID
* @param {type} nodeName
* @returns {undefined}
* @author Mustafa Zeynel Dağlı
* @since 15/07/2016
*/
window.addRolePrivilege = function (property_id, role_id, tag) {
var property_id = property_id;
var role_id = role_id;
var tagText = tagText;
var loader = $("#lrolePrivilegeBlock").loadImager();
loader.loadImager('appendImage');
var aj = $(window).ajaxCall({
proxy : 'https://proxy.trf.com/SlimProxyBoot.php',
data : {
url:'pkTransferPropertyMachineGroup_sysMachineToolPropertyDefinition' ,
property_id : property_id,
role_id : role_id,
pk : $("#pk").val()
}
})
aj.ajaxCall ({
onError : function (event, textStatus, errorThrown) {
dm.dangerMessage('resetOnShown');
dm.dangerMessage('show', 'Role Yetki Ekleme İşlemi Başarısız...',
'Role yetki ekleme işlemi başarısız, sistem yöneticisi ile temasa geçiniz... ')
console.error('"pkTransferPropertyMachineGroup_sysMachineToolPropertyDefinition" servis hatası->'+textStatus);
},
onSuccess : function (event, data) {
var data = data;
sm.successMessage({
onShown: function( event, data ) {
window.tagBuilderPopup.tagCabin('addTagManually', property_id,
tag.text(),
{role_id : role_id});
window.tagBuilderPopupNot.tagCabin('removeTag', tag);
loader.loadImager('removeLoadImage');
}
});
sm.successMessage('show', 'Role Yetki Ekleme İşlemi Başarılı...',
'Role yetki ekleme İşlemini gerçekleştirdiniz... ',
data);
},
onErrorDataNull : function (event, data) {
dm.dangerMessage('resetOnShown');
dm.dangerMessage('show', 'Role Yetki Ekleme İşlemi Başarısız...',
'Role Yetki ekleme işlemi başarısız, sistem yöneticisi ile temasa geçiniz... ');
console.error('"pkTransferPropertyMachineGroup_sysMachineToolPropertyDefinition" servis datası boştur!!');
},
onErrorMessage : function (event, data) {
dm.dangerMessage('resetOnShown');
dm.dangerMessage('show', 'Role Yetki Ekleme İşlemi Başarısız...',
'Role yetki ekleme işlemi başarısız, sistem yöneticisi ile temasa geçiniz... ');
console.error('"pkTransferPropertyMachineGroup_sysMachineToolPropertyDefinition" servis hatası->'+textStatus);
},
onError23503 : function (event, data) {
},
onError23505 : function (event, data) {
dm.dangerMessage({
onShown : function(event, data) {
//$('#machPropFormInsertPopup')[0].reset();
loader.loadImager('removeLoadImage');
}
});
dm.dangerMessage('show', 'Role Yetki Ekleme İşlemi Başarısız...',
'Yetki daha önce eklenmiştir, yeni bir yetki deneyiniz... ');
}
})
aj.ajaxCall('call');
}
});
| bsd-3-clause |
nwjs/chromium.src | third_party/blink/renderer/core/paint/cull_rect_updater_test.cc | 2756 | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/paint/cull_rect_updater.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h"
namespace blink {
class CullRectUpdaterTest : public RenderingTest {
protected:
CullRect GetCullRect(const char* id) {
return GetLayoutObjectByElementId(id)->FirstFragment().GetCullRect();
}
};
// TODO(wangxianzhu): Move other cull rect tests from PaintLayerPainterTest
// into this file.
CullRect GetCullRect(const PaintLayer& layer) {
return layer.GetLayoutObject().FirstFragment().GetCullRect();
}
TEST_F(CullRectUpdaterTest, FixedPositionUnderClipPath) {
GetDocument().View()->Resize(800, 600);
SetBodyInnerHTML(R"HTML(
<div style="height: 100vh"></div>
<div style="width: 100px; height: 100px; clip-path: inset(0 0 0 0)">
<div id="fixed" style="position: fixed; top: 0; left: 0; width: 1000px;
height: 1000px"></div>
</div>
)HTML");
EXPECT_EQ(gfx::Rect(0, 0, 800, 600), GetCullRect("fixed").Rect());
GetDocument().GetFrame()->DomWindow()->scrollTo(0, 1000);
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint(
DocumentUpdateReason::kTest);
UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(gfx::Rect(0, 0, 800, 600), GetCullRect("fixed").Rect());
GetDocument().View()->Resize(800, 1000);
UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(gfx::Rect(0, 0, 800, 1000), GetCullRect("fixed").Rect());
}
TEST_F(CullRectUpdaterTest, FixedPositionUnderClipPathWillChangeTransform) {
GetDocument().View()->Resize(800, 600);
SetBodyInnerHTML(R"HTML(
<div style="height: 100vh"></div>
<div style="width: 100px; height: 100px; clip-path: inset(0 0 0 0)">
<div id="fixed" style="position: fixed; top: 0; left: 0; width: 1000px;
height: 1000px; will-change: transform"></div>
</div>
)HTML");
EXPECT_EQ(gfx::Rect(-4000, -4000, 8800, 8600), GetCullRect("fixed").Rect());
GetDocument().GetFrame()->DomWindow()->scrollTo(0, 1000);
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint(
DocumentUpdateReason::kTest);
UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(gfx::Rect(-4000, -4000, 8800, 8600), GetCullRect("fixed").Rect());
GetDocument().View()->Resize(800, 1000);
UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(gfx::Rect(-4000, -4000, 8800, 9000), GetCullRect("fixed").Rect());
}
} // namespace blink
| bsd-3-clause |
antonioribeiro/glottos | src/Repositories/Locales/Language.php | 1048 | <?php namespace PragmaRX\Glottos\Repositories\Locales;
/**
* Part of the Glottos package.
*
* NOTICE OF LICENSE
*
* Licensed under the 3-clause BSD License.
*
* This source file is subject to the 3-clause BSD License that is
* bundled with this package in the LICENSE file. It is also available at
* the following URL: http://www.opensource.org/licenses/BSD-3-Clause
*
* @package Glottos
* @version 1.0.0
* @author Antonio Carlos Ribeiro @ PragmaRX
* @license BSD License (3-clause)
* @copyright (c) 2013, PragmaRX
* @link http://pragmarx.com
*/
class Language extends LocaleBase implements LanguageInterface {
/**
* Find a language in dataset
*
* @param string $language
* @return object|null
*/
public function find($language)
{
$cacheKey = __CLASS__.__FUNCTION__.$language;
if ( ! $cached = $model = $this->cache->get($cacheKey))
{
$model = $this->model->find($language);
}
if ( ! $cached && $model )
{
$this->cache->put($cacheKey, $model);
}
return $model;
}
} | bsd-3-clause |
keishi/chromium | chrome/browser/ui/views/ash/balloon_view_ash.cc | 5859 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/ash/balloon_view_ash.h"
#include "ash/shell.h"
#include "ash/system/status_area_widget.h"
#include "ash/system/web_notification/web_notification_tray.h"
#include "base/logging.h"
#include "chrome/browser/favicon/favicon_util.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/notifications/balloon_collection.h"
#include "chrome/browser/notifications/notification.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/icon_messages.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/browser/web_contents_observer.h"
#include "ipc/ipc_message.h"
#include "ipc/ipc_message_macros.h"
#include "ui/gfx/image/image_skia.h"
#include "webkit/glue/image_resource_fetcher.h"
namespace {
const int kNotificationIconImageSize = 32;
ash::WebNotificationTray* GetWebNotificationTray() {
return ash::Shell::GetInstance()->
status_area_widget()->web_notification_tray();
}
} // namespace
class BalloonViewAsh::IconFetcher : public content::WebContentsObserver {
public:
IconFetcher(content::WebContents* web_contents,
const std::string& notification_id,
const GURL& icon_url)
: content::WebContentsObserver(web_contents),
request_id_(0),
notification_id_(notification_id),
icon_url_(icon_url) {
Observe(web_contents);
content::RenderViewHost* host = web_contents->GetRenderViewHost();
request_id_ = FaviconUtil::DownloadFavicon(host,
icon_url,
kNotificationIconImageSize);
}
// content::WebContentsObserver override.
virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE {
bool message_handled = false; // Allow other handlers to receive these.
IPC_BEGIN_MESSAGE_MAP(IconFetcher, message)
IPC_MESSAGE_HANDLER(IconHostMsg_DidDownloadFavicon, OnDidDownloadFavicon)
IPC_MESSAGE_UNHANDLED(message_handled = false)
IPC_END_MESSAGE_MAP()
return message_handled;
}
void OnDidDownloadFavicon(int id,
const GURL& image_url,
bool errored,
const SkBitmap& bitmap) {
if (image_url != icon_url_ || id != request_id_)
return;
GetWebNotificationTray()->SetNotificationImage(
notification_id_, gfx::ImageSkia(bitmap));
}
private:
int request_id_;
std::string notification_id_;
GURL icon_url_;
DISALLOW_COPY_AND_ASSIGN(IconFetcher);
};
BalloonViewAsh::BalloonViewAsh(BalloonCollection* collection)
: collection_(collection),
balloon_(NULL) {
}
BalloonViewAsh::~BalloonViewAsh() {
}
// BalloonView interface.
void BalloonViewAsh::Show(Balloon* balloon) {
balloon_ = balloon;
const Notification& notification = balloon_->notification();
std::string extension_id = GetExtensionId(balloon);
GetWebNotificationTray()->AddNotification(notification.notification_id(),
notification.title(),
notification.body(),
notification.display_source(),
extension_id);
FetchIcon(notification);
}
void BalloonViewAsh::Update() {
const Notification& notification = balloon_->notification();
GetWebNotificationTray()->UpdateNotification(notification.notification_id(),
notification.title(),
notification.body());
FetchIcon(notification);
}
void BalloonViewAsh::RepositionToBalloon() {
}
void BalloonViewAsh::Close(bool by_user) {
Notification notification(balloon_->notification()); // Copy notification
collection_->OnBalloonClosed(balloon_); // Deletes balloon.
notification.Close(by_user);
GetWebNotificationTray()->RemoveNotification(notification.notification_id());
}
gfx::Size BalloonViewAsh::GetSize() const {
return gfx::Size();
}
BalloonHost* BalloonViewAsh::GetHost() const {
return NULL;
}
void BalloonViewAsh::FetchIcon(const Notification& notification) {
if (!notification.icon().empty()) {
ash::Shell::GetInstance()->status_area_widget()->
web_notification_tray()->SetNotificationImage(
notification.notification_id(), notification.icon());
return;
}
if (notification.icon_url().is_empty())
return;
content::RenderViewHost* rvh = notification.GetRenderViewHost();
if (!rvh) {
LOG(WARNING) << "Notification has icon url but no RenderViewHost";
return;
}
content::WebContents* web_contents =
content::WebContents::FromRenderViewHost(rvh);
if (!web_contents) {
LOG(WARNING) << "Notification has icon url but no WebContents";
return;
}
icon_fetcher_.reset(new IconFetcher(web_contents,
notification.notification_id(),
notification.icon_url()));
}
std::string BalloonViewAsh::GetExtensionId(Balloon* balloon) {
ExtensionService* extension_service =
balloon_->profile()->GetExtensionService();
const GURL& origin = balloon_->notification().origin_url();
const extensions::Extension* extension =
extension_service->extensions()->GetExtensionOrAppByURL(
ExtensionURLInfo(origin));
if (extension)
return extension->id();
return std::string();
}
| bsd-3-clause |
mtaki/BongoERP | modules/setting/views/aplpo/create.php | 1431 | <?php
use yii\helpers\Html;
?>
<div class="contentpanel">
<!--\\\\\\\ contentpanel start\\\\\\-->
<div class="pull-left breadcrumb_admin clear_both">
<div class="pull-left page_title theme_color">
<h1>Setting</h1>
<h2 class="">ap-lpo</h2>
</div>
<div class="pull-right">
<ol class="breadcrumb">
<li><a href="#">Home</a></li>
<li><a href="#">FORMS</a></li>
<li class="active">Form</li>
</ol>
</div>
</div>
<div class="container clear_both padding_fix">
<!--\\\\\\\ container start \\\\\\-->
<div class="row">
<div class="col-md-12">
<div class="block-web">
<div class="header">
<div class="actions">
<a class="minimize" href="#"><i class="fa fa-chevron-down"></i></a>
<a class="close-down" href="#"><i class="fa fa-times"></i></a>
</div>
<h3 class="content-header">Create </h3>
</div>
<div class="porlets-content">
<div class="ap-lpo-index">
<h1><?= Html::encode($this->title) ?></h1>
<p><?= Html::a(Yii::t('app', 'Create Ap Lpo'), ['create'], ['class' => 'btn btn-success']) ?></p>
<?= $this->render('_form', [ 'model' => $model,]) ?>
</div><!--/col-md-6-->
</div>
</div>
<!--\\\\\\\ container end \\\\\\-->
</div>
<!--\\\\\\\ content panel end \\\\\\-->
| bsd-3-clause |
danakj/chromium | components/data_reduction_proxy/core/common/data_reduction_proxy_event_store.cc | 8880 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_event_store.h"
#include <stddef.h>
#include <stdint.h>
#include <utility>
#include <vector>
#include "base/json/json_writer.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/time/time.h"
#include "base/values.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_event_storage_delegate.h"
namespace {
const size_t kMaxEventsToStore = 100;
// Used by Data Reduction Proxy feedback reports. If the last bypass happened in
// the last 5 minutes, the url will be cropped to only the host.
const int kLastBypassTimeDeltaInMinutes = 5;
struct StringToConstant {
const char* name;
const int constant;
};
// Creates an associative array of the enum name to enum value for
// DataReductionProxyBypassType. Ensures that the same enum space is used
// without having to keep an enum map in sync.
const StringToConstant kDataReductionProxyBypassEventTypeTable[] = {
#define BYPASS_EVENT_TYPE(label, value) { \
# label, data_reduction_proxy::BYPASS_EVENT_TYPE_ ## label },
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_bypass_type_list.h"
#undef BYPASS_EVENT_TYPE
};
// Creates an associate array of the enum name to enum value for
// DataReductionProxyBypassAction. Ensures that the same enum space is used
// without having to keep an enum map in sync.
const StringToConstant kDataReductionProxyBypassActionTypeTable[] = {
#define BYPASS_ACTION_TYPE(label, value) \
{ #label, data_reduction_proxy::BYPASS_ACTION_TYPE_##label } \
,
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_bypass_action_list.h"
#undef BYPASS_ACTION_TYPE
};
std::string JoinListValueStrings(base::ListValue* list_value) {
std::vector<std::string> values;
for (const auto& value : *list_value) {
std::string value_string;
if (!value->GetAsString(&value_string))
return std::string();
values.push_back(value_string);
}
return base::JoinString(values, ";");
}
} // namespace
namespace data_reduction_proxy {
// static
void DataReductionProxyEventStore::AddConstants(
base::DictionaryValue* constants_dict) {
auto dict = base::MakeUnique<base::DictionaryValue>();
for (size_t i = 0;
i < arraysize(kDataReductionProxyBypassEventTypeTable); ++i) {
dict->SetInteger(kDataReductionProxyBypassEventTypeTable[i].name,
kDataReductionProxyBypassEventTypeTable[i].constant);
}
constants_dict->Set("dataReductionProxyBypassEventType", std::move(dict));
dict = base::MakeUnique<base::DictionaryValue>();
for (size_t i = 0; i < arraysize(kDataReductionProxyBypassActionTypeTable);
++i) {
dict->SetInteger(kDataReductionProxyBypassActionTypeTable[i].name,
kDataReductionProxyBypassActionTypeTable[i].constant);
}
constants_dict->Set("dataReductionProxyBypassActionType", std::move(dict));
}
DataReductionProxyEventStore::DataReductionProxyEventStore()
: enabled_(false),
secure_proxy_check_state_(CHECK_UNKNOWN),
expiration_ticks_(0) {
}
DataReductionProxyEventStore::~DataReductionProxyEventStore() {
}
std::unique_ptr<base::DictionaryValue>
DataReductionProxyEventStore::GetSummaryValue() const {
DCHECK(thread_checker_.CalledOnValidThread());
auto data_reduction_proxy_values = base::MakeUnique<base::DictionaryValue>();
data_reduction_proxy_values->SetBoolean("enabled", enabled_);
if (current_configuration_) {
data_reduction_proxy_values->Set("proxy_config",
current_configuration_->DeepCopy());
}
switch (secure_proxy_check_state_) {
case CHECK_PENDING:
data_reduction_proxy_values->SetString("probe", "Pending");
break;
case CHECK_SUCCESS:
data_reduction_proxy_values->SetString("probe", "Success");
break;
case CHECK_FAILED:
data_reduction_proxy_values->SetString("probe", "Failed");
break;
case CHECK_UNKNOWN:
break;
}
base::Value* last_bypass_event = last_bypass_event_.get();
if (last_bypass_event) {
int current_time_ticks_ms =
(base::TimeTicks::Now() - base::TimeTicks()).InMilliseconds();
if (expiration_ticks_ > current_time_ticks_ms) {
data_reduction_proxy_values->Set("last_bypass",
last_bypass_event->DeepCopy());
}
}
auto events_list = base::MakeUnique<base::ListValue>();
for (const auto& event : stored_events_)
events_list->Append(event->DeepCopy());
data_reduction_proxy_values->Set("events", std::move(events_list));
return data_reduction_proxy_values;
}
void DataReductionProxyEventStore::AddEvent(
std::unique_ptr<base::Value> event) {
if (stored_events_.size() == kMaxEventsToStore)
stored_events_.pop_front();
stored_events_.push_back(std::move(event));
}
void DataReductionProxyEventStore::AddEnabledEvent(
std::unique_ptr<base::Value> event,
bool enabled) {
DCHECK(thread_checker_.CalledOnValidThread());
enabled_ = enabled;
if (enabled)
current_configuration_.reset(event->DeepCopy());
else
current_configuration_.reset();
AddEvent(std::move(event));
}
void DataReductionProxyEventStore::AddEventAndSecureProxyCheckState(
std::unique_ptr<base::Value> event,
SecureProxyCheckState state) {
DCHECK(thread_checker_.CalledOnValidThread());
secure_proxy_check_state_ = state;
AddEvent(std::move(event));
}
void DataReductionProxyEventStore::AddAndSetLastBypassEvent(
std::unique_ptr<base::Value> event,
int64_t expiration_ticks) {
DCHECK(thread_checker_.CalledOnValidThread());
last_bypass_event_.reset(event->DeepCopy());
expiration_ticks_ = expiration_ticks;
AddEvent(std::move(event));
}
std::string DataReductionProxyEventStore::GetHttpProxyList() const {
DCHECK(thread_checker_.CalledOnValidThread());
if (!enabled_ || !current_configuration_)
return std::string();
base::DictionaryValue* config_dict;
if (!current_configuration_->GetAsDictionary(&config_dict))
return std::string();
base::DictionaryValue* params_dict;
if (!config_dict->GetDictionary("params", ¶ms_dict))
return std::string();
base::ListValue* proxy_list;
if (!params_dict->GetList("http_proxy_list", &proxy_list))
return std::string();
return JoinListValueStrings(proxy_list);
}
std::string DataReductionProxyEventStore::SanitizedLastBypassEvent() const {
DCHECK(thread_checker_.CalledOnValidThread());
if (!enabled_ || !last_bypass_event_)
return std::string();
base::DictionaryValue* bypass_dict;
base::DictionaryValue* params_dict;
if (!last_bypass_event_->GetAsDictionary(&bypass_dict))
return std::string();
if (!bypass_dict->GetDictionary("params", ¶ms_dict))
return std::string();
// Explicitly add parameters to prevent automatic adding of new parameters.
auto last_bypass = base::MakeUnique<base::DictionaryValue>();
std::string str_value;
int int_value;
if (params_dict->GetInteger("bypass_type", &int_value))
last_bypass->SetInteger("bypass_type", int_value);
if (params_dict->GetInteger("bypass_action_type", &int_value))
last_bypass->SetInteger("bypass_action", int_value);
if (params_dict->GetString("bypass_duration_seconds", &str_value))
last_bypass->SetString("bypass_seconds", str_value);
bool truncate_url_to_host = true;
if (bypass_dict->GetString("time", &str_value)) {
last_bypass->SetString("bypass_time", str_value);
int64_t bypass_ticks_ms;
base::StringToInt64(str_value, &bypass_ticks_ms);
base::TimeTicks bypass_ticks =
base::TimeTicks() + base::TimeDelta::FromMilliseconds(bypass_ticks_ms);
// If the last bypass happened in the last 5 minutes, don't crop the url to
// the host.
if (base::TimeTicks::Now() - bypass_ticks <
base::TimeDelta::FromMinutes(kLastBypassTimeDeltaInMinutes)) {
truncate_url_to_host = false;
}
}
if (params_dict->GetString("method", &str_value))
last_bypass->SetString("method", str_value);
if (params_dict->GetString("url", &str_value)) {
GURL url(str_value);
if (truncate_url_to_host) {
last_bypass->SetString("url", url.host());
} else {
GURL::Replacements replacements;
replacements.ClearQuery();
GURL clean_url = url.ReplaceComponents(replacements);
last_bypass->SetString("url", clean_url.spec());
}
}
std::string json;
base::JSONWriter::Write(*last_bypass.get(), &json);
return json;
}
} // namespace data_reduction_proxy
| bsd-3-clause |
cychenyin/postmill | tests/testlynx.js | 1417 | #!/bin/env node
var lynx = require('lynx');
var opt = {}; // opt.prefix = 'myPrefix';
var metrics = new lynx('localhost', 8125, opt); // StatsD IP & Port
metrics.gauge('test.backend.lynx.gauge', 300); // Send our first metric
metrics.increment('test.backend.lynx.inc', 1, 0.1);
metrics.increment('test.backend.lynx.inc', 1, 0.1);
metrics.decrement('test.backend.lynx.inc',1, 0.1);
// metrics.count('test.backend.lynx.inc', 10, 0.1);
// metrics.timing('test.backend.lynx.time', 500, 0.1);
// metrics.gauge('test.backend.lynx.gauge.one', 100, 0.1);
// metrics.set('test.back.lynx.set.one', 10, 0.1);
// return;
var end = +new Date + 24 * 3600 * 1000; // 1 day
var i = 0;
while(+new Date < end ) {
i++;
//sdc.increment('test.backend.nodejs.x1', (+new Date) % 100 );
metrics.increment('test.backend.lynx.inc', 10, 0.1);
//metrics.decrement('test.backend.lynx.inc',1, 0.1);
//metrics.count('test.backend.lynx.inc', 10, 0.1);
//metrics.timing('test.backend.lynx.time', 500, 0.1);
//metrics.gauge('test.backend.lynx.gauge.one', 100, 0.1);
//metrics.set('test.back.lynx.set.one', 10, 0.1);
if( i % 10 == 0) {
console.log(i);
console.log(+new Date);
}
sleep(100);
}
metrics.close();
function sleep(sleepTime) {
for(var start = +new Date; +new Date - start <= sleepTime; ) { }
}
| bsd-3-clause |
cloud-mes/cloud-mes | core/app/models/mes/order_type.rb | 56 | module Mes
class OrderType < Mes::NamedType
end
end
| bsd-3-clause |
adminion/adminion | lib/transport/realtime/games.js | 8121 |
// node core modules
var url = require('url'),
util = require('util');
// 3rd-party modules
var debug = require('debug')('adminion:transport:realtime:games'),
mongoose = require('mongoose'),
passportSocketio = require('passport.socketio');
module.exports = function gamesNsp (io, data, authOptions) {
var games = io.of('/games')
// setup authorization
.use(passportSocketio.authorize(authOptions))
// setup connection event
.on('connect', socketConnect);
function roster (players) {
var account,
i,
displayName,
player,
ready,
roster = {},
seat = {};
// debug('players', players);
for ( i in players) {
// debug('i', i);
player = players[i];
account = (player) ? data.accounts.byID(player.account) : undefined;
// debug('account', account);
displayName = (account) ? account.displayName : ' ';
ready = (player) ? player.ready : ' ';
roster [i] = {
displayName: displayName,
ready: ready
};
}
return roster;
};
function socketConnect (socket, next) {
var accountID = socket.request.user._id,
displayName = socket.request.user.displayName;
socket.on('join', onJoin);
socket.on('watch', onWatch);
function onJoin () {
var gameID = url.parse(socket.request.headers.referer).pathname.split('/')[2],
game,
openSeats,
startTimer;
if (!gameID) {
return new Error('invalid gameID: ' + gameID);
}
// get a working copy of the game
game = data.games.byID(gameID);
// if the game is undefined
if (!game) {
return new Error('game not found');
}
// if the account is not registered
if (!game.isRegistered(accountID)) {
// if registration is still open
if (game.registration.state === 'open') {
game.register(accountID);
}
// otherwise the account is not registered
else {
// if the account is player one
if (game.isPlayerOne(accountID)) {
// register player One
}
}
socket.gameID = gameID;
data.games.set(game);
// tell all clients the new roster
games.in(gameID).emit('roster', roster(game.playersConnected()));
// tell all the other accounts that the new account entered the lobby
games.in(gameID).emit('joined', displayName);
// debug(util.format('%s entered game lobby %s', displayName, gameID));
};
// add socket to cache
data.sockets.add(socket);
// greet the new socket
socket.emit('sysMsg', util.format('Welcome, %s!', displayName));
// send the roster to the new socket
socket.emit('roster', roster(game.playersConnected()));
// assign event handler for when the player says "i'm ready!"
socket.on('player ready', onPlayerReady );
// if the socket is playerOne, setup these event handlers
if (game.isPlayerOne(accountID)) {
socket.on('start', onStart);
socket.on('kill', onKill);
socket.on('config', onConfig);
}
// join the socket to the chat room "gameID"
socket.join(gameID);
socket.emit('join', true);
function onConfig (option, value) {
// debug('option', option);
// debug('value', value);
if (game.config.hasOwnProperty(option)) {
game.config[option] = value;
data.games.set()(game);
games.in(socket.gameID).emit('config', option, value);
}
// debug('player one has adjusted the configuration.');
// debug(option, value);
}
function onKill (value) {
if (value === true) {
data.games.remove(socket.gameID, function (err) {
if (err) {
// notify playerOne of failure
socket.emit('kill', false);
throw err;
}
// otherwise, tell all sockets the game has been killed
games.in(socket.gameID).emit('kill', true);
data.games.remove(socket.gameID);
});
}
};
function onPlayerReady (value) {
var regID,
playerOneSockets,
readyPlayerSockets;
debug(util.format('socket ready: %s', value));
debug('startTimer', startTimer);
if (startTimer && !value) {
clearTimeout(startTimer);
startTimer = undefined;
games.in(gameID).emit('starting', false, displayName);
}
game.playerReady(accountID, value);
// tell all sockets belonging to this account that they are ready (in case multiple windows are open)
readyPlayerSockets = data.sockets.byAccount(accountID);
readyPlayerSockets.forEach(function (socket) {
socket.emit('player ready', value);
});
games.in(gameID).emit('roster', roster(game.playersConnected()));
// debug('game.playerOne', game.playerOne);
playerOneSockets = data.sockets.byAccount(game.playerOne._id);
// debug('playerOneSockets', playerOneSockets);
if (game.ready()) {
// debug('all players ready!');
playerOneSockets.forEach(function (socket) {
socket.emit('ready', true);
});
} else {
if (playerOneSockets) {
playerOneSockets.forEach(function (socket) {
socket.emit('ready', false);
});
}
}
};
function onStart () {
var delay = 10000;
if (game.allReady()) {
games.in(socket.gameID).emit('starting', delay);
// debug('game', game);
startTimer = setTimeout(function startTimerCallback () {
// close registration and start the game...
game.startGame(onceGameStarted);
}, delay);
debug('start timer', startTimer);
}
};
return true;
};
function onWatch () {
debug('socket watching games list')
socket.emit('list', data.games());
};
function onceStarted (err, savedGame) {
if (err) {
// debug('the game was not saved!');
throw err;
}
// debug('savedGame', savedGame);
// debug('the game was saved!')
data.games.set()(savedGame);
// tell socket clients to redirect to the game ...board...?
games.in(socket.gameID).emit('start');
}
// next();
};
return games;
}
| bsd-3-clause |
LeonidLyalin/vova | common/humhub/protected/humhub/modules/admin/messages/tr/base.php | 817 | <?php
return array (
'About' => 'Hakkımda',
'Add purchased module by licence key' => 'Satın alınan lisans anahtarı ile modül ekle',
'Admin' => 'Yönetici',
'Administration' => 'Yönetim',
'Approval' => 'Onay',
'Authentication' => 'Kimlik doğrulama',
'Basic' => 'Temel',
'Caching' => 'Ön bellekleme',
'Cronjobs' => 'Cronjobs',
'Design' => 'Tasarım',
'Files' => 'Dosyalar',
'Groups' => 'Gruplar',
'Logging' => 'Oturum',
'Mailing' => 'Posta',
'Modules' => 'Modüller',
'OEmbed providers' => 'OEmbed sağlayıcılar',
'Proxy' => 'Proxy',
'Security' => 'Güvenlik',
'Self test' => 'Test et',
'Spaces' => 'Mekanlar',
'Statistics' => 'İstatistikler',
'User posts' => 'Kullanıcı mesajlar',
'Userprofiles' => 'Kullanıcı profilleri',
'Users' => 'Kullanıcılar',
);
| bsd-3-clause |
endlessm/chromium-browser | third_party/webrtc/video/video_send_stream_impl_unittest.cc | 41668 | /*
* Copyright 2018 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "video/video_send_stream_impl.h"
#include <algorithm>
#include <memory>
#include <string>
#include "absl/types/optional.h"
#include "api/rtc_event_log/rtc_event_log.h"
#include "call/rtp_video_sender.h"
#include "call/test/mock_bitrate_allocator.h"
#include "call/test/mock_rtp_transport_controller_send.h"
#include "modules/rtp_rtcp/source/rtp_sequence_number_map.h"
#include "modules/utility/include/process_thread.h"
#include "modules/video_coding/fec_controller_default.h"
#include "rtc_base/experiments/alr_experiment.h"
#include "rtc_base/fake_clock.h"
#include "rtc_base/task_queue_for_test.h"
#include "test/field_trial.h"
#include "test/gmock.h"
#include "test/gtest.h"
#include "test/mock_transport.h"
#include "video/call_stats.h"
#include "video/test/mock_video_stream_encoder.h"
namespace webrtc {
bool operator==(const BitrateAllocationUpdate& a,
const BitrateAllocationUpdate& b) {
return a.target_bitrate == b.target_bitrate &&
a.round_trip_time == b.round_trip_time &&
a.packet_loss_ratio == b.packet_loss_ratio;
}
namespace internal {
namespace {
using ::testing::_;
using ::testing::AllOf;
using ::testing::Field;
using ::testing::Invoke;
using ::testing::NiceMock;
using ::testing::Return;
constexpr int64_t kDefaultInitialBitrateBps = 333000;
const double kDefaultBitratePriority = 0.5;
const float kAlrProbingExperimentPaceMultiplier = 1.0f;
std::string GetAlrProbingExperimentString() {
return std::string(
AlrExperimentSettings::kScreenshareProbingBweExperimentName) +
"/1.0,2875,80,40,-60,3/";
}
class MockRtpVideoSender : public RtpVideoSenderInterface {
public:
MOCK_METHOD1(RegisterProcessThread, void(ProcessThread*));
MOCK_METHOD0(DeRegisterProcessThread, void());
MOCK_METHOD1(SetActive, void(bool));
MOCK_METHOD1(SetActiveModules, void(const std::vector<bool>));
MOCK_METHOD0(IsActive, bool());
MOCK_METHOD1(OnNetworkAvailability, void(bool));
MOCK_CONST_METHOD0(GetRtpStates, std::map<uint32_t, RtpState>());
MOCK_CONST_METHOD0(GetRtpPayloadStates,
std::map<uint32_t, RtpPayloadState>());
MOCK_METHOD2(DeliverRtcp, void(const uint8_t*, size_t));
MOCK_METHOD1(OnBitrateAllocationUpdated, void(const VideoBitrateAllocation&));
MOCK_METHOD3(OnEncodedImage,
EncodedImageCallback::Result(const EncodedImage&,
const CodecSpecificInfo*,
const RTPFragmentationHeader*));
MOCK_METHOD1(OnTransportOverheadChanged, void(size_t));
MOCK_METHOD1(OnOverheadChanged, void(size_t));
MOCK_METHOD2(OnBitrateUpdated, void(BitrateAllocationUpdate, int));
MOCK_CONST_METHOD0(GetPayloadBitrateBps, uint32_t());
MOCK_CONST_METHOD0(GetProtectionBitrateBps, uint32_t());
MOCK_METHOD3(SetEncodingData, void(size_t, size_t, size_t));
MOCK_CONST_METHOD2(GetSentRtpPacketInfos,
std::vector<RtpSequenceNumberMap::Info>(
uint32_t ssrc,
rtc::ArrayView<const uint16_t> sequence_numbers));
MOCK_METHOD1(SetFecAllowed, void(bool fec_allowed));
};
BitrateAllocationUpdate CreateAllocation(int bitrate_bps) {
BitrateAllocationUpdate update;
update.target_bitrate = DataRate::BitsPerSec(bitrate_bps);
update.packet_loss_ratio = 0;
update.round_trip_time = TimeDelta::Zero();
return update;
}
} // namespace
class VideoSendStreamImplTest : public ::testing::Test {
protected:
VideoSendStreamImplTest()
: clock_(1000 * 1000 * 1000),
config_(&transport_),
send_delay_stats_(&clock_),
test_queue_("test_queue"),
process_thread_(ProcessThread::Create("test_thread")),
call_stats_(&clock_, process_thread_.get()),
stats_proxy_(&clock_,
config_,
VideoEncoderConfig::ContentType::kRealtimeVideo) {
config_.rtp.ssrcs.push_back(8080);
config_.rtp.payload_type = 1;
EXPECT_CALL(transport_controller_, packet_router())
.WillRepeatedly(Return(&packet_router_));
EXPECT_CALL(transport_controller_, CreateRtpVideoSender)
.WillRepeatedly(Return(&rtp_video_sender_));
EXPECT_CALL(rtp_video_sender_, SetActive(_))
.WillRepeatedly(::testing::Invoke(
[&](bool active) { rtp_video_sender_active_ = active; }));
EXPECT_CALL(rtp_video_sender_, IsActive())
.WillRepeatedly(
::testing::Invoke([&]() { return rtp_video_sender_active_; }));
}
~VideoSendStreamImplTest() {}
std::unique_ptr<VideoSendStreamImpl> CreateVideoSendStreamImpl(
int initial_encoder_max_bitrate,
double initial_encoder_bitrate_priority,
VideoEncoderConfig::ContentType content_type) {
EXPECT_CALL(bitrate_allocator_, GetStartBitrate(_))
.WillOnce(Return(123000));
std::map<uint32_t, RtpState> suspended_ssrcs;
std::map<uint32_t, RtpPayloadState> suspended_payload_states;
return std::make_unique<VideoSendStreamImpl>(
&clock_, &stats_proxy_, &test_queue_, &call_stats_,
&transport_controller_, &bitrate_allocator_, &send_delay_stats_,
&video_stream_encoder_, &event_log_, &config_,
initial_encoder_max_bitrate, initial_encoder_bitrate_priority,
suspended_ssrcs, suspended_payload_states, content_type,
std::make_unique<FecControllerDefault>(&clock_));
}
protected:
NiceMock<MockTransport> transport_;
NiceMock<MockRtpTransportControllerSend> transport_controller_;
NiceMock<MockBitrateAllocator> bitrate_allocator_;
NiceMock<MockVideoStreamEncoder> video_stream_encoder_;
NiceMock<MockRtpVideoSender> rtp_video_sender_;
bool rtp_video_sender_active_ = false;
SimulatedClock clock_;
RtcEventLogNull event_log_;
VideoSendStream::Config config_;
SendDelayStats send_delay_stats_;
TaskQueueForTest test_queue_;
std::unique_ptr<ProcessThread> process_thread_;
// TODO(tommi): Use internal::CallStats
CallStats call_stats_;
SendStatisticsProxy stats_proxy_;
PacketRouter packet_router_;
};
TEST_F(VideoSendStreamImplTest, RegistersAsBitrateObserverOnStart) {
test_queue_.SendTask(
[this] {
const bool kSuspend = false;
config_.suspend_below_min_bitrate = kSuspend;
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kRealtimeVideo);
EXPECT_CALL(bitrate_allocator_, AddObserver(vss_impl.get(), _))
.WillOnce(Invoke([&](BitrateAllocatorObserver*,
MediaStreamAllocationConfig config) {
EXPECT_EQ(config.min_bitrate_bps, 0u);
EXPECT_EQ(config.max_bitrate_bps, kDefaultInitialBitrateBps);
EXPECT_EQ(config.pad_up_bitrate_bps, 0u);
EXPECT_EQ(config.enforce_min_bitrate, !kSuspend);
EXPECT_EQ(config.bitrate_priority, kDefaultBitratePriority);
}));
vss_impl->Start();
EXPECT_CALL(bitrate_allocator_, RemoveObserver(vss_impl.get()))
.Times(1);
vss_impl->Stop();
},
RTC_FROM_HERE);
}
TEST_F(VideoSendStreamImplTest, UpdatesObserverOnConfigurationChange) {
test_queue_.SendTask(
[this] {
const bool kSuspend = false;
config_.suspend_below_min_bitrate = kSuspend;
config_.rtp.extensions.emplace_back(
RtpExtension::kTransportSequenceNumberUri, 1);
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kRealtimeVideo);
vss_impl->Start();
// QVGA + VGA configuration matching defaults in
// media/engine/simulcast.cc.
VideoStream qvga_stream;
qvga_stream.width = 320;
qvga_stream.height = 180;
qvga_stream.max_framerate = 30;
qvga_stream.min_bitrate_bps = 30000;
qvga_stream.target_bitrate_bps = 150000;
qvga_stream.max_bitrate_bps = 200000;
qvga_stream.max_qp = 56;
qvga_stream.bitrate_priority = 1;
VideoStream vga_stream;
vga_stream.width = 640;
vga_stream.height = 360;
vga_stream.max_framerate = 30;
vga_stream.min_bitrate_bps = 150000;
vga_stream.target_bitrate_bps = 500000;
vga_stream.max_bitrate_bps = 700000;
vga_stream.max_qp = 56;
vga_stream.bitrate_priority = 1;
int min_transmit_bitrate_bps = 30000;
config_.rtp.ssrcs.emplace_back(1);
config_.rtp.ssrcs.emplace_back(2);
EXPECT_CALL(bitrate_allocator_, AddObserver(vss_impl.get(), _))
.WillRepeatedly(Invoke([&](BitrateAllocatorObserver*,
MediaStreamAllocationConfig config) {
EXPECT_EQ(config.min_bitrate_bps,
static_cast<uint32_t>(min_transmit_bitrate_bps));
EXPECT_EQ(config.max_bitrate_bps,
static_cast<uint32_t>(qvga_stream.max_bitrate_bps +
vga_stream.max_bitrate_bps));
if (config.pad_up_bitrate_bps != 0) {
EXPECT_EQ(config.pad_up_bitrate_bps,
static_cast<uint32_t>(qvga_stream.target_bitrate_bps +
vga_stream.min_bitrate_bps));
}
EXPECT_EQ(config.enforce_min_bitrate, !kSuspend);
}));
static_cast<VideoStreamEncoderInterface::EncoderSink*>(vss_impl.get())
->OnEncoderConfigurationChanged(
std::vector<VideoStream>{qvga_stream, vga_stream}, false,
VideoEncoderConfig::ContentType::kRealtimeVideo,
min_transmit_bitrate_bps);
vss_impl->Stop();
},
RTC_FROM_HERE);
}
TEST_F(VideoSendStreamImplTest, UpdatesObserverOnConfigurationChangeWithAlr) {
test_queue_.SendTask(
[this] {
const bool kSuspend = false;
config_.suspend_below_min_bitrate = kSuspend;
config_.rtp.extensions.emplace_back(
RtpExtension::kTransportSequenceNumberUri, 1);
config_.periodic_alr_bandwidth_probing = true;
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kScreen);
vss_impl->Start();
// Simulcast screenshare.
VideoStream low_stream;
low_stream.width = 1920;
low_stream.height = 1080;
low_stream.max_framerate = 5;
low_stream.min_bitrate_bps = 30000;
low_stream.target_bitrate_bps = 200000;
low_stream.max_bitrate_bps = 1000000;
low_stream.num_temporal_layers = 2;
low_stream.max_qp = 56;
low_stream.bitrate_priority = 1;
VideoStream high_stream;
high_stream.width = 1920;
high_stream.height = 1080;
high_stream.max_framerate = 30;
high_stream.min_bitrate_bps = 60000;
high_stream.target_bitrate_bps = 1250000;
high_stream.max_bitrate_bps = 1250000;
high_stream.num_temporal_layers = 2;
high_stream.max_qp = 56;
high_stream.bitrate_priority = 1;
// With ALR probing, this will be the padding target instead of
// low_stream.target_bitrate_bps + high_stream.min_bitrate_bps.
int min_transmit_bitrate_bps = 400000;
config_.rtp.ssrcs.emplace_back(1);
config_.rtp.ssrcs.emplace_back(2);
EXPECT_CALL(bitrate_allocator_, AddObserver(vss_impl.get(), _))
.WillRepeatedly(Invoke([&](BitrateAllocatorObserver*,
MediaStreamAllocationConfig config) {
EXPECT_EQ(config.min_bitrate_bps,
static_cast<uint32_t>(low_stream.min_bitrate_bps));
EXPECT_EQ(config.max_bitrate_bps,
static_cast<uint32_t>(low_stream.max_bitrate_bps +
high_stream.max_bitrate_bps));
if (config.pad_up_bitrate_bps != 0) {
EXPECT_EQ(config.pad_up_bitrate_bps,
static_cast<uint32_t>(min_transmit_bitrate_bps));
}
EXPECT_EQ(config.enforce_min_bitrate, !kSuspend);
}));
static_cast<VideoStreamEncoderInterface::EncoderSink*>(vss_impl.get())
->OnEncoderConfigurationChanged(
std::vector<VideoStream>{low_stream, high_stream}, false,
VideoEncoderConfig::ContentType::kScreen,
min_transmit_bitrate_bps);
vss_impl->Stop();
},
RTC_FROM_HERE);
}
TEST_F(VideoSendStreamImplTest,
UpdatesObserverOnConfigurationChangeWithSimulcastVideoHysteresis) {
test::ScopedFieldTrials hysteresis_experiment(
"WebRTC-VideoRateControl/video_hysteresis:1.25/");
test_queue_.SendTask(
[this] {
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kRealtimeVideo);
vss_impl->Start();
// 2-layer video simulcast.
VideoStream low_stream;
low_stream.width = 320;
low_stream.height = 240;
low_stream.max_framerate = 30;
low_stream.min_bitrate_bps = 30000;
low_stream.target_bitrate_bps = 100000;
low_stream.max_bitrate_bps = 200000;
low_stream.max_qp = 56;
low_stream.bitrate_priority = 1;
VideoStream high_stream;
high_stream.width = 640;
high_stream.height = 480;
high_stream.max_framerate = 30;
high_stream.min_bitrate_bps = 150000;
high_stream.target_bitrate_bps = 500000;
high_stream.max_bitrate_bps = 750000;
high_stream.max_qp = 56;
high_stream.bitrate_priority = 1;
config_.rtp.ssrcs.emplace_back(1);
config_.rtp.ssrcs.emplace_back(2);
EXPECT_CALL(bitrate_allocator_, AddObserver(vss_impl.get(), _))
.WillRepeatedly(Invoke([&](BitrateAllocatorObserver*,
MediaStreamAllocationConfig config) {
EXPECT_EQ(config.min_bitrate_bps,
static_cast<uint32_t>(low_stream.min_bitrate_bps));
EXPECT_EQ(config.max_bitrate_bps,
static_cast<uint32_t>(low_stream.max_bitrate_bps +
high_stream.max_bitrate_bps));
if (config.pad_up_bitrate_bps != 0) {
EXPECT_EQ(
config.pad_up_bitrate_bps,
static_cast<uint32_t>(low_stream.target_bitrate_bps +
1.25 * high_stream.min_bitrate_bps));
}
}));
static_cast<VideoStreamEncoderInterface::EncoderSink*>(vss_impl.get())
->OnEncoderConfigurationChanged(
std::vector<VideoStream>{low_stream, high_stream}, false,
VideoEncoderConfig::ContentType::kRealtimeVideo,
/*min_transmit_bitrate_bps=*/0);
vss_impl->Stop();
},
RTC_FROM_HERE);
}
TEST_F(VideoSendStreamImplTest, SetsScreensharePacingFactorWithFeedback) {
test::ScopedFieldTrials alr_experiment(GetAlrProbingExperimentString());
test_queue_.SendTask(
[this] {
constexpr int kId = 1;
config_.rtp.extensions.emplace_back(
RtpExtension::kTransportSequenceNumberUri, kId);
EXPECT_CALL(transport_controller_,
SetPacingFactor(kAlrProbingExperimentPaceMultiplier))
.Times(1);
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kScreen);
vss_impl->Start();
vss_impl->Stop();
},
RTC_FROM_HERE);
}
TEST_F(VideoSendStreamImplTest, DoesNotSetPacingFactorWithoutFeedback) {
test::ScopedFieldTrials alr_experiment(GetAlrProbingExperimentString());
test_queue_.SendTask(
[this] {
EXPECT_CALL(transport_controller_, SetPacingFactor(_)).Times(0);
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kScreen);
vss_impl->Start();
vss_impl->Stop();
},
RTC_FROM_HERE);
}
TEST_F(VideoSendStreamImplTest, ForwardsVideoBitrateAllocationWhenEnabled) {
test_queue_.SendTask(
[this] {
EXPECT_CALL(transport_controller_, SetPacingFactor(_)).Times(0);
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kScreen);
vss_impl->Start();
VideoBitrateAllocationObserver* const observer =
static_cast<VideoBitrateAllocationObserver*>(vss_impl.get());
// Populate a test instance of video bitrate allocation.
VideoBitrateAllocation alloc;
alloc.SetBitrate(0, 0, 10000);
alloc.SetBitrate(0, 1, 20000);
alloc.SetBitrate(1, 0, 30000);
alloc.SetBitrate(1, 1, 40000);
// Encoder starts out paused, don't forward allocation.
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc))
.Times(0);
observer->OnBitrateAllocationUpdated(alloc);
// Unpause encoder, allocation should be passed through.
const uint32_t kBitrateBps = 100000;
EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps())
.Times(1)
.WillOnce(Return(kBitrateBps));
static_cast<BitrateAllocatorObserver*>(vss_impl.get())
->OnBitrateUpdated(CreateAllocation(kBitrateBps));
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc))
.Times(1);
observer->OnBitrateAllocationUpdated(alloc);
// Pause encoder again, and block allocations.
EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps())
.Times(1)
.WillOnce(Return(0));
static_cast<BitrateAllocatorObserver*>(vss_impl.get())
->OnBitrateUpdated(CreateAllocation(0));
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc))
.Times(0);
observer->OnBitrateAllocationUpdated(alloc);
vss_impl->Stop();
},
RTC_FROM_HERE);
}
TEST_F(VideoSendStreamImplTest, ThrottlesVideoBitrateAllocationWhenTooSimilar) {
test_queue_.SendTask(
[this] {
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kScreen);
vss_impl->Start();
// Unpause encoder, to allows allocations to be passed through.
const uint32_t kBitrateBps = 100000;
EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps())
.Times(1)
.WillOnce(Return(kBitrateBps));
static_cast<BitrateAllocatorObserver*>(vss_impl.get())
->OnBitrateUpdated(CreateAllocation(kBitrateBps));
VideoBitrateAllocationObserver* const observer =
static_cast<VideoBitrateAllocationObserver*>(vss_impl.get());
// Populate a test instance of video bitrate allocation.
VideoBitrateAllocation alloc;
alloc.SetBitrate(0, 0, 10000);
alloc.SetBitrate(0, 1, 20000);
alloc.SetBitrate(1, 0, 30000);
alloc.SetBitrate(1, 1, 40000);
// Initial value.
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc))
.Times(1);
observer->OnBitrateAllocationUpdated(alloc);
VideoBitrateAllocation updated_alloc = alloc;
// Needs 10% increase in bitrate to trigger immediate forward.
const uint32_t base_layer_min_update_bitrate_bps =
alloc.GetBitrate(0, 0) + alloc.get_sum_bps() / 10;
// Too small increase, don't forward.
updated_alloc.SetBitrate(0, 0, base_layer_min_update_bitrate_bps - 1);
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(_)).Times(0);
observer->OnBitrateAllocationUpdated(updated_alloc);
// Large enough increase, do forward.
updated_alloc.SetBitrate(0, 0, base_layer_min_update_bitrate_bps);
EXPECT_CALL(rtp_video_sender_,
OnBitrateAllocationUpdated(updated_alloc))
.Times(1);
observer->OnBitrateAllocationUpdated(updated_alloc);
// This is now a decrease compared to last forward allocation, forward
// immediately.
updated_alloc.SetBitrate(0, 0, base_layer_min_update_bitrate_bps - 1);
EXPECT_CALL(rtp_video_sender_,
OnBitrateAllocationUpdated(updated_alloc))
.Times(1);
observer->OnBitrateAllocationUpdated(updated_alloc);
vss_impl->Stop();
},
RTC_FROM_HERE);
}
TEST_F(VideoSendStreamImplTest, ForwardsVideoBitrateAllocationOnLayerChange) {
test_queue_.SendTask(
[this] {
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kScreen);
vss_impl->Start();
// Unpause encoder, to allows allocations to be passed through.
const uint32_t kBitrateBps = 100000;
EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps())
.Times(1)
.WillOnce(Return(kBitrateBps));
static_cast<BitrateAllocatorObserver*>(vss_impl.get())
->OnBitrateUpdated(CreateAllocation(kBitrateBps));
VideoBitrateAllocationObserver* const observer =
static_cast<VideoBitrateAllocationObserver*>(vss_impl.get());
// Populate a test instance of video bitrate allocation.
VideoBitrateAllocation alloc;
alloc.SetBitrate(0, 0, 10000);
alloc.SetBitrate(0, 1, 20000);
alloc.SetBitrate(1, 0, 30000);
alloc.SetBitrate(1, 1, 40000);
// Initial value.
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc))
.Times(1);
observer->OnBitrateAllocationUpdated(alloc);
// Move some bitrate from one layer to a new one, but keep sum the same.
// Since layout has changed, immediately trigger forward.
VideoBitrateAllocation updated_alloc = alloc;
updated_alloc.SetBitrate(2, 0, 10000);
updated_alloc.SetBitrate(1, 1, alloc.GetBitrate(1, 1) - 10000);
EXPECT_EQ(alloc.get_sum_bps(), updated_alloc.get_sum_bps());
EXPECT_CALL(rtp_video_sender_,
OnBitrateAllocationUpdated(updated_alloc))
.Times(1);
observer->OnBitrateAllocationUpdated(updated_alloc);
vss_impl->Stop();
},
RTC_FROM_HERE);
}
TEST_F(VideoSendStreamImplTest, ForwardsVideoBitrateAllocationAfterTimeout) {
test_queue_.SendTask(
[this] {
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kScreen);
vss_impl->Start();
const uint32_t kBitrateBps = 100000;
// Unpause encoder, to allows allocations to be passed through.
EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps())
.Times(1)
.WillRepeatedly(Return(kBitrateBps));
static_cast<BitrateAllocatorObserver*>(vss_impl.get())
->OnBitrateUpdated(CreateAllocation(kBitrateBps));
VideoBitrateAllocationObserver* const observer =
static_cast<VideoBitrateAllocationObserver*>(vss_impl.get());
// Populate a test instance of video bitrate allocation.
VideoBitrateAllocation alloc;
alloc.SetBitrate(0, 0, 10000);
alloc.SetBitrate(0, 1, 20000);
alloc.SetBitrate(1, 0, 30000);
alloc.SetBitrate(1, 1, 40000);
EncodedImage encoded_image;
CodecSpecificInfo codec_specific;
EXPECT_CALL(rtp_video_sender_, OnEncodedImage(_, _, _))
.WillRepeatedly(Return(EncodedImageCallback::Result(
EncodedImageCallback::Result::OK)));
// Max time we will throttle similar video bitrate allocations.
static constexpr int64_t kMaxVbaThrottleTimeMs = 500;
{
// Initial value.
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc))
.Times(1);
observer->OnBitrateAllocationUpdated(alloc);
}
{
// Sending same allocation again, this one should be throttled.
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc))
.Times(0);
observer->OnBitrateAllocationUpdated(alloc);
}
clock_.AdvanceTimeMicroseconds(kMaxVbaThrottleTimeMs * 1000);
{
// Sending similar allocation again after timeout, should forward.
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc))
.Times(1);
observer->OnBitrateAllocationUpdated(alloc);
}
{
// Sending similar allocation again without timeout, throttle.
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc))
.Times(0);
observer->OnBitrateAllocationUpdated(alloc);
}
{
// Send encoded image, should be a noop.
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc))
.Times(0);
static_cast<EncodedImageCallback*>(vss_impl.get())
->OnEncodedImage(encoded_image, &codec_specific, nullptr);
}
{
// Advance time and send encoded image, this should wake up and send
// cached bitrate allocation.
clock_.AdvanceTimeMicroseconds(kMaxVbaThrottleTimeMs * 1000);
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc))
.Times(1);
static_cast<EncodedImageCallback*>(vss_impl.get())
->OnEncodedImage(encoded_image, &codec_specific, nullptr);
}
{
// Advance time and send encoded image, there should be no cached
// allocation to send.
clock_.AdvanceTimeMicroseconds(kMaxVbaThrottleTimeMs * 1000);
EXPECT_CALL(rtp_video_sender_, OnBitrateAllocationUpdated(alloc))
.Times(0);
static_cast<EncodedImageCallback*>(vss_impl.get())
->OnEncodedImage(encoded_image, &codec_specific, nullptr);
}
vss_impl->Stop();
},
RTC_FROM_HERE);
}
TEST_F(VideoSendStreamImplTest, CallsVideoStreamEncoderOnBitrateUpdate) {
test_queue_.SendTask(
[this] {
const bool kSuspend = false;
config_.suspend_below_min_bitrate = kSuspend;
config_.rtp.extensions.emplace_back(
RtpExtension::kTransportSequenceNumberUri, 1);
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kRealtimeVideo);
vss_impl->Start();
VideoStream qvga_stream;
qvga_stream.width = 320;
qvga_stream.height = 180;
qvga_stream.max_framerate = 30;
qvga_stream.min_bitrate_bps = 30000;
qvga_stream.target_bitrate_bps = 150000;
qvga_stream.max_bitrate_bps = 200000;
qvga_stream.max_qp = 56;
qvga_stream.bitrate_priority = 1;
int min_transmit_bitrate_bps = 30000;
config_.rtp.ssrcs.emplace_back(1);
static_cast<VideoStreamEncoderInterface::EncoderSink*>(vss_impl.get())
->OnEncoderConfigurationChanged(
std::vector<VideoStream>{qvga_stream}, false,
VideoEncoderConfig::ContentType::kRealtimeVideo,
min_transmit_bitrate_bps);
const DataRate network_constrained_rate =
DataRate::BitsPerSec(qvga_stream.target_bitrate_bps);
BitrateAllocationUpdate update;
update.target_bitrate = network_constrained_rate;
update.stable_target_bitrate = network_constrained_rate;
update.round_trip_time = TimeDelta::Millis(1);
EXPECT_CALL(rtp_video_sender_, OnBitrateUpdated(update, _));
EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps())
.WillOnce(Return(network_constrained_rate.bps()));
EXPECT_CALL(
video_stream_encoder_,
OnBitrateUpdated(network_constrained_rate, network_constrained_rate,
network_constrained_rate, 0, _, 0));
static_cast<BitrateAllocatorObserver*>(vss_impl.get())
->OnBitrateUpdated(update);
// Test allocation where the link allocation is larger than the target,
// meaning we have some headroom on the link.
const DataRate qvga_max_bitrate =
DataRate::BitsPerSec(qvga_stream.max_bitrate_bps);
const DataRate headroom = DataRate::BitsPerSec(50000);
const DataRate rate_with_headroom = qvga_max_bitrate + headroom;
update.target_bitrate = rate_with_headroom;
update.stable_target_bitrate = rate_with_headroom;
EXPECT_CALL(rtp_video_sender_, OnBitrateUpdated(update, _));
EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps())
.WillOnce(Return(rate_with_headroom.bps()));
EXPECT_CALL(video_stream_encoder_,
OnBitrateUpdated(qvga_max_bitrate, qvga_max_bitrate,
rate_with_headroom, 0, _, 0));
static_cast<BitrateAllocatorObserver*>(vss_impl.get())
->OnBitrateUpdated(update);
// Add protection bitrate to the mix, this should be subtracted from the
// headroom.
const uint32_t protection_bitrate_bps = 10000;
EXPECT_CALL(rtp_video_sender_, GetProtectionBitrateBps())
.WillOnce(Return(protection_bitrate_bps));
EXPECT_CALL(rtp_video_sender_, OnBitrateUpdated(update, _));
EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps())
.WillOnce(Return(rate_with_headroom.bps()));
const DataRate headroom_minus_protection =
rate_with_headroom - DataRate::BitsPerSec(protection_bitrate_bps);
EXPECT_CALL(video_stream_encoder_,
OnBitrateUpdated(qvga_max_bitrate, qvga_max_bitrate,
headroom_minus_protection, 0, _, 0));
static_cast<BitrateAllocatorObserver*>(vss_impl.get())
->OnBitrateUpdated(update);
// Protection bitrate exceeds head room, link allocation should be
// capped to target bitrate.
EXPECT_CALL(rtp_video_sender_, GetProtectionBitrateBps())
.WillOnce(Return(headroom.bps() + 1000));
EXPECT_CALL(rtp_video_sender_, OnBitrateUpdated(update, _));
EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps())
.WillOnce(Return(rate_with_headroom.bps()));
EXPECT_CALL(video_stream_encoder_,
OnBitrateUpdated(qvga_max_bitrate, qvga_max_bitrate,
qvga_max_bitrate, 0, _, 0));
static_cast<BitrateAllocatorObserver*>(vss_impl.get())
->OnBitrateUpdated(update);
// Set rates to zero on stop.
EXPECT_CALL(video_stream_encoder_,
OnBitrateUpdated(DataRate::Zero(), DataRate::Zero(),
DataRate::Zero(), 0, 0, 0));
vss_impl->Stop();
},
RTC_FROM_HERE);
}
TEST_F(VideoSendStreamImplTest, DisablesPaddingOnPausedEncoder) {
int padding_bitrate = 0;
std::unique_ptr<VideoSendStreamImpl> vss_impl;
test_queue_.SendTask(
[&] {
vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kRealtimeVideo);
// Capture padding bitrate for testing.
EXPECT_CALL(bitrate_allocator_, AddObserver(vss_impl.get(), _))
.WillRepeatedly(Invoke([&](BitrateAllocatorObserver*,
MediaStreamAllocationConfig config) {
padding_bitrate = config.pad_up_bitrate_bps;
}));
// If observer is removed, no padding will be sent.
EXPECT_CALL(bitrate_allocator_, RemoveObserver(vss_impl.get()))
.WillRepeatedly(Invoke(
[&](BitrateAllocatorObserver*) { padding_bitrate = 0; }));
EXPECT_CALL(rtp_video_sender_, OnEncodedImage(_, _, _))
.WillRepeatedly(Return(EncodedImageCallback::Result(
EncodedImageCallback::Result::OK)));
const bool kSuspend = false;
config_.suspend_below_min_bitrate = kSuspend;
config_.rtp.extensions.emplace_back(
RtpExtension::kTransportSequenceNumberUri, 1);
VideoStream qvga_stream;
qvga_stream.width = 320;
qvga_stream.height = 180;
qvga_stream.max_framerate = 30;
qvga_stream.min_bitrate_bps = 30000;
qvga_stream.target_bitrate_bps = 150000;
qvga_stream.max_bitrate_bps = 200000;
qvga_stream.max_qp = 56;
qvga_stream.bitrate_priority = 1;
int min_transmit_bitrate_bps = 30000;
config_.rtp.ssrcs.emplace_back(1);
vss_impl->Start();
// Starts without padding.
EXPECT_EQ(0, padding_bitrate);
// Reconfigure e.g. due to a fake frame.
static_cast<VideoStreamEncoderInterface::EncoderSink*>(vss_impl.get())
->OnEncoderConfigurationChanged(
std::vector<VideoStream>{qvga_stream}, false,
VideoEncoderConfig::ContentType::kRealtimeVideo,
min_transmit_bitrate_bps);
// Still no padding because no actual frames were passed, only
// reconfiguration happened.
EXPECT_EQ(0, padding_bitrate);
// Unpause encoder.
const uint32_t kBitrateBps = 100000;
EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps())
.Times(1)
.WillOnce(Return(kBitrateBps));
static_cast<BitrateAllocatorObserver*>(vss_impl.get())
->OnBitrateUpdated(CreateAllocation(kBitrateBps));
// A frame is encoded.
EncodedImage encoded_image;
CodecSpecificInfo codec_specific;
static_cast<EncodedImageCallback*>(vss_impl.get())
->OnEncodedImage(encoded_image, &codec_specific, nullptr);
// Only after actual frame is encoded are we enabling the padding.
EXPECT_GT(padding_bitrate, 0);
},
RTC_FROM_HERE);
rtc::Event done;
test_queue_.PostDelayedTask(
[&] {
// No padding supposed to be sent for paused observer
EXPECT_EQ(0, padding_bitrate);
testing::Mock::VerifyAndClearExpectations(&bitrate_allocator_);
vss_impl->Stop();
vss_impl.reset();
done.Set();
},
5000);
// Pause the test suite so that the last delayed task executes.
ASSERT_TRUE(done.Wait(10000));
}
TEST_F(VideoSendStreamImplTest, KeepAliveOnDroppedFrame) {
std::unique_ptr<VideoSendStreamImpl> vss_impl;
test_queue_.SendTask(
[&] {
vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
VideoEncoderConfig::ContentType::kRealtimeVideo);
vss_impl->Start();
const uint32_t kBitrateBps = 100000;
EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps())
.Times(1)
.WillOnce(Return(kBitrateBps));
static_cast<BitrateAllocatorObserver*>(vss_impl.get())
->OnBitrateUpdated(CreateAllocation(kBitrateBps));
// Keep the stream from deallocating by dropping a frame.
static_cast<EncodedImageCallback*>(vss_impl.get())
->OnDroppedFrame(
EncodedImageCallback::DropReason::kDroppedByEncoder);
EXPECT_CALL(bitrate_allocator_, RemoveObserver(vss_impl.get()))
.Times(0);
},
RTC_FROM_HERE);
rtc::Event done;
test_queue_.PostDelayedTask(
[&] {
testing::Mock::VerifyAndClearExpectations(&bitrate_allocator_);
vss_impl->Stop();
vss_impl.reset();
done.Set();
},
2000);
ASSERT_TRUE(done.Wait(5000));
}
TEST_F(VideoSendStreamImplTest, ConfiguresBitratesForSvc) {
struct TestConfig {
bool screenshare = false;
bool alr = false;
int min_padding_bitrate_bps = 0;
};
std::vector<TestConfig> test_variants;
for (bool screenshare : {false, true}) {
for (bool alr : {false, true}) {
for (int min_padding : {0, 400000}) {
test_variants.push_back({screenshare, alr, min_padding});
}
}
}
for (const TestConfig& test_config : test_variants) {
test_queue_.SendTask(
[this, test_config] {
const bool kSuspend = false;
config_.suspend_below_min_bitrate = kSuspend;
config_.rtp.extensions.emplace_back(
RtpExtension::kTransportSequenceNumberUri, 1);
config_.periodic_alr_bandwidth_probing = test_config.alr;
auto vss_impl = CreateVideoSendStreamImpl(
kDefaultInitialBitrateBps, kDefaultBitratePriority,
test_config.screenshare
? VideoEncoderConfig::ContentType::kScreen
: VideoEncoderConfig::ContentType::kRealtimeVideo);
vss_impl->Start();
// Svc
VideoStream stream;
stream.width = 1920;
stream.height = 1080;
stream.max_framerate = 30;
stream.min_bitrate_bps = 60000;
stream.target_bitrate_bps = 6000000;
stream.max_bitrate_bps = 1250000;
stream.num_temporal_layers = 2;
stream.max_qp = 56;
stream.bitrate_priority = 1;
config_.rtp.ssrcs.emplace_back(1);
config_.rtp.ssrcs.emplace_back(2);
EXPECT_CALL(
bitrate_allocator_,
AddObserver(
vss_impl.get(),
AllOf(Field(&MediaStreamAllocationConfig::min_bitrate_bps,
static_cast<uint32_t>(stream.min_bitrate_bps)),
Field(&MediaStreamAllocationConfig::max_bitrate_bps,
static_cast<uint32_t>(stream.max_bitrate_bps)),
// Stream not yet active - no padding.
Field(&MediaStreamAllocationConfig::pad_up_bitrate_bps,
0u),
Field(&MediaStreamAllocationConfig::enforce_min_bitrate,
!kSuspend))));
static_cast<VideoStreamEncoderInterface::EncoderSink*>(vss_impl.get())
->OnEncoderConfigurationChanged(
std::vector<VideoStream>{stream}, true,
test_config.screenshare
? VideoEncoderConfig::ContentType::kScreen
: VideoEncoderConfig::ContentType::kRealtimeVideo,
test_config.min_padding_bitrate_bps);
::testing::Mock::VerifyAndClearExpectations(&bitrate_allocator_);
// Simulate an encoded image, this will turn the stream active and
// enable padding.
EncodedImage encoded_image;
CodecSpecificInfo codec_specific;
EXPECT_CALL(rtp_video_sender_, OnEncodedImage)
.WillRepeatedly(Return(EncodedImageCallback::Result(
EncodedImageCallback::Result::OK)));
// Screensharing implicitly forces ALR.
const bool using_alr = test_config.alr || test_config.screenshare;
// If ALR is used, pads only to min bitrate as rampup is handled by
// probing. Otherwise target_bitrate contains the padding target.
int expected_padding =
using_alr ? stream.min_bitrate_bps : stream.target_bitrate_bps;
// Min padding bitrate may override padding target.
expected_padding =
std::max(expected_padding, test_config.min_padding_bitrate_bps);
EXPECT_CALL(
bitrate_allocator_,
AddObserver(
vss_impl.get(),
AllOf(Field(&MediaStreamAllocationConfig::min_bitrate_bps,
static_cast<uint32_t>(stream.min_bitrate_bps)),
Field(&MediaStreamAllocationConfig::max_bitrate_bps,
static_cast<uint32_t>(stream.max_bitrate_bps)),
// Stream now active - min bitrate use as padding target
// when ALR is active.
Field(&MediaStreamAllocationConfig::pad_up_bitrate_bps,
expected_padding),
Field(&MediaStreamAllocationConfig::enforce_min_bitrate,
!kSuspend))));
static_cast<EncodedImageCallback*>(vss_impl.get())
->OnEncodedImage(encoded_image, &codec_specific, nullptr);
::testing::Mock::VerifyAndClearExpectations(&bitrate_allocator_);
vss_impl->Stop();
},
RTC_FROM_HERE);
}
}
} // namespace internal
} // namespace webrtc
| bsd-3-clause |
chromium2014/src | chrome/browser/guest_view/web_view/web_view_permission_helper.cc | 21950 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/guest_view/web_view/web_view_permission_helper.h"
#include "chrome/browser/content_settings/tab_specific_content_settings.h"
#include "chrome/browser/geolocation/geolocation_permission_context.h"
#include "chrome/browser/geolocation/geolocation_permission_context_factory.h"
#include "chrome/browser/guest_view/web_view/web_view_constants.h"
#include "chrome/browser/guest_view/web_view/web_view_guest.h"
#include "chrome/browser/guest_view/web_view/web_view_permission_types.h"
#include "chrome/browser/plugins/chrome_plugin_service_filter.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/render_messages.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/user_metrics.h"
using content::BrowserPluginGuestDelegate;
using content::RenderViewHost;
namespace {
static std::string PermissionTypeToString(WebViewPermissionType type) {
switch (type) {
case WEB_VIEW_PERMISSION_TYPE_DOWNLOAD:
return webview::kPermissionTypeDownload;
case WEB_VIEW_PERMISSION_TYPE_FILESYSTEM:
return webview::kPermissionTypeFileSystem;
case WEB_VIEW_PERMISSION_TYPE_GEOLOCATION:
return webview::kPermissionTypeGeolocation;
case WEB_VIEW_PERMISSION_TYPE_JAVASCRIPT_DIALOG:
return webview::kPermissionTypeDialog;
case WEB_VIEW_PERMISSION_TYPE_LOAD_PLUGIN:
return webview::kPermissionTypeLoadPlugin;
case WEB_VIEW_PERMISSION_TYPE_MEDIA:
return webview::kPermissionTypeMedia;
case WEB_VIEW_PERMISSION_TYPE_NEW_WINDOW:
return webview::kPermissionTypeNewWindow;
case WEB_VIEW_PERMISSION_TYPE_POINTER_LOCK:
return webview::kPermissionTypePointerLock;
default:
NOTREACHED();
return std::string();
}
}
// static
void RecordUserInitiatedUMA(
const WebViewPermissionHelper::PermissionResponseInfo& info,
bool allow) {
if (allow) {
// Note that |allow| == true means the embedder explicitly allowed the
// request. For some requests they might still fail. An example of such
// scenario would be: an embedder allows geolocation request but doesn't
// have geolocation access on its own.
switch (info.permission_type) {
case WEB_VIEW_PERMISSION_TYPE_DOWNLOAD:
content::RecordAction(
UserMetricsAction("WebView.PermissionAllow.Download"));
break;
case WEB_VIEW_PERMISSION_TYPE_FILESYSTEM:
content::RecordAction(
UserMetricsAction("WebView.PermissionAllow.FileSystem"));
break;
case WEB_VIEW_PERMISSION_TYPE_GEOLOCATION:
content::RecordAction(
UserMetricsAction("WebView.PermissionAllow.Geolocation"));
break;
case WEB_VIEW_PERMISSION_TYPE_JAVASCRIPT_DIALOG:
content::RecordAction(
UserMetricsAction("WebView.PermissionAllow.JSDialog"));
break;
case WEB_VIEW_PERMISSION_TYPE_LOAD_PLUGIN:
content::RecordAction(
UserMetricsAction("WebView.Guest.PermissionAllow.PluginLoad"));
case WEB_VIEW_PERMISSION_TYPE_MEDIA:
content::RecordAction(
UserMetricsAction("WebView.PermissionAllow.Media"));
break;
case WEB_VIEW_PERMISSION_TYPE_NEW_WINDOW:
content::RecordAction(
UserMetricsAction("BrowserPlugin.PermissionAllow.NewWindow"));
break;
case WEB_VIEW_PERMISSION_TYPE_POINTER_LOCK:
content::RecordAction(
UserMetricsAction("WebView.PermissionAllow.PointerLock"));
break;
default:
break;
}
} else {
switch (info.permission_type) {
case WEB_VIEW_PERMISSION_TYPE_DOWNLOAD:
content::RecordAction(
UserMetricsAction("WebView.PermissionDeny.Download"));
break;
case WEB_VIEW_PERMISSION_TYPE_FILESYSTEM:
content::RecordAction(
UserMetricsAction("WebView.PermissionDeny.FileSystem"));
break;
case WEB_VIEW_PERMISSION_TYPE_GEOLOCATION:
content::RecordAction(
UserMetricsAction("WebView.PermissionDeny.Geolocation"));
break;
case WEB_VIEW_PERMISSION_TYPE_JAVASCRIPT_DIALOG:
content::RecordAction(
UserMetricsAction("WebView.PermissionDeny.JSDialog"));
break;
case WEB_VIEW_PERMISSION_TYPE_LOAD_PLUGIN:
content::RecordAction(
UserMetricsAction("WebView.Guest.PermissionDeny.PluginLoad"));
break;
case WEB_VIEW_PERMISSION_TYPE_MEDIA:
content::RecordAction(
UserMetricsAction("WebView.PermissionDeny.Media"));
break;
case WEB_VIEW_PERMISSION_TYPE_NEW_WINDOW:
content::RecordAction(
UserMetricsAction("BrowserPlugin.PermissionDeny.NewWindow"));
break;
case WEB_VIEW_PERMISSION_TYPE_POINTER_LOCK:
content::RecordAction(
UserMetricsAction("WebView.PermissionDeny.PointerLock"));
break;
default:
break;
}
}
}
} // namespace
WebViewPermissionHelper::WebViewPermissionHelper(WebViewGuest* web_view_guest)
: content::WebContentsObserver(web_view_guest->guest_web_contents()),
next_permission_request_id_(guestview::kInstanceIDNone),
web_view_guest_(web_view_guest),
weak_factory_(this) {
}
WebViewPermissionHelper::~WebViewPermissionHelper() {
}
// static
WebViewPermissionHelper* WebViewPermissionHelper::FromFrameID(
int render_process_id,
int render_frame_id) {
WebViewGuest* web_view_guest = WebViewGuest::FromFrameID(
render_process_id, render_frame_id);
if (!web_view_guest) {
return NULL;
}
return web_view_guest->web_view_permission_helper_.get();
}
// static
WebViewPermissionHelper* WebViewPermissionHelper::FromWebContents(
content::WebContents* web_contents) {
WebViewGuest* web_view_guest = WebViewGuest::FromWebContents(web_contents);
if (!web_view_guest)
return NULL;
return web_view_guest->web_view_permission_helper_.get();
}
#if defined(ENABLE_PLUGINS)
bool WebViewPermissionHelper::OnMessageReceived(
const IPC::Message& message,
content::RenderFrameHost* render_frame_host) {
IPC_BEGIN_MESSAGE_MAP(WebViewPermissionHelper, message)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_BlockedOutdatedPlugin,
OnBlockedOutdatedPlugin)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_BlockedUnauthorizedPlugin,
OnBlockedUnauthorizedPlugin)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_NPAPINotSupported,
OnNPAPINotSupported)
#if defined(ENABLE_PLUGIN_INSTALLATION)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_FindMissingPlugin,
OnFindMissingPlugin)
#endif
IPC_MESSAGE_UNHANDLED(return false)
IPC_END_MESSAGE_MAP()
return true;
}
bool WebViewPermissionHelper::OnMessageReceived(const IPC::Message& message) {
IPC_BEGIN_MESSAGE_MAP(WebViewPermissionHelper, message)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_CouldNotLoadPlugin,
OnCouldNotLoadPlugin)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_OpenAboutPlugins,
OnOpenAboutPlugins)
#if defined(ENABLE_PLUGIN_INSTALLATION)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_RemovePluginPlaceholderHost,
OnRemovePluginPlaceholderHost)
#endif
IPC_MESSAGE_UNHANDLED(return false)
IPC_END_MESSAGE_MAP()
return true;
}
void WebViewPermissionHelper::OnBlockedUnauthorizedPlugin(
const base::string16& name,
const std::string& identifier) {
const char kPluginName[] = "name";
const char kPluginIdentifier[] = "identifier";
base::DictionaryValue info;
info.SetString(std::string(kPluginName), name);
info.SetString(std::string(kPluginIdentifier), identifier);
RequestPermission(
WEB_VIEW_PERMISSION_TYPE_LOAD_PLUGIN,
info,
base::Bind(&WebViewPermissionHelper::OnPermissionResponse,
weak_factory_.GetWeakPtr(),
identifier),
true /* allowed_by_default */);
content::RecordAction(
base::UserMetricsAction("WebView.Guest.PluginLoadRequest"));
}
void WebViewPermissionHelper::OnCouldNotLoadPlugin(
const base::FilePath& plugin_path) {
}
void WebViewPermissionHelper::OnBlockedOutdatedPlugin(
int placeholder_id,
const std::string& identifier) {
}
void WebViewPermissionHelper::OnNPAPINotSupported(const std::string& id) {
}
void WebViewPermissionHelper::OnOpenAboutPlugins() {
}
#if defined(ENABLE_PLUGIN_INSTALLATION)
void WebViewPermissionHelper::OnFindMissingPlugin(
int placeholder_id,
const std::string& mime_type) {
Send(new ChromeViewMsg_DidNotFindMissingPlugin(placeholder_id));
}
void WebViewPermissionHelper::OnRemovePluginPlaceholderHost(
int placeholder_id) {
}
#endif // defined(ENABLE_PLUGIN_INSTALLATION)
void WebViewPermissionHelper::OnPermissionResponse(
const std::string& identifier,
bool allow,
const std::string& input) {
if (allow) {
ChromePluginServiceFilter::GetInstance()->AuthorizeAllPlugins(
web_contents(), true, identifier);
}
}
#endif // defined(ENABLE_PLUGINS)
void WebViewPermissionHelper::RequestMediaAccessPermission(
content::WebContents* source,
const content::MediaStreamRequest& request,
const content::MediaResponseCallback& callback) {
base::DictionaryValue request_info;
request_info.Set(guestview::kUrl,
new base::StringValue(request.security_origin.spec()));
RequestPermission(WEB_VIEW_PERMISSION_TYPE_MEDIA,
request_info,
base::Bind(&WebViewPermissionHelper::
OnMediaPermissionResponse,
base::Unretained(this),
request,
callback),
false /* allowed_by_default */);
}
void WebViewPermissionHelper::OnMediaPermissionResponse(
const content::MediaStreamRequest& request,
const content::MediaResponseCallback& callback,
bool allow,
const std::string& user_input) {
if (!allow || !web_view_guest_->attached()) {
// Deny the request.
callback.Run(content::MediaStreamDevices(),
content::MEDIA_DEVICE_INVALID_STATE,
scoped_ptr<content::MediaStreamUI>());
return;
}
if (!web_view_guest_->embedder_web_contents()->GetDelegate())
return;
web_view_guest_->embedder_web_contents()->GetDelegate()->
RequestMediaAccessPermission(web_view_guest_->embedder_web_contents(),
request,
callback);
}
void WebViewPermissionHelper::CanDownload(
content::RenderViewHost* render_view_host,
const GURL& url,
const std::string& request_method,
const base::Callback<void(bool)>& callback) {
base::DictionaryValue request_info;
request_info.Set(guestview::kUrl, new base::StringValue(url.spec()));
RequestPermission(
WEB_VIEW_PERMISSION_TYPE_DOWNLOAD,
request_info,
base::Bind(&WebViewPermissionHelper::OnDownloadPermissionResponse,
base::Unretained(this),
callback),
false /* allowed_by_default */);
}
void WebViewPermissionHelper::OnDownloadPermissionResponse(
const base::Callback<void(bool)>& callback,
bool allow,
const std::string& user_input) {
callback.Run(allow && web_view_guest_->attached());
}
void WebViewPermissionHelper::RequestPointerLockPermission(
bool user_gesture,
bool last_unlocked_by_target,
const base::Callback<void(bool)>& callback) {
base::DictionaryValue request_info;
request_info.Set(guestview::kUserGesture,
base::Value::CreateBooleanValue(user_gesture));
request_info.Set(webview::kLastUnlockedBySelf,
base::Value::CreateBooleanValue(last_unlocked_by_target));
request_info.Set(guestview::kUrl,
new base::StringValue(
web_contents()->GetLastCommittedURL().spec()));
RequestPermission(
WEB_VIEW_PERMISSION_TYPE_POINTER_LOCK,
request_info,
base::Bind(
&WebViewPermissionHelper::OnPointerLockPermissionResponse,
base::Unretained(this),
callback),
false /* allowed_by_default */);
}
void WebViewPermissionHelper::OnPointerLockPermissionResponse(
const base::Callback<void(bool)>& callback,
bool allow,
const std::string& user_input) {
callback.Run(allow && web_view_guest_->attached());
}
void WebViewPermissionHelper::RequestGeolocationPermission(
int bridge_id,
const GURL& requesting_frame,
bool user_gesture,
const base::Callback<void(bool)>& callback) {
base::DictionaryValue request_info;
request_info.Set(guestview::kUrl,
new base::StringValue(requesting_frame.spec()));
request_info.Set(guestview::kUserGesture,
base::Value::CreateBooleanValue(user_gesture));
// It is safe to hold an unretained pointer to WebViewPermissionHelper because
// this callback is called from WebViewPermissionHelper::SetPermission.
const PermissionResponseCallback permission_callback =
base::Bind(
&WebViewPermissionHelper::OnGeolocationPermissionResponse,
base::Unretained(this),
bridge_id,
user_gesture,
callback);
int request_id = RequestPermission(
WEB_VIEW_PERMISSION_TYPE_GEOLOCATION,
request_info,
permission_callback,
false /* allowed_by_default */);
bridge_id_to_request_id_map_[bridge_id] = request_id;
}
void WebViewPermissionHelper::OnGeolocationPermissionResponse(
int bridge_id,
bool user_gesture,
const base::Callback<void(bool)>& callback,
bool allow,
const std::string& user_input) {
// The <webview> embedder has allowed the permission. We now need to make sure
// that the embedder has geolocation permission.
RemoveBridgeID(bridge_id);
if (!allow || !web_view_guest_->attached()) {
callback.Run(false);
return;
}
Profile* profile = Profile::FromBrowserContext(
web_view_guest_->browser_context());
GeolocationPermissionContextFactory::GetForProfile(profile)->
RequestGeolocationPermission(
web_view_guest_->embedder_web_contents(),
// The geolocation permission request here is not initiated
// through WebGeolocationPermissionRequest. We are only interested
// in the fact whether the embedder/app has geolocation
// permission. Therefore we use an invalid |bridge_id|.
-1,
web_view_guest_->embedder_web_contents()->GetLastCommittedURL(),
user_gesture,
callback,
NULL);
}
void WebViewPermissionHelper::CancelGeolocationPermissionRequest(
int bridge_id) {
int request_id = RemoveBridgeID(bridge_id);
RequestMap::iterator request_itr =
pending_permission_requests_.find(request_id);
if (request_itr == pending_permission_requests_.end())
return;
pending_permission_requests_.erase(request_itr);
}
int WebViewPermissionHelper::RemoveBridgeID(int bridge_id) {
std::map<int, int>::iterator bridge_itr =
bridge_id_to_request_id_map_.find(bridge_id);
if (bridge_itr == bridge_id_to_request_id_map_.end())
return webview::kInvalidPermissionRequestID;
int request_id = bridge_itr->second;
bridge_id_to_request_id_map_.erase(bridge_itr);
return request_id;
}
void WebViewPermissionHelper::RequestFileSystemPermission(
const GURL& url,
bool allowed_by_default,
const base::Callback<void(bool)>& callback) {
base::DictionaryValue request_info;
request_info.Set(guestview::kUrl, new base::StringValue(url.spec()));
RequestPermission(
WEB_VIEW_PERMISSION_TYPE_FILESYSTEM,
request_info,
base::Bind(
&WebViewPermissionHelper::OnFileSystemPermissionResponse,
base::Unretained(this),
callback),
allowed_by_default);
}
void WebViewPermissionHelper::OnFileSystemPermissionResponse(
const base::Callback<void(bool)>& callback,
bool allow,
const std::string& user_input) {
callback.Run(allow && web_view_guest_->attached());
}
void WebViewPermissionHelper::FileSystemAccessedAsync(int render_process_id,
int render_frame_id,
int request_id,
const GURL& url,
bool blocked_by_policy) {
RequestFileSystemPermission(
url,
!blocked_by_policy,
base::Bind(&WebViewPermissionHelper::FileSystemAccessedAsyncResponse,
base::Unretained(this),
render_process_id,
render_frame_id,
request_id,
url));
}
void WebViewPermissionHelper::FileSystemAccessedAsyncResponse(
int render_process_id,
int render_frame_id,
int request_id,
const GURL& url,
bool allowed) {
TabSpecificContentSettings::FileSystemAccessed(
render_process_id, render_frame_id, url, !allowed);
Send(new ChromeViewMsg_RequestFileSystemAccessAsyncResponse(
render_frame_id, request_id, allowed));
}
void WebViewPermissionHelper::FileSystemAccessedSync(int render_process_id,
int render_frame_id,
const GURL& url,
bool blocked_by_policy,
IPC::Message* reply_msg) {
RequestFileSystemPermission(
url,
!blocked_by_policy,
base::Bind(&WebViewPermissionHelper::FileSystemAccessedSyncResponse,
base::Unretained(this),
render_process_id,
render_frame_id,
url,
reply_msg));
}
void WebViewPermissionHelper::FileSystemAccessedSyncResponse(
int render_process_id,
int render_frame_id,
const GURL& url,
IPC::Message* reply_msg,
bool allowed) {
TabSpecificContentSettings::FileSystemAccessed(
render_process_id, render_frame_id, url, !allowed);
ChromeViewHostMsg_RequestFileSystemAccessSync::WriteReplyParams(reply_msg,
allowed);
Send(reply_msg);
}
int WebViewPermissionHelper::RequestPermission(
WebViewPermissionType permission_type,
const base::DictionaryValue& request_info,
const PermissionResponseCallback& callback,
bool allowed_by_default) {
// If there are too many pending permission requests then reject this request.
if (pending_permission_requests_.size() >=
webview::kMaxOutstandingPermissionRequests) {
// Let the stack unwind before we deny the permission request so that
// objects held by the permission request are not destroyed immediately
// after creation. This is to allow those same objects to be accessed again
// in the same scope without fear of use after freeing.
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&PermissionResponseCallback::Run,
base::Owned(new PermissionResponseCallback(callback)),
allowed_by_default,
std::string()));
return webview::kInvalidPermissionRequestID;
}
int request_id = next_permission_request_id_++;
pending_permission_requests_[request_id] =
PermissionResponseInfo(callback, permission_type, allowed_by_default);
scoped_ptr<base::DictionaryValue> args(request_info.DeepCopy());
args->SetInteger(webview::kRequestId, request_id);
switch (permission_type) {
case WEB_VIEW_PERMISSION_TYPE_NEW_WINDOW: {
web_view_guest_->DispatchEventToEmbedder(
new GuestViewBase::Event(webview::kEventNewWindow, args.Pass()));
break;
}
case WEB_VIEW_PERMISSION_TYPE_JAVASCRIPT_DIALOG: {
web_view_guest_->DispatchEventToEmbedder(
new GuestViewBase::Event(webview::kEventDialog, args.Pass()));
break;
}
default: {
args->SetString(webview::kPermission,
PermissionTypeToString(permission_type));
web_view_guest_->DispatchEventToEmbedder(new GuestViewBase::Event(
webview::kEventPermissionRequest,
args.Pass()));
break;
}
}
return request_id;
}
WebViewPermissionHelper::SetPermissionResult
WebViewPermissionHelper::SetPermission(
int request_id,
PermissionResponseAction action,
const std::string& user_input) {
RequestMap::iterator request_itr =
pending_permission_requests_.find(request_id);
if (request_itr == pending_permission_requests_.end())
return SET_PERMISSION_INVALID;
const PermissionResponseInfo& info = request_itr->second;
bool allow = (action == ALLOW) ||
((action == DEFAULT) && info.allowed_by_default);
info.callback.Run(allow, user_input);
// Only record user initiated (i.e. non-default) actions.
if (action != DEFAULT)
RecordUserInitiatedUMA(info, allow);
pending_permission_requests_.erase(request_itr);
return allow ? SET_PERMISSION_ALLOWED : SET_PERMISSION_DENIED;
}
WebViewPermissionHelper::PermissionResponseInfo::PermissionResponseInfo()
: permission_type(WEB_VIEW_PERMISSION_TYPE_UNKNOWN),
allowed_by_default(false) {
}
WebViewPermissionHelper::PermissionResponseInfo::PermissionResponseInfo(
const PermissionResponseCallback& callback,
WebViewPermissionType permission_type,
bool allowed_by_default)
: callback(callback),
permission_type(permission_type),
allowed_by_default(allowed_by_default) {
}
WebViewPermissionHelper::PermissionResponseInfo::~PermissionResponseInfo() {
}
| bsd-3-clause |
Dench/resistor | common/models/OfferItem.php | 2482 | <?php
namespace common\models;
use Yii;
use yii\db\ActiveRecord;
use yii\helpers\FileHelper;
/**
* This is the model class for table "offer_item".
*
* @property integer $id
* @property integer $group_id
* @property string $name
* @property string $text
*
* @property Offer $group
* @property OfferPhoto $photos
* @property array $images
*/
class OfferItem extends ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'offer_item';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['name'], 'default', 'value' => '(no name)'],
[['text'], 'string'],
[['name'], 'string', 'max' => 255],
[['group_id'], 'exist', 'skipOnError' => true, 'targetClass' => Offer::className(), 'targetAttribute' => ['group_id' => 'id']],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'group_id' => Yii::t('app', 'Group ID'),
'name' => Yii::t('app', 'Name'),
'text' => Yii::t('app', 'Text'),
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getGroup()
{
return $this->hasOne(Offer::className(), ['id' => 'group_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getPhotos()
{
return $this->hasMany(OfferPhoto::className(), ['item_id' => 'id']);
}
public function afterDelete()
{
Yii::info('delPhotos'.$this->id);
OfferPhoto::delPhotos($this->id);
$path = Yii::$app->params['uploadOfferPath'].DIRECTORY_SEPARATOR.$this->id;
FileHelper::removeDirectory($path);
return parent::afterDelete();
}
public function getImages()
{
$images['thumb'] = [];
$images['small'] = [];
$images['big'] = [];
$images['slider'] = [];
foreach ($this->photos as $i) {
$images['thumb'][$i['id']] = Yii::$app->params['offerPhotoThumb']['path'].$i['id'].'.jpg';
$images['small'][$i['id']] = Yii::$app->params['offerPhotoSmall']['path'].$i['id'].'.jpg';
$images['big'][$i['id']] = Yii::$app->params['offerPhotoBig']['path'].$i['id'].'.jpg';
$images['slider'][$i['id']] = Yii::$app->params['offerPhotoSlider']['path'].$i['id'].'.jpg';
}
return $images;
}
}
| bsd-3-clause |
LukasBanana/ForkENGINE | sources/Physics/Engine/Newton/NwWorld.cpp | 7584 | /*
* Newton physics world file
*
* This file is part of the "ForkENGINE" (Copyright (c) 2014 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "NwWorld.h"
#include "NwMaterial.h"
#include "NwCollider.h"
#include "Dynamic/NwRigidBody.h"
#include "Dynamic/NwStaticBody.h"
#include "Core/Exception/PointerConversionException.h"
namespace Fork
{
namespace Physics
{
NwWorld::NwWorld()
{
world_ = NewtonCreate();
}
NwWorld::~NwWorld()
{
NewtonDestroy(world_);
}
/* --- Material --- */
MaterialPtr NwWorld::CreateMaterial()
{
auto material = std::make_shared<NwMaterial>(world_);
materials_.push_back(material);
return material;
}
void NwWorld::SetupMaterialBehavior(
Material* materialA, Material* materialB, const Material::Behavior& behavior)
{
/* Get newton materials */
auto materialANw = dynamic_cast<NwMaterial*>(materialA);
auto materialBNw = dynamic_cast<NwMaterial*>(materialB);
if (!materialANw || !materialBNw)
throw PointerConversionException(__FUNCTION__, "Material", "NwMaterial");
auto groupID0 = materialANw->GetGroupID();
auto groupID1 = materialBNw->GetGroupID();
/* Setup material configuration */
NewtonMaterialSetDefaultCollidable(
world_, groupID0, groupID1,
behavior.collidable ? 1 : 0
);
NewtonMaterialSetDefaultFriction(
world_, groupID0, groupID1,
behavior.staticFriction, behavior.kineticFriction
);
NewtonMaterialSetDefaultElasticity(
world_, groupID0, groupID1,
behavior.elasticity
);
NewtonMaterialSetDefaultSoftness(
world_, groupID0, groupID1,
behavior.softness
);
}
/* --- Collider --- */
ColliderPtr NwWorld::CreateNullCollider()
{
return NwCollider::CreateNull(world_);
}
ColliderPtr NwWorld::CreateSphereCollider(float radius, const Math::Matrix4f* offsetMatrix)
{
return NwCollider::CreateSphere(world_, radius, offsetMatrix);
}
ColliderPtr NwWorld::CreateBoxCollider(const Math::Size3f& size, const Math::Matrix4f* offsetMatrix)
{
return NwCollider::CreateBox(world_, size, offsetMatrix);
}
ColliderPtr NwWorld::CreateConeCollider(float radius, float height, const Math::Matrix4f* offsetMatrix)
{
return NwCollider::CreateCone(world_, radius, height, offsetMatrix);
}
ColliderPtr NwWorld::CreateCapsuleCollider(float radius, float height, const Math::Matrix4f* offsetMatrix)
{
return NwCollider::CreateCapsule(world_, radius, height, offsetMatrix);
}
ColliderPtr NwWorld::CreateCylinderCollider(float radius, float height, const Math::Matrix4f* offsetMatrix)
{
return NwCollider::CreateCylinder(world_, radius, height, offsetMatrix);
}
ColliderPtr NwWorld::CreateChamferCylinderCollider(float radius, float height, const Math::Matrix4f* offsetMatrix)
{
return NwCollider::CreateChamferCylinder(world_, radius, height, offsetMatrix);
}
ColliderPtr NwWorld::CreateConvexHullCollider(
const void* vertexData, unsigned int numVertices, unsigned int vertexStride,
const Math::Matrix4f* offsetMatrix, float tolerance)
{
return NwCollider::CreateConvexHull(world_, vertexData, numVertices, vertexStride, offsetMatrix, tolerance);
}
ColliderPtr NwWorld::CreateMeshCollider(
const void* vertexData, unsigned int numVertices, unsigned int vertexStride,
const Math::Matrix4f* offsetMatrix, bool optimize)
{
return NwCollider::CreateMesh(world_, vertexData, numVertices, vertexStride, offsetMatrix, optimize);
}
ColliderPtr NwWorld::CreateMeshCollider(
const void* vertexData, unsigned int numVertices, unsigned int vertexStride,
const void* indexData, unsigned int numIndices, unsigned int indexStride,
const Math::Matrix4f* offsetMatrix, bool optimize)
{
return NwCollider::CreateMesh(
world_,
vertexData, numVertices, vertexStride,
indexData, numIndices, indexStride,
offsetMatrix, optimize
);
}
/* --- Bodies --- */
RigidBodyPtr NwWorld::CreateRigidBody(
const ColliderPtr& collider, const Math::Matrix4f& initTransform)
{
/* Get newton geometry */
auto colliderNw = std::dynamic_pointer_cast<NwCollider>(collider);
if (!colliderNw)
throw PointerConversionException(__FUNCTION__, "Collider", "NwCollider");
/* Create rigid body */
return std::make_shared<NwRigidBody>(world_, colliderNw, initTransform);
}
StaticBodyPtr NwWorld::CreateStaticBody(
const ColliderPtr& collider, const Math::Matrix4f& initTransform)
{
/* Get newton geometry */
auto colliderNw = std::dynamic_pointer_cast<NwCollider>(collider);
if (!colliderNw)
throw PointerConversionException(__FUNCTION__, "Collider", "NwCollider");
/* Create static body */
return std::make_shared<NwStaticBody>(world_, colliderNw, initTransform);
}
/* --- Physics simulation --- */
void NwWorld::Simulate(float timeStep)
{
NewtonUpdate(world_, timeStep);
}
/* --- Intersection tests --- */
struct WorldRayCastUserDataWrapper
{
void* userData = nullptr;
World::RayCastEventHandler* eventHandler = nullptr;
};
static unsigned NwWorldRayPrefilterCallback(
const NewtonBody* const body, const NewtonCollision* const collision, void* const userData)
{
/* Get physics system objects */
auto bodyRef = reinterpret_cast<const Body*>(NewtonBodyGetUserData(body));
auto geometryRef = reinterpret_cast<const Collider*>(NewtonCollisionGetUserData(collision));
/* Call event handler */
auto userDataWrapper = reinterpret_cast<WorldRayCastUserDataWrapper*>(userData);
if (!userDataWrapper->eventHandler->OnContactAABB(bodyRef, geometryRef, userDataWrapper->userData))
return 0;
return 1;
}
static dFloat NwWorldRayFilterCallback(
const NewtonBody* const body, const NewtonCollision* const collision,
const dFloat* const hitContact, const dFloat* const hitNormal,
dLong collisionID, void* const userData, dFloat intersectParam)
{
/* Get physics system objects */
auto bodyRef = reinterpret_cast<const Body*>(NewtonBodyGetUserData(body));
auto geometryRef = reinterpret_cast<const Collider*>(NewtonCollisionGetUserData(collision));
/* Setup intersection */
Math::Intersection3f intersection
{
{ hitContact[0], hitContact[1], hitContact[2] },
{ hitNormal[0], hitNormal[1], hitNormal[2] }
};
/* Call event handler */
auto userDataWrapper = reinterpret_cast<WorldRayCastUserDataWrapper*>(userData);
auto proceeding = userDataWrapper->eventHandler->OnContact(
bodyRef, geometryRef, intersection, userDataWrapper->userData
);
/* Check ray cast procedding */
switch (proceeding)
{
case World::RayCastProceedings::Continue:
return 1.0f;
case World::RayCastProceedings::Nearest:
return intersectParam;
case World::RayCastProceedings::Cancel:
default:
break;
}
return 0.0f;
}
void NwWorld::RayCast(
const Math::Line3f& line, RayCastEventHandler* eventHandler, void* userData) const
{
if (eventHandler)
{
WorldRayCastUserDataWrapper userDataWrapper;
{
userDataWrapper.userData = userData;
userDataWrapper.eventHandler = eventHandler;
}
NewtonWorldRayCast(
world_, line.start.Ptr(), line.end.Ptr(),
NwWorldRayFilterCallback, &userDataWrapper, NwWorldRayPrefilterCallback, 0
);
}
}
} // /namespace Physics
} // /namespace Fork
// ======================== | bsd-3-clause |
mycrazydream/bra | framework/filesystem/GD.php | 12148 | <?php
/**
* A wrapper class for GD-based images, with lots of manipulation functions.
* @package framework
* @subpackage filesystem
*/
class GD extends Object {
protected $gd, $width, $height;
protected $quality;
protected static $default_quality = 75;
/**
* Set the default image quality.
* @param quality int A number from 0 to 100, 100 being the best quality.
*/
static function set_default_quality($quality) {
if(is_numeric($quality) && (int) $quality >= 0 && (int) $quality <= 100) {
self::$default_quality = (int) $quality;
}
}
function __construct($filename = null) {
// If we're working with image resampling, things could take a while. Bump up the time-limit
increase_time_limit_to(300);
if($filename) {
// We use getimagesize instead of extension checking, because sometimes extensions are wrong.
list($width, $height, $type, $attr) = getimagesize($filename);
switch($type) {
case 1: if(function_exists('imagecreatefromgif')) $this->setGD(imagecreatefromgif($filename)); break;
case 2: if(function_exists('imagecreatefromjpeg')) $this->setGD(imagecreatefromjpeg($filename)); break;
case 3: if(function_exists('imagecreatefrompng')) {
$img = imagecreatefrompng($filename);
imagesavealpha($img, true); // save alphablending setting (important)
$this->setGD($img);
break;
}
}
}
$this->quality = self::$default_quality;
parent::__construct();
}
public function setGD($gd) {
$this->gd = $gd;
$this->width = imagesx($gd);
$this->height = imagesy($gd);
}
public function getGD() {
return $this->gd;
}
/**
* Set the image quality, used when saving JPEGs.
*/
function setQuality($quality) {
$this->quality = $quality;
}
/**
* Resize an image to cover the given width/height completely, and crop off any overhanging edges.
*/
function croppedResize($width, $height) {
if(!$this->gd) return;
$width = round($width);
$height = round($height);
// Check that a resize is actually necessary.
if ($width == $this->width && $height == $this->height) {
return $this;
}
$newGD = imagecreatetruecolor($width, $height);
// Preserves transparency between images
imagealphablending($newGD, false);
imagesavealpha($newGD, true);
$destAR = $width / $height;
if ($this->width > 0 && $this->height > 0 ){
// We can't divide by zero theres something wrong.
$srcAR = $this->width / $this->height;
// Destination narrower than the source
if($destAR < $srcAR) {
$srcY = 0;
$srcHeight = $this->height;
$srcWidth = round( $this->height * $destAR );
$srcX = round( ($this->width - $srcWidth) / 2 );
// Destination shorter than the source
} else {
$srcX = 0;
$srcWidth = $this->width;
$srcHeight = round( $this->width / $destAR );
$srcY = round( ($this->height - $srcHeight) / 2 );
}
imagecopyresampled($newGD, $this->gd, 0,0, $srcX, $srcY, $width, $height, $srcWidth, $srcHeight);
}
$output = clone $this;
$output->setGD($newGD);
return $output;
}
/**
* Resizes the image to fit within the given region.
* Behaves similarly to paddedResize but without the padding.
* @todo This method isn't very efficent
*/
function fittedResize($width, $height) {
$gd = $this->resizeByHeight($height);
if($gd->width > $width) $gd = $gd->resizeByWidth($width);
return $gd;
}
function hasGD() {
return $this->gd ? true : false;
}
/**
* Resize an image, skewing it as necessary.
*/
function resize($width, $height) {
if(!$this->gd) return;
$width = round($width);
$height = round($height);
// Check that a resize is actually necessary.
if ($width == $this->width && $height == $this->height) {
return $this;
}
if(!$width && !$height) user_error("No dimensions given", E_USER_ERROR);
if(!$width) user_error("Width not given", E_USER_ERROR);
if(!$height) user_error("Height not given", E_USER_ERROR);
$newGD = imagecreatetruecolor($width, $height);
// Preserves transparency between images
imagealphablending($newGD, false);
imagesavealpha($newGD, true);
imagecopyresampled($newGD, $this->gd, 0,0, 0, 0, $width, $height, $this->width, $this->height);
$output = clone $this;
$output->setGD($newGD);
return $output;
}
/**
* Rotates image by given angle.
*
* @param angle
*
* @return GD
*/
function rotate($angle) {
if(!$this->gd) return;
if(function_exists("imagerotate")) {
$newGD = imagerotate($this->gd, $angle,0);
} else {
//imagerotate is not included in PHP included in Ubuntu
$newGD = $this->rotatePixelByPixel($angle);
}
$output = clone $this;
$output->setGD($newGD);
return $output;
}
/**
* Rotates image by given angle. It's slow because makes it pixel by pixel rather than
* using built-in function. Used when imagerotate function is not available(i.e. Ubuntu)
*
* @param angle
*
* @return GD
*/
function rotatePixelByPixel($angle) {
$sourceWidth = imagesx($this->gd);
$sourceHeight = imagesy($this->gd);
if ($angle == 180) {
$destWidth = $sourceWidth;
$destHeight = $sourceHeight;
} else {
$destWidth = $sourceHeight;
$destHeight = $sourceWidth;
}
$rotate=imagecreatetruecolor($destWidth,$destHeight);
imagealphablending($rotate, false);
for ($x = 0; $x < ($sourceWidth); $x++) {
for ($y = 0; $y < ($sourceHeight); $y++) {
$color = imagecolorat($this->gd, $x, $y);
switch ($angle) {
case 90:
imagesetpixel($rotate, $y, $destHeight - $x - 1, $color);
break;
case 180:
imagesetpixel($rotate, $destWidth - $x - 1, $destHeight - $y - 1, $color);
break;
case 270:
imagesetpixel($rotate, $destWidth - $y - 1, $x, $color);
break;
default: $rotate = $this->gd;
};
}
}
return $rotate;
}
/**
* Crop's part of image.
*
* @param top y position of left upper corner of crop rectangle
* @param left x position of left upper corner of crop rectangle
* @param width rectangle width
* @param height rectangle height
*
* @return GD
*/
function crop($top, $left, $width, $height) {
$newGD = imagecreatetruecolor($width, $height);
imagecopyresampled($newGD, $this->gd, 0, 0, $left, $top, $width, $height, $width, $height);
$output = clone $this;
$output->setGD($newGD);
return $output;
}
/**
* Method return width of image.
*
* @return integer width.
*/
function getWidth() {
return $this->width;
}
/**
* Method return height of image.
*
* @return integer height
*/
function getHeight() {
return $this->height;
}
/**
* Resize an image by width. Preserves aspect ratio.
*/
function resizeByWidth( $width ) {
$heightScale = $width / $this->width;
return $this->resize( $width, $heightScale * $this->height );
}
/**
* Resize an image by height. Preserves aspect ratio
*/
function resizeByHeight( $height ) {
$scale = $height / $this->height;
return $this->resize( $scale * $this->width, $height );
}
/**
* Resize the image by preserving aspect ratio. By default, it will keep the image inside the maxWidth and maxHeight
* Passing useAsMinimum will make the smaller dimension equal to the maximum corresponding dimension
*/
function resizeRatio( $maxWidth, $maxHeight, $useAsMinimum = false ) {
$widthRatio = $maxWidth / $this->width;
$heightRatio = $maxHeight / $this->height;
if( $widthRatio < $heightRatio )
return $useAsMinimum ? $this->resizeByHeight( $maxHeight ) : $this->resizeByWidth( $maxWidth );
else
return $useAsMinimum ? $this->resizeByWidth( $maxWidth ) : $this->resizeByHeight( $maxHeight );
}
static function color_web2gd($image, $webColor) {
if(substr($webColor,0,1) == "#") $webColor = substr($webColor,1);
$r = hexdec(substr($webColor,0,2));
$g = hexdec(substr($webColor,2,2));
$b = hexdec(substr($webColor,4,2));
return imagecolorallocate($image, $r, $g, $b);
}
/**
* Resize to fit fully within the given box, without resizing. Extra space left around
* the image will be padded with the background color.
* @param width
* @param height
* @param backgroundColour
*/
function paddedResize($width, $height, $backgroundColor = "FFFFFF") {
if(!$this->gd) return;
$width = round($width);
$height = round($height);
// Check that a resize is actually necessary.
if ($width == $this->width && $height == $this->height) {
return $this;
}
$newGD = imagecreatetruecolor($width, $height);
// Preserves transparency between images
imagealphablending($newGD, false);
imagesavealpha($newGD, true);
$bg = GD::color_web2gd($newGD, $backgroundColor);
imagefilledrectangle($newGD, 0, 0, $width, $height, $bg);
$destAR = $width / $height;
if ($this->width > 0 && $this->height > 0) {
// We can't divide by zero theres something wrong.
$srcAR = $this->width / $this->height;
// Destination narrower than the source
if($destAR > $srcAR) {
$destY = 0;
$destHeight = $height;
$destWidth = round( $height * $srcAR );
$destX = round( ($width - $destWidth) / 2 );
// Destination shorter than the source
} else {
$destX = 0;
$destWidth = $width;
$destHeight = round( $width / $srcAR );
$destY = round( ($height - $destHeight) / 2 );
}
imagecopyresampled($newGD, $this->gd, $destX, $destY, 0, 0, $destWidth, $destHeight, $this->width, $this->height);
}
$output = clone $this;
$output->setGD($newGD);
return $output;
}
/**
* Make the image greyscale
* $rv = red value, defaults to 38
* $gv = green value, defaults to 36
* $bv = blue value, defaults to 26
* Based (more or less entirely, with changes for readability) on code from http://www.teckis.com/scriptix/thumbnails/teck.html
*/
function greyscale($rv=38, $gv=36, $bv=26) {
$width = $this->width;
$height = $this->height;
$newGD = imagecreatetruecolor($this->width, $this->height);
$rt = $rv + $bv + $gv;
$rr = ($rv == 0) ? 0 : 1/($rt/$rv);
$br = ($bv == 0) ? 0 : 1/($rt/$bv);
$gr = ($gv == 0) ? 0 : 1/($rt/$gv);
for($dy = 0; $dy < $height; $dy++) {
for($dx = 0; $dx < $width; $dx++) {
$pxrgb = imagecolorat($this->gd, $dx, $dy);
$heightgb = ImageColorsforIndex($this->gd, $pxrgb);
$newcol = ($rr*$heightgb['red']) + ($br*$heightgb['blue']) + ($gr*$heightgb['green']);
$setcol = ImageColorAllocate($newGD, $newcol, $newcol, $newcol);
imagesetpixel($newGD, $dx, $dy, $setcol);
}
}
$output = clone $this;
$output->setGD($newGD);
return $output;
}
function makeDir($dirname) {
if(!file_exists(dirname($dirname))) $this->makeDir(dirname($dirname));
if(!file_exists($dirname)) mkdir($dirname, Filesystem::$folder_create_mask);
}
function writeTo($filename) {
$this->makeDir(dirname($filename));
if($filename) {
if(file_exists($filename)) list($width, $height, $type, $attr) = getimagesize($filename);
if(file_exists($filename)) unlink($filename);
$ext = strtolower(substr($filename, strrpos($filename,'.')+1));
if(!isset($type)) switch($ext) {
case "gif": $type = 1; break;
case "jpeg": case "jpg": case "jpe": $type = 2; break;
default: $type = 3; break;
}
// if the extension does not exist, the file will not be created!
switch($type) {
case 1: imagegif($this->gd, $filename); break;
case 2: imagejpeg($this->gd, $filename, $this->quality); break;
// case 3, and everything else
default:
// Save them as 8-bit images
// imagetruecolortopalette($this->gd, false, 256);
imagepng($this->gd, $filename); break;
}
if(file_exists($filename)) @chmod($filename,0664);
}
}
}
| bsd-3-clause |
wernedres/m2smart-zend | module/M2smart/src/M2smart/View/Helper/UserIdentity.php | 735 | <?php
namespace M2smart\View\Helper;
use Zend\View\Helper\AbstractHelper;
use Zend\Authentication\AuthenticationService,
Zend\Authentication\Storage\Session as SessionStorage;
class UserIdentity extends AbstractHelper {
protected $authService;
public function getAuthService() {
return $this->authService;
}
public function __invoke($namespace = null) {
$sessionStorage = new SessionStorage($namespace);
$this->authService = new AuthenticationService;
$this->authService->setStorage($sessionStorage);
if ($this->getAuthService()->hasIdentity()) {
return $this->getAuthService()->getIdentity();
} else {
return false;
}
}
}
| bsd-3-clause |
davidfang/MySKD | console/migrations/m160128_080101_post.php | 3786 | <?php
use yii\db\Schema;
class m160128_080101_post extends \yii\db\Migration
{
public function up()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB';
}
$this->createTable('{{%post}}', [
'id' => 'int(10) unsigned NOT NULL AUTO_INCREMENT ',
'name' => 'varchar(30) DEFAULT NULL COMMENT "广告位名称"',
'sort' => 'int(10) unsigned NOT NULL DEFAULT "0" COMMENT "显示排序"',
'image' => 'varchar(255) DEFAULT NULL COMMENT "广告图片"',
'jump_url' => 'varchar(30) DEFAULT NULL COMMENT "跳转地址"',
'jump_type_r' => 'enum("0","1") NOT NULL DEFAULT "1" COMMENT "跳转类型 0 自定义 1 单品页"',
'status' => 'enum("1","2","3","4") NOT NULL DEFAULT "2" COMMENT "状态,1 停止 2 暂停 3 删除 4启用"',
'start_date' => 'date NOT NULL DEFAULT "0000-00-00" COMMENT "开始时间"',
'end_date' => 'date NOT NULL DEFAULT "0000-00-00" COMMENT "结束时间"',
'date_type_r' => 'enum("0","1") NOT NULL DEFAULT "0" COMMENT "时间类型 0 使用已定义时间 1 不限时间"',
'PRIMARY KEY ([[id]])',
], $tableOptions);
$sql = "INSERT INTO {{%post}} (`id`,`name`,`sort`,`image`,`jump_url`,`jump_type_r`,`status`,`start_date`,`end_date`,`date_type_r`) VALUES
('29','qqqq','11','162690','www.123.com','0','3','2015-12-09','2016-12-10','0'),
('28','不求上进上','5','162970','http://www.163.com','1','3','2015-12-08','2015-12-31','1'),
('5','sssssss','2','uploads/20151110105003-853.png','http://www.baidu.com','1','3','2015-11-01','2016-11-20','1'),
('9','gdfddfgdfg','2','172908','http://www.baidu.com','1','3','2015-10-26','2016-12-03','1'),
('11','机器猫001','1','14728','https://www.123.com','1','4','2015-11-23','2015-11-24','1'),
('14','机器猫','3','14752','https://ww.234.com','1','4','2015-11-24','2015-11-25','0'),
('15','大师','2','14753','https://www.321.com','1','3','2015-11-24','2015-11-25','1'),
('16','大大','3','14754','sdadasdada','0','3','2015-11-24','2015-11-25','0'),
('19','机器猫','2','15766','https://www.123.com','0','3','2015-11-27','2015-11-28','1'),
('18','快乐','7','14950','https://www.123.com','0','3','2015-11-25','2015-11-26','0'),
('20','sd ','2','15767','http;//www.123.com','1','3','2015-11-12','2015-11-13','0'),
('21','we','2','15768','https://www.123.com','0','3','2015-11-23','2015-11-24','0'),
('22','gdfddfgdfgss','5','16704','http://www.163.com','1','3','2015-12-17','2015-12-31','1'),
('23','问问','2','16706','https://www.123.com','1','3','2015-12-25','2015-12-27','1'),
('24','123','123','156210','www.baidu.com','0','3','2015-12-08','2015-12-31','1'),
('25','机器猫','12','156211','www.sohu.com','0','3','2015-12-08','2015-12-09','0'),
('26','电视','2','156665','www.123.com','1','3','2015-12-09','2015-12-10','1'),
('27','是','2','156666','www.123.com','1','3','2015-12-09','2015-12-10','1'),
('30','2','2','162743','www.sohu.com','1','3','2015-12-09','2015-12-10','1'),
('31','hu ji','6','172518','www.123.com','1','3','2015-12-11','2015-12-12','0'),
('32','231','2','172909','www.123.com','1','3','2016-01-27','2016-01-28','1'),
('33','请问','1','172910','额q','1','3','2015-12-18','2015-12-31','0');";
$this->execute($sql);
}
public function down()
{
$this->dropTable('{{%post}}');
}
}
| bsd-3-clause |
endlessm/chromium-browser | chrome/browser/download/download_test_file_activity_observer.cc | 3385 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/download/download_test_file_activity_observer.h"
#include <utility>
#include "base/bind.h"
#include "base/location.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/download/chrome_download_manager_delegate.h"
#include "chrome/browser/download/download_core_service.h"
#include "chrome/browser/download/download_core_service_factory.h"
#include "chrome/browser/profiles/profile.h"
namespace download {
class DownloadItem;
}
// Test ChromeDownloadManagerDelegate that controls whether how file chooser
// dialogs are handled, and how files are opend.
// By default, file chooser dialogs are disabled.
class DownloadTestFileActivityObserver::MockDownloadManagerDelegate
: public ChromeDownloadManagerDelegate {
public:
explicit MockDownloadManagerDelegate(Profile* profile)
: ChromeDownloadManagerDelegate(profile),
file_chooser_enabled_(false),
file_chooser_displayed_(false) {
if (!profile->IsOffTheRecord())
GetDownloadIdReceiverCallback().Run(download::DownloadItem::kInvalidId +
1);
}
~MockDownloadManagerDelegate() override {}
void EnableFileChooser(bool enable) {
file_chooser_enabled_ = enable;
}
bool TestAndResetDidShowFileChooser() {
bool did_show = file_chooser_displayed_;
file_chooser_displayed_ = false;
return did_show;
}
base::WeakPtr<MockDownloadManagerDelegate> GetWeakPtr() {
return weak_ptr_factory_.GetWeakPtr();
}
protected:
void ShowFilePickerForDownload(
download::DownloadItem* download,
const base::FilePath& suggested_path,
const DownloadTargetDeterminerDelegate::ConfirmationCallback& callback)
override {
file_chooser_displayed_ = true;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(
&MockDownloadManagerDelegate::OnConfirmationCallbackComplete,
base::Unretained(this), callback,
(file_chooser_enabled_ ? DownloadConfirmationResult::CONFIRMED
: DownloadConfirmationResult::CANCELED),
suggested_path));
}
void OpenDownload(download::DownloadItem* item) override {}
private:
bool file_chooser_enabled_;
bool file_chooser_displayed_;
base::WeakPtrFactory<MockDownloadManagerDelegate> weak_ptr_factory_{this};
};
DownloadTestFileActivityObserver::DownloadTestFileActivityObserver(
Profile* profile) {
std::unique_ptr<MockDownloadManagerDelegate> mock_delegate(
new MockDownloadManagerDelegate(profile));
test_delegate_ = mock_delegate->GetWeakPtr();
DownloadCoreServiceFactory::GetForBrowserContext(profile)
->SetDownloadManagerDelegateForTesting(std::move(mock_delegate));
}
DownloadTestFileActivityObserver::~DownloadTestFileActivityObserver() {
}
void DownloadTestFileActivityObserver::EnableFileChooser(bool enable) {
if (test_delegate_.get())
test_delegate_->EnableFileChooser(enable);
}
bool DownloadTestFileActivityObserver::TestAndResetDidShowFileChooser() {
return test_delegate_.get() &&
test_delegate_->TestAndResetDidShowFileChooser();
}
| bsd-3-clause |
NCIP/geneconnect | Coding and Testing/GeneConnectWeb/WEB-INF/src/edu/wustl/geneconnect/bizlogic/ValidationResultData.java | 1096 | /*L
* Copyright Washington University at St. Louis
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/geneconnect/LICENSE.txt for details.
*/
/**
*<p>ClassName: java edu.wustl.geneconnect.bizlogic.ValidationResultData</p>
*/
package edu.wustl.geneconnect.bizlogic;
import java.util.List;
/**
* This class represents the resultdata returned by BusinessLogic
* when some validation exception occurs during the operation.
* It contains the list of validation errors.
* @author mahesh_nalkande
* @version 1.0
*/
public class ValidationResultData
{
/**
* List of validation errors.
*/
private List errorList;
/**
* Default constructor
*/
public ValidationResultData()
{
}
/**
* Getter method for Error List.
* @return Returns the errorList.
*/
public List getErrorList()
{
return errorList;
}
/**
* Setter method for Error List.
* @param errorList The errorList to set.
*/
public void setErrorList(List errorList)
{
this.errorList = errorList;
}
} | bsd-3-clause |
rafadev/django-maintenancemode | maintenancemode/middleware.py | 1822 | from django.conf import settings
from django.template import RequestContext
from maintenancemode.http import Http503
from maintenancemode.shortcuts import render_to_503
from maintenancemode.conf.settings import MAINTENANCE_MODE
import re
HAS_LANG_PREFIX_RE = re.compile(r"^/(%s)/.*" % "|".join(map(lambda l: re.escape(l[0]), settings.LANGUAGES)))
def has_lang_prefix(path):
check = HAS_LANG_PREFIX_RE.match(path)
if check is not None:
return check.group(1)
else:
return False
class MaintenanceModeMiddleware(object):
def process_request(self, request):
prefix = has_lang_prefix(request.path_info)
if prefix:
path_info = "/" + "/".join(request.path_info.split("/")[2:])
else:
path_info = request.path_info
if request.path_info.startswith(settings.MEDIA_URL) \
or request.path_info.startswith(settings.ADMIN_MEDIA_PREFIX) \
or path_info.startswith('/admin'): #should be changed to be independent of where the admin is set up
return None
# Allow access if middleware is not activated
if not MAINTENANCE_MODE:
return None
# Allow access if remote ip is in INTERNAL_IPS
if request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
return None
# Allow acess if the user doing the request is logged in and a
# staff member.
if hasattr(request, 'user') and request.user.is_staff:
return None
# Otherwise show the user the 503 page
return self.process_exception(request, Http503())
def process_exception(self,request,exception):
if isinstance(exception, Http503):
return render_to_503(context_instance=RequestContext(request)) | bsd-3-clause |
alexsegura/Oops | library/Oops/Db/ConfigurationTableMap.php | 1659 | <?php
/**
* This class defines the structure of the 'configuration' table.
*
*
*
* This map class is used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
* @package propel.generator.prestashop.map
*/
class Oops_Db_ConfigurationTableMap extends TableMap
{
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'prestashop.map.Oops_Db_ConfigurationTableMap';
/**
* Initialize the table attributes, columns and validators
* Relations are not initialized by this method since they are lazy loaded
*
* @return void
* @throws PropelException
*/
public function initialize()
{
// attributes
$this->setName(_DB_PREFIX_ . 'configuration');
$this->setPhpName('Configuration');
$this->setClassname('Oops_Db_Configuration');
$this->setPackage('prestashop');
$this->setUseIdGenerator(true);
// columns
$this->addPrimaryKey('ID_CONFIGURATION', 'IdConfiguration', 'INTEGER', true, 10, null);
$this->addColumn('NAME', 'Name', 'VARCHAR', true, 32, null);
$this->addColumn('VALUE', 'Value', 'LONGVARCHAR', false, null, null);
$this->addColumn('DATE_ADD', 'DateAdd', 'TIMESTAMP', true, null, null);
$this->addColumn('DATE_UPD', 'DateUpd', 'TIMESTAMP', true, null, null);
// validators
} // initialize()
/**
* Build the RelationMap objects for this table relationships
*/
public function buildRelations()
{
} // buildRelations()
} // Oops_Db_ConfigurationTableMap
| bsd-3-clause |
openmetaversefoundation/simiangrid | GridFrontend/application/libraries/SimianGrid.php | 15961 | <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class SimianGrid
{
var $_user_cache;
function SimianGrid()
{
$this->ci =& get_instance();
$this->_user_cache = array();
log_message('debug', 'SimianGridClient Initialized');
$this->ci->load->library('Curl');
$this->_init();
}
function _init()
{
$this->grid_service = $this->ci->config->item('grid_service');
$this->user_service = $this->ci->config->item('user_service');
$this->asset_service = $this->ci->config->item('asset_service');
$this->hypergrid_service = $this->ci->config->item('hypergrid_service');
}
function _rest_post($url, $params)
{
$response = $this->ci->curl->simple_post($url, $params);
$response = decode_recursive_json($response);
if (!isset($response))
$response = array('Message' => 'Invalid or missing response');
return $response;
}
function search_user($thing)
{
$query = array(
'RequestMethod' => 'GetUsers',
'NameQuery' => $thing
);
$response = $this->_rest_post($this->user_service, $query);
if ( is_array($response['Users']) ) {
$result = array();
foreach ( $response['Users'] as $user ) {
$this_result = array(
'name' => $user['Name'],
'id' => $user['UserID']
);
array_push($result, $this_result);
}
return $result;
}
return array();
}
function user_delete($user_id)
{
$query = array(
'RequestMethod' => 'RemoveUser',
'UserID' => $user_id
);
$response = $this->_rest_post($this->user_service, $query);
if (element('Success', $response)) {
return true;
} else {
return false;
}
}
function get_user($user_id, $force = false)
{
if ( $force || empty($this->_user_cache[$user_id]) ) {
$user = $this->_user_get('id', $user_id);
$this->_user_cache[$user_id] = $user;
return $user;
} else {
return $this->_user_cache[$user_id];
}
}
function get_user_by_name($name)
{
$user = $this->_user_get('name', $name);
if ( $user != null ) {
$this->_user_cache[$user['UserID']] = $user;
}
return $user;
}
function get_user_by_email($email)
{
$user = $this->_user_get('email', $email);
if ( $user != null ) {
$this->_user_cache[$user['UserID']] = $user;
}
return $user;
}
function user_id_from_name($name)
{
$user = $this->get_user_by_name($name);
if ( $user === null ) {
return null;
} else {
return $user['UserID'];
}
}
function is_user($user_id)
{
$user = $this->user_get($user_id);
if ( $user == null ) {
return false;
} else {
return true;
}
}
function _user_get($type, $thing)
{
// Fetch account data for this user
if ($type == 'id') {
$query = array(
'RequestMethod' => 'GetUser',
'UserID' => $thing
);
} elseif ($type == 'name') {
$query = array(
'RequestMethod' => 'GetUser',
'Name' => $thing
);
} elseif ( $type =='email' ) {
$query = array(
'RequestMethod' => 'GetUser',
'Email' => $thing
);
} else {
return;
}
$response = $this->_rest_post($this->user_service, $query);
if (element('Success', $response) && is_array($response['User'])) {
return $response['User'];
} else {
return;
}
}
function get_identity($identifier)
{
$identities = $this->_get_user_identities('name', $identifier);
if ( count($identities) == 0 ) {
return null;
} else {
return $identities[0];
}
}
function get_user_identities($thing)
{
return $this->_get_user_identities('id', $thing);
}
function _get_user_identities($type, $thing)
{
if ( $type == 'id' ) {
$query = array(
'RequestMethod' => 'GetIdentities',
'UserID' => $thing
);
} else if ( $type == 'name' ) {
$query = array(
'RequestMethod' => 'GetIdentities',
'Identifier' => $thing
);
}
$response = $this->_rest_post($this->user_service, $query);
if (element('Success', $response) && is_array($response['Identities'])) {
return $response['Identities'];
} else {
return null;
}
}
function auth_user($username, $password)
{
return $this->authorize_identity('md5hash', $username, '$1$' . md5($password));
}
function auth_openid($openid)
{
return $this->authorize_identity('openid', $openid);
}
function auth_facebook($token)
{
return $this->authorize_identity('facebook', $token);
}
function authorize_identity($type, $identifier, $credential='') {
$query = array(
'RequestMethod' => 'AuthorizeIdentity',
'Identifier' => $identifier,
'Credential' => $credential,
'Type' => $type
);
$response = $this->_rest_post($this->user_service, $query);
if (element('Success', $response, false) ) {
return element('UserID', $response);
} else {
return null;
}
}
function add_capability($owner_id, $resource, $expiration_timestamp)
{
$query = array(
'RequestMethod' => 'AddCapability',
'OwnerID' => $owner_id,
'Resource' => $resource,
'Expiration' => $expiration_timestamp
);
$response = $this->_rest_post($this->user_service, $query);
if ( element('Success', $response, false) ) {
return element('CapabilityID', $response, null);
} else {
return null;
}
}
function set_user_data($user_id, $key, $value)
{
$query = array(
'RequestMethod' => 'AddUserData',
'UserID' => $user_id,
$key => $value
);
$response = $this->_rest_post($this->user_service, $query);
if ( element('Success', $response, false) ) {
return true;
} else {
return false;
}
}
function remove_user_data($user_id, $key)
{
$query = array(
'RequestMethod' => 'RemoveUserData',
'UserID' => $user_id,
'Key' => $key
);
$this->_rest_post($this->user_service, $query);
}
function search_scene($name) {
return $this->_search_scene('name', $name);
}
function get_hyperlinks($enabled = true)
{
return $this->_search_scene('hypergrid', $enabled);
}
function _search_scene($request, $thing)
{
if ( $request == "name" ) {
$query = array(
'RequestMethod' => 'GetScenes',
'NameQuery' => $thing
);
} else if ( $request === 'hypergrid' ) {
$query = array(
'RequestMethod' => 'GetScenes',
'HyperGrid' => 'true',
'Enabled' => $thing
);
} else {
return null;
}
$response = $this->_rest_post($this->grid_service, $query);
if ( is_array($response['Scenes']) ) {
$result = array();
foreach ( $response['Scenes'] as $scene ) {
$this_result = array(
'name' => $scene['Name'],
'id' => $scene['SceneID'],
'x' => $scene['MinPosition'][0] / 256,
'y' => $scene['MinPosition'][1] / 256
);
array_push($result, $this_result);
}
return $result;
}
return null;
}
function set_scene_data($scene_id, $key, $value)
{
$query = array(
'RequestMethod' => 'AddSceneData',
'SceneID' => $scene_id,
'Key' => $key,
'Value' => $value
);
$response = $this->_rest_post($this->grid_service, $query);
if ( element('Success', $response, false) ) {
return true;
} else {
return false;
}
}
function get_scene($scene_id)
{
return $this->_get_scene_info('id', $scene_id);
}
function get_scene_by_name($name)
{
$result = $this->_search_scene('name', $name);
if ( $result != null && count($result) > 0 ) {
return $this->get_scene($result[0]['id']);
} else {
return null;
}
}
function get_scene_by_pos($x, $y)
{
return $this->_get_scene_info('pos', "<$x, $y, 0>");
}
function get_scene_by_owner($owner)
{
return $this->_get_scene_info('owner', $owner);
}
function _get_scene_info($request, $thing = null)
{
if ( $request == "id" ) {
$query = array(
'RequestMethod' => 'GetScene',
'SceneID' => $thing
);
} else if ( $request == "pos" ) {
$query = array(
'RequestMethod' => 'GetScene',
'Position' => $thing
);
} else if ( $request == "name" ) {
$query = array(
'RequestMethod' => 'GetScene',
'Name' => $thing
);
} else if ( $request == "owner" ) {
$query = array(
'RequestMethod' => 'GetScene',
'EstateOwner' => $thing
);
} else {
return null;
}
$response = $this->_rest_post($this->grid_service, $query);
if (element('Success', $response) ) {
return $response;
} else {
return;
}
}
function get_texture($uuid, $x = null, $y = null)
{
$image = $this->ci->curl->simple_get($this->asset_service . $uuid);
if ( $image == null ) {
return null;
}
$im = new imagick();
$im->readImageBlob($image);
$im->setImageFormat("jpeg");
if ( $x != null && $y != null ) {
$im->scaleImage(200, 200, true);
}
return $im;
}
function register($username, $email)
{
$userid = random_uuid();
$query = array(
'RequestMethod' => 'AddUser',
'UserID' => $userid,
'Name' => $username,
'Email' => $email
);
$response = $this->_rest_post($this->user_service, $query);
if (element('Success', $response)) {
return $userid;
} else {
return null;
}
}
function identity_set($user_id, $type, $identifier, $credential='')
{
$query = array(
'RequestMethod' => 'AddIdentity',
'Identifier' => $identifier,
'Credential' => $credential,
'Type' => $type,
'UserID' => $user_id
);
$response = $this->_rest_post($this->user_service, $query);
if (element('Success', $response)) {
return true;
} else {
return false;
}
}
function identity_remove($user_id, $type, $identifier)
{
$query = array(
'RequestMethod' => 'RemoveIdentity',
'Type' => $type,
'Identifier' => $identifier,
'UserID' => $user_id
);
$response = $this->_rest_post($this->user_service, $query);
if (element('Success', $response)) {
return true;
} else {
return false;
}
}
function create_avatar($user_id, $avtype)
{
$query = array(
'RequestMethod' => 'AddInventory',
'AvatarType' => $avtype,
'OwnerID' => $user_id
);
$response = $this->_rest_post($this->user_service, $query);
if (element('Success', $response)) {
return true;
} else {
return false;
}
}
function set_access_level($user_id, $level)
{
$user_data = $this->get_user($user_id, true);
$query = array(
'RequestMethod' => 'AddUser',
'UserID' => $user_data['UserID'],
'Email' => $user_data['Email'],
'Name' => $user_data['Name'],
'AccessLevel' => $level
);
$response = $this->_rest_post($this->user_service, $query);
if (element('Success', $response)) {
return true;
} else {
return false;
}
}
function simulator_details($scene_id)
{
$scene = $this->get_scene($scene_id);
if ( $scene == null ) {
return null;
}
$url = $scene['Address'] . "monitorstats/$scene_id";
$url2 = $scene['Address'] . "jsonSimStats";
$result = $this->ci->curl->simple_get($url);
if ( $result == null ) {
log_message('debug', "Unable to retrieve simulator stats from $url");
return null;
}
$result2 = $this->ci->curl->simple_get($url2);
$json_result = array();
if ( $result2 == null ) {
log_message('debug', "Unable to retrieve instance information from $result2");
$json_result['Version'] = "??";
$json_result['Uptime'] = "??";
} else {
$json_result = decode_recursive_json($result2);
}
$xml = new SimpleXMLElement($result);
$result = array(
'simulation_fps' => $xml->SimFPSMonitor,
'physics_fps' => $xml->PhysicsFPSMonitor,
'version' => $json_result['Version'],
'uptime' => $json_result['Uptime'],
'dilation' => $xml->TimeDilationMonitor,
'prim_count' => $xml->ObjectCountMonitor,
'agents' => $xml->AgentCountMonitor,
'child_agents' => $xml->ChildAgentCountMonitor
);
return $result;
}
function total_user_count()
{
$data = array(
'RequestMethod' => 'GetUserStats'
);
$result = $this->_rest_post($this->user_service, $data);
if ( isset($result['Success']) ) {
return $result['UserCount'];
} else {
log_message('error', "Unknown response to GetUserStats. Returning 0.");
return 0;
}
}
function total_scene_count()
{
$data = array(
'RequestMethod' => 'GetSceneStats'
);
$result = $this->_rest_post($this->grid_service, $data);
if ( isset($result['Success']) ) {
return $result['SceneCount'];
} else {
log_message('error', "Unknown response to GetSceneStats. Returning 0.");
return 0;
}
}
function link_region($hg_uri, $region_name, $x, $y)
{
$data = array(
'x' => $x,
'y' => $y,
'hg_uri' => $hg_uri,
'region_name' => $region_name
);
$result = $this->_rest_post($this->hypergrid_service . '/sg_api/link_remote', $data);
return $result['Success'];
}
}
?> | bsd-3-clause |
350dotorg/aktlet | standalone_django_project/required_environ.py | 1890 | DJANGO_DEBUG = "1"
DJANGO_DEBUG_TOOLBAR = "1"
SITE_NAME = "My Organization"
SECRET_KEY = "secret!"
ACTIONKIT_DATABASE_NAME = "ak_yourclientdbname"
ACTIONKIT_DATABASE_USER = "username"
ACTIONKIT_DATABASE_PASSWORD = "password"
ACTIONKIT_API_HOST = "act.example.com"
ACTIONKIT_API_USER = "api_username"
ACTIONKIT_API_PASSWORD = "api_password"
if __name__ == '__main__':
import random, sys, os
assert not os.path.exists(sys.argv[1]), "Please enter a path to a file that doesn't already exist"
vars = {}
vars['DJANGO_SECRET'] = ''.join([random.choice('abcdefghijklmnopqrxtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()-=_+') for i in range(30)])
vars['SITE_NAME'] = raw_input("What is your organization's name? ")
vars['ACTIONKIT_API_HOST'] = raw_input("Enter the base URL of your Actionkit instance (e.g. https://act.example.com) ")
vars['ACTIONKIT_API_USER'] = raw_input("Enter the username of an Actionkit user with API access: ")
vars['ACTIONKIT_API_PASSWORD'] = raw_input("What is the password for that user? ")
vars['ACTIONKIT_DATABASE_NAME'] = raw_input("What is your Actionkit database name? (e.g. ak_example) ")
vars['ACTIONKIT_DATABASE_USER'] = raw_input("Enter a username that you use to connect to the Actionkit client-db: ")
vars['ACTIONKIT_DATABASE_PASSWORD'] = raw_input("What is the password for that database user? ")
vars['SITE_DOMAIN'] = raw_input("What is the domain that you will be serving the AKtlet from? Note that you will need a valid SSL certificate for this domain. (e.g. aktlet.example.com -- leave off the https:// portion) ")
vars['SITE_LOGO_URL'] = raw_input("Enter the full URL to an image file on the web containing your organization's logo")
env = "\n".join(["=".join((key, val)) for key, val in vars.items()])
with open(sys.argv[1], 'w') as fp:
print >> fp, env
| bsd-3-clause |
dCache/CDMI | cdmi-core/src/main/java/org/snia/cdmiserver/dao/CapabilityDaoImpl.java | 8117 | /*
* Copyright (c) 2010, Sun Microsystems, Inc.
* Copyright (c) 2010, The Storage Networking Industry Association.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of The Storage Networking Industry Association (SNIA) nor
* the names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.snia.cdmiserver.dao.filesystem;
import org.snia.cdmiserver.dao.CapabilityDao;
import org.snia.cdmiserver.model.Capability;
import org.snia.cdmiserver.util.ObjectID;
/**
* <p>
* Concrete implementation of {@link CapabilityObjectDao} using the local filesystem as the backing
* store.
* </p>
*/
public class CapabilityDaoImpl implements CapabilityDao {
// -------------------------------------------------------------- Properties
/**
* <p>
* Injected {@link CapabilityDao} instance.
* </p>
*/
private CapabilityDao capabilityDao;
private String ROOTobjectID = ObjectID.getObjectID(8);
private String CONTAINERobjectID = ObjectID.getObjectID(8);
private String DEFAULTobjectID = ObjectID.getObjectID(8);
private String OBJECTobjectID = ObjectID.getObjectID(8);
public void setCapabilityDao(CapabilityDao capabilityDao) {
this.capabilityDao = capabilityDao;
}
// ---------------------------------------------------- ContainerDao Methods
@Override
public Capability findByObjectId(String objectId) {
throw new UnsupportedOperationException("CapabilityDaoImpl.findByObjectId()");
}
@Override
public Capability findByPath(String path) {
Capability capability = new Capability();
System.out.print("In Capability.findByPath, path is: ");
System.out.println(path);
if (path.equals("container/")) {
System.out.println("Container Capabilities");
// Container Capabilities
// cdmi_list_children = true
// cdmi_list_children_range = unset until implemented
// cdmi_read_metadata = true
// cdmi_modify_metadata = true
// cdmi_snapshot = unset, stretch goal (filesystem support?)
// cdmi_serialize_container = unset until implemented
// cdmi_create_dataobject = true
// cdmi_post_dataobject = true
// cdmi_create_container = true
capability.getMetadata().put("cdmi_list_children", "true");
capability.getMetadata().put("cdmi_read_metadata", "true");
capability.getMetadata().put("cdmi_modify_metadata", "true");
capability.getMetadata().put("cdmi_create_dataobject", "true");
// capability.getMetadata().put("cdmi_post_dataobject", "true");
capability.getMetadata().put("cdmi_create_container", "true");
capability.getChildren().add("default");
capability.setObjectID(CONTAINERobjectID);
capability.setObjectType("application/cdmi-capability");
capability.setParentURI("cdmi_capabilities/");
capability.setParentID(ROOTobjectID);
} else if (path.equals("container/default/")) {
System.out.println("Default Container Capabilities");
capability.getMetadata().put("cdmi_list_children", "true");
capability.getMetadata().put("cdmi_read_metadata", "true");
capability.getMetadata().put("cdmi_modify_metadata", "true");
capability.getMetadata().put("cdmi_create_dataobject", "true");
capability.getMetadata().put("cdmi_post_dataobject", "true");
capability.getMetadata().put("cdmi_create_container", "true");
capability.setObjectID(DEFAULTobjectID);
capability.setObjectType("application/cdmi-capability");
capability.setParentURI("cdmi_capabilities/container");
capability.setParentID(CONTAINERobjectID);
} else if (path.equals("dataobject/")) {
// Data Object Capabilities
System.out.println("Data Object Capabilities");
// cdmi_read_value = true
// cdmi_read_value_range = unset initially, then true when implemented
// cdmi_read_metadata = true
// cdmi_modify_value = true
// cdmi_modify_value_range = unset until implemented
// cdmi_modify_metadata = true
// cdmi_serialize_dataobject, cdmi_deserialize_dataobject = unset until implemented
// cdmi_delete_dataobject = true
capability.getMetadata().put("cdmi_read_value", "true");
capability.getMetadata().put("cdmi_read_metadata", "true");
capability.getMetadata().put("cdmi_modify_metadata", "true");
capability.getMetadata().put("cdmi_modify_value", "true");
capability.getMetadata().put("cdmi_delete_dataobject", "true");
capability.setObjectID(OBJECTobjectID);
capability.setObjectType("application/cdmi-capability");
capability.setParentURI("cdmi_capabilities/");
capability.setParentID(ROOTobjectID);
} else {
// System Capabilities
System.out.println("System Capabilities");
// cdmi_domains = later version true
// cdmi_export_occi_iscsi = true for demo?
// cdmi_metadata_maxitems, cdmi_metadata_maxsize = TBD based on our limits
// cdmi_notification, cdmi_query, cdmi_queues, cdmi_security_audit = exposed as
// implementations become available
// cdmi_security_data_integrity, cdmi_security_encryption, ditto
// cdmi_security_https_transport = present and true
// cdmi_security_immutability = as XAM SDK code is integrated
// cdmi_security_sanitization = should we implement?
// cdmi_serialization_json = propose using this form for RI
capability.getMetadata().put("domains", "false");
capability.getMetadata().put("cdmi_export_occi_iscsi", "true");
capability.getMetadata().put("cdmi_metadata_maxitems", "1024");
capability.getMetadata().put("cdmi_metadata_maxsize", "4096");
// capability.getMetadata().put("cdmi_security_https_transport", "true");
// capability.getMetadata().put("cdmi_serialization_json", "true");
capability.getChildren().add("container");
capability.getChildren().add("dataobject");
capability.setObjectID(ROOTobjectID);
capability.setObjectType("application/cdmi-capability");
capability.setParentURI("/");
capability.setParentID(ROOTobjectID);
}
return (capability);
// throw new UnsupportedOperationException("CapabilityDaoImpl.findByPath()");
}
}
| bsd-3-clause |
simphony/simphony-remote | remoteappmanager/tests/utils.py | 3082 | import contextlib
import sys
from tornado import gen
from remoteappmanager.command_line_config import CommandLineConfig
from remoteappmanager.file_config import FileConfig
from remoteappmanager.environment_config import EnvironmentConfig
from remoteappmanager.db.orm import Database
from remoteappmanager.tests import fixtures
from remoteappmanager.utils import remove_quotes
# A set of viable start arguments. As they would arrive from outside
arguments = {
"user": "johndoe",
"port": 57022,
"cookie-name": "jupyter-hub-token-johndoe",
"base-urlpath": "\"/user/johndoe/\"",
"hub-host": "",
"hub-prefix": "/hub/",
"hub-api-url": "http://172.17.5.167:8081/hub/api",
"proxy-api-url": "http://192.168.100.99/proxy/api",
"ip": "127.0.0.1",
"config-file": fixtures.get("remoteappmanager_config.py")
}
def init_sqlite_db(path):
"""Initializes the sqlite database at a given path.
"""
db = Database("sqlite:///"+path)
db.reset()
def basic_command_line_config():
"""Returns a basic application config for testing purposes.
The database is in memory.
"""
options = {k.replace("-", "_"): remove_quotes(v)
for k, v in arguments.items()}
return CommandLineConfig(**options)
def basic_file_config():
return FileConfig()
def basic_environment_config():
config = EnvironmentConfig()
config.proxy_api_token = "dummy_token"
config.jpy_api_token = "dummy_token"
return config
@contextlib.contextmanager
def invocation_argv():
"""Replaces and restores the argv arguments"""
saved_argv = sys.argv[:]
new_args = ["--{}={}".format(key, value)
for key, value in arguments.items()]
sys.argv[:] = [sys.argv[0]] + new_args
yield
sys.argv[:] = saved_argv
def mock_coro_new_callable(return_value=None, side_effect=None):
"""Creates a patch suitable callable that returns a coroutine
with appropriate return value and side effect."""
coro = mock_coro_factory(return_value, side_effect)
def new_callable():
return coro
return new_callable
def mock_coro_factory(return_value=None, side_effect=None):
"""Creates a mock coroutine with a given return value"""
@gen.coroutine
def coro(*args, **kwargs):
coro.called = True
coro.call_args = (args, kwargs)
yield gen.sleep(0.1)
if side_effect:
if isinstance(side_effect, Exception):
raise side_effect
else:
side_effect(*args, **kwargs)
return coro.return_value
coro.called = False
coro.call_args = ([], {})
coro.return_value = return_value
return coro
def assert_containers_equal(test_case, actual, expected):
test_case.assertEqual(
set(actual.trait_names()),
set(expected.trait_names()))
for name in expected.trait_names():
if getattr(actual, name) != getattr(expected, name):
message = '{!r} is not identical to the expected {!r}.'
test_case.fail(message.format(actual, expected))
| bsd-3-clause |
CyEy/CyberEyes | CyberEyes/CyberEyes/IFileHelper.cs | 319 | using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace CyberEyes
{
public interface IFileHelper
{
bool Exists(string filename);
void WriteText(string filename, string text);
string ReadText(string filename);
IEnumerable<string> GetFiles();
void Delete(string filename);
}
}
| bsd-3-clause |
healthchecks/healthchecks | hc/api/tests/test_get_badges.py | 1425 | from datetime import timedelta as td
from hc.api.models import Check
from hc.test import BaseTestCase
class GetBadgesTestCase(BaseTestCase):
def setUp(self):
super().setUp()
self.a1 = Check(project=self.project, name="Alice 1")
self.a1.timeout = td(seconds=3600)
self.a1.grace = td(seconds=900)
self.a1.n_pings = 0
self.a1.status = "new"
self.a1.tags = "foo bar"
self.a1.save()
self.url = "/api/v1/badges/"
def get(self, api_key="X" * 32, qs=""):
return self.client.get(self.url + qs, HTTP_X_API_KEY=api_key)
def test_it_works(self):
r = self.get()
self.assertEqual(r.status_code, 200)
self.assertEqual(r["Access-Control-Allow-Origin"], "*")
doc = r.json()
self.assertTrue("foo" in doc["badges"])
self.assertTrue("svg" in doc["badges"]["foo"])
def test_readonly_key_is_allowed(self):
self.project.api_key_readonly = "R" * 32
self.project.save()
r = self.get(api_key=self.project.api_key_readonly)
self.assertEqual(r.status_code, 200)
def test_it_rejects_post(self):
r = self.csrf_client.post(self.url, HTTP_X_API_KEY="X" * 32)
self.assertEqual(r.status_code, 405)
def test_it_handles_missing_api_key(self):
r = self.client.get(self.url)
self.assertContains(r, "missing api key", status_code=401)
| bsd-3-clause |
stepancher/yii2-content-module | assets/js/content.js | 3789 | /**
* Created by mkv on 10.07.15.
*/
$(document).ready(function () {
/**
* Групповые действия с элементами
*/
$('a.btn-multiple').on('click', function () {
if(confirm('Вы действительно хотите выполнить это действие?')) {
var obj = $(this);
var url = document.location.href;
var keys = $('#grid').yiiGridView('getSelectedRows');
var model = obj.data('classname');
var action = obj.data('action');
if(keys.length > 0) {
$.ajax({
url: $('#grid').data('url'),
type: 'POST',
data: 'keys=' + keys + '&model=' + model + '&action=' + action + '&url=' + url,
success: function (data) {},
dataType: 'json'
});
}
}
return false;
});
// Изменение видимости статей
$('.visible_checkbox').change(function () {
var $obj = $(this);
$.ajax({
url: $obj.data('url'),
type: "POST",
data: 'id=' + $obj.data('id') + '&visible=' + ($obj.prop('checked') ? 1 : 0),
success: function($data) {
$obj.after('<span style="margin: 0 10px" class="label label-' + $data.type + '">' + $data.message + '</span>');
$obj.next('span').fadeOut(2000, function() {
$( this ).remove();
});
},
dataType: 'json'
});
});
// Скрываем элементы редактирования
$('.sort_button').css('display', 'none');
$('.sort_change').css('display', 'none');
// Событие по нажатию на кнопку изменить поле
$('.sort_input').on('click', function () {
var $obj = $(this);
$obj.next('.sort_change').css('display', 'inline-block');
$obj.next('.sort_change').next('.sort_button').css('display', 'inline-block');
$obj.next('.sort_change').focus();
$obj.css('display', 'none');
});
// Событие после нажатие на кнопку применить изменения
$('.sort_button').on('click', function () {
var $obj = $(this);
var $input = $obj.prev('.sort_change');
$.ajax({
url: '/admin/content/sort',
type: "POST",
data: 'id=' + $input.data('id') + '&sort=' + $input.val(),
success: function($data) {
$obj.after('<span style="margin: 0 10px" class="label label-' + $data.type + '">' + $data.message + '</span>');
$obj.next('span').fadeOut(2000, function() {
$( this ).remove();
});
$input.prev('.sort_input').html('<i class="icon icon fa fa-edit">' + $input.val() + '</i>');
},
dataType: 'json'
});
$obj.css('display', 'none');
$input.css('display', 'none');
$input.prev('.sort_input').css('display', 'inline-block');
return false;
});
//$('.sort_change').focusout(function (e) {
// if($(this).prev('.sort_input').css('display') == 'none') {
// $(this).prev('.sort_input').css('display', 'block');
// $(this).css('display', 'none');
// $(this).next('.sort_button').css('display', 'none');
// }
//});
// Событие по нажатию на Enter
//$(document).keydown(function (e) {
// if(e.keyCode == 13) {
// $obj = $("input:focus");
// $obj.next('.sort_button').click();
//
// return false;
// }
//});
}); | bsd-3-clause |
koparasy/faultinjection-gem5 | configs/example/memtest.py | 7177 | # Copyright (c) 2006-2007 The Regents of The University of Michigan
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Ron Dreslinski
import optparse
import sys
import m5
from m5.objects import *
parser = optparse.OptionParser()
parser.add_option("-a", "--atomic", action="store_true",
help="Use atomic (non-timing) mode")
parser.add_option("-b", "--blocking", action="store_true",
help="Use blocking caches")
parser.add_option("-l", "--maxloads", metavar="N", default=0,
help="Stop after N loads")
parser.add_option("-m", "--maxtick", type="int", default=m5.MaxTick,
metavar="T",
help="Stop after T ticks")
#
# The "tree" specification is a colon-separated list of one or more
# integers. The first integer is the number of caches/testers
# connected directly to main memory. The last integer in the list is
# the number of testers associated with the uppermost level of memory
# (L1 cache, if there are caches, or main memory if no caches). Thus
# if there is only one integer, there are no caches, and the integer
# specifies the number of testers connected directly to main memory.
# The other integers (if any) specify the number of caches at each
# level of the hierarchy between.
#
# Examples:
#
# "2:1" Two caches connected to memory with a single tester behind each
# (single-level hierarchy, two testers total)
#
# "2:2:1" Two-level hierarchy, 2 L1s behind each of 2 L2s, 4 testers total
#
parser.add_option("-t", "--treespec", type="string", default="8:1",
help="Colon-separated multilevel tree specification, "
"see script comments for details "
"[default: %default]")
parser.add_option("--force-bus", action="store_true",
help="Use bus between levels even with single cache")
parser.add_option("-f", "--functional", type="int", default=0,
metavar="PCT",
help="Target percentage of functional accesses "
"[default: %default]")
parser.add_option("-u", "--uncacheable", type="int", default=0,
metavar="PCT",
help="Target percentage of uncacheable accesses "
"[default: %default]")
parser.add_option("--progress", type="int", default=1000,
metavar="NLOADS",
help="Progress message interval "
"[default: %default]")
(options, args) = parser.parse_args()
if args:
print "Error: script doesn't take any positional arguments"
sys.exit(1)
block_size = 64
try:
treespec = [int(x) for x in options.treespec.split(':')]
numtesters = reduce(lambda x,y: x*y, treespec)
except:
print "Error parsing treespec option"
sys.exit(1)
if numtesters > block_size:
print "Error: Number of testers limited to %s because of false sharing" \
% (block_size)
sys.exit(1)
if len(treespec) < 1:
print "Error parsing treespec"
sys.exit(1)
# define prototype L1 cache
proto_l1 = BaseCache(size = '32kB', assoc = 4, block_size = block_size,
latency = '1ns', tgts_per_mshr = 8)
if options.blocking:
proto_l1.mshrs = 1
else:
proto_l1.mshrs = 4
# build a list of prototypes, one for each level of treespec, starting
# at the end (last entry is tester objects)
prototypes = [ MemTest(atomic=options.atomic, max_loads=options.maxloads,
percent_functional=options.functional,
percent_uncacheable=options.uncacheable,
progress_interval=options.progress) ]
# next comes L1 cache, if any
if len(treespec) > 1:
prototypes.insert(0, proto_l1)
# now add additional cache levels (if any) by scaling L1 params
for scale in treespec[:-2]:
# clone previous level and update params
prev = prototypes[0]
next = prev()
next.size = prev.size * scale
next.latency = prev.latency * 10
next.assoc = prev.assoc * scale
next.mshrs = prev.mshrs * scale
prototypes.insert(0, next)
# system simulated
system = System(funcmem = PhysicalMemory(),
physmem = PhysicalMemory(latency = "100ns"))
def make_level(spec, prototypes, attach_obj, attach_port):
fanout = spec[0]
parent = attach_obj # use attach obj as config parent too
if len(spec) > 1 and (fanout > 1 or options.force_bus):
new_bus = Bus(clock="500MHz", width=16)
new_bus.port = getattr(attach_obj, attach_port)
parent.cpu_side_bus = new_bus
attach_obj = new_bus
attach_port = "port"
objs = [prototypes[0]() for i in xrange(fanout)]
if len(spec) > 1:
# we just built caches, more levels to go
parent.cache = objs
for cache in objs:
cache.mem_side = getattr(attach_obj, attach_port)
make_level(spec[1:], prototypes[1:], cache, "cpu_side")
else:
# we just built the MemTest objects
parent.cpu = objs
for t in objs:
t.test = getattr(attach_obj, attach_port)
t.functional = system.funcmem.port
make_level(treespec, prototypes, system.physmem, "port")
# -----------------------
# run simulation
# -----------------------
root = Root( system = system )
if options.atomic:
root.system.mem_mode = 'atomic'
else:
root.system.mem_mode = 'timing'
# Not much point in this being higher than the L1 latency
m5.ticks.setGlobalFrequency('1ns')
# instantiate configuration
m5.instantiate()
# simulate until program terminates
exit_event = m5.simulate(options.maxtick)
print 'Exiting @ tick', m5.curTick(), 'because', exit_event.getCause()
| bsd-3-clause |
soothion/wxy | protected/controllers/LoginController.php | 2334 | <?php
class LoginController extends Controller{
public function actionIndex(){
$user = Yii::app()->user;
if(!$user->isGuest){
$domain = 'http://'.$_SERVER['SERVER_NAME'];
$redirect_uri = $domain.$this->createUrl('/login/wechat');
$appid = 'wxf7b2f9f903f9aa2b';
$scope = 'snsapi_userinfo';
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope={$scope}&state=123#wechat_redirect";
$this->redirect($url);
}
$this->renderPartial('index',array('note'=>'','user'=>$user));
}
public function actionWechat(){
$user = Yii::app()->user;
$user = Users::model()->findByAttributes(array('id'=>$user->id));
$code = $_REQUEST['code'];
$appid = 'wxf7b2f9f903f9aa2b';
$secret = 'd902190a34e3cf9ec84ed871146696c8';
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code";
$result = file_get_contents($url);
$result = json_decode($result);
$openid = $result->openid;
Yii::app()->session['openid'] = $openid;
if($user->openid==''){
$user->openid = $openid;
$user->save();
$this->redirect('/blog/index/1');
}
elseif($user->openid==$openid){
$this->redirect('/blog/index/1');
}
elseif($user->openid!=$openid){
header("Content-type: text/html; charset=utf-8");
echo '<h2>此帐号已绑定其他微信帐号</h2>';
$login = $this->createUrl('/login/logout');
echo "<a href='{$login}'>切换帐号</a>";
die;
}
}
public function actionLogin() {
$result = 0;
if (isset($_POST['LoginForm'])) {
$model = new LoginForm();
$model->attributes = $_POST['LoginForm'];
if ($model->validate() && $model->login()) {
$result = 1;
}
else $result = 0;
}
else
$result = 0;
echo $result;
}
public function actionLogout(){
Yii::app()->user->logout(true);
$this->redirect(array('/login/index'));
}
} | bsd-3-clause |
pmeisen/dis-timeintervaldataanalyzer | src/net/meisen/dissertation/exceptions/GroupEvaluatorException.java | 938 | package net.meisen.dissertation.exceptions;
/**
* Exception thrown whenever a problem with {@code GroupEvaluator} occurs.
*
* @author pmeisen
*
*/
public class GroupEvaluatorException extends RuntimeException {
private static final long serialVersionUID = -4516087108710395650L;
/**
* Creates an exception which should been thrown whenever there is no other
* reason for the exception, i.e. the exception is the root.
*
* @param message
* the message of the exception
*/
public GroupEvaluatorException(final String message) {
super(message);
}
/**
* Creates an exception which should been thrown whenever another
* <code>Throwable</code> is the reason for this.
*
* @param message
* the message of the exception
* @param t
* the reason for the exception
*/
public GroupEvaluatorException(final String message, final Throwable t) {
super(message, t);
}
}
| bsd-3-clause |
NUBIC/psc-mirror | domain/src/main/java/edu/northwestern/bioinformatics/studycalendar/domain/delta/PropertyChange.java | 5487 | package edu.northwestern.bioinformatics.studycalendar.domain.delta;
import edu.northwestern.bioinformatics.studycalendar.domain.NaturallyKeyed;
import edu.northwestern.bioinformatics.studycalendar.domain.UniquelyKeyed;
import edu.northwestern.bioinformatics.studycalendar.domain.tools.Differences;
import gov.nih.nci.cabig.ctms.lang.ComparisonTools;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Transient;
import java.util.Date;
/**
* @author Rhett Sutphin
*/
@Entity
@DiscriminatorValue("property")
public class PropertyChange extends Change {
private String oldValue;
private String newValue;
private String propertyName;
////// FACTORY
public static PropertyChange create(String prop, Object oldValue, Object newValue) {
PropertyChange change = new PropertyChange();
change.setPropertyName(prop);
change.setOldValue(serializeValue(oldValue));
change.setNewValue(serializeValue(newValue));
return change;
}
private static String serializeValue(Object value) {
if (value instanceof UniquelyKeyed) {
return ((UniquelyKeyed) value).getUniqueKey();
} else if (value instanceof NaturallyKeyed) {
return ((NaturallyKeyed) value).getNaturalKey();
} else {
return value == null ? null : value.toString();
}
}
////// LOGIC
@Override
@Transient
public boolean isNoop() {
return ComparisonTools.nullSafeEquals(getOldValue(), getNewValue());
}
@Override
@Transient
public ChangeAction getAction() {
return ChangeAction.CHANGE_PROPERTY;
}
@Override
protected MergeLogic createMergeLogic(Delta<?> delta, Date updateTime) {
return new PropertyMergeLogic(delta, updateTime);
}
@Transient
public String getNaturalKey() {
return String.format("property change for %s", getPropertyName());
}
////// BEAN PROPERTIES
@Column(name="old_value")
public String getOldValue() {
return oldValue;
}
public void setOldValue(String oldValue) {
this.oldValue = oldValue;
}
@Column(name="new_value")
public String getNewValue() {
return newValue;
}
public void setNewValue(String newValue) {
this.newValue = newValue;
}
@Column(name="attribute", nullable = false)
public String getPropertyName() {
return propertyName;
}
public void setPropertyName(String propertyName) {
this.propertyName = propertyName;
}
////// OBJECT METHODS
@Override
public String toString() {
return new StringBuilder(getClass().getSimpleName())
.append("[id=").append(getId()).append("; change property ").append(getPropertyName())
.append(" from ").append(getOldValue()).append(" to ").append(getNewValue())
.append(']')
.toString();
}
@Override
public Differences deepEquals(Change o) {
Differences differences = new Differences();
if (this == o) return differences;
if (o == null || getClass() != o.getClass()) {
differences.addMessage("Object is not instance of " +getClass());
return differences;
}
PropertyChange that = (PropertyChange) o;
return differences.
registerValueDifference("property", this.getPropertyName(), that.getPropertyName()).
registerValueDifference("new value", this.getNewValue(), that.getNewValue()).
registerValueDifference("old value", this.getOldValue(), that.getOldValue())
;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PropertyChange that = (PropertyChange) o;
if (newValue != null ? !newValue.equals(that.getNewValue()) : that.getNewValue() != null)
return false;
if (oldValue != null ? !oldValue.equals(that.getOldValue()) : that.getOldValue() != null)
return false;
if (propertyName != null ? !propertyName.equals(that.getPropertyName()) : that.getPropertyName() != null)
return false;
return true;
}
public int hashCode() {
int result;
result = (oldValue != null ? oldValue.hashCode() : 0);
result = 31 * result + (newValue != null ? newValue.hashCode() : 0);
result = 31 * result + (propertyName != null ? propertyName.hashCode() : 0);
return result;
}
private class PropertyMergeLogic extends MergeLogic {
private Delta<?> delta;
private Date updateTime;
public PropertyMergeLogic(Delta<?> delta, Date updateTime) {
this.delta = delta;
this.updateTime = updateTime;
}
@Override
public boolean encountered(PropertyChange change) {
if (change.getPropertyName().equals(getPropertyName())) {
change.setNewValue(getNewValue());
change.setUpdatedDate(updateTime);
return true;
}
return false;
}
@Override
public void postProcess(boolean merged) {
if (!merged) {
PropertyChange.this.setUpdatedDate(updateTime);
delta.addChange(PropertyChange.this);
}
}
}
}
| bsd-3-clause |
mrdon/SAL | sal-api/src/main/java/com/atlassian/sal/api/net/Request.java | 7662 | package com.atlassian.sal.api.net;
import com.atlassian.sal.api.net.auth.Authenticator;
import java.util.List;
import java.util.Map;
/**
* Interface Request represents a request to retrieve data. To execute a request call {@link Request#execute(ResponseHandler)}.
*
* @param <T> the type of request used for method chaining
* @since 2.0
*/
public interface Request<T extends Request<?, ?>, RESP extends Response>
{
/**
* Represents type of network request
*/
public static enum MethodType
{
GET, POST, PUT, DELETE, HEAD, TRACE, OPTIONS
}
/**
* Setting connection timeout in milliseconds.
*
* @param connectionTimeout The timeout in milliseconds
* @return a reference to this object.
*/
T setConnectionTimeout(int connectionTimeout);
/**
* Setting socket timeout in milliseconds.
*
* @param soTimeout the timeout in milliseconds
* @return a reference to this object.
*/
T setSoTimeout(int soTimeout);
/**
* @param url the url to request
* @return a reference to this object.
*/
T setUrl(String url);
/**
* Sets the body of the request. In default implementation only requests of type {@link MethodType#POST} and {@link MethodType#PUT} can have a request body.
*
* @param requestBody the body of the request
* @return a reference to this object.
*/
T setRequestBody(String requestBody);
/**
* Sets file parts of the request. File parts can only be added if the request body is empty.
* Only requests of type {@link MethodType#POST} and {@link MethodType#PUT} can have file parts.
*
* @param files the file parts, cannot be null.
* @return a reference to this object.
*
* @throws IllegalArgumentException if the method of this request is not a POST or PUT or files is NULL.
* @throws IllegalStateException if the request body for this request has already been set.
*
* @since 2.6
*/
T setFiles(List<RequestFilePart> files);
/**
* Set an entity as the request body
*
* @param entity the request entity to be marshalled, not null
* @return this Request object
*/
T setEntity(Object entity);
/**
* Sets Content-Type of the body of the request. In default implementation only requests of type {@link MethodType#POST} and {@link MethodType#PUT} can have a request body.
*
* @param contentType the contentType of the request
* @return a reference to this object.
*/
T setRequestContentType(String contentType);
/**
* Sets parameters of the request. In default implementation only requests of type {@link MethodType#POST} can have parameters.
* For other requests include parameters in url. This method accepts an even number of arguments, in form of name, value, name, value, name, value, etc
*
* @param params parameters of the request in as name, value pairs
* @return a reference to this object.
*/
T addRequestParameters(String... params);
/**
* Adds generic Authenticator to the request.
*
* @param authenticator the authenticator to use for authentication
* @return a reference to this object.
*/
T addAuthentication(Authenticator authenticator);
/**
* Adds TrustedTokenAuthentication to the request. Trusted token authenticator uses current user to make a trusted application call.
*
* @return a reference to this object.
*/
T addTrustedTokenAuthentication();
/**
* Adds TrustedTokenAuthentication to the request. Trusted token authenticator uses the passed user to make a trusted application call.
*
* @param username The user to make the request with
* @return this
*/
T addTrustedTokenAuthentication(String username);
/**
* Adds basic authentication to the request.
*
* @param username The user name
* @param password The password
* @return a reference to this object.
*/
T addBasicAuthentication(String username, String password);
/**
* Adds seraph authentication to the request.
*
* @param username The user name
* @param password The password
* @return a reference to this object.
*/
T addSeraphAuthentication(String username, String password);
/**
* Adds the specified header to the request, not overwriting any previous value.
* Support for this operation is optional.
*
* @param headerName the header's name
* @param headerValue the header's value
* @return a reference to this object
* @see RequestFactory#supportsHeader()
*/
T addHeader(String headerName, String headerValue);
/**
* Sets the specified header to the request, overwriting any previous value.
* Support for this operation is optional.
*
* @param headerName the header's name
* @param headerValue the header's value
* @return a reference to this object
* @see RequestFactory#supportsHeader()
*/
T setHeader(String headerName, String headerValue);
/**
* Sets whether the request should transparently follow a redirect from the server. The
* default behavior is that when a response is received with a status code in the 300s, a new request
* is made using the location header of the response without notifying the client. Set this to false to
* turn this behavior off.
*
* @param follow set this to false to have the request not transparently follow redirects.
* @return a reference to this object.
*/
T setFollowRedirects(boolean follow);
/**
* @return an immutable Map of headers added to the request so far
* @since 2.1
*/
Map<String, List<String>> getHeaders();
/**
* Executes the request.
*
* @param responseHandler Callback handler of the response.
* @throws ResponseProtocolException If the server returned a malformed response
* @throws ResponseTimeoutException If a connection timeout or read timeout occurred
* @throws ResponseTransportException If an I/O error occurred in request transport
* @throws ResponseException For all errors not otherwise specified
*/
void execute(ResponseHandler<RESP> responseHandler) throws ResponseException;
/**
* Executes a request and if response is successful, returns response as a string. @see {@link Response#getResponseBodyAsString()}
*
* @return response as String
* @throws ResponseStatusException If the server returned a response that contained an error code
* @throws ResponseProtocolException If the server returned a malformed response
* @throws ResponseTimeoutException If a connection timeout or read timeout occurred
* @throws ResponseTransportException If an I/O error occurred in request transport
* @throws ResponseException For all errors not otherwise specified
*/
String execute() throws ResponseException;
/**
* Executes the request and returns a result value.
*
* @param responseHandler Callback handler of the response.
* @throws ResponseProtocolException If the server returned a malformed response
* @throws ResponseTimeoutException If a connection timeout or read timeout occurred
* @throws ResponseTransportException If an I/O error occurred in request transport
* @throws ResponseException For all errors not otherwise specified
* @since v2.2.0
*/
<RET> RET executeAndReturn(ReturningResponseHandler<RESP, RET> responseHandler) throws ResponseException;
}
| bsd-3-clause |
eehlers/QuantLibAddin | qlo/enumerations/constructors/enumeratedclasses.cpp | 26144 | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2007, 2008 Ferdinando Ametrano
Copyright (C) 2006 Marco Bianchetti
Copyright (C) 2006, 2007 Eric Ehlers
Copyright (C) 2006 Giorgio Facchinetti
Copyright (C) 2006 Chiara Fornarola
Copyright (C) 2007 Katiuscia Manzoni
Copyright (C) 2005 Plamen Neykov
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
#include <qlo/enumerations/constructors/enumeratedclasses.hpp>
#include <qlo/conversions/conversions.hpp>
#include <ql/indexes/ibor/euribor.hpp>
#include <ql/indexes/ibor/eurlibor.hpp>
#include <ql/indexes/swap/euriborswap.hpp>
#include <ql/indexes/swap/eurliborswap.hpp>
#include <ql/math/interpolations/backwardflatinterpolation.hpp>
#include <ql/math/interpolations/forwardflatinterpolation.hpp>
#include <ql/math/interpolations/loginterpolation.hpp>
#include <ql/math/interpolations/abcdinterpolation.hpp>
#include <ql/math/interpolations/bilinearinterpolation.hpp>
#include <ql/math/interpolations/bicubicsplineinterpolation.hpp>
#include <ql/processes/blackscholesprocess.hpp>
#include <ql/instruments/vanillaoption.hpp>
namespace QuantLibAddin {
/* *** StrikedTypePayoff *** */
/* *** Option::Type + 1 parameter *** */
boost::shared_ptr<QuantLib::Payoff> VANILLA_Payoff(
const QuantLib::Option::Type& optionType,
const double strike) {
return boost::shared_ptr<QuantLib::Payoff> (
new QuantLib::PlainVanillaPayoff(optionType, strike));
}
boost::shared_ptr<QuantLib::Payoff> ASSETORNOTHING_Payoff(
const QuantLib::Option::Type& optionType,
const double strike) {
return boost::shared_ptr<QuantLib::Payoff> (
new QuantLib::AssetOrNothingPayoff(optionType, strike));
}
boost::shared_ptr<QuantLib::Payoff> PERCENTAGESTRIKE_Payoff(
const QuantLib::Option::Type& optionType,
const double moneyness) {
return boost::shared_ptr<QuantLib::Payoff> (
new QuantLib::PercentageStrikePayoff(optionType, moneyness));
}
/* *** Option::Type + 2 parameters *** */
boost::shared_ptr<QuantLib::Payoff> CASHORNOTHING_Payoff(
const QuantLib::Option::Type& optionType,
const double strike,
const double cashPayoff) {
return boost::shared_ptr<QuantLib::Payoff> (
new QuantLib::CashOrNothingPayoff(optionType, strike, cashPayoff));
}
boost::shared_ptr<QuantLib::Payoff> GAP_Payoff(
const QuantLib::Option::Type& optionType,
const double strike,
const double secondStrike) {
return boost::shared_ptr<QuantLib::Payoff> (
new QuantLib::GapPayoff(optionType, strike, secondStrike));
}
/* *** 2 parameters *** */
boost::shared_ptr<QuantLib::Payoff> SUPERFUND_Payoff(
const QuantLib::Option::Type&,
const double strike,
const double secondStrike) {
return boost::shared_ptr<QuantLib::Payoff> (
new QuantLib::SuperFundPayoff(strike, secondStrike));
}
/* *** 3 parameters *** */
boost::shared_ptr<QuantLib::Payoff> SUPERSHARE_Payoff(
const QuantLib::Option::Type&,
const double strike,
const double secondStrike,
const double cashPayoff) {
return boost::shared_ptr<QuantLib::Payoff> (
new QuantLib::SuperSharePayoff(strike, secondStrike, cashPayoff));
}
/* *** PricingEngines - without timesteps *** */
boost::shared_ptr<QuantLib::PricingEngine> AB_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process) {
return boost::shared_ptr<QuantLib::PricingEngine> (
new QuantLib::AnalyticBarrierEngine(process));
}
boost::shared_ptr<QuantLib::PricingEngine> AC_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process) {
return boost::shared_ptr<QuantLib::PricingEngine> (
new QuantLib::AnalyticCliquetEngine(process));
}
boost::shared_ptr<QuantLib::PricingEngine> ACGAPA_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process) {
return boost::shared_ptr<QuantLib::PricingEngine> (
new QuantLib::AnalyticContinuousGeometricAveragePriceAsianEngine(process));
}
boost::shared_ptr<QuantLib::PricingEngine> ADA_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process) {
return boost::shared_ptr<QuantLib::PricingEngine> (
new QuantLib::AnalyticDigitalAmericanEngine(process));
}
boost::shared_ptr<QuantLib::PricingEngine> ADE_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process) {
return boost::shared_ptr<QuantLib::PricingEngine> (
new QuantLib::AnalyticDividendEuropeanEngine(process));
}
boost::shared_ptr<QuantLib::PricingEngine> ADGAPA_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process) {
return boost::shared_ptr<QuantLib::PricingEngine> (
new QuantLib::AnalyticDiscreteGeometricAveragePriceAsianEngine(process));
}
boost::shared_ptr<QuantLib::PricingEngine> AE_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process) {
return boost::shared_ptr<QuantLib::PricingEngine> (
new QuantLib::AnalyticEuropeanEngine(process));
}
boost::shared_ptr<QuantLib::PricingEngine> AP_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process) {
return boost::shared_ptr<QuantLib::PricingEngine> (
new QuantLib::AnalyticPerformanceEngine(process));
}
boost::shared_ptr<QuantLib::PricingEngine> BAWA_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process) {
return boost::shared_ptr<QuantLib::PricingEngine> (
new QuantLib::BaroneAdesiWhaleyApproximationEngine(process));
}
boost::shared_ptr<QuantLib::PricingEngine> BSA_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process) {
return boost::shared_ptr<QuantLib::PricingEngine> (
new QuantLib::BjerksundStenslandApproximationEngine(process));
}
boost::shared_ptr<QuantLib::PricingEngine> I_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process) {
return boost::shared_ptr<QuantLib::PricingEngine> (
new QuantLib::IntegralEngine(process));
}
boost::shared_ptr<QuantLib::PricingEngine> PE_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process) {
return boost::shared_ptr<QuantLib::PricingEngine>();
}
boost::shared_ptr<QuantLib::PricingEngine> SE_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process) {
return boost::shared_ptr<QuantLib::PricingEngine> (
new QuantLib::StulzEngine(process, process, 0));//FIXME dummy inputs
}
// FIXME these seem not to work following pricing engines redesign?
//boost::shared_ptr<QuantLib::PricingEngine> FE_Engine(
// const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process) {
// boost::shared_ptr<QuantLib::VanillaOption::engine>
// underlyingEngine(new QuantLib::AnalyticEuropeanEngine(process));
// return boost::shared_ptr<QuantLib::PricingEngine> (
// new QuantLib::ForwardEngine<QuantLib::VanillaOption::arguments,
// QuantLib::VanillaOption::results>(underlyingEngine));
//}
//boost::shared_ptr<QuantLib::PricingEngine> FPE_Engine(
// const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process) {
// boost::shared_ptr<QuantLib::VanillaOption::engine>
// underlyingEngine(new QuantLib::AnalyticEuropeanEngine(process));
// return boost::shared_ptr<QuantLib::PricingEngine> (
// new QuantLib::ForwardPerformanceEngine
// <QuantLib::VanillaOption::arguments,
// QuantLib::VanillaOption::results>(underlyingEngine));
//}
//boost::shared_ptr<QuantLib::PricingEngine> QE_Engine(
// const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process) {
// boost::shared_ptr<QuantLib::VanillaOption::engine>
// underlyingEngine(new QuantLib::AnalyticEuropeanEngine(process));
// return boost::shared_ptr<QuantLib::PricingEngine> (
// new QuantLib::QuantoEngine<QuantLib::VanillaOption,
// QuantLib::PricingEngine>(underlyingEngine));
//}
//boost::shared_ptr<QuantLib::PricingEngine> QFE_Engine(
// const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process) {
// boost::shared_ptr<QuantLib::VanillaOption::engine>
// underlyingEngine(new QuantLib::AnalyticEuropeanEngine(process));
// boost::shared_ptr<QuantLib::ForwardVanillaOption::engine> forwardEngine(
// new QuantLib::ForwardEngine<QuantLib::VanillaOption::arguments,
// QuantLib::VanillaOption::results>(underlyingEngine));
// return boost::shared_ptr<QuantLib::PricingEngine> (
// new QuantLib::QuantoEngine<QuantLib::ForwardVanillaOption::arguments,
// QuantLib::ForwardVanillaOption::results>(forwardEngine));
//}
/* *** PricingEngines - with timesteps *** */
boost::shared_ptr<QuantLib::PricingEngine> AEQPB_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process, const long& timeSteps) {
return boost::shared_ptr<QuantLib::PricingEngine> (
new QuantLib::BinomialVanillaEngine<QuantLib::AdditiveEQPBinomialTree>(process, timeSteps));
}
boost::shared_ptr<QuantLib::PricingEngine> CRR_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process, const long& timeSteps) {
return boost::shared_ptr<QuantLib::PricingEngine> (
new QuantLib::BinomialVanillaEngine<QuantLib::CoxRossRubinstein>(process, timeSteps));
}
boost::shared_ptr<QuantLib::PricingEngine> FDA_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process, const long& timeSteps) {
return boost::shared_ptr<QuantLib::PricingEngine> (
new QuantLib::FDAmericanEngine<>(process, timeSteps, timeSteps-1));
}
boost::shared_ptr<QuantLib::PricingEngine> FDB_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process, const long& timeSteps) {
return boost::shared_ptr<QuantLib::PricingEngine> (
new QuantLib::FDBermudanEngine<>(process, timeSteps, timeSteps-1));
}
boost::shared_ptr<QuantLib::PricingEngine> FDE_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process, const long& timeSteps) {
return boost::shared_ptr<QuantLib::PricingEngine> (
new QuantLib::FDEuropeanEngine<>(process, timeSteps, timeSteps-1));
}
boost::shared_ptr<QuantLib::PricingEngine> JOSHI_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process, const long& timeSteps) {
return boost::shared_ptr<QuantLib::PricingEngine> (
new QuantLib::BinomialVanillaEngine<QuantLib::Joshi4>(process, timeSteps));
}
boost::shared_ptr<QuantLib::PricingEngine> JR_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process, const long& timeSteps) {
return boost::shared_ptr<QuantLib::PricingEngine> (
new QuantLib::BinomialVanillaEngine<QuantLib::JarrowRudd>(process, timeSteps));
}
boost::shared_ptr<QuantLib::PricingEngine> LR_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process, const long& timeSteps) {
return boost::shared_ptr<QuantLib::PricingEngine> (
new QuantLib::BinomialVanillaEngine<QuantLib::LeisenReimer>(process, timeSteps));
}
boost::shared_ptr<QuantLib::PricingEngine> TIAN_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process, const long& timeSteps) {
return boost::shared_ptr<QuantLib::PricingEngine> (
new QuantLib::BinomialVanillaEngine<QuantLib::Tian>(process, timeSteps));
}
boost::shared_ptr<QuantLib::PricingEngine> TRI_Engine(
const boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& process, const long& timeSteps) {
return boost::shared_ptr<QuantLib::PricingEngine> (
new QuantLib::BinomialVanillaEngine<QuantLib::Trigeorgis>(process, timeSteps));
}
/* *** 1D Interpolation *** */
boost::shared_ptr<QuantLib::Interpolation> BACKWARDFLAT_Interpolation(
reposit::dbl_itr& xBegin,
reposit::dbl_itr& xEnd,
reposit::dbl_itr& yBegin) {
return boost::shared_ptr<QuantLib::Interpolation>(new
QuantLib::BackwardFlatInterpolation(xBegin, xEnd, yBegin));
}
boost::shared_ptr<QuantLib::Interpolation> FORWARDFLAT_Interpolation(
reposit::dbl_itr& xBegin,
reposit::dbl_itr& xEnd,
reposit::dbl_itr& yBegin) {
return boost::shared_ptr<QuantLib::Interpolation>(new
QuantLib::ForwardFlatInterpolation(xBegin, xEnd, yBegin));
}
boost::shared_ptr<QuantLib::Interpolation> LINEAR_Interpolation(
reposit::dbl_itr& xBegin,
reposit::dbl_itr& xEnd,
reposit::dbl_itr& yBegin) {
return boost::shared_ptr<QuantLib::Interpolation>(new
QuantLib::LinearInterpolation(xBegin, xEnd, yBegin));
}
boost::shared_ptr<QuantLib::Interpolation> LOGLINEAR_Interpolation(
reposit::dbl_itr& xBegin,
reposit::dbl_itr& xEnd,
reposit::dbl_itr& yBegin) {
return boost::shared_ptr<QuantLib::Interpolation>(new
QuantLib::LogLinearInterpolation(xBegin, xEnd, yBegin));
}
boost::shared_ptr<QuantLib::Interpolation> CUBICNATURALSPLINE_Interpolation(
reposit::dbl_itr& xBegin,
reposit::dbl_itr& xEnd,
reposit::dbl_itr& yBegin) {
return boost::shared_ptr<QuantLib::Interpolation>(new
QuantLib::CubicInterpolation(xBegin, xEnd, yBegin,
QuantLib::CubicInterpolation::Spline, false,
QuantLib::CubicInterpolation::SecondDerivative, 0.0,
QuantLib::CubicInterpolation::SecondDerivative, 0.0));
}
boost::shared_ptr<QuantLib::Interpolation> MONOTONICCUBICNATURALSPLINE_Interpolation(
reposit::dbl_itr& xBegin,
reposit::dbl_itr& xEnd,
reposit::dbl_itr& yBegin) {
return boost::shared_ptr<QuantLib::Interpolation>(new
QuantLib::CubicInterpolation(xBegin, xEnd, yBegin,
QuantLib::CubicInterpolation::Spline, true,
QuantLib::CubicInterpolation::SecondDerivative, 0.0,
QuantLib::CubicInterpolation::SecondDerivative, 0.0));
}
boost::shared_ptr<QuantLib::Interpolation> LOGCUBICNATURALSPLINE_Interpolation(
reposit::dbl_itr& xBegin,
reposit::dbl_itr& xEnd,
reposit::dbl_itr& yBegin) {
return boost::shared_ptr<QuantLib::Interpolation>(new
QuantLib::LogCubicInterpolation(xBegin, xEnd, yBegin,
QuantLib::CubicInterpolation::Spline, false,
QuantLib::CubicInterpolation::SecondDerivative, 0.0,
QuantLib::CubicInterpolation::SecondDerivative, 0.0));
}
boost::shared_ptr<QuantLib::Interpolation> MONOTONICLOGCUBICNATURALSPLINE_Interpolation(
reposit::dbl_itr& xBegin,
reposit::dbl_itr& xEnd,
reposit::dbl_itr& yBegin) {
return boost::shared_ptr<QuantLib::Interpolation>(new
QuantLib::LogCubicInterpolation(xBegin, xEnd, yBegin,
QuantLib::CubicInterpolation::Spline, true,
QuantLib::CubicInterpolation::SecondDerivative, 0.0,
QuantLib::CubicInterpolation::SecondDerivative, 0.0));
}
boost::shared_ptr<QuantLib::Interpolation> KrugerCubic_Interpolation(
reposit::dbl_itr& xBegin,
reposit::dbl_itr& xEnd,
reposit::dbl_itr& yBegin) {
return boost::shared_ptr<QuantLib::Interpolation>(new
QuantLib::CubicInterpolation(xBegin, xEnd, yBegin,
QuantLib::CubicInterpolation::Kruger, false,
QuantLib::CubicInterpolation::SecondDerivative, 0.0,
QuantLib::CubicInterpolation::SecondDerivative, 0.0));
}
boost::shared_ptr<QuantLib::Interpolation> KrugerLogCubic_Interpolation(
reposit::dbl_itr& xBegin,
reposit::dbl_itr& xEnd,
reposit::dbl_itr& yBegin) {
return boost::shared_ptr<QuantLib::Interpolation>(new
QuantLib::LogCubicInterpolation(xBegin, xEnd, yBegin,
QuantLib::CubicInterpolation::Kruger, false,
QuantLib::CubicInterpolation::SecondDerivative, 0.0,
QuantLib::CubicInterpolation::SecondDerivative, 0.0));
}
boost::shared_ptr<QuantLib::Interpolation> FritschButlandCubic_Interpolation(
reposit::dbl_itr& xBegin,
reposit::dbl_itr& xEnd,
reposit::dbl_itr& yBegin) {
return boost::shared_ptr<QuantLib::Interpolation>(new
QuantLib::CubicInterpolation(xBegin, xEnd, yBegin,
QuantLib::CubicInterpolation::FritschButland, false,
QuantLib::CubicInterpolation::SecondDerivative, 0.0,
QuantLib::CubicInterpolation::SecondDerivative, 0.0));
}
boost::shared_ptr<QuantLib::Interpolation> FritschButlandLogCubic_Interpolation(
reposit::dbl_itr& xBegin,
reposit::dbl_itr& xEnd,
reposit::dbl_itr& yBegin) {
return boost::shared_ptr<QuantLib::Interpolation>(new
QuantLib::LogCubicInterpolation(xBegin, xEnd, yBegin,
QuantLib::CubicInterpolation::FritschButland, false,
QuantLib::CubicInterpolation::SecondDerivative, 0.0,
QuantLib::CubicInterpolation::SecondDerivative, 0.0));
}
boost::shared_ptr<QuantLib::Interpolation> Parabolic_Interpolation(
reposit::dbl_itr& xBegin,
reposit::dbl_itr& xEnd,
reposit::dbl_itr& yBegin) {
return boost::shared_ptr<QuantLib::Interpolation>(new
QuantLib::CubicInterpolation(xBegin, xEnd, yBegin,
QuantLib::CubicInterpolation::Parabolic, false,
QuantLib::CubicInterpolation::SecondDerivative, 0.0,
QuantLib::CubicInterpolation::SecondDerivative, 0.0));
}
boost::shared_ptr<QuantLib::Interpolation> MonotonicParabolic_Interpolation(
reposit::dbl_itr& xBegin,
reposit::dbl_itr& xEnd,
reposit::dbl_itr& yBegin) {
return boost::shared_ptr<QuantLib::Interpolation>(new
QuantLib::CubicInterpolation(xBegin, xEnd, yBegin,
QuantLib::CubicInterpolation::Parabolic, true,
QuantLib::CubicInterpolation::SecondDerivative, 0.0,
QuantLib::CubicInterpolation::SecondDerivative, 0.0));
}
boost::shared_ptr<QuantLib::Interpolation> LogParabolic_Interpolation(
reposit::dbl_itr& xBegin,
reposit::dbl_itr& xEnd,
reposit::dbl_itr& yBegin) {
return boost::shared_ptr<QuantLib::Interpolation>(new
QuantLib::LogCubicInterpolation(xBegin, xEnd, yBegin,
QuantLib::CubicInterpolation::Parabolic, false,
QuantLib::CubicInterpolation::SecondDerivative, 0.0,
QuantLib::CubicInterpolation::SecondDerivative, 0.0));
}
boost::shared_ptr<QuantLib::Interpolation> MonotonicLogParabolic_Interpolation(
reposit::dbl_itr& xBegin,
reposit::dbl_itr& xEnd,
reposit::dbl_itr& yBegin) {
return boost::shared_ptr<QuantLib::Interpolation>(new
QuantLib::LogCubicInterpolation(xBegin, xEnd, yBegin,
QuantLib::CubicInterpolation::Parabolic, true,
QuantLib::CubicInterpolation::SecondDerivative, 0.0,
QuantLib::CubicInterpolation::SecondDerivative, 0.0));
}
boost::shared_ptr<QuantLib::Interpolation> ABCD_Interpolation(
reposit::dbl_itr& xBegin,
reposit::dbl_itr& xEnd,
reposit::dbl_itr& yBegin) {
return boost::shared_ptr<QuantLib::Interpolation>(new
QuantLib::AbcdInterpolation(xBegin, xEnd, yBegin));
}
/* *** Interpolation2D *** */
boost::shared_ptr<QuantLib::Interpolation2D> BILINEAR_Interpolation(
reposit::dbl_itr& xBegin, reposit::dbl_itr& xEnd, reposit::dbl_itr& yBegin, reposit::dbl_itr& yEnd,
const QuantLib::Matrix& zData) {
return boost::shared_ptr<QuantLib::Interpolation2D>(
new QuantLib::BilinearInterpolation(
xBegin, xEnd, yBegin, yEnd, zData));
}
boost::shared_ptr<QuantLib::Interpolation2D> BICUBICSPLINE(
reposit::dbl_itr& xBegin, reposit::dbl_itr& xEnd, reposit::dbl_itr& yBegin, reposit::dbl_itr& yEnd,
const QuantLib::Matrix& zData) {
return boost::shared_ptr<QuantLib::Interpolation2D>(
new QuantLib::BicubicSpline(
xBegin, xEnd, yBegin, yEnd, zData));
}
/* *** Pricers *** */
/* *** IborCouponPricer *** */
boost::shared_ptr<QuantLib::IborCouponPricer> IBOR_BY_BLACK_Pricer(
const QuantLib::Handle<QuantLib::OptionletVolatilityStructure>& capletVol){
return boost::shared_ptr<QuantLib::IborCouponPricer>(
new QuantLib::BlackIborCouponPricer(capletVol));
};
/* *** CmsCouponPricer **** */
boost::shared_ptr<QuantLib::CmsCouponPricer> CONUNDRUM_BY_BLACK_Pricer(
const QuantLib::Handle<QuantLib::SwaptionVolatilityStructure>& swaptionVol,
const QuantLib::GFunctionFactory::YieldCurveModel modelOfYieldCurve,
const QuantLib::Handle<QuantLib::Quote>& meanReversion){
return boost::shared_ptr<QuantLib::CmsCouponPricer>(
new QuantLib::AnalyticHaganPricer(swaptionVol, modelOfYieldCurve, meanReversion));
};
boost::shared_ptr<QuantLib::CmsCouponPricer> CONUNDRUM_BY_NUMERICAL_INTEGRATION_Pricer(
const QuantLib::Handle<QuantLib::SwaptionVolatilityStructure>& swaptionVol,
const QuantLib::GFunctionFactory::YieldCurveModel modelOfYieldCurve,
const QuantLib::Handle<QuantLib::Quote>& meanReversion){
return boost::shared_ptr<QuantLib::CmsCouponPricer>(
new QuantLib::NumericHaganPricer(swaptionVol, modelOfYieldCurve, meanReversion));
};
}
| bsd-3-clause |
datagr4m/org.datagr4m | datagr4m-drawing/src/main/java/org/datagr4m/drawing/model/items/hierarchical/pair/HierarchicalPairModel.java | 3662 | package org.datagr4m.drawing.model.items.hierarchical.pair;
import java.awt.geom.CubicCurve2D;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.datagr4m.drawing.model.items.IBoundedItem;
import org.datagr4m.drawing.model.items.hierarchical.AbstractHierarchicalModel;
import org.datagr4m.drawing.model.items.hierarchical.IHierarchicalNodeModel;
import org.jzy3d.maths.Coord2d;
public class HierarchicalPairModel extends AbstractHierarchicalModel implements IHierarchicalPairModel{
public HierarchicalPairModel(IHierarchicalNodeModel parent, IBoundedItem first, IBoundedItem second) {
super(parent);
// register first and second as children
this.first = first;
this.second = second;
if(first!=null)
addChild(first, false);
if(second!=null)
addChild(second, false);
refreshBounds(true);
}
public HierarchicalPairModel(IBoundedItem first, IBoundedItem second) {
this(null, first, second);
}
public HierarchicalPairModel(IHierarchicalNodeModel parent) {
this(parent, null, null);
}
public HierarchicalPairModel() {
this(null, null, null);
}
/***************/
@Override
public IBoundedItem getFirst() {
return first;
}
@Override
public IBoundedItem getSecond() {
return second;
}
@Override
public CubicCurve2D getCurve() {
return curve;
}
/** Set a curve for this pair model, assuming it is computed by the layout
*/
@Override
public void setCurve(CubicCurve2D curve) {
this.curve = curve;
}
@Override
public boolean addChild(IBoundedItem item, boolean refreshBounds){
boolean s = super.addChild(item, refreshBounds);
List<IBoundedItem> list = new ArrayList<IBoundedItem>(children);
if(list.size()==1)
first = list.get(0);
else if(list.size()==2){
second = list.get(1);
}
else{
throw new RuntimeException("no children was added!");
}
return s;
}
@Override
public boolean addChildren(Collection<IBoundedItem> items){
throw new RuntimeException("should call setFirst/setSecond to setup children of this model.");
}
/**
* Spacing is not cached and simply computes the distance between first and second item.
*/
@Override
public float getSpacing(){
if(first==null || second==null)
return -1;
else
return (float)first.getPosition().distance(second.getPosition());
}
public void setFirst(IBoundedItem item) {
this.first = item;
refreshChildren();
}
public void setSecond(IBoundedItem item) {
this.second = item;
refreshChildren();
}
protected void refreshChildren(){
clearChildren(false);
addChild(first, false);
addChild(second, false);
refreshBounds(true);
}
/*******************/
protected void computeRadialBounds(){
double x1 = first.getPosition().distance(Coord2d.ORIGIN)+first.getRadialBounds();
double x2 = second.getPosition().distance(Coord2d.ORIGIN)+second.getRadialBounds();
cachedRadialBounds = (float)Math.max(x1,x2);
}
protected IBoundedItem first;
protected IBoundedItem second;
protected float spacing;
protected CubicCurve2D curve;
private static final long serialVersionUID = -2084464710276992579L;
}
| bsd-3-clause |
bg0jr/Maui | src/Dynamics/Maui.Dynamics/Data/ServiceProviderExtensions.cs | 681 | using System.Linq;
using Maui;
namespace Maui.Dynamics.Data
{
public static class ServiceProviderExtensions
{
public static ScriptingInterface TomScripting( this ServiceProvider serviceProvider )
{
if ( !serviceProvider.RegisteredServices.Contains( typeof( ScriptingInterface ).ToString() ) )
{
ScriptingInterface service = new ScriptingInterface();
service.Init( serviceProvider );
serviceProvider.RegisterService( typeof( ScriptingInterface ), service );
}
return serviceProvider.GetService<ScriptingInterface>();
}
}
}
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE762_Mismatched_Memory_Management_Routines/s06/CWE762_Mismatched_Memory_Management_Routines__new_array_free_wchar_t_04.cpp | 5097 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__new_array_free_wchar_t_04.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__new_array_free.label.xml
Template File: sources-sinks-04.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: Allocate data using new []
* GoodSource: Allocate data using malloc()
* Sinks:
* GoodSink: Deallocate data using delete []
* BadSink : Deallocate data using free()
* Flow Variant: 04 Control flow: if(STATIC_CONST_TRUE) and if(STATIC_CONST_FALSE)
*
* */
#include "std_testcase.h"
/* The two variables below are declared "const", so a tool should
be able to identify that reads of these will always return their
initialized values. */
static const int STATIC_CONST_TRUE = 1; /* true */
static const int STATIC_CONST_FALSE = 0; /* false */
namespace CWE762_Mismatched_Memory_Management_Routines__new_array_free_wchar_t_04
{
#ifndef OMITBAD
void bad()
{
wchar_t * data;
/* Initialize data*/
data = NULL;
if(STATIC_CONST_TRUE)
{
/* POTENTIAL FLAW: Allocate memory with a function that requires delete [] to free the memory */
data = new wchar_t[100];
}
if(STATIC_CONST_TRUE)
{
/* POTENTIAL FLAW: Deallocate memory using free() - the source memory allocation function may
* require a call to delete [] to deallocate the memory */
free(data);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G1() - use badsource and goodsink by changing the second STATIC_CONST_TRUE to STATIC_CONST_FALSE */
static void goodB2G1()
{
wchar_t * data;
/* Initialize data*/
data = NULL;
if(STATIC_CONST_TRUE)
{
/* POTENTIAL FLAW: Allocate memory with a function that requires delete [] to free the memory */
data = new wchar_t[100];
}
if(STATIC_CONST_FALSE)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Deallocate the memory using delete [] */
delete [] data;
}
}
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */
static void goodB2G2()
{
wchar_t * data;
/* Initialize data*/
data = NULL;
if(STATIC_CONST_TRUE)
{
/* POTENTIAL FLAW: Allocate memory with a function that requires delete [] to free the memory */
data = new wchar_t[100];
}
if(STATIC_CONST_TRUE)
{
/* FIX: Deallocate the memory using delete [] */
delete [] data;
}
}
/* goodG2B1() - use goodsource and badsink by changing the first STATIC_CONST_TRUE to STATIC_CONST_FALSE */
static void goodG2B1()
{
wchar_t * data;
/* Initialize data*/
data = NULL;
if(STATIC_CONST_FALSE)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Allocate memory from the heap using malloc() */
data = (wchar_t *)malloc(100*sizeof(wchar_t));
if (data == NULL) {exit(-1);}
}
if(STATIC_CONST_TRUE)
{
/* POTENTIAL FLAW: Deallocate memory using free() - the source memory allocation function may
* require a call to delete [] to deallocate the memory */
free(data);
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */
static void goodG2B2()
{
wchar_t * data;
/* Initialize data*/
data = NULL;
if(STATIC_CONST_TRUE)
{
/* FIX: Allocate memory from the heap using malloc() */
data = (wchar_t *)malloc(100*sizeof(wchar_t));
if (data == NULL) {exit(-1);}
}
if(STATIC_CONST_TRUE)
{
/* POTENTIAL FLAW: Deallocate memory using free() - the source memory allocation function may
* require a call to delete [] to deallocate the memory */
free(data);
}
}
void good()
{
goodB2G1();
goodB2G2();
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE762_Mismatched_Memory_Management_Routines__new_array_free_wchar_t_04; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| bsd-3-clause |
yuttapong/webapp | backend/modules/qtn/views/questionnaire/view.php | 1051 | <?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $model backend\modules\qtn\models\Questionnaire */
$this->title = $model->name;
$this->params['breadcrumbs'][] = ['label' => 'Questionnaires', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="questionnaire-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'survey_id',
'table_name',
'name',
'status',
'created_at',
'created_by',
],
]) ?>
</div>
| bsd-3-clause |
petablox-project/petablox | src/petablox/analyses/point/RelPM.java | 1303 | package petablox.analyses.point;
import soot.SootMethod;
import soot.Unit;
import soot.toolkits.graph.Block;
import java.util.Iterator;
import petablox.analyses.method.DomM;
import petablox.analyses.point.DomP;
import petablox.program.Program;
import petablox.project.Petablox;
import petablox.project.analyses.ProgramRel;
import petablox.util.soot.ICFG;
import petablox.util.soot.SootUtilities;
/**
* Relation containing each tuple (p,m) such that the statement
* at program point p is contained in method m
*/
@Petablox(
name = "PM",
sign = "P0,M0:P0_M0"
)
public class RelPM extends ProgramRel {
private DomP domP;
private DomM domM;
public void fill() {
domP = (DomP) doms[0];
domM = (DomM) doms[1];
for (SootMethod m : Program.g().getMethods()) {
if(!m.isConcrete())
continue;
ICFG cfg = SootUtilities.getCFG(m);
for(Block bb : cfg.getBlocks()){
Iterator<Unit> itr = bb.iterator();
while(itr.hasNext()){
Unit u = itr.next();
int mIdx = domM.indexOf(m);
int pIdx = domP.indexOf(u);
if(mIdx == -1 || pIdx == -1){
System.out.println("WARN: Index not found! Unit: "+u+" Method:"+m+" Class:"+m.getDeclaringClass().getName());
}else{
add (pIdx, mIdx);
}
}
}
}
}
}
| bsd-3-clause |
pg-irc/pathways-frontend | src/stores/topics/index.ts | 1224 | import { TopicStore, LoadingTopicStore, InValidTopicStore } from './stores';
import { buildTasksFixture } from '../../fixtures/buildFixtures';
import { TopicAction } from './actions';
import { reduceLoadingStore } from './reduce_loading_store';
import { reduceInvalidStore } from './reduce_invalid_store';
import { reduceValidStore } from './reduce_valid_store';
export { TopicStore, ValidTopicStore, LoadingTopicStore, InValidTopicStore, toValidOrThrow } from './stores';
export { Id, TopicList, TopicMap, Topic } from '../../fixtures/types/topics';
export {
bookmarkTopic, BookmarkTopicAction, unbookmarkTopic, UnbookmarkTopicAction,
expandDetail, ExpandDetailAction,
collapseDeail, CollapseDetailAction,
} from './actions';
export const buildDefaultStore = (): TopicStore => (
buildTasksFixture()
);
export const reducer = (store: TopicStore = buildDefaultStore(), action?: TopicAction): TopicStore => {
if (!action) {
return store;
}
if (store instanceof LoadingTopicStore) {
return reduceLoadingStore(store, action);
}
if (store instanceof InValidTopicStore) {
return reduceInvalidStore(store, action);
}
return reduceValidStore(store, action);
};
| bsd-3-clause |
aino/aino-convert | convert/fields.py | 1553 | from django.core.exceptions import ValidationError
from django.db import models
from django.utils.encoding import force_unicode
from base import MediaFile
class South(object):
"""
Just a south introspection Mixin
"""
def south_field_triple(self):
from south.modelsinspector import introspector
cls_name = '%s.%s' % (self.__class__.__module__ , self.__class__.__name__)
args, kwargs = introspector(self)
return (cls_name, args, kwargs)
class MediaFileField(South, models.CharField):
"""
The main idea is to have a filepath relative MEDIA_ROOT in this field. It
is up to the user to implement how this is acheived. It does by design not
delete or handle files in any other way than to instantiate a MediaFile
class with the db value.
"""
__metaclass__ = models.SubfieldBase
def __init__(self, *args, **kwargs):
kwargs['max_length'] = kwargs.get('max_length', 200)
super(MediaFileField, self).__init__(*args, **kwargs)
def get_internal_type(self):
return 'CharField'
def get_prep_value(self, value):
"""
MediaFile instance returns MEDIA_ROOT relative path in __unicode__
"""
if not value:
return value
return force_unicode(value)
def to_python(self, value):
if not value:
return value
try:
return MediaFile(value)
except Exception, e:
raise ValidationError(e.message)
| bsd-3-clause |
endlessm/chromium-browser | chrome/browser/ssl/connection_help_tab_helper_browsertest.cc | 6556 | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "chrome/browser/ssl/connection_help_tab_helper.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/common/chrome_features.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_navigation_observer.h"
#include "net/base/net_errors.h"
#include "net/cert/cert_status_flags.h"
#include "net/cert/cert_verify_result.h"
#include "net/dns/mock_host_resolver.h"
#include "ui/base/l10n/l10n_util.h"
#include "url/gurl.h"
class ConnectionHelpTabHelperTest : public InProcessBrowserTest {
public:
ConnectionHelpTabHelperTest()
: https_server_(net::EmbeddedTestServer::TYPE_HTTPS),
https_expired_server_(net::EmbeddedTestServer::TYPE_HTTPS) {}
void SetUpOnMainThread() override {
https_server_.SetSSLConfig(net::EmbeddedTestServer::CERT_OK);
https_expired_server_.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
https_server_.ServeFilesFromSourceDirectory(GetChromeTestDataDir());
https_expired_server_.ServeFilesFromSourceDirectory(GetChromeTestDataDir());
ASSERT_TRUE(https_server_.Start());
ASSERT_TRUE(https_expired_server_.Start());
}
protected:
void SetHelpCenterUrl(Browser* browser, const GURL& url) {
ConnectionHelpTabHelper::FromWebContents(
browser->tab_strip_model()->GetActiveWebContents())
->SetHelpCenterUrlForTesting(url);
}
net::EmbeddedTestServer* https_server() { return &https_server_; }
net::EmbeddedTestServer* https_expired_server() {
return &https_expired_server_;
}
private:
net::EmbeddedTestServer https_server_;
net::EmbeddedTestServer https_expired_server_;
DISALLOW_COPY_AND_ASSIGN(ConnectionHelpTabHelperTest);
};
// Tests that the chrome://connection-help redirect is not triggered for an
// interstitial on a site that is not the help center.
IN_PROC_BROWSER_TEST_F(ConnectionHelpTabHelperTest,
InterstitialOnNonSupportURL) {
GURL expired_non_support_url = https_expired_server()->GetURL("/title2.html");
GURL good_support_url = https_server()->GetURL("/title2.html");
SetHelpCenterUrl(browser(), good_support_url);
ui_test_utils::NavigateToURL(browser(), expired_non_support_url);
base::string16 tab_title;
ui_test_utils::GetCurrentTabTitle(browser(), &tab_title);
EXPECT_EQ(base::UTF16ToUTF8(tab_title), "Privacy error");
}
// Tests that the chrome://connection-help redirect is not triggered for the
// help center URL if there was no interstitial.
IN_PROC_BROWSER_TEST_F(ConnectionHelpTabHelperTest,
SupportURLWithNoInterstitial) {
GURL good_support_url = https_server()->GetURL("/title2.html");
SetHelpCenterUrl(browser(), good_support_url);
ui_test_utils::NavigateToURL(browser(), good_support_url);
base::string16 tab_title;
ui_test_utils::GetCurrentTabTitle(browser(), &tab_title);
EXPECT_EQ(base::UTF16ToUTF8(tab_title), "Title Of Awesomeness");
}
// Tests that the chrome://connection-help redirect is triggered for the help
// center URL if there was an interstitial.
IN_PROC_BROWSER_TEST_F(ConnectionHelpTabHelperTest, InterstitialOnSupportURL) {
GURL expired_url = https_expired_server()->GetURL("/title2.html");
SetHelpCenterUrl(browser(), expired_url);
ui_test_utils::NavigateToURL(browser(), expired_url);
base::string16 tab_title;
ui_test_utils::GetCurrentTabTitle(browser(), &tab_title);
EXPECT_EQ(base::UTF16ToUTF8(tab_title),
l10n_util::GetStringUTF8(IDS_CONNECTION_HELP_TITLE));
}
// Tests that if the help content site is opened with an error code that refers
// to a certificate error, the certificate error section is automatically
// expanded.
IN_PROC_BROWSER_TEST_F(ConnectionHelpTabHelperTest,
CorrectlyExpandsCertErrorSection) {
GURL expired_url = https_expired_server()->GetURL("/title2.html#-200");
GURL::Replacements replacements;
replacements.ClearRef();
SetHelpCenterUrl(browser(), expired_url.ReplaceComponents(replacements));
ui_test_utils::NavigateToURL(browser(), expired_url);
// Check that we got redirected to the offline help content.
base::string16 tab_title;
ui_test_utils::GetCurrentTabTitle(browser(), &tab_title);
EXPECT_EQ(base::UTF16ToUTF8(tab_title),
l10n_util::GetStringUTF8(IDS_CONNECTION_HELP_TITLE));
// Check that the cert error details section is not hidden.
std::string cert_error_is_hidden_js =
"var certSection = document.getElementById('details-certerror'); "
"window.domAutomationController.send(certSection.className == "
"'hidden');";
bool cert_error_is_hidden;
ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
browser()->tab_strip_model()->GetActiveWebContents(),
cert_error_is_hidden_js, &cert_error_is_hidden));
EXPECT_FALSE(cert_error_is_hidden);
}
// Tests that if the help content site is opened with an error code that refers
// to an expired certificate, the clock section is automatically expanded.
IN_PROC_BROWSER_TEST_F(ConnectionHelpTabHelperTest,
CorrectlyExpandsClockSection) {
GURL expired_url = https_expired_server()->GetURL("/title2.html#-201");
GURL::Replacements replacements;
replacements.ClearRef();
SetHelpCenterUrl(browser(), expired_url.ReplaceComponents(replacements));
ui_test_utils::NavigateToURL(browser(), expired_url);
// Check that we got redirected to the offline help content.
base::string16 tab_title;
ui_test_utils::GetCurrentTabTitle(browser(), &tab_title);
EXPECT_EQ(base::UTF16ToUTF8(tab_title),
l10n_util::GetStringUTF8(IDS_CONNECTION_HELP_TITLE));
// Check that the clock details section is not hidden.
std::string clock_is_hidden_js =
"var clockSection = document.getElementById('details-clock'); "
"window.domAutomationController.send(clockSection.className == "
"'hidden');";
bool clock_is_hidden;
ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
browser()->tab_strip_model()->GetActiveWebContents(), clock_is_hidden_js,
&clock_is_hidden));
EXPECT_FALSE(clock_is_hidden);
}
| bsd-3-clause |
toggl/bugsnag-xamarin | Bugsnag.iOS/Json/OrientationConverter.cs | 2162 | using System;
using UIKit;
using Newtonsoft.Json;
namespace Bugsnag.Json
{
internal class OrientationConverter : JsonConverter
{
public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer)
{
switch ((UIDeviceOrientation)value) {
case UIDeviceOrientation.PortraitUpsideDown:
writer.WriteValue ("portraitupsidedown");
break;
case UIDeviceOrientation.Portrait:
writer.WriteValue ("portrait");
break;
case UIDeviceOrientation.LandscapeRight:
writer.WriteValue ("landscaperight");
break;
case UIDeviceOrientation.LandscapeLeft:
writer.WriteValue ("landscapeleft");
break;
case UIDeviceOrientation.FaceUp:
writer.WriteValue ("faceup");
break;
case UIDeviceOrientation.FaceDown:
writer.WriteValue ("facedown");
break;
case UIDeviceOrientation.Unknown:
default:
writer.WriteValue ("unknown");
break;
}
}
public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
switch ((string)reader.Value) {
case "portraitupsidedown":
return UIDeviceOrientation.PortraitUpsideDown;
case "portrait":
return UIDeviceOrientation.Portrait;
case "landscaperight":
return UIDeviceOrientation.LandscapeRight;
case "landscapeleft":
return UIDeviceOrientation.LandscapeLeft;
case "faceup":
return UIDeviceOrientation.FaceUp;
case "facedown":
return UIDeviceOrientation.FaceDown;
default:
return UIDeviceOrientation.Unknown;
}
}
public override bool CanConvert (Type objectType)
{
return objectType == typeof(UIDeviceOrientation);
}
}
}
| bsd-3-clause |
jlazio/rtpipe | rtlib/setup.py | 340 | from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
ext_modules = [Extension("rtlib_cython", ["rtlib_cython.pyx"], include_dirs=[numpy.get_include()])]
setup(
name = 'rtlib_cython app',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)
| bsd-3-clause |
vanadium/intellij-vdl-plugin | src/io/v/vdl/psi/VdlTypeStub.java | 674 | // Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package io.v.vdl.psi;
import com.intellij.psi.stubs.IStubElementType;
import com.intellij.psi.stubs.StubElement;
import com.intellij.util.io.StringRef;
public class VdlTypeStub extends StubWithText<VdlType> {
public VdlTypeStub(StubElement parent, IStubElementType elementType, StringRef ref) {
super(parent, elementType, ref);
}
public VdlTypeStub(StubElement parent, IStubElementType elementType, String text) {
this(parent, elementType, StringRef.fromString(text));
}
}
| bsd-3-clause |
meghana0507/grpc-java-poll | netty/src/main/java/io/grpc/transport/netty/NettyClientTransportFactory.java | 2961 | /*
* Copyright 2014, Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.grpc.transport.netty;
import com.google.common.base.Preconditions;
import io.grpc.transport.ClientTransportFactory;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.handler.ssl.SslContext;
import java.net.SocketAddress;
/**
* Factory that manufactures instances of {@link NettyClientTransport}.
*/
class NettyClientTransportFactory implements ClientTransportFactory {
private final SocketAddress address;
private final NegotiationType negotiationType;
private final Class<? extends Channel> channelType;
private final EventLoopGroup group;
private final SslContext sslContext;
public NettyClientTransportFactory(SocketAddress address, Class<? extends Channel> channelType,
NegotiationType negotiationType, EventLoopGroup group, SslContext sslContext) {
this.address = Preconditions.checkNotNull(address, "address");
this.group = Preconditions.checkNotNull(group, "group");
this.negotiationType = Preconditions.checkNotNull(negotiationType, "negotiationType");
this.channelType = Preconditions.checkNotNull(channelType, "channelType");
this.sslContext = sslContext;
}
@Override
public NettyClientTransport newClientTransport() {
return new NettyClientTransport(address, channelType, negotiationType, group, sslContext);
}
}
| bsd-3-clause |
lpsinger/flask-twilio | example.py | 4894 | #!/usr/bin/env python
"""
Demo Flask-Twilio application
"""
import os
import socket
from flask import flash, Flask, render_template, request
from flask_twilio import Twilio, Response
from twilio.base.exceptions import TwilioRestException
from twilio.twiml.messaging_response import Message
from twilio.twiml.voice_response import Say
from jinja2 import DictLoader
# A standard test number.
# See https://www.twilio.com/docs/api/rest/test-credentials.
DEFAULT_NUMBER = '+15005550006'
# Application configuration.
app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)
app.config['SERVER_NAME'] = socket.getfqdn() + ':5000'
app.config['TWILIO_ACCOUNT_SID'] = os.environ.get('TWILIO_ACCOUNT_SID')
app.config['TWILIO_AUTH_SID'] = os.environ.get('TWILIO_AUTH_SID')
app.config['TWILIO_AUTH_TOKEN'] = os.environ.get('TWILIO_AUTH_TOKEN')
app.config['TWILIO_FROM'] = os.environ.get('TWILIO_FROM', DEFAULT_NUMBER)
twilio = Twilio(app)
# Main form template.
app.jinja_loader = DictLoader({'example.html': '''\
<!doctype html>
<title>Flask-Twilio Test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<style>
.vertical-container {
min-height: 100%;
min-height: 100vh;
display: flex;
align-items: center;
}
</style>
<div class=vertical-container>
<div class=container>
<div class=jumbotron>
<h2>Flask-Twilio Test</h2>
</div>
{% with messages = get_flashed_messages(with_categories=true) %}
{% for category, message in messages %}
<div class="alert alert-{{ category }}">{{ message }}</div>
{% endfor %}
{% endwith %}
<form method=post>
<input type=hidden id=say name=say value=1>
<input type=hidden id=sms name=sms value=1>
<div class=input-group>
<input autofocus class=form-control type=tel name=to value="{{ to }}">
<div class=input-group-append>
<button class="btn btn-outline-primary" type=submit>
Say + SMS
</button>
<button type=button class="btn btn-outline-primary dropdown-toggle" data-toggle=dropdown aria-haspopup=true aria-expanded=false>
</button>
<div class="dropdown-menu dropdown-menu-right">
<a class=dropdown-item href="#" onclick="$('form').submit();">Say + SMS</a></li>
<a class=dropdown-item href="#" onclick="$('#sms').val(0); $('form').submit();">Say only</a></li>
<a class=dropdown-item href="#" onclick="$('#say').val(0); $('form').submit();">SMS only</a></li>
</div>
</div>
</div>
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
'''})
@app.route('/twiml')
@twilio.twiml
def test_call():
"""View for producing the TwiML document."""
say = int(request.values.get('say', 1))
sms = int(request.values.get('sms', 1))
resp = Response()
if say:
resp.append(Say('This is a voice call from Twilio!', voice='female'))
if sms:
resp.append(Message('This is an SMS message from Twilio!'))
return resp
@app.route('/', methods=['GET'])
def index_get():
"""Main form view."""
return render_template(
'example.html',
to=request.values.get('to', DEFAULT_NUMBER))
@app.route('/', methods=['POST'])
def index_post():
"""Main form action."""
try:
say = int(request.values.get('say', 1))
sms = int(request.values.get('sms', 1))
to = request.values.get('to', None)
if say:
twilio.call_for('test_call', to, say=say, sms=sms)
else:
twilio.message('This is an SMS message from Twilio!', to)
flash('Request was successfully sent to Twilio.', 'success')
except TwilioRestException as e:
flash('Failed to make call: ' + e.msg, 'danger')
app.logger.exception('Failed to make call')
return index_get()
# Start application.
app.run('0.0.0.0')
| bsd-3-clause |
tmatt95/cinyWeb | www/protected/modules/admin/controllers/IndexController.php | 2116 | <?php
class IndexController extends Controller
{
/**
* Having a main menu at the top of the page can be confusing for the user
* when they are navigating around the admin panel.
*
* If you would like to use the menu in a controller action, then override
* it with "$this->layout = true" to turn it back on again.
* @var boolean
*/
public $hideMainMenu = true;
/**
* Having the news box on the administration pages gets in the way of the
* content, therefore the column1 style has been chosen which in effect
* turns it off.
*
* @var string
*/
public $layout = '//layouts/column1';
/**
* @return array action filters
*/
public function filters()
{
return array(
'accessControl'
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array(
'allow',
'actions'=>array(
'index'
),
'expression'=>'Users::model()->isAdmin()'
),
array(
// deny all userss
'deny',
'users'=>array('*'),
),
);
}
/**
* This displays the administration index section. From which the user can
* dive down to administer the various parts of the application.
*/
public function actionIndex()
{
$baseScriptUrl = Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('zii.widgets.assets')).'/gridview';
$cs=Yii::app()->getClientScript();
$cs->registerCoreScript('jquery');
$cs->registerCoreScript('bbq');
$cs->registerCoreScript('jquery-ui.min.js');
$cs->registerCoreScript('maskedinput');
$cs->registerScriptFile($baseScriptUrl.'/jquery.yiigridview.js',CClientScript::POS_END);
$staticSections = new StaticSections();
$staticMenu = $staticSections->getAllStaticSections();
/**
* As there are no yii components on the page, jquery needs to be
* manually added otherwise the page wont work
* - Please do not remove
*/
$this->breadcrumbs=array('Administration');
$this->render(
'index',
array(
'staticMenu'=>$staticMenu
)
);
}
} | bsd-3-clause |
pongad/api-client-staging | generated/java/proto-google-cloud-dialogflow-v2beta1/src/main/java/com/google/cloud/dialogflow/v2beta1/DeleteContextRequestOrBuilder.java | 1738 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dialogflow/v2beta1/context.proto
package com.google.cloud.dialogflow.v2beta1;
public interface DeleteContextRequestOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.cloud.dialogflow.v2beta1.DeleteContextRequest)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* Required. The name of the context to delete. Format:
* `projects/<Project ID>/agent/sessions/<Session ID>/contexts/<Context ID>`
* or `projects/<Project ID>/agent/environments/<Environment ID>/users/<User
* ID>/sessions/<Session ID>/contexts/<Context ID>`. Note: Environments and
* users are under construction and will be available soon. If <Environment
* ID> is not specified, we assume default 'draft' environment. If <User ID>
* is not specified, we assume default
* '-' user.
* </pre>
*
* <code>string name = 1;</code>
*/
java.lang.String getName();
/**
* <pre>
* Required. The name of the context to delete. Format:
* `projects/<Project ID>/agent/sessions/<Session ID>/contexts/<Context ID>`
* or `projects/<Project ID>/agent/environments/<Environment ID>/users/<User
* ID>/sessions/<Session ID>/contexts/<Context ID>`. Note: Environments and
* users are under construction and will be available soon. If <Environment
* ID> is not specified, we assume default 'draft' environment. If <User ID>
* is not specified, we assume default
* '-' user.
* </pre>
*
* <code>string name = 1;</code>
*/
com.google.protobuf.ByteString
getNameBytes();
}
| bsd-3-clause |