code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
"use strict";
const { BrowserWindow } = require("electron");
module.exports = (dirname, storage) => {
let win;
let init = () => {
if (win === null || win === undefined) {
createWindow();
}
};
let createWindow = () => {
const { screen } = require("electron");
const { width, height } = screen.getPrimaryDisplay().workAreaSize;
win = new BrowserWindow({
frame: false,
autoHideMenuBar: true,
width: width,
height: height,
transparent: true,
alwaysOnTop: true,
resizable: false,
movable: false,
hasShadow: false,
});
win.loadURL(`file://${dirname}/views/support.html`);
win.on("closed", () => {
win = undefined;
});
};
let getWindow = () => win;
return {
init: init,
getWindow: getWindow,
};
};
|
Toinane/colorpicker
|
src/browsers/support.js
|
JavaScript
|
gpl-3.0
| 950 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
/**
* Copyright (C) 2014-2015 University of Arizona.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Author: Jerald Paul Abraham <jeraldabraham@email.arizona.edu>
*/
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <string>
#include <unistd.h>
#include <vector>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/filesystem.hpp>
#include <boost/noncopyable.hpp>
#include <ndn-cxx/exclude.hpp>
#include <ndn-cxx/face.hpp>
#include <ndn-cxx/name-component.hpp>
#include <ndn-cxx/util/backports.hpp>
#include "logger.hpp"
namespace ndn {
class NdnTrafficClient : boost::noncopyable
{
public:
explicit
NdnTrafficClient(const char* programName)
: m_programName(programName)
, m_logger("NdnTrafficClient")
, m_instanceId(to_string(std::rand()))
, m_hasError(false)
, m_hasQuietLogging(false)
, m_interestInterval(getDefaultInterestInterval())
, m_nMaximumInterests(-1)
, m_face(m_ioService)
, m_nInterestsSent(0)
, m_nPatternsSent(0)
, m_nInterestsReceived(0)
, m_nContentInconsistencies(0)
, m_minimumInterestRoundTripTime(std::numeric_limits<double>::max())
, m_maximumInterestRoundTripTime(0)
, m_totalInterestRoundTripTime(0)
{
}
class InterestTrafficConfiguration
{
public:
InterestTrafficConfiguration()
: m_trafficPercentage(-1)
, m_nameAppendBytes(-1)
, m_nameAppendSequenceNumber(-1)
, m_minSuffixComponents(-1)
, m_maxSuffixComponents(-1)
, m_excludeBeforeBytes(-1)
, m_excludeAfterBytes(-1)
, m_childSelector(-1)
, m_mustBeFresh(-1)
, m_nonceDuplicationPercentage(-1)
, m_interestLifetime(getDefaultInterestLifetime())
, m_nInterestsSent(0)
, m_nInterestsReceived(0)
, m_minimumInterestRoundTripTime(std::numeric_limits<double>::max())
, m_maximumInterestRoundTripTime(0)
, m_totalInterestRoundTripTime(0)
, m_nContentInconsistencies(0)
{
}
static time::milliseconds
getDefaultInterestLifetime()
{
return time::milliseconds(-1);
}
void
printTrafficConfiguration(Logger& logger)
{
std::string detail;
if (m_trafficPercentage > 0)
detail += "TrafficPercentage=" + to_string(m_trafficPercentage) + ", ";
if (!m_names.empty())
detail += "Name=" + m_names.at(0) + ", ";
if (m_nameAppendBytes > 0)
detail += "NameAppendBytes=" + to_string(m_nameAppendBytes) + ", ";
if (m_nameAppendSequenceNumber > 0)
detail += "NameAppendSequenceNumber=" + to_string(m_nameAppendSequenceNumber) + ", ";
if (m_minSuffixComponents >= 0)
detail += "MinSuffixComponents=" + to_string(m_minSuffixComponents) + ", ";
if (m_maxSuffixComponents >= 0)
detail += "MaxSuffixComponents=" + to_string(m_maxSuffixComponents) + ", ";
if (!m_excludeBefore.empty())
detail += "ExcludeBefore=" + m_excludeBefore + ", ";
if (!m_excludeAfter.empty())
detail += "ExcludeAfter=" + m_excludeAfter + ", ";
if (m_excludeBeforeBytes > 0)
detail += "ExcludeBeforeBytes=" + to_string(m_excludeBeforeBytes) + ", ";
if (m_excludeAfterBytes > 0)
detail += "ExcludeAfterBytes=" + to_string(m_excludeAfterBytes) + ", ";
if (m_childSelector >= 0)
detail += "ChildSelector=" + to_string(m_childSelector) + ", ";
if (m_mustBeFresh >= 0)
detail += "MustBeFresh=" + to_string(m_mustBeFresh) + ", ";
if (m_nonceDuplicationPercentage > 0)
detail += "NonceDuplicationPercentage=" + to_string(m_nonceDuplicationPercentage) + ", ";
if (m_interestLifetime >= time::milliseconds(0))
detail += "InterestLifetime=" + to_string(m_interestLifetime.count()) + ", ";
if (!m_expectedContents.empty())
detail += "ExpectedContent=" + m_expectedContents.at(0) + ", ";
if (detail.length() >= 2)
detail = detail.substr(0, detail.length() - 2); // Removing suffix ", "
logger.log(detail, false, false);
}
bool
extractParameterValue(const std::string& detail, std::string& parameter, std::string& value)
{
std::string allowedCharacters = ":/+._-%";
std::size_t i = 0;
parameter = "";
value = "";
while (detail[i] != '=' && i < detail.length()) {
parameter += detail[i];
i++;
}
if (i == detail.length())
return false;
i++;
while ((std::isalnum(detail[i]) ||
allowedCharacters.find(detail[i]) != std::string::npos) &&
i < detail.length()) {
value += detail[i];
i++;
}
if (parameter.empty() || value.empty())
return false;
else
return true;
}
bool
processConfigurationDetail(const std::string& detail, Logger& logger, int lineNumber)
{
std::string parameter, value;
if (extractParameterValue(detail, parameter, value))
{
if (parameter == "TrafficPercentage")
m_trafficPercentage = std::stoi(value);
else if (parameter == "Name")
{
std::cout << "Reading: "<<value<<"\n";
m_names.push_back(value);
}
else if (parameter == "NameAppendBytes")
m_nameAppendBytes = std::stoi(value);
else if (parameter == "NameAppendSequenceNumber")
m_nameAppendSequenceNumber = std::stoi(value);
else if (parameter == "MinSuffixComponents")
m_minSuffixComponents = std::stoi(value);
else if (parameter == "MaxSuffixComponents")
m_maxSuffixComponents = std::stoi(value);
else if (parameter == "ExcludeBefore")
m_excludeBefore = value;
else if (parameter == "ExcludeAfter")
m_excludeAfter = value;
else if (parameter == "ExcludeBeforeBytes")
m_excludeBeforeBytes = std::stoi(value);
else if (parameter == "ExcludeAfterBytes")
m_excludeAfterBytes = std::stoi(value);
else if (parameter == "ChildSelector")
m_childSelector = std::stoi(value);
else if (parameter == "MustBeFresh")
m_mustBeFresh = std::stoi(value);
else if (parameter == "NonceDuplicationPercentage")
m_nonceDuplicationPercentage = std::stoi(value);
else if (parameter == "InterestLifetime")
m_interestLifetime = time::milliseconds(std::stoi(value));
else if (parameter == "ExpectedContent")
{
m_expectedContents.push_back(value);
std::cout << "Reading content value: "<<value<<"\n";
}
else
logger.log("Line " + to_string(lineNumber) +
" \t- Invalid Parameter='" + parameter + "'", false, true);
}
else
{
logger.log("Line " + to_string(lineNumber) +
" \t- Improper Traffic Configuration Line- " + detail, false, true);
return false;
}
return true;
}
bool
checkTrafficDetailCorrectness()
{
return true;
}
private:
int m_trafficPercentage;
std::vector<std::string> m_names;
int m_nameAppendBytes;
int m_nameAppendSequenceNumber;
int m_minSuffixComponents;
int m_maxSuffixComponents;
std::string m_excludeBefore;
std::string m_excludeAfter;
int m_excludeBeforeBytes;
int m_excludeAfterBytes;
int m_childSelector;
int m_mustBeFresh;
int m_nonceDuplicationPercentage;
time::milliseconds m_interestLifetime;
int m_nInterestsSent;
int m_nInterestsReceived;
//round trip time is stored as milliseconds with fractional
//sub-millisecond precision
double m_minimumInterestRoundTripTime;
double m_maximumInterestRoundTripTime;
double m_totalInterestRoundTripTime;
int m_nContentInconsistencies;
std::vector<std::string> m_expectedContents;
friend class NdnTrafficClient;
}; // class InterestTrafficConfiguration
bool
hasError() const
{
return m_hasError;
}
void
usage() const
{
std::cout << "Usage:\n"
<< " " << m_programName << " [options] <Traffic_Configuration_File>\n"
<< "\n"
<< "Generate Interest traffic as per provided Traffic Configuration File.\n"
<< "Interests are continuously generated unless a total number is specified.\n"
<< "Set environment variable NDN_TRAFFIC_LOGFOLDER to redirect output to a log file.\n"
<< "\n"
<< "Options:\n"
<< " [-i interval] - set interest generation interval in milliseconds (default "
<< getDefaultInterestInterval() << ")\n"
<< " [-c count] - set total number of interests to be generated\n"
<< " [-q] - quiet mode: no interest reception/data generation logging\n"
<< " [-h] - print this help text and exit\n";
exit(EXIT_FAILURE);
}
static time::milliseconds
getDefaultInterestInterval()
{
return time::milliseconds(1000);
}
void
setInterestInterval(int interestInterval)
{
if (interestInterval <= 0)
usage();
m_interestInterval = time::milliseconds(interestInterval);
}
void
setMaximumInterests(int maximumInterests)
{
if (maximumInterests <= 0)
usage();
m_nMaximumInterests = maximumInterests;
}
void
setConfigurationFile(char* configurationFile)
{
m_configurationFile = configurationFile;
}
void
setQuietLogging()
{
m_hasQuietLogging = true;
}
void
signalHandler()
{
logStatistics();
m_logger.shutdownLogger();
m_face.shutdown();
m_ioService.stop();
exit(m_hasError ? EXIT_FAILURE : EXIT_SUCCESS);
}
void
logStatistics()
{
m_logger.log("\n\n== Interest Traffic Report ==\n", false, true);
m_logger.log("Total Traffic Pattern Types = " +
to_string(m_trafficPatterns.size()), false, true);
m_logger.log("Total Interests Sent = " +
to_string(m_nInterestsSent), false, true);
m_logger.log("Total Responses Received = " +
to_string(m_nInterestsReceived), false, true);
double loss = 0;
if (m_nInterestsSent > 0)
loss = (m_nInterestsSent - m_nInterestsReceived) * 100.0 / m_nInterestsSent;
m_logger.log("Total Interest Loss = " + to_string(loss) + "%", false, true);
if (m_nContentInconsistencies != 0 || m_nInterestsSent != m_nInterestsReceived)
m_hasError = true;
double average = 0;
double inconsistency = 0;
if (m_nInterestsReceived > 0)
{
average = m_totalInterestRoundTripTime / m_nInterestsReceived;
inconsistency = m_nContentInconsistencies * 100.0 / m_nInterestsReceived;
}
m_logger.log("Total Data Inconsistency = " +
to_string(inconsistency) + "%", false, true);
m_logger.log("Total Round Trip Time = " +
to_string(m_totalInterestRoundTripTime) + "ms", false, true);
m_logger.log("Average Round Trip Time = " +
to_string(average) + "ms\n", false, true);
for (std::size_t patternId = 0; patternId < m_trafficPatterns.size(); patternId++)
{
m_logger.log("Traffic Pattern Type #" +
to_string(patternId + 1), false, true);
m_trafficPatterns[patternId].printTrafficConfiguration(m_logger);
m_logger.log("Total Interests Sent = " +
to_string(m_trafficPatterns[patternId].m_nInterestsSent), false, true);
m_logger.log("Total Responses Received = " +
to_string(m_trafficPatterns[patternId].m_nInterestsReceived), false, true);
loss = 0;
if (m_trafficPatterns[patternId].m_nInterestsSent > 0)
{
loss = (m_trafficPatterns[patternId].m_nInterestsSent -
m_trafficPatterns[patternId].m_nInterestsReceived);
loss *= 100.0;
loss /= m_trafficPatterns[patternId].m_nInterestsSent;
}
m_logger.log("Total Interest Loss = " + to_string(loss) + "%", false, true);
average = 0;
inconsistency = 0;
if (m_trafficPatterns[patternId].m_nInterestsReceived > 0)
{
average = (m_trafficPatterns[patternId].m_totalInterestRoundTripTime /
m_trafficPatterns[patternId].m_nInterestsReceived);
inconsistency = m_trafficPatterns[patternId].m_nContentInconsistencies;
inconsistency *= 100.0 / m_trafficPatterns[patternId].m_nInterestsReceived;
}
m_logger.log("Total Data Inconsistency = " +
to_string(inconsistency) + "%", false, true);
m_logger.log("Total Round Trip Time = " +
to_string(m_trafficPatterns[patternId].m_totalInterestRoundTripTime) +
"ms", false, true);
m_logger.log("Average Round Trip Time = " +
to_string(average) + "ms\n", false, true);
}
}
bool
checkTrafficPatternCorrectness()
{
return true;
}
void
parseConfigurationFile()
{
std::string patternLine;
std::ifstream patternFile;
m_logger.log("Analyzing Traffic Configuration File: " + m_configurationFile, true, true);
patternFile.open(m_configurationFile.c_str());
if (patternFile.is_open())
{
int lineNumber = 0;
while (getline(patternFile, patternLine))
{
lineNumber++;
if (std::isalpha(patternLine[0]))
{
InterestTrafficConfiguration interestData;
bool shouldSkipLine = false;
if (interestData.processConfigurationDetail(patternLine, m_logger, lineNumber))
{
while (getline(patternFile, patternLine) && std::isalpha(patternLine[0]))
{
lineNumber++;
if (!interestData.processConfigurationDetail(patternLine,
m_logger, lineNumber))
{
shouldSkipLine = true;
break;
}
}
lineNumber++;
}
else
shouldSkipLine = true;
if (!shouldSkipLine)
{
if (interestData.checkTrafficDetailCorrectness())
m_trafficPatterns.push_back(interestData);
}
}
}
patternFile.close();
if (!checkTrafficPatternCorrectness())
{
m_logger.log("ERROR - Traffic Configuration Provided Is Not Proper- " +
m_configurationFile, false, true);
m_logger.shutdownLogger();
exit(EXIT_FAILURE);
}
m_logger.log("Traffic Configuration File Processing Completed\n", true, false);
for (std::size_t patternId = 0; patternId < m_trafficPatterns.size(); patternId++)
{
m_logger.log("Traffic Pattern Type #" +
to_string(patternId + 1), false, false);
m_trafficPatterns[patternId].printTrafficConfiguration(m_logger);
m_logger.log("", false, false);
}
}
else
{
m_logger.log("ERROR - Unable To Open Traffic Configuration File: " +
m_configurationFile, false, true);
m_logger.shutdownLogger();
exit(EXIT_FAILURE);
}
}
void
initializeTrafficConfiguration()
{
if (boost::filesystem::exists(boost::filesystem::path(m_configurationFile)))
{
if (boost::filesystem::is_regular_file(boost::filesystem::path(m_configurationFile)))
{
parseConfigurationFile();
}
else
{
m_logger.log("ERROR - Traffic Configuration File Is Not A Regular File: " +
m_configurationFile, false, true);
m_logger.shutdownLogger();
exit(EXIT_FAILURE);
}
}
else
{
m_logger.log("ERROR - Traffic Configuration File Does Not Exist: " +
m_configurationFile, false, true);
m_logger.shutdownLogger();
exit(EXIT_FAILURE);
}
}
uint32_t
getOldNonce()
{
if (m_nonces.size() == 0)
return getNewNonce();
int randomNonceIndex = std::rand() % m_nonces.size();
return m_nonces[randomNonceIndex];
}
uint32_t
getNewNonce()
{
//Performance Enhancement
if (m_nonces.size() > 1000)
m_nonces.clear();
uint32_t randomNonce = static_cast<uint32_t>(std::rand());
while (std::find(m_nonces.begin(), m_nonces.end(), randomNonce) != m_nonces.end())
randomNonce = static_cast<uint32_t>(std::rand());
m_nonces.push_back(randomNonce);
return randomNonce;
}
static name::Component
generateRandomNameComponent(size_t length)
{
Buffer buffer(length);
for (size_t i = 0; i < length; i++) {
buffer[i] = static_cast<uint8_t>(std::rand() % 256);
}
return name::Component(buffer);
}
void
onData(const ndn::Interest& interest,
ndn::Data& data,
int globalReference,
int localReference,
int patternId,
time::steady_clock::TimePoint sentTime)
{
std::string logLine = "Data Received - PatternType=" + to_string(patternId + 1);
logLine += ", GlobalID=" + to_string(globalReference);
logLine += ", LocalID=" + to_string(localReference);
logLine += ", Name=" + interest.getName().toUri();
unsigned int i;
bool consistent=false;
m_nInterestsReceived++;
m_trafficPatterns[patternId].m_nInterestsReceived++;
if (!m_trafficPatterns[patternId].m_expectedContents.empty())
{
std::string receivedContent = reinterpret_cast<const char*>(data.getContent().value());
int receivedContentLength = data.getContent().value_size();
receivedContent = receivedContent.substr(0, receivedContentLength);
for (i = 0; i < m_trafficPatterns[patternId].m_expectedContents.size(); i++)
{
std::cout <<"Comparing "<<receivedContent<<" with "<<m_trafficPatterns[patternId].m_expectedContents.at(i)<<"\n";
if (receivedContent == m_trafficPatterns[patternId].m_expectedContents.at(i))
{
logLine += ", IsConsistent=Yes";
consistent = true;
break;
}
}
if(!consistent)
{
m_nContentInconsistencies++;
m_trafficPatterns[patternId].m_nContentInconsistencies++;
logLine += ", IsConsistent=No";
}
}
else
logLine += ", IsConsistent=NotChecked";
if (!m_hasQuietLogging)
m_logger.log(logLine, true, false);
double roundTripTime = (time::steady_clock::now() - sentTime).count() / 1000000.0;
if (m_minimumInterestRoundTripTime > roundTripTime)
m_minimumInterestRoundTripTime = roundTripTime;
if (m_maximumInterestRoundTripTime < roundTripTime)
m_maximumInterestRoundTripTime = roundTripTime;
if (m_trafficPatterns[patternId].m_minimumInterestRoundTripTime > roundTripTime)
m_trafficPatterns[patternId].m_minimumInterestRoundTripTime = roundTripTime;
if (m_trafficPatterns[patternId].m_maximumInterestRoundTripTime < roundTripTime)
m_trafficPatterns[patternId].m_maximumInterestRoundTripTime = roundTripTime;
m_totalInterestRoundTripTime += roundTripTime;
m_trafficPatterns[patternId].m_totalInterestRoundTripTime += roundTripTime;
if (m_nMaximumInterests >= 0 && globalReference == m_nMaximumInterests)
{
logStatistics();
m_logger.shutdownLogger();
m_face.shutdown();
m_ioService.stop();
}
}
void
onTimeout(const ndn::Interest& interest,
int globalReference,
int localReference,
int patternId)
{
std::string logLine = "Interest Timed Out - PatternType=" + to_string(patternId + 1);
logLine += ", GlobalID=" + to_string(globalReference);
logLine += ", LocalID=" + to_string(localReference);
logLine += ", Name=" + interest.getName().toUri();
m_logger.log(logLine, true, false);
if (m_nMaximumInterests >= 0 && globalReference == m_nMaximumInterests)
{
logStatistics();
m_logger.shutdownLogger();
m_face.shutdown();
m_ioService.stop();
}
}
void
generateTraffic(boost::asio::deadline_timer* timer)
{
if (m_nMaximumInterests < 0 || m_nPatternsSent < m_nMaximumInterests)
{
int trafficKey = std::rand() % 100;
int cumulativePercentage = 0;
std::size_t patternId;
for (patternId = 0; patternId < m_trafficPatterns.size(); patternId++)
{
cumulativePercentage += m_trafficPatterns[patternId].m_trafficPercentage;
if (trafficKey <= cumulativePercentage)
{
m_nPatternsSent++;
std::cout<<"Size of the m_names is "<<m_trafficPatterns[patternId].m_names.size()<<"\n";
bool timer_scheduled = false;
for(unsigned int i = 0; i < m_trafficPatterns[patternId].m_names.size(); i++)
{
//Name interestName(m_trafficPatterns[patternId].m_name);
Name interestName(m_trafficPatterns[patternId].m_names.at(i));
std::cout <<"Name in interest: "<<interestName<<"\n";
if (m_trafficPatterns[patternId].m_nameAppendBytes > 0)
interestName.append(generateRandomNameComponent(m_trafficPatterns[patternId].m_nameAppendBytes));
if (m_trafficPatterns[patternId].m_nameAppendSequenceNumber >= 0)
{
interestName.append(to_string(m_trafficPatterns[patternId].m_nameAppendSequenceNumber));
m_trafficPatterns[patternId].m_nameAppendSequenceNumber++;
}
Interest interest(interestName);
if (m_trafficPatterns[patternId].m_minSuffixComponents >= 0)
interest.setMinSuffixComponents(
m_trafficPatterns[patternId].m_minSuffixComponents);
if (m_trafficPatterns[patternId].m_maxSuffixComponents >= 0)
interest.setMaxSuffixComponents(
m_trafficPatterns[patternId].m_maxSuffixComponents);
Exclude exclude;
if (!m_trafficPatterns[patternId].m_excludeBefore.empty() &&
!m_trafficPatterns[patternId].m_excludeAfter.empty())
{
exclude.excludeRange(
name::Component(
m_trafficPatterns[patternId].m_excludeAfter),
name::Component(m_trafficPatterns[patternId].m_excludeBefore));
interest.setExclude(exclude);
}
else if (!m_trafficPatterns[patternId].m_excludeBefore.empty())
{
exclude.excludeBefore(
name::Component(m_trafficPatterns[patternId].m_excludeBefore));
interest.setExclude(exclude);
}
else if (!m_trafficPatterns[patternId].m_excludeAfter.empty())
{
exclude.excludeAfter(
name::Component(m_trafficPatterns[patternId].m_excludeAfter));
interest.setExclude(exclude);
}
if (m_trafficPatterns[patternId].m_excludeBeforeBytes > 0 &&
m_trafficPatterns[patternId].m_excludeAfterBytes > 0)
{
exclude.excludeRange(
generateRandomNameComponent(
m_trafficPatterns[patternId].m_excludeAfterBytes),
generateRandomNameComponent(
m_trafficPatterns[patternId].m_excludeBeforeBytes));
interest.setExclude(exclude);
}
else if (m_trafficPatterns[patternId].m_excludeBeforeBytes > 0)
{
exclude.excludeBefore(
generateRandomNameComponent(
m_trafficPatterns[patternId].m_excludeBeforeBytes));
interest.setExclude(exclude);
}
else if (m_trafficPatterns[patternId].m_excludeAfterBytes > 0)
{
exclude.excludeAfter(
generateRandomNameComponent(
m_trafficPatterns[patternId].m_excludeAfterBytes));
interest.setExclude(exclude);
}
if (m_trafficPatterns[patternId].m_childSelector >= 0)
interest.setChildSelector(m_trafficPatterns[patternId].m_childSelector);
if (m_trafficPatterns[patternId].m_mustBeFresh == 0)
interest.setMustBeFresh(false);
else if (m_trafficPatterns[patternId].m_mustBeFresh > 0)
interest.setMustBeFresh(true);
if (m_trafficPatterns[patternId].m_nonceDuplicationPercentage > 0)
{
int duplicationPercentage = std::rand() % 100;
if (m_trafficPatterns[patternId].m_nonceDuplicationPercentage <=
duplicationPercentage)
interest.setNonce(getOldNonce());
else
interest.setNonce(getNewNonce());
}
else
interest.setNonce(getNewNonce());
if (m_trafficPatterns[patternId].m_interestLifetime >= time::milliseconds(0))
interest.setInterestLifetime(m_trafficPatterns[patternId].m_interestLifetime);
try {
m_nInterestsSent++;
m_trafficPatterns[patternId].m_nInterestsSent++;
time::steady_clock::TimePoint sentTime = time::steady_clock::now();
m_face.expressInterest(interest,
bind(&NdnTrafficClient::onData,
this, _1, _2, m_nPatternsSent,
m_trafficPatterns[patternId].m_nInterestsSent,
patternId, sentTime),
bind(&NdnTrafficClient::onTimeout,
this, _1, m_nInterestsSent,
m_trafficPatterns[patternId].m_nInterestsSent,
patternId));
if (!m_hasQuietLogging) {
std::string logLine =
"Sending Interest - PatternType=" + to_string(patternId + 1) +
", GlobalID=" + to_string(m_nInterestsSent) +
", LocalID=" +
to_string(m_trafficPatterns[patternId].m_nInterestsSent) +
", Name=" + interest.getName().toUri();
m_logger.log(logLine, true, false);
}
if(!timer_scheduled)
{
timer->expires_at(timer->expires_at() +
boost::posix_time::millisec(m_interestInterval.count()));
timer->async_wait(bind(&NdnTrafficClient::generateTraffic, this, timer));
timer_scheduled = true;
}
}
catch (const std::exception& e) {
m_logger.log("ERROR: " + std::string(e.what()), true, true);
}
}
break;
}
}
if (patternId == m_trafficPatterns.size())
{
timer->expires_at(timer->expires_at() +
boost::posix_time::millisec(m_interestInterval.count()));
timer->async_wait(bind(&NdnTrafficClient::generateTraffic, this, timer));
}
}
}
void
run()
{
boost::asio::signal_set signalSet(m_ioService, SIGINT, SIGTERM);
signalSet.async_wait(bind(&NdnTrafficClient::signalHandler, this));
m_logger.initializeLog(m_instanceId);
initializeTrafficConfiguration();
if (m_nMaximumInterests == 0)
{
logStatistics();
m_logger.shutdownLogger();
return;
}
boost::asio::deadline_timer deadlineTimer(m_ioService,
boost::posix_time::millisec(m_interestInterval.count()));
deadlineTimer.async_wait(bind(&NdnTrafficClient::generateTraffic, this, &deadlineTimer));
try {
m_face.processEvents();
}
catch (const std::exception& e) {
m_logger.log("ERROR: " + std::string(e.what()), true, true);
m_logger.shutdownLogger();
m_hasError = true;
m_ioService.stop();
}
}
private:
std::string m_programName;
Logger m_logger;
std::string m_instanceId;
bool m_hasError;
bool m_hasQuietLogging;
time::milliseconds m_interestInterval;
int m_nMaximumInterests;
std::string m_configurationFile;
boost::asio::io_service m_ioService;
Face m_face;
std::vector<InterestTrafficConfiguration> m_trafficPatterns;
std::vector<uint32_t> m_nonces;
int m_nInterestsSent;
int m_nPatternsSent;
int m_nInterestsReceived;
int m_nContentInconsistencies;
//round trip time is stored as milliseconds with fractional
//sub-milliseconds precision
double m_minimumInterestRoundTripTime;
double m_maximumInterestRoundTripTime;
double m_totalInterestRoundTripTime;
};
} // namespace ndn
int
main(int argc, char* argv[])
{
std::srand(std::time(nullptr));
ndn::NdnTrafficClient client(argv[0]);
int option;
while ((option = getopt(argc, argv, "hqi:c:")) != -1) {
switch (option) {
case 'h':
client.usage();
break;
case 'i':
client.setInterestInterval(atoi(optarg));
break;
case 'c':
client.setMaximumInterests(atoi(optarg));
break;
case 'q':
client.setQuietLogging();
break;
default:
client.usage();
break;
}
}
argc -= optind;
argv += optind;
if (!argc)
client.usage();
client.setConfigurationFile(argv[0]);
client.run();
return client.hasError() ? EXIT_FAILURE : EXIT_SUCCESS;
}
|
oascigil/trafficgen
|
src/ndn-traffic-client.cpp
|
C++
|
gpl-3.0
| 31,588 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import *
from unittest import TestCase
__author__ = 'nicolas'
import os
class TestTauPyModel(TestCase):
def test_create_taup_model(self):
"""
See if the create model function in the tau interface runs smoothly.
"""
from taupy import tau
try:
os.remove("ak135.taup")
except FileNotFoundError:
pass
ak135 = tau.TauPyModel("ak135", taup_model_path=".")
os.remove("ak135.taup")
|
obspy/TauPy
|
taupy/tests/test_tauPyModel.py
|
Python
|
gpl-3.0
| 645 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* View
* @copyright (c) 2017, Davi Menezes (davimenezes.dvi@gmail.com)
*/
?>
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Read Mail <small> https://bitbucket.org/DaviMenezes</small>
</h1>
<ol class="breadcrumb">
<li><a href="<?= base_url() ?>"><i class="fa fa-dashboard"></i> Home </a></li>
<!--'<li class="active"></li>'-->
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-md-3">
<a href="<?= base_url("page/mail_compose") ?>" class="btn btn-primary btn-block margin-bottom">Compose</a>
<div class="box box-solid">
<div class="box-header with-border">
<h3 class="box-title">Folders</h3>
<div class="box-tools">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
</button>
</div>
</div>
<div class="box-body no-padding">
<ul class="nav nav-pills nav-stacked">
<li><a href="<?= base_url("page/mailbox") ?>">
<i class = "fa fa-inbox"></i> Inbox
<span class="label label-primary pull-right">12</span>
</a>
</li>
<li><a href="#"><i class="fa fa-envelope-o"></i> Sent</a></li>
<li><a href="#"><i class="fa fa-file-text-o"></i> Drafts</a></li>
<li><a href="#"><i class="fa fa-filter"></i> Junk <span class="label label-warning pull-right">65</span></a>
</li>
<li><a href="#"><i class="fa fa-trash-o"></i> Trash</a></li>
</ul>
</div>
<!-- /.box-body -->
</div>
<!-- /. box -->
<div class="box box-solid">
<div class="box-header with-border">
<h3 class="box-title">Labels</h3>
<div class="box-tools">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
</button>
</div>
</div>
<div class="box-body no-padding">
<ul class="nav nav-pills nav-stacked">
<li><a href="#"><i class="fa fa-circle-o text-red"></i> Important</a></li>
<li><a href="#"><i class="fa fa-circle-o text-yellow"></i> Promotions</a></li>
<li><a href="#"><i class="fa fa-circle-o text-light-blue"></i> Social</a></li>
</ul>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
<div class="col-md-9">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Read Mail</h3>
<div class="box-tools pull-right">
<a href="#" class="btn btn-box-tool" data-toggle="tooltip" title="Previous"><i class="fa fa-chevron-left"></i></a>
<a href="#" class="btn btn-box-tool" data-toggle="tooltip" title="Next"><i class="fa fa-chevron-right"></i></a>
</div>
</div>
<!-- /.box-header -->
<div class="box-body no-padding">
<div class="mailbox-read-info">
<h3>Message Subject Is Placed Here</h3>
<h5>From: help@example.com
<span class="mailbox-read-time pull-right">15 Feb. 2016 11:03 PM</span></h5>
</div>
<!-- /.mailbox-read-info -->
<div class="mailbox-controls with-border text-center">
<div class="btn-group">
<button type="button" class="btn btn-default btn-sm" data-toggle="tooltip" data-container="body" title="Delete">
<i class="fa fa-trash-o"></i></button>
<button type="button" class="btn btn-default btn-sm" data-toggle="tooltip" data-container="body" title="Reply">
<i class="fa fa-reply"></i></button>
<button type="button" class="btn btn-default btn-sm" data-toggle="tooltip" data-container="body" title="Forward">
<i class="fa fa-share"></i></button>
</div>
<!-- /.btn-group -->
<button type="button" class="btn btn-default btn-sm" data-toggle="tooltip" title="Print">
<i class="fa fa-print"></i></button>
</div>
<!-- /.mailbox-controls -->
<div class="mailbox-read-message">
<p>Hello John,</p>
<p>Keffiyeh blog actually fashion axe vegan, irony biodiesel. Cold-pressed hoodie chillwave put a bird
on it aesthetic, bitters brunch meggings vegan iPhone. Dreamcatcher vegan scenester mlkshk. Ethical
master cleanse Bushwick, occupy Thundercats banjo cliche ennui farm-to-table mlkshk fanny pack
gluten-free. Marfa butcher vegan quinoa, bicycle rights disrupt tofu scenester chillwave 3 wolf moon
asymmetrical taxidermy pour-over. Quinoa tote bag fashion axe, Godard disrupt migas church-key tofu
blog locavore. Thundercats cronut polaroid Neutra tousled, meh food truck selfies narwhal American
Apparel.</p>
<p>Raw denim McSweeney's bicycle rights, iPhone trust fund quinoa Neutra VHS kale chips vegan PBR&B
literally Thundercats +1. Forage tilde four dollar toast, banjo health goth paleo butcher. Four dollar
toast Brooklyn pour-over American Apparel sustainable, lumbersexual listicle gluten-free health goth
umami hoodie. Synth Echo Park bicycle rights DIY farm-to-table, retro kogi sriracha dreamcatcher PBR&B
flannel hashtag irony Wes Anderson. Lumbersexual Williamsburg Helvetica next level. Cold-pressed
slow-carb pop-up normcore Thundercats Portland, cardigan literally meditation lumbersexual crucifix.
Wayfarers raw denim paleo Bushwick, keytar Helvetica scenester keffiyeh 8-bit irony mumblecore
whatever viral Truffaut.</p>
<p>Post-ironic shabby chic VHS, Marfa keytar flannel lomo try-hard keffiyeh cray. Actually fap fanny
pack yr artisan trust fund. High Life dreamcatcher church-key gentrify. Tumblr stumptown four dollar
toast vinyl, cold-pressed try-hard blog authentic keffiyeh Helvetica lo-fi tilde Intelligentsia. Lomo
locavore salvia bespoke, twee fixie paleo cliche brunch Schlitz blog McSweeney's messenger bag swag
slow-carb. Odd Future photo booth pork belly, you probably haven't heard of them actually tofu ennui
keffiyeh lo-fi Truffaut health goth. Narwhal sustainable retro disrupt.</p>
<p>Skateboard artisan letterpress before they sold out High Life messenger bag. Bitters chambray
leggings listicle, drinking vinegar chillwave synth. Fanny pack hoodie American Apparel twee. American
Apparel PBR listicle, salvia aesthetic occupy sustainable Neutra kogi. Organic synth Tumblr viral
plaid, shabby chic single-origin coffee Etsy 3 wolf moon slow-carb Schlitz roof party tousled squid
vinyl. Readymade next level literally trust fund. Distillery master cleanse migas, Vice sriracha
flannel chambray chia cronut.</p>
<p>Thanks,<br>Jane</p>
</div>
<!-- /.mailbox-read-message -->
</div>
<!-- /.box-body -->
<div class="box-footer">
<ul class="mailbox-attachments clearfix">
<li>
<span class="mailbox-attachment-icon"><i class="fa fa-file-pdf-o"></i></span>
<div class="mailbox-attachment-info">
<a href="#" class="mailbox-attachment-name"><i class="fa fa-paperclip"></i> Sep2014-report.pdf</a>
<span class="mailbox-attachment-size">
1,245 KB
<a href="#" class="btn btn-default btn-xs pull-right"><i class="fa fa-cloud-download"></i></a>
</span>
</div>
</li>
<li>
<span class="mailbox-attachment-icon"><i class="fa fa-file-word-o"></i></span>
<div class="mailbox-attachment-info">
<a href="#" class="mailbox-attachment-name"><i class="fa fa-paperclip"></i> App Description.docx</a>
<span class="mailbox-attachment-size">
1,245 KB
<a href="#" class="btn btn-default btn-xs pull-right"><i class="fa fa-cloud-download"></i></a>
</span>
</div>
</li>
<li>
<span class="mailbox-attachment-icon has-img"><img src="<?= base_url('assets/img/photo1.png') ?>" alt="Attachment"></span>
<div class="mailbox-attachment-info">
<a href="#" class="mailbox-attachment-name"><i class="fa fa-camera"></i> photo1.png</a>
<span class="mailbox-attachment-size">
2.67 MB
<a href="#" class="btn btn-default btn-xs pull-right"><i class="fa fa-cloud-download"></i></a>
</span>
</div>
</li>
<li>
<span class="mailbox-attachment-icon has-img"><img src="<?= base_url('assets/img/photo2.png') ?>" alt="Attachment"></span>
<div class="mailbox-attachment-info">
<a href="#" class="mailbox-attachment-name"><i class="fa fa-camera"></i> photo2.png</a>
<span class="mailbox-attachment-size">
1.9 MB
<a href="#" class="btn btn-default btn-xs pull-right"><i class="fa fa-cloud-download"></i></a>
</span>
</div>
</li>
</ul>
</div>
<!-- /.box-footer -->
<div class="box-footer">
<div class="pull-right">
<button type="button" class="btn btn-default"><i class="fa fa-reply"></i> Reply</button>
<button type="button" class="btn btn-default"><i class="fa fa-share"></i> Forward</button>
</div>
<button type="button" class="btn btn-default"><i class="fa fa-trash-o"></i> Delete</button>
<button type="button" class="btn btn-default"><i class="fa fa-print"></i> Print</button>
</div>
<!-- /.box-footer -->
</div>
<!-- /. box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
|
DaviMenezes/DviCodeIgniter
|
application/views/examples/mailbox/read_mail.php
|
PHP
|
gpl-3.0
| 12,385 |
package edu.xjtu.wwh.rmi;
import java.io.IOException;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import edu.xjtu.wwh.core.OperHDFS;
import edu.xjtu.wwh.parameter.DefaultParameter;
public class ThirdParty {
public static void main(String[] args) {
// TODO Auto-generated method stub
//First First get unique clientID and attr_str and base path.
String base=getBase();
String clientID=getClientID();
String attr_str=getAttrStr();
//ๅจRMIๆๅกๆณจๅ่กจไธญๆฅๆพๅ็งฐไธบeci็ๅฏน่ฑก๏ผๅนถ่ฐ็จๅ
ถไธ็ๆนๆณ
CoreFunc cf=null;
try {
cf=(CoreFunc) Naming.lookup("rmi://localhost:8888/cf");
cf.init(base, clientID);
} catch (MalformedURLException | RemoteException | NotBoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Generate related private keys using attr_str
try {
cf.keyInitial(attr_str);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Call decFun
byte[] cipher=OperHDFS.readFromHDFS("cipher").getBytes();
System.out.println(""+cipher.length);
try {
byte[] rs=cf.decFunc(cipher);
System.out.println("DEC:"+new String(rs));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//upd decFun
byte[] newCipher=OperHDFS.readFromHDFS("newCipher").getBytes();
System.out.println(newCipher.length);
try {
byte[] rs=cf.decFunc(newCipher);
System.out.println("UPD:"+new String(rs));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String getBase() {
// TODO Auto-generated method stub
return DefaultParameter.BASE;
}
public static String getClientID(){
return DefaultParameter.TEST_CLIENT_ID;
}
public static String getAttrStr(){
return DefaultParameter.TEST_ATTR_STR;
}
}
|
SteadyStill/rfid
|
src/edu/xjtu/wwh/rmi/ThirdParty.java
|
Java
|
gpl-3.0
| 1,997 |
<?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Service definition for YouTube (v3).
*
* <p>
* The YouTube Data API v3 is an API that provides access to YouTube data, such
* as videos, playlists, and channels.</p>
*
* <p>
* For more information about this service, see the API
* <a href="https://developers.google.com/youtube/" target="_blank">Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class Google_Service_YouTube extends Google_Service
{
/** Manage your YouTube account. */
const YOUTUBE =
"https://www.googleapis.com/auth/youtube";
/** See a list of your current active channel members, their current level, and when they became a member. */
const YOUTUBE_CHANNEL_MEMBERSHIPS_CREATOR =
"https://www.googleapis.com/auth/youtube.channel-memberships.creator";
/** See, edit, and permanently delete your YouTube videos, ratings, comments and captions. */
const YOUTUBE_FORCE_SSL =
"https://www.googleapis.com/auth/youtube.force-ssl";
/** View your YouTube account. */
const YOUTUBE_READONLY =
"https://www.googleapis.com/auth/youtube.readonly";
/** Manage your YouTube videos. */
const YOUTUBE_UPLOAD =
"https://www.googleapis.com/auth/youtube.upload";
/** View and manage your assets and associated content on YouTube. */
const YOUTUBEPARTNER =
"https://www.googleapis.com/auth/youtubepartner";
/** View private information of your YouTube channel relevant during the audit process with a YouTube partner. */
const YOUTUBEPARTNER_CHANNEL_AUDIT =
"https://www.googleapis.com/auth/youtubepartner-channel-audit";
public $abuseReports;
public $activities;
public $captions;
public $channelBanners;
public $channelSections;
public $channels;
public $commentThreads;
public $comments;
public $i18nLanguages;
public $i18nRegions;
public $liveBroadcasts;
public $liveChatBans;
public $liveChatMessages;
public $liveChatModerators;
public $liveStreams;
public $members;
public $membershipsLevels;
public $playlistItems;
public $playlists;
public $search;
public $sponsors;
public $subscriptions;
public $superChatEvents;
public $tests;
public $thirdPartyLinks;
public $thumbnails;
public $videoAbuseReportReasons;
public $videoCategories;
public $videos;
public $watermarks;
/**
* Constructs the internal representation of the YouTube service.
*
* @param Google_Client $client The client used to deliver requests.
* @param string $rootUrl The root URL used for requests to the service.
*/
public function __construct(Google_Client $client, $rootUrl = null)
{
parent::__construct($client);
$this->rootUrl = $rootUrl ?: 'https://youtube.googleapis.com/';
$this->servicePath = '';
$this->batchPath = 'batch';
$this->version = 'v3';
$this->serviceName = 'youtube';
$this->abuseReports = new Google_Service_YouTube_Resource_AbuseReports(
$this,
$this->serviceName,
'abuseReports',
array(
'methods' => array(
'insert' => array(
'path' => 'youtube/v3/abuseReports',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),
)
)
);
$this->activities = new Google_Service_YouTube_Resource_Activities(
$this,
$this->serviceName,
'activities',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/activities',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'home' => array(
'location' => 'query',
'type' => 'boolean',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'publishedBefore' => array(
'location' => 'query',
'type' => 'string',
),
'regionCode' => array(
'location' => 'query',
'type' => 'string',
),
'publishedAfter' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->captions = new Google_Service_YouTube_Resource_Captions(
$this,
$this->serviceName,
'captions',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/captions',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOf' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'download' => array(
'path' => 'youtube/v3/captions/{id}',
'httpMethod' => 'GET',
'parameters' => array(
'id' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'tfmt' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOf' => array(
'location' => 'query',
'type' => 'string',
),
'tlang' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'youtube/v3/captions',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOf' => array(
'location' => 'query',
'type' => 'string',
),
'sync' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'list' => array(
'path' => 'youtube/v3/captions',
'httpMethod' => 'GET',
'parameters' => array(
'videoId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'onBehalfOf' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'youtube/v3/captions',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOf' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'sync' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),
)
)
);
$this->channelBanners = new Google_Service_YouTube_Resource_ChannelBanners(
$this,
$this->serviceName,
'channelBanners',
array(
'methods' => array(
'insert' => array(
'path' => 'youtube/v3/channelBanners/insert',
'httpMethod' => 'POST',
'parameters' => array(
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->channelSections = new Google_Service_YouTube_Resource_ChannelSections(
$this,
$this->serviceName,
'channelSections',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/channelSections',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'youtube/v3/channelSections',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'youtube/v3/channelSections',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
),
),'update' => array(
'path' => 'youtube/v3/channelSections',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->channels = new Google_Service_YouTube_Resource_Channels(
$this,
$this->serviceName,
'channels',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/channels',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'mySubscribers' => array(
'location' => 'query',
'type' => 'boolean',
),
'forUsername' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'categoryId' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'managedByMe' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'update' => array(
'path' => 'youtube/v3/channels',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->commentThreads = new Google_Service_YouTube_Resource_CommentThreads(
$this,
$this->serviceName,
'commentThreads',
array(
'methods' => array(
'insert' => array(
'path' => 'youtube/v3/commentThreads',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),'list' => array(
'path' => 'youtube/v3/commentThreads',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'searchTerms' => array(
'location' => 'query',
'type' => 'string',
),
'videoId' => array(
'location' => 'query',
'type' => 'string',
),
'order' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'moderationStatus' => array(
'location' => 'query',
'type' => 'string',
),
'textFormat' => array(
'location' => 'query',
'type' => 'string',
),
'allThreadsRelatedToChannelId' => array(
'location' => 'query',
'type' => 'string',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
),
),'update' => array(
'path' => 'youtube/v3/commentThreads',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),
)
)
);
$this->comments = new Google_Service_YouTube_Resource_Comments(
$this,
$this->serviceName,
'comments',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/comments',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'insert' => array(
'path' => 'youtube/v3/comments',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),'list' => array(
'path' => 'youtube/v3/comments',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'textFormat' => array(
'location' => 'query',
'type' => 'string',
),
'parentId' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),'markAsSpam' => array(
'path' => 'youtube/v3/comments/markAsSpam',
'httpMethod' => 'POST',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),'setModerationStatus' => array(
'path' => 'youtube/v3/comments/setModerationStatus',
'httpMethod' => 'POST',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'moderationStatus' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'banAuthor' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'update' => array(
'path' => 'youtube/v3/comments',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),
)
)
);
$this->i18nLanguages = new Google_Service_YouTube_Resource_I18nLanguages(
$this,
$this->serviceName,
'i18nLanguages',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/i18nLanguages',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->i18nRegions = new Google_Service_YouTube_Resource_I18nRegions(
$this,
$this->serviceName,
'i18nRegions',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/i18nRegions',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->liveBroadcasts = new Google_Service_YouTube_Resource_LiveBroadcasts(
$this,
$this->serviceName,
'liveBroadcasts',
array(
'methods' => array(
'bind' => array(
'path' => 'youtube/v3/liveBroadcasts/bind',
'httpMethod' => 'POST',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'streamId' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'control' => array(
'path' => 'youtube/v3/liveBroadcasts/control',
'httpMethod' => 'POST',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'displaySlate' => array(
'location' => 'query',
'type' => 'boolean',
),
'offsetTimeMs' => array(
'location' => 'query',
'type' => 'string',
),
'walltime' => array(
'location' => 'query',
'type' => 'string',
),
),
),'delete' => array(
'path' => 'youtube/v3/liveBroadcasts',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'youtube/v3/liveBroadcasts',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'youtube/v3/liveBroadcasts',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'broadcastStatus' => array(
'location' => 'query',
'type' => 'string',
),
'broadcastType' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
),
),'transition' => array(
'path' => 'youtube/v3/liveBroadcasts/transition',
'httpMethod' => 'POST',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'broadcastStatus' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'youtube/v3/liveBroadcasts',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->liveChatBans = new Google_Service_YouTube_Resource_LiveChatBans(
$this,
$this->serviceName,
'liveChatBans',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/liveChat/bans',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'insert' => array(
'path' => 'youtube/v3/liveChat/bans',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),
)
)
);
$this->liveChatMessages = new Google_Service_YouTube_Resource_LiveChatMessages(
$this,
$this->serviceName,
'liveChatMessages',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/liveChat/messages',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'insert' => array(
'path' => 'youtube/v3/liveChat/messages',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),'list' => array(
'path' => 'youtube/v3/liveChat/messages',
'httpMethod' => 'GET',
'parameters' => array(
'liveChatId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'profileImageSize' => array(
'location' => 'query',
'type' => 'integer',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->liveChatModerators = new Google_Service_YouTube_Resource_LiveChatModerators(
$this,
$this->serviceName,
'liveChatModerators',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/liveChat/moderators',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'insert' => array(
'path' => 'youtube/v3/liveChat/moderators',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),'list' => array(
'path' => 'youtube/v3/liveChat/moderators',
'httpMethod' => 'GET',
'parameters' => array(
'liveChatId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->liveStreams = new Google_Service_YouTube_Resource_LiveStreams(
$this,
$this->serviceName,
'liveStreams',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/liveStreams',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'youtube/v3/liveStreams',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'youtube/v3/liveStreams',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'youtube/v3/liveStreams',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->members = new Google_Service_YouTube_Resource_Members(
$this,
$this->serviceName,
'members',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/members',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'mode' => array(
'location' => 'query',
'type' => 'string',
),
'filterByMemberChannelId' => array(
'location' => 'query',
'type' => 'string',
),
'hasAccessToLevel' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->membershipsLevels = new Google_Service_YouTube_Resource_MembershipsLevels(
$this,
$this->serviceName,
'membershipsLevels',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/membershipsLevels',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),
)
)
);
$this->playlistItems = new Google_Service_YouTube_Resource_PlaylistItems(
$this,
$this->serviceName,
'playlistItems',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/playlistItems',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'youtube/v3/playlistItems',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'youtube/v3/playlistItems',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'videoId' => array(
'location' => 'query',
'type' => 'string',
),
'playlistId' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
),
),'update' => array(
'path' => 'youtube/v3/playlistItems',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->playlists = new Google_Service_YouTube_Resource_Playlists(
$this,
$this->serviceName,
'playlists',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/playlists',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'youtube/v3/playlists',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'youtube/v3/playlists',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'youtube/v3/playlists',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->search = new Google_Service_YouTube_Resource_Search(
$this,
$this->serviceName,
'search',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/search',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'location' => array(
'location' => 'query',
'type' => 'string',
),
'regionCode' => array(
'location' => 'query',
'type' => 'string',
),
'publishedAfter' => array(
'location' => 'query',
'type' => 'string',
),
'channelType' => array(
'location' => 'query',
'type' => 'string',
),
'order' => array(
'location' => 'query',
'type' => 'string',
),
'videoDuration' => array(
'location' => 'query',
'type' => 'string',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'locationRadius' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'safeSearch' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'publishedBefore' => array(
'location' => 'query',
'type' => 'string',
),
'relatedToVideoId' => array(
'location' => 'query',
'type' => 'string',
),
'type' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'videoDefinition' => array(
'location' => 'query',
'type' => 'string',
),
'forContentOwner' => array(
'location' => 'query',
'type' => 'boolean',
),
'videoCaption' => array(
'location' => 'query',
'type' => 'string',
),
'relevanceLanguage' => array(
'location' => 'query',
'type' => 'string',
),
'videoSyndicated' => array(
'location' => 'query',
'type' => 'string',
),
'videoLicense' => array(
'location' => 'query',
'type' => 'string',
),
'forDeveloper' => array(
'location' => 'query',
'type' => 'boolean',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'videoDimension' => array(
'location' => 'query',
'type' => 'string',
),
'eventType' => array(
'location' => 'query',
'type' => 'string',
),
'q' => array(
'location' => 'query',
'type' => 'string',
),
'videoCategoryId' => array(
'location' => 'query',
'type' => 'string',
),
'topicId' => array(
'location' => 'query',
'type' => 'string',
),
'videoEmbeddable' => array(
'location' => 'query',
'type' => 'string',
),
'videoType' => array(
'location' => 'query',
'type' => 'string',
),
'forMine' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),
)
)
);
$this->sponsors = new Google_Service_YouTube_Resource_Sponsors(
$this,
$this->serviceName,
'sponsors',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/sponsors',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'filter' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->subscriptions = new Google_Service_YouTube_Resource_Subscriptions(
$this,
$this->serviceName,
'subscriptions',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/subscriptions',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'insert' => array(
'path' => 'youtube/v3/subscriptions',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),'list' => array(
'path' => 'youtube/v3/subscriptions',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'order' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'forChannelId' => array(
'location' => 'query',
'type' => 'string',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'mySubscribers' => array(
'location' => 'query',
'type' => 'boolean',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'myRecentSubscribers' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),
)
)
);
$this->superChatEvents = new Google_Service_YouTube_Resource_SuperChatEvents(
$this,
$this->serviceName,
'superChatEvents',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/superChatEvents',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->tests = new Google_Service_YouTube_Resource_Tests(
$this,
$this->serviceName,
'tests',
array(
'methods' => array(
'insert' => array(
'path' => 'youtube/v3/tests',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),
)
)
);
$this->thirdPartyLinks = new Google_Service_YouTube_Resource_ThirdPartyLinks(
$this,
$this->serviceName,
'thirdPartyLinks',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/thirdPartyLinks',
'httpMethod' => 'DELETE',
'parameters' => array(
'linkingToken' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'type' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
),
),'insert' => array(
'path' => 'youtube/v3/thirdPartyLinks',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),'list' => array(
'path' => 'youtube/v3/thirdPartyLinks',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'linkingToken' => array(
'location' => 'query',
'type' => 'string',
),
'type' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'youtube/v3/thirdPartyLinks',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),
)
)
);
$this->thumbnails = new Google_Service_YouTube_Resource_Thumbnails(
$this,
$this->serviceName,
'thumbnails',
array(
'methods' => array(
'set' => array(
'path' => 'youtube/v3/thumbnails/set',
'httpMethod' => 'POST',
'parameters' => array(
'videoId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->videoAbuseReportReasons = new Google_Service_YouTube_Resource_VideoAbuseReportReasons(
$this,
$this->serviceName,
'videoAbuseReportReasons',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/videoAbuseReportReasons',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->videoCategories = new Google_Service_YouTube_Resource_VideoCategories(
$this,
$this->serviceName,
'videoCategories',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/videoCategories',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'regionCode' => array(
'location' => 'query',
'type' => 'string',
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->videos = new Google_Service_YouTube_Resource_Videos(
$this,
$this->serviceName,
'videos',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/videos',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'getRating' => array(
'path' => 'youtube/v3/videos/getRating',
'httpMethod' => 'GET',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'youtube/v3/videos',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'stabilize' => array(
'location' => 'query',
'type' => 'boolean',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'autoLevels' => array(
'location' => 'query',
'type' => 'boolean',
),
'notifySubscribers' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'list' => array(
'path' => 'youtube/v3/videos',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'locale' => array(
'location' => 'query',
'type' => 'string',
),
'maxHeight' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'videoCategoryId' => array(
'location' => 'query',
'type' => 'string',
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
'myRating' => array(
'location' => 'query',
'type' => 'string',
),
'chart' => array(
'location' => 'query',
'type' => 'string',
),
'maxWidth' => array(
'location' => 'query',
'type' => 'integer',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'regionCode' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'rate' => array(
'path' => 'youtube/v3/videos/rate',
'httpMethod' => 'POST',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'rating' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'reportAbuse' => array(
'path' => 'youtube/v3/videos/reportAbuse',
'httpMethod' => 'POST',
'parameters' => array(
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'youtube/v3/videos',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->watermarks = new Google_Service_YouTube_Resource_Watermarks(
$this,
$this->serviceName,
'watermarks',
array(
'methods' => array(
'set' => array(
'path' => 'youtube/v3/watermarks/set',
'httpMethod' => 'POST',
'parameters' => array(
'channelId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'unset' => array(
'path' => 'youtube/v3/watermarks/unset',
'httpMethod' => 'POST',
'parameters' => array(
'channelId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
}
}
|
ftisunpar/BlueTape
|
vendor/google/apiclient-services/src/Google/Service/YouTube.php
|
PHP
|
gpl-3.0
| 70,431 |
define(['backbone'], function(Backbone){
var Role = Backbone.Model.extend({
idAttribute: 'UID',
url: '/api/role'
});
var role = new Role();
role.fetch();
return role;
});
|
gsmlg/oneblog
|
app/assets/javascript/app/role.js
|
JavaScript
|
gpl-3.0
| 207 |
# GNU Solfege - free ear training software
# Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2011,
# 2013 Tom Cato Amundsen
# Copyright (C) 2013 Jan Baumgart (Folkwang Universitaet der Kuenste)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
from __future__ import division
from gi.repository import GObject
from gi.repository import Gtk
from gi.repository import Gdk
from solfege import abstract
from solfege import abstract_solmisation_addon
from solfege import gu
from solfege import lessonfile
from solfege import mpd
from solfege.const import solmisation_syllables, solmisation_notenames
class Teacher(abstract.Teacher, abstract_solmisation_addon.SolmisationAddOnClass):
OK = 0
ERR_PICKY = 1
ERR_NO_ELEMS = 2
def __init__(self, exname):
abstract.Teacher.__init__(self, exname)
self.lessonfileclass = lessonfile.HeaderLessonfile
def play_question(self):
if self.q_status == self.QSTATUS_NO:
return
self.play(self.get_music_string())
def guess_answer(self, a):
assert self.q_status in [self.QSTATUS_NEW, self.QSTATUS_WRONG]
v = []
for idx in range(len(self.m_question)):
v.append(self.m_question[idx] == a[idx])
if not [x for x in v if x == 0]:
self.q_status = self.QSTATUS_SOLVED
self.maybe_auto_new_question()
return 1
else:
self.q_status = self.QSTATUS_WRONG
class RhythmViewer(Gtk.Frame):
def __init__(self, parent):
Gtk.Frame.__init__(self)
self.set_shadow_type(Gtk.ShadowType.IN)
self.g_parent = parent
self.g_box = Gtk.HBox()
self.g_box.show()
self.g_box.set_spacing(gu.PAD_SMALL)
self.g_box.set_border_width(gu.PAD)
self.add(self.g_box)
self.m_data = []
# the number of rhythm elements the viewer is supposed to show
self.m_num_notes = 0
self.g_face = None
self.__timeout = None
def set_num_notes(self, i):
self.m_num_notes = i
def clear(self):
for child in self.g_box.get_children():
child.destroy()
self.m_data = []
def create_holders(self):
"""
create those |__| that represents one beat
"""
if self.__timeout:
GObject.source_remove(self.__timeout)
self.clear()
for x in range(self.m_num_notes):
self.g_box.pack_start(gu.create_png_image('holder'), False, False, 0)
self.m_data = []
def clear_wrong_part(self):
"""When the user have answered the question, this method is used
to clear all but the first correct elements."""
# this assert is always true because if there is no rhythm element,
# then there is a rhythm holder ( |__| )
assert self.m_num_notes == len(self.g_parent.m_t.m_question)
self.g_face.destroy()
self.g_face = None
for n in range(self.m_num_notes):
if self.m_data[n] != self.g_parent.m_t.m_question[n]:
break
for x in range(n, len(self.g_box.get_children())):
self.g_box.get_children()[n].destroy()
self.m_data = self.m_data[:n]
for x in range(n, self.m_num_notes):
self.g_box.pack_start(gu.create_png_image('holder'), False, False, 0)
def add_rhythm_element(self, i):
assert len(self.m_data) <= self.m_num_notes
if len(self.g_box.get_children()) >= self.m_num_notes:
self.g_box.get_children()[self.m_num_notes-1].destroy()
vbox = Gtk.VBox()
vbox.show()
# im = gu.create_rhythm_image(const.RHYTHMS[i])
im = self.g_parent.solbutton(i, False)
vbox.pack_start(im, True, True, 0)
vbox.pack_start(gu.create_png_image('rhythm-wrong'), False, False, 0)
vbox.get_children()[-1].hide()
self.g_box.pack_start(vbox, False, False, 0)
self.g_box.reorder_child(vbox, len(self.m_data))
self.m_data.append(i)
def backspace(self):
if len(self.m_data) > 0:
if self.g_face:
self.g_box.get_children()[-2].destroy()
self.g_face.destroy()
self.g_face = None
self.g_box.get_children()[len(self.m_data)-1].destroy()
self.g_box.pack_start(gu.create_png_image('holder'), False, False, 0)
del self.m_data[-1]
def mark_wrong(self, idx):
"""
Mark the rhythm elements that was wrong by putting the content of
graphics/rhythm-wrong.png (normally a red line) under the element.
"""
self.g_box.get_children()[idx].get_children()[1].show()
def len(self):
"return the number of rhythm elements currently viewed"
return len(self.m_data)
def sad_face(self):
l = gu.HarmonicProgressionLabel(_("Wrong"))
l.show()
self.g_box.pack_start(l, False, False, 0)
self.g_face = Gtk.EventBox()
self.g_face.connect('button_press_event', self.on_sadface_event)
self.g_face.show()
im = Gtk.Image()
im.set_from_stock('solfege-sadface', Gtk.IconSize.LARGE_TOOLBAR)
im.show()
self.g_face.add(im)
self.g_box.pack_start(self.g_face, False, False, 0)
def happy_face(self):
l = gu.HarmonicProgressionLabel(_("Correct"))
l.show()
self.g_box.pack_start(l, False, False, 0)
self.g_face = Gtk.EventBox()
self.g_face.connect('button_press_event', self.on_happyface_event)
self.g_face.show()
im = Gtk.Image()
im.set_from_stock('solfege-happyface', Gtk.IconSize.LARGE_TOOLBAR)
im.show()
self.g_face.add(im)
self.g_box.pack_start(self.g_face, False, False, 0)
def on_happyface_event(self, obj, event):
if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 1:
self.g_parent.new_question()
def on_sadface_event(self, obj, event):
if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 1:
self.clear_wrong_part()
def flash(self, s):
self.clear()
l = Gtk.Label(label=s)
l.set_name("Feedback")
l.set_alignment(0.0, 0.5)
l.show()
self.g_box.pack_start(l, True, True, 0)
self.g_box.set_size_request(
max(l.size_request().width + gu.PAD * 2, self.g_box.size_request().width),
max(l.size_request().height + gu.PAD * 2, self.g_box.size_request().height))
self.__timeout = GObject.timeout_add(2000, self.unflash)
def unflash(self, *v):
self.__timeout = None
self.clear()
class Gui(abstract.Gui, abstract_solmisation_addon.SolmisationAddOnGuiClass):
lesson_heading = _("Solmisation Diktat")
def __init__(self, teacher):
abstract.Gui.__init__(self, teacher)
self.m_key_bindings = {'backspace_ak': self.on_backspace}
self.g_answer_box = Gtk.VBox()
self.answer_buttons = []
self.m_answer_buttons = {}
#-------
hbox = gu.bHBox(self.practise_box)
b = Gtk.Button(_("Play"))
b.show()
b.connect('clicked', self.play_users_answer)
hbox.pack_start(b, False, True, 0)
self.practise_box.pack_start(Gtk.HBox(), False, False,
padding=gu.PAD_SMALL)
self.g_rhythm_viewer = RhythmViewer(self)
self.g_rhythm_viewer.create_holders()
hbox.pack_start(self.g_rhythm_viewer, True, True, 0)
self.practise_box.pack_start(self.g_answer_box, False, False, 0)
# action area
self.std_buttons_add(
('new', self.new_question),
('repeat', self.repeat_question),
#('play_answer', self.play_users_answer),
('give_up', self.give_up),
('backspace', self.on_backspace))
self.practise_box.show_all()
##############
# config_box #
##############
self.add_select_elements_gui()
#--------
self.config_box.pack_start(Gtk.HBox(), False, False,
padding=gu.PAD_SMALL)
self.add_select_num_notes_gui()
#-----
self.config_box.pack_start(Gtk.HBox(), False, False,
padding=gu.PAD_SMALL)
#------
hbox = gu.bHBox(self.config_box, False)
hbox.set_spacing(gu.PAD_SMALL)
hbox.pack_start(Gtk.Label(_("Beats per minute:")), False, False, 0)
spin = gu.nSpinButton(self.m_exname, 'bpm',
Gtk.Adjustment(60, 20, 240, 1, 10))
hbox.pack_start(spin, False, False, 0)
hbox = gu.bHBox(self.config_box, False)
hbox.set_spacing(gu.PAD_SMALL)
hbox.pack_start(gu.nCheckButton(self.m_exname,
"show_first_note",
_("Show the first tone")), False, False, 0)
hbox.pack_start(gu.nCheckButton(self.m_exname,
"play_cadence",
_("Play cadence")), False, False, 0)
self._add_auto_new_question_gui(self.config_box)
self.config_box.show_all()
def solbutton(self, i, connect):
if i > len(solmisation_syllables) or i < 0:
btn = Gtk.Button()
else:
btn = Gtk.Button(solmisation_syllables[i])
btn.show()
if connect:
btn.connect('clicked', self.guess_element, i)
return btn
def select_element_cb(self, button, element_num):
super(Gui, self).select_element_cb(button, element_num)
self.m_answer_buttons[element_num].set_sensitive(button.get_active())
#self.update_answer_buttons()
def on_backspace(self, widget=None):
if self.m_t.q_status == self.QSTATUS_SOLVED:
return
self.g_rhythm_viewer.backspace()
if not self.g_rhythm_viewer.m_data:
self.g_backspace.set_sensitive(False)
def play_users_answer(self, widget):
if self.g_rhythm_viewer.m_data:
melody = ""
p = mpd.MusicalPitch()
for k in self.g_rhythm_viewer.m_data:
melody += " " + mpd.transpose_notename(solmisation_notenames[k], self.m_t.m_transp) + "4"
self.m_t.play(r"\staff{ \time 1000000/4 %s }" % melody)
def guess_element(self, sender, i):
if self.m_t.q_status == self.QSTATUS_NO:
self.g_rhythm_viewer.flash(_("Click 'New' to begin."))
return
if self.m_t.q_status == self.QSTATUS_SOLVED:
return
if self.g_rhythm_viewer.len() == len(self.m_t.m_question):
self.g_rhythm_viewer.clear_wrong_part()
self.g_backspace.set_sensitive(True)
self.g_rhythm_viewer.add_rhythm_element(i)
if self.g_rhythm_viewer.len() == len(self.m_t.m_question):
if self.m_t.guess_answer(self.g_rhythm_viewer.m_data):
self.g_rhythm_viewer.happy_face()
self.std_buttons_answer_correct()
else:
v = []
for idx in range(len(self.m_t.m_question)):
v.append(self.m_t.m_question[idx] == self.g_rhythm_viewer.m_data[idx])
for x in range(len(v)):
if not v[x]:
self.g_rhythm_viewer.mark_wrong(x)
self.g_rhythm_viewer.sad_face()
self.std_buttons_answer_wrong()
def new_question(self, widget=None):
g = self.m_t.new_question()
if g == self.m_t.OK:
self.g_first_rhythm_button.grab_focus()
self.g_rhythm_viewer.set_num_notes(self.get_int('num_notes'))
self.g_rhythm_viewer.create_holders()
self.std_buttons_new_question()
if self.m_t.get_bool('show_first_note'):
self.g_rhythm_viewer.add_rhythm_element(self.m_t.m_question[0])
try:
self.m_t.play_question()
except Exception, e:
if not self.standard_exception_handler(e, self.on_end_practise):
raise
return
elif g == self.m_t.ERR_PICKY:
self.g_rhythm_viewer.flash(_("You have to solve this question first."))
else:
assert g == self.m_t.ERR_NO_ELEMS
self.g_repeat.set_sensitive(False)
self.g_rhythm_viewer.flash(_("You have to configure this exercise properly"))
def repeat_question(self, *w):
self.m_t.play_question()
self.g_first_rhythm_button.grab_focus()
def update_answer_buttons(self):
"""
(Re)create the buttons needed to answer the questions.
We recreate the buttons for each lesson file because the
header may specify a different set of rhythm elements to use.
"""
for but in self.answer_buttons:
but.destroy()
self.answer_buttons = []
self.g_first_rhythm_button = None
gs = Gtk.SizeGroup(Gtk.SizeGroupMode.HORIZONTAL)
for i, v in enumerate((
[1, 4, -1, 8, 11, -1, 15, 18, 21, -1, 25, 28, -1, 32],
[0, 3, 6, 7, 10, 13, 14, 17, 20, 23, 24, 27, 30, 31, 34],
[2, 5, -1, 9, 12, -1, 16, 19, 22, -1, 26, 29, -1, 33])):
hbox = Gtk.HBox(True, 0)
for k in v:
b = self.solbutton(k, True)
gs.add_widget(b)
b.set_sensitive(False)
for n in self.m_t.m_P.header.solmisation_elements:
if k == n:
b.set_sensitive(True)
if not self.g_first_rhythm_button:
self.g_first_rhythm_button = b
hbox.pack_start(b, True, True, 0)
self.answer_buttons.append(b)
if k != -1:
self.m_answer_buttons[k] = b
spacing = Gtk.Alignment()
if i in (0, 2):
spacing.set_property('left-padding', 16)
spacing.set_property('right-padding', 16)
spacing.add(hbox)
self.g_answer_box.pack_start(spacing, True, True, 0)
spacing.show_all()
def on_start_practise(self):
# FIXME for now, we run in custom_mode all the time, so we don't
# have to add lots of lesson files. We can change this later.
#self.m_t.m_custom_mode = self.get_bool('gui/expert_mode')
self.m_t.m_custom_mode = True
super(Gui, self).on_start_practise()
if not self.m_t.m_P.header.solmisation_elements:
self.m_t.m_P.header.solmisation_elements = self.m_t.elements[:]
self.update_answer_buttons()
self.std_buttons_start_practise()
if self.m_t.m_custom_mode:
self.update_select_elements_buttons()
self.g_element_frame.show()
else:
self.g_element_frame.hide()
self.m_t.set_default_header_values()
if 'show_first_note' in self.m_t.m_P.header:
self.m_t.set_bool('show_first_note', self.m_t.m_P.header.show_first_note)
if 'play_cadence' in self.m_t.m_P.header:
self.m_t.set_bool('play_cadence', self.m_t.m_P.header.play_cadence)
self.g_rhythm_viewer.flash(_("Click 'New' to begin."))
def on_end_practise(self):
self.m_t.end_practise()
self.std_buttons_end_practise()
self.g_rhythm_viewer.create_holders()
def give_up(self, widget=None):
if self.m_t.q_status == self.QSTATUS_NO:
return
self.g_rhythm_viewer.clear()
for i in self.m_t.m_question:
self.g_rhythm_viewer.add_rhythm_element(i)
self.m_t.q_status = self.QSTATUS_SOLVED
self.std_buttons_give_up()
|
RannyeriDev/Solfege
|
solfege/exercises/solmisation.py
|
Python
|
gpl-3.0
| 16,440 |
package org.cgiar.ccafs.marlo.data.model;
// Generated May 17, 2017 3:36:29 PM by Hibernate Tools 4.3.1.Final
/**
* CustomParameter generated by hbm2java
*/
public class CustomParameter extends MarloAuditableEntity implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 9127311887995427567L;
private GlobalUnit crp;
private Parameter parameter;
private String value;
public CustomParameter() {
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
CustomParameter other = (CustomParameter) obj;
if (this.getId() == null) {
if (other.getId() != null) {
return false;
}
} else if (!this.getId().equals(other.getId())) {
return false;
}
return true;
}
public GlobalUnit getCrp() {
return crp;
}
public Parameter getParameter() {
return parameter;
}
public Long getParameterId() {
return this.getParameter().getId();
}
public String getValue() {
return value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.getId() == null) ? 0 : this.getId().hashCode());
return result;
}
public void setCrp(GlobalUnit crp) {
this.crp = crp;
}
public void setParameter(Parameter parameter) {
this.parameter = parameter;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return "CustomParameter [id=" + this.getId() + ", crp=" + crp + ", parameter=" + parameter + ", value=" + value
+ "]";
}
}
|
CCAFS/MARLO
|
marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/model/CustomParameter.java
|
Java
|
gpl-3.0
| 1,703 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2018-02-15 11:53
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sigad', '0033_auto_20180207_1028'),
]
operations = [
migrations.AddField(
model_name='documento',
name='capa',
field=models.BooleanField(choices=[(True, 'Sim'), (False, 'Nรฃo')], default=False, help_text='Sรณ um objeto pode ser capa de sua classe. Caso haja outro jรก selecionado, ele serรก desconsiderado.', verbose_name='Capa de sua Classe'),
),
migrations.AlterField(
model_name='classe',
name='template_classe',
field=models.IntegerField(choices=[(1, 'Listagem em Linha'), (2, 'Galeria Albuns'), (3, 'Pรกgina dos Parlamentares'), (4, 'Pรกgina individual de Parlamentar'), (5, 'Banco de Imagens'), (6, 'Galeria de รudios'), (7, 'Galeria de Vรญdeos'), (99, 'Documento Especรญfico')], default=1, verbose_name='Template para a Classe'),
),
]
|
cmjatai/cmj
|
cmj/sigad/migrations/0034_auto_20180215_0953.py
|
Python
|
gpl-3.0
| 1,088 |
#region Copyright & License Information
/*
* Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. For more
* information, see COPYING.
*/
#endregion
using System.Collections.Generic;
using System.Linq;
using OpenRA.Graphics;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Traits
{
public class GameSaveViewportManagerInfo : ITraitInfo
{
public object Create(ActorInitializer init) { return new GameSaveViewportManager(); }
}
public class GameSaveViewportManager : IWorldLoaded, IGameSaveTraitData
{
WorldRenderer worldRenderer;
void IWorldLoaded.WorldLoaded(World w, WorldRenderer wr) { worldRenderer = wr; }
List<MiniYamlNode> IGameSaveTraitData.IssueTraitData(Actor self)
{
// HACK: Store the viewport state for the skirmish observer on the first bot's trait
// TODO: This won't make sense for MP saves
var localPlayer = worldRenderer.World.LocalPlayer;
if ((localPlayer != null && localPlayer.PlayerActor != self) ||
(localPlayer == null && self.Owner != self.World.Players.FirstOrDefault(p => p.IsBot)))
return null;
var nodes = new List<MiniYamlNode>()
{
new MiniYamlNode("Viewport", FieldSaver.FormatValue(worldRenderer.Viewport.CenterPosition))
};
var renderPlayer = worldRenderer.World.RenderPlayer;
if (localPlayer == null && renderPlayer != null)
nodes.Add(new MiniYamlNode("RenderPlayer", FieldSaver.FormatValue(renderPlayer.PlayerActor.ActorID)));
return nodes;
}
void IGameSaveTraitData.ResolveTraitData(Actor self, List<MiniYamlNode> data)
{
var viewportNode = data.FirstOrDefault(n => n.Key == "Viewport");
if (viewportNode != null)
worldRenderer.Viewport.Center(FieldLoader.GetValue<WPos>("Viewport", viewportNode.Value.Value));
var renderPlayerNode = data.FirstOrDefault(n => n.Key == "RenderPlayer");
if (renderPlayerNode != null)
{
var renderPlayerActorID = FieldLoader.GetValue<uint>("RenderPlayer", renderPlayerNode.Value.Value);
worldRenderer.World.RenderPlayer = worldRenderer.World.GetActorById(renderPlayerActorID).Owner;
}
}
}
}
|
tysonliddell/OpenRA
|
OpenRA.Mods.Common/Traits/World/GameSaveViewportManager.cs
|
C#
|
gpl-3.0
| 2,338 |
/*
* Copyright (C) 2016 Salvatore D'Angelo
* This file is part of Mr Snake project.
* This file derive from the Mr Nom project developed by Mario Zechner for the Beginning Android
* Games book (chapter 6).
*
* Mr Snake is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Mr Snake is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License.
*/
package org.androidforfun.mrsnake.model;
import java.util.ArrayList;
import java.util.List;
/*
* This class represents the snake. A snake is composed by several pieces described by the class
* SnakeBody. In particular the first piece is the head represented by SnakeHead class and the last
* piece is the tail represented by SnakeTail class.
*
* @author Salvatore D'Angelo
*/
public class Snake {
// the list of pieces of the snake
private List<SnakeBody> parts = new ArrayList<>();
// the direction of the snake. Possible values are: UP, DOWN, LEFT and RIGHT.
private Direction direction;
// when the head of the snake turn this variable contains the direction of the neck. Its value
// depends on if the snake turned clockwise or anticlockwise. In the former case the possible
// values are: UP_RIGHT, RIGHT_DOWN, DOWN_LEFT, LEFT_UP. In the latter case the possible values
// are: UP_LEFT, LEFT_DOWN, DOWN_RIGHT, RIGHT_UP.
private Direction neckDirection;
public Snake() {
reset();
}
/*
* The snake is turned clockwise. The new direction and neck direction depends on the old
* direction.
* UP -> LEFT - UP_LEFT
* LEFT -> DOWN - LEFT_DOWN
* DOWN -> RIGHT - DOWN_RIGHT
* RIGHT -> UP - RIGHT_UP
*/
public void turnAntiClockwise() {
switch (direction) {
case UP:
neckDirection=Direction.UP_LEFT;
direction=Direction.LEFT;
break;
case LEFT:
neckDirection=Direction.LEFT_DOWN;
direction=Direction.DOWN;
break;
case DOWN:
neckDirection=Direction.DOWN_RIGHT;
direction=Direction.RIGHT;
break;
case RIGHT:
neckDirection=Direction.RIGHT_UP;
direction=Direction.UP;
break;
}
}
/*
* The snake is turned anticlockwise. The new direction and neck direction depends on the old
* direction.
* UP -> RIGHT - UP_RIGHT
* RIGHT -> DOWN - RIGHT_DOWN
* DOWN -> LEFT - DOWN_LEFT
* LEFT -> UP - LEFT_UP
*/
public void turnClockwise() {
switch (direction) {
case UP:
neckDirection=Direction.UP_RIGHT;
direction=Direction.RIGHT;
break;
case RIGHT:
neckDirection=Direction.RIGHT_DOWN;
direction=Direction.DOWN;
break;
case DOWN:
neckDirection=Direction.DOWN_LEFT;
direction=Direction.LEFT;
break;
case LEFT:
neckDirection=Direction.LEFT_UP;
direction=Direction.UP;
break;
}
}
/*
* When the snake eat a fruti its size must be increased by 1 piece. This piece is added in the
* middle so the tail should shift by a position. The direction of this shift depends on the
* current direction of the tail
*/
public void eat() {
// add a new piece to the snake
SnakeTail tail = (SnakeTail) parts.get(parts.size()-1);
parts.add(parts.size()-1, new SnakeBody(tail.getX(), tail.getY(), tail.direction));
// shift the tail by 1 position with a direction that depends on its current position.
switch (tail.direction) {
case UP:
tail.moveDown();
break;
case DOWN:
tail.moveUp();
break;
case LEFT:
tail.moveRight();
break;
case RIGHT:
tail.moveLeft();
break;
}
}
/*
* Advance the snake on the grid by a position that depends on the current snake direction.
*/
public void advance() {
int last = parts.size() - 1;
SnakeHead head = (SnakeHead) parts.get(0);
SnakeBody neck = parts.get(1);
SnakeTail tail = (SnakeTail) parts.get(last);
// move all the snake pieces but head, one step forward
for(int i = last; i > 0; i--) {
SnakeBody before = parts.get(i-1);
SnakeBody part = parts.get(i);
part.setX(before.getX());
part.setY(before.getY());
part.direction=before.direction;
}
// move the head towards the snake direction.
head.direction=direction;
switch (direction) {
case UP:
head.moveUp();
break;
case LEFT:
head.moveLeft();
break;
case DOWN:
head.moveDown();
break;
case RIGHT:
head.moveRight();
break;
}
// determine the neck direction
switch (neckDirection) {
case UP_RIGHT:
case LEFT_UP:
case DOWN_LEFT:
case RIGHT_DOWN:
case LEFT_DOWN:
case UP_LEFT:
case DOWN_RIGHT:
case RIGHT_UP:
neck.direction=neckDirection;
neckDirection=Direction.UP;
break;
}
// determine the tail direction
switch (tail.direction) {
case DOWN_LEFT:
case UP_LEFT:
tail.direction=Direction.LEFT;
break;
case LEFT_UP:
case RIGHT_UP:
tail.direction=Direction.UP;
break;
case RIGHT_DOWN:
case LEFT_DOWN:
tail.direction=Direction.DOWN;
break;
case UP_RIGHT:
case DOWN_RIGHT:
tail.direction=Direction.RIGHT;
break;
}
}
/*
* Initializes the snake with a head, a tail and 2 pieces in the middle.
* Direction is UP.
*/
public void reset() {
direction = Direction.UP;
neckDirection = Direction.UP;
parts.clear();
parts.add(new SnakeHead(5, 6, Direction.UP));
parts.add(new SnakeBody(5, 7, Direction.UP));
parts.add(new SnakeBody(5, 8, Direction.UP));
parts.add(new SnakeTail(5, 9, Direction.UP));
}
/*
* Check if snake eat itself.
*/
public boolean checkBitten() {
int len = parts.size();
SnakeBody head = parts.get(0);
for(int i = 1; i < len; i++) {
SnakeBody part = parts.get(i);
if (head.collide(part))
return true;
}
return false;
}
public SnakeHead getSnakeHead() {
return (SnakeHead) parts.get(0);
}
public SnakeBody getSnakeBody(int i) {
return parts.get(i);
}
public int getLength() {
return parts.size();
}
}
|
sasadangelo/MrSnake
|
app/src/main/java/org/androidforfun/mrsnake/model/Snake.java
|
Java
|
gpl-3.0
| 7,705 |
"use strict";
var TransitionHookPhase;
(function (TransitionHookPhase) {
TransitionHookPhase[TransitionHookPhase["CREATE"] = 0] = "CREATE";
TransitionHookPhase[TransitionHookPhase["BEFORE"] = 1] = "BEFORE";
TransitionHookPhase[TransitionHookPhase["RUN"] = 2] = "RUN";
TransitionHookPhase[TransitionHookPhase["SUCCESS"] = 3] = "SUCCESS";
TransitionHookPhase[TransitionHookPhase["ERROR"] = 4] = "ERROR";
})(TransitionHookPhase = exports.TransitionHookPhase || (exports.TransitionHookPhase = {}));
var TransitionHookScope;
(function (TransitionHookScope) {
TransitionHookScope[TransitionHookScope["TRANSITION"] = 0] = "TRANSITION";
TransitionHookScope[TransitionHookScope["STATE"] = 1] = "STATE";
})(TransitionHookScope = exports.TransitionHookScope || (exports.TransitionHookScope = {}));
//# sourceMappingURL=interface.js.map
|
DigitalCookiesGroup/SWEDesigner
|
Front-End/node_modules/@uirouter/core/lib/transition/interface.js
|
JavaScript
|
gpl-3.0
| 852 |
/**
* Copyright Universitรฉ Lyon 1 / Universitรฉ Lyon 2 (2009,2010)
*
* <ithaca@liris.cnrs.fr>
*
* This file is part of Visu.
*
* This software is a computer program whose purpose is to provide an
* enriched videoconference application.
*
* Visu is a free software subjected to a double license.
* You can redistribute it and/or modify since you respect the terms of either
* (at least one of the both license) :
* - the GNU Lesser General Public License as published by the Free Software Foundation;
* either version 3 of the License, or any later version.
* - the CeCILL-C as published by CeCILL; either version 2 of the License, or any later version.
*
* -- GNU LGPL license
*
* Visu is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Visu is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Visu. If not, see <http://www.gnu.org/licenses/>.
*
* -- CeCILL-C license
*
* This software is governed by the CeCILL-C license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/ or redistribute the software under the terms of the CeCILL-C
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL-C license and that you accept its terms.
*
* -- End of licenses
*/
package com.lyon2.utils;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
public class UserAccountHelpers
{
public static String key (int nb)
{
Random rand = new Random();
String password = new String();
String dico = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
int size = dico.length();
for(int i = 0; i < nb ; ++i)
{
password += dico.charAt( rand.nextInt(size) );
}
return password;
}
public static String md5(String str)
{
String hash = new String();
try
{
String s="test";
MessageDigest m=MessageDigest.getInstance("MD5");
m.update(s.getBytes(),0,s.length());
hash = new BigInteger( 1,m.digest()).toString(16);
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
return hash;
}
}
|
ithaca/visu
|
VisuServeur/visu/src/com/lyon2/utils/UserAccountHelpers.java
|
Java
|
gpl-3.0
| 3,804 |
/*
* Copyright (c) 2019. Bernard Bou <1313ou@gmail.com>
*/
package treebolic.glue.component;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.TypedValue;
import android.view.Display;
import android.view.WindowManager;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.content.res.ResourcesCompat;
import androidx.core.graphics.drawable.DrawableCompat;
/**
* Utilities
*
* @author Bernard Bou
*/
@SuppressWarnings("WeakerAccess")
public class Utils
{
@NonNull
static public int[] fetchColors(@NonNull final Context context, @NonNull int... attrs)
{
final TypedValue typedValue = new TypedValue();
final TypedArray array = context.obtainStyledAttributes(typedValue.data, attrs);
final int[] colors = new int[attrs.length];
for (int i = 0; i < attrs.length; i++)
{
colors[i] = array.getColor(i, 0);
}
array.recycle();
return colors;
}
/*
* Get color from theme
*
* @param context context
* @param styleId style id (ex: R.style.MyTheme)
* @param colorAttrIds attr ids (ex: R.attr.editTextColor)
* @return colors
*/
/*
@SuppressWarnings("WeakerAccess")
@NonNull
static public int[] fetchColorsFromStyle(@NonNull final Context context, @NonNull int styleId, @NonNull int... colorAttrIds)
{
final TypedArray array = context.obtainStyledAttributes(styleId, colorAttrIds);
final int[] colors = new int[colorAttrIds.length];
for (int i = 0; i < colorAttrIds.length; i++)
{
colors[i] = array.getColor(i, 0);
}
array.recycle();
return colors;
}
*/
@NonNull
static public Integer[] fetchColorsNullable(@NonNull final Context context, @NonNull @SuppressWarnings("SameParameterValue") int... attrs)
{
final TypedValue typedValue = new TypedValue();
final TypedArray array = context.obtainStyledAttributes(typedValue.data, attrs);
final Integer[] colors = new Integer[attrs.length];
for (int i = 0; i < attrs.length; i++)
{
colors[i] = array.hasValue(i) ? array.getColor(i, 0) : null;
}
array.recycle();
return colors;
}
/*
static public int fetchColor(final Context context, int attr)
{
final TypedValue typedValue = new TypedValue();
final Resources.Theme theme = context.getTheme();
theme.resolveAttribute(attr, typedValue, true);
return typedValue.data;
}
*/
/*
static public Integer fetchColorNullable(final Context context, int attr)
{
final TypedValue typedValue = new TypedValue();
final Resources.Theme theme = context.getTheme();
theme.resolveAttribute(attr, typedValue, true);
return typedValue.type == TypedValue.TYPE_NULL ? null : typedValue.data;
}
*/
static public int getColor(@NonNull final Context context, @ColorRes @SuppressWarnings("SameParameterValue") int resId)
{
return ContextCompat.getColor(context, resId);
}
/**
* Get drawable
*
* @param context context
* @param resId drawable id
* @return drawable
*/
static public Drawable getDrawable(@NonNull final Context context, @DrawableRes int resId)
{
return ResourcesCompat.getDrawable(context.getResources(), resId, context.getTheme());
}
/**
* Get drawables
*
* @param context context
* @param resIds drawable ids
* @return drawables
*/
@NonNull
static public Drawable[] getDrawables(@NonNull final Context context, @NonNull @SuppressWarnings("SameParameterValue") int... resIds)
{
final Resources resources = context.getResources();
final Resources.Theme theme = context.getTheme();
Drawable[] drawables = new Drawable[resIds.length];
for (int i = 0; i < resIds.length; i++)
{
drawables[i] = ResourcesCompat.getDrawable(resources, resIds[i], theme);
}
return drawables;
}
static public void tint(@NonNull final Drawable drawable, @ColorInt int iconTint)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
drawable.setTint(iconTint);
}
else
{
DrawableCompat.setTint(DrawableCompat.wrap(drawable), iconTint);
}
}
static public int screenWidth(@NonNull final Context context)
{
final WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
assert wm != null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
{
final Rect bounds = wm.getCurrentWindowMetrics().getBounds();
return bounds.width();
}
else
{
final Display display = wm.getDefaultDisplay();
final Point size = new Point();
display.getSize(size);
// int height = size.y;
return size.x;
}
}
static public Point screenSize(@NonNull final Context context)
{
final WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
assert wm != null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
{
final Rect bounds = wm.getCurrentWindowMetrics().getBounds();
return new Point(bounds.width(),bounds.height());
}
else
{
final Display display = wm.getDefaultDisplay();
final Point size = new Point();
display.getSize(size);
return size;
}
}
public static String join(@NonNull final CharSequence delim, @Nullable final CharSequence[] strs)
{
if (strs == null)
{
return "";
}
StringBuilder sb = new StringBuilder();
boolean first = true;
for (CharSequence str : strs)
{
if (str == null || str.length() == 0)
{
continue;
}
if (first)
{
first = false;
}
else
{
sb.append(delim);
}
sb.append(str);
}
return sb.toString();
}
}
|
1313ou/TreebolicLib
|
treebolicGlue/src/main/java/treebolic/glue/component/Utils.java
|
Java
|
gpl-3.0
| 5,780 |
class CreatePermissions < ActiveRecord::Migration
def self.up
create_table :permissions do |t|
t.integer :role_id
t.integer :user_id
t.timestamps
end
end
def self.down
drop_table :permissions
end
end
|
alfrenovsky/Digesto
|
db/migrate/20110908115724_create_permissions.rb
|
Ruby
|
gpl-3.0
| 240 |
/* -*- mia-c++ -*-
*
* This file is part of MIA - a toolbox for medical image analysis
* Copyright (c) Leipzig, Madrid 1999-2017 Gert Wollny
*
* MIA is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MIA; if not, see <http://www.gnu.org/licenses/>.
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <mia/core/histogram.hh>
#include <mia/core/cmdlineparser.hh>
#include <mia/core/cmeans.hh>
#include <mia/2d.hh>
#include <memory>
#include <vector>
#include <numeric>
using namespace mia;
using namespace std;
typedef vector<C2DFImage> C2DFImageVec;
const SProgramDescription g_description = {
{pdi_group, "Analysis, filtering, combining, and segmentation of 2D images"},
{pdi_short, "Run a c-means segmentation of a 2D image."},
{
pdi_description, "This program runs the segmentation of a 2D image by applying "
"a localized c-means approach that helps to overcome intensity inhomogeneities "
"in the image. The approach evaluates a global c-means clustering, and then "
"separates the image into overlapping regions where more c-means iterations "
"are run only including the locally present classes, i.e. the classes that "
"relatively contain more pixels than a given threshold. This program implements "
"a 2D prototype of the algorithm described in: "
"[Dunmore CJ, Wollny G, Skinner MM. (2018) MIA-Clustering: a novel method "
"for segmentation of paleontological material. PeerJ 6:e4374.](https://doi.org/10.7717/peerj.4374)"
},
{
pdi_example_descr, "Run the segmentation on image test.png using three classes, "
"local regions of 40 pixels (grid width 20 pixels), and a class ignore threshold of 0.01."
},
{pdi_example_code, "-i test.png -o label.png -n 3 -g 20 -t 0.01"}
};
class FRunHistogram : public TFilter<void>
{
public:
template <typename T>
void operator()(const T2DImage<T>& image);
CSparseHistogram::Compressed get_histogram() const;
private:
CSparseHistogram m_sparse_histogram;
};
class FLocalCMeans: public TFilter<void>
{
public:
typedef map<int, CMeans::DVector> Probmap;
FLocalCMeans(float epsilon, const vector<double>& global_class_centers,
const C2DBounds& start, const C2DBounds& end,
const Probmap& global_probmap,
float rel_cluster_threshold,
const map<int, unsigned>& segmap,
vector<C2DFDatafield>& prob_buffer);
template <typename T>
void operator()(const T2DImage<T>& image);
private:
const float m_epsilon;
const vector<double>& m_global_class_centers;
const C2DBounds m_start;
const C2DBounds m_end;
const Probmap& m_global_probmap;
const float m_rel_cluster_threshold;
const map<int, unsigned>& m_segmap;
vector<C2DFDatafield>& m_prob_buffer;
size_t m_count;
};
class FCrispSeg: public TFilter<P2DImage>
{
public:
FCrispSeg(const map<int, unsigned>& segmap):
m_segmap(segmap)
{
}
template <typename T>
P2DImage operator()(const T2DImage<T>& image) const
{
P2DImage out_image = make_shared<C2DUBImage>(image.get_size());
C2DUBImage *help = static_cast<C2DUBImage *>(out_image.get());
transform(image.begin(), image.end(), help->begin(),
[this](T x) {
return m_segmap.at(x);
});
return out_image;
}
private:
const map<int, unsigned>& m_segmap;
};
int do_main(int argc, char *argv[])
{
string in_filename;
string out_filename;
string out_filename2;
string cls_filename;
string debug_filename;
int blocksize = 15;
double rel_cluster_threshold = 0.02;
float cmeans_epsilon = 0.0001;
CMeans::PInitializer class_center_initializer;
const auto& image2dio = C2DImageIOPluginHandler::instance();
CCmdOptionList opts(g_description);
opts.set_group("File-IO");
opts.add(make_opt( in_filename, "in-file", 'i', "image to be segmented",
CCmdOptionFlags::required_input, &image2dio ));
opts.add(make_opt( out_filename, "out-file", 'o', "class label image based on "
"merging local labels", CCmdOptionFlags::output, &image2dio ));
opts.add(make_opt( out_filename2, "out-global-crisp", 'G', "class label image based on "
"global segmentation", CCmdOptionFlags::output, &image2dio ));
opts.add(make_opt( cls_filename, "class-prob", 'C', "class probability image file, filetype "
"must support floating point multi-frame images", CCmdOptionFlags::output, &image2dio ));
opts.set_group("Parameters");
opts.add(make_opt( blocksize, EParameterBounds::bf_min_closed, {3},
"grid-spacing", 'g', "Spacing of the grid used to modulate "
"the intensity inhomogeneities"));
opts.add(make_opt( class_center_initializer, "kmeans:nc=3",
"cmeans", 'c', "c-means initializer"));
opts.add(make_opt( cmeans_epsilon, EParameterBounds::bf_min_open,
{0.0}, "c-means-epsilon", 'e', "c-means breaking condition for update tolerance"));
opts.add(make_opt( rel_cluster_threshold, EParameterBounds::bf_min_closed | EParameterBounds::bf_max_open,
{0.0, 1.0}, "relative-cluster-threshold", 't', "threshhold to ignore classes when initializing"
" the local cmeans from the global one."));
if (opts.parse(argc, argv) != CCmdOptionList::hr_no)
return EXIT_SUCCESS;
if (out_filename.empty() && out_filename2.empty()) {
throw invalid_argument("You must specify at least one output file");
}
auto in_image = load_image2d(in_filename);
FRunHistogram global_histogram;
mia::accumulate(global_histogram, *in_image);
CMeans globale_cmeans(cmeans_epsilon, class_center_initializer);
auto gh = global_histogram.get_histogram();
CMeans::DVector global_class_centers;
auto global_sparse_probmap = globale_cmeans.run(gh, global_class_centers, false);
cvinfo() << "Histogram range: [" << gh[0].first << ", " << gh[gh.size() - 1].first << "]\n";
cvinfo() << "Global class centers: " << global_class_centers << "\n";
cvinfo() << "Probmap size = " << global_sparse_probmap.size()
<< " weight number " << global_sparse_probmap[0].second.size() << "\n";
auto n_classes = global_class_centers.size();
// need the normalized class centers
map<int, unsigned> segmap;
for_each(global_sparse_probmap.begin(), global_sparse_probmap.end(),
[&segmap](const CMeans::SparseProbmap::value_type & x) {
int c = 0;
float max_prob = 0.0f;
for (unsigned i = 0; i < x.second.size(); ++i) {
auto f = x.second[i];
if (f > max_prob) {
max_prob = f;
c = i;
};
}
segmap[x.first] = c;
});
FLocalCMeans::Probmap global_probmap;
for (auto k : global_sparse_probmap) {
global_probmap[k.first] = k.second;
};
if (!out_filename2.empty()) {
FCrispSeg cs(segmap);
auto crisp_global_seg = mia::filter(cs, *in_image);
if (!save_image (out_filename2, crisp_global_seg)) {
cverr() << "Unable to save to '" << out_filename2 << "'\n";
}
}
int nx = (in_image->get_size().x + blocksize - 1) / blocksize;
int ny = (in_image->get_size().y + blocksize - 1) / blocksize;
int start_x = (nx * blocksize - in_image->get_size().x) / 2;
int start_y = (ny * blocksize - in_image->get_size().y) / 2;
vector<C2DFDatafield> prob_buffer(global_class_centers.size());
for (unsigned i = 0; i < global_class_centers.size(); ++i)
prob_buffer[i] = C2DFDatafield(in_image->get_size());
for (int iy_base = start_y; iy_base < (int)in_image->get_size().y; iy_base += blocksize) {
unsigned iy = iy_base < 0 ? 0 : iy_base;
unsigned iy_end = iy_base + 2 * blocksize;
if (iy_end > in_image->get_size().y)
iy_end = in_image->get_size().y;
for (int ix_base = start_x; ix_base < (int)in_image->get_size().x; ix_base += blocksize) {
unsigned ix = ix_base < 0 ? 0 : ix_base;
unsigned ix_end = ix_base + 2 * blocksize;
if (ix_end > in_image->get_size().x)
ix_end = in_image->get_size().x;
FLocalCMeans lcm(cmeans_epsilon, global_class_centers,
C2DBounds(ix, iy), C2DBounds(ix_end, iy_end),
global_probmap,
rel_cluster_threshold,
segmap,
prob_buffer);
mia::accumulate(lcm, *in_image);
}
}
// save the prob images ?
// normalize probability images
C2DFImage sum(prob_buffer[0]);
for (unsigned c = 1; c < n_classes; ++c) {
transform(sum.begin(), sum.end(), prob_buffer[c].begin(), sum.begin(),
[](float x, float y) {
return x + y;
});
}
for (unsigned c = 0; c < n_classes; ++c) {
transform(sum.begin(), sum.end(), prob_buffer[c].begin(), prob_buffer[c].begin(),
[](float s, float p) {
return p / s;
});
}
if (!cls_filename.empty()) {
C2DImageIOPluginHandler::Instance::Data classes;
for (unsigned c = 0; c < n_classes; ++c)
classes.push_back(make_shared<C2DFImage>(prob_buffer[c]));
if (!C2DImageIOPluginHandler::instance().save(cls_filename, classes))
cverr() << "Error writing class images to '" << cls_filename << "'\n";
}
// now for each pixel we have a probability sume that should take inhomogeinities
// into account
C2DUBImage out_image(in_image->get_size(), *in_image);
fill(out_image.begin(), out_image.end(), 0);
for (unsigned c = 1; c < n_classes; ++c) {
auto iout = out_image.begin();
auto eout = out_image.end();
auto itest = prob_buffer[0].begin();
auto iprob = prob_buffer[c].begin();
while ( iout != eout ) {
if (*itest < *iprob) {
*itest = *iprob;
*iout = c;
}
++iout;
++itest;
++iprob;
}
}
return save_image(out_filename, out_image) ? EXIT_SUCCESS : EXIT_FAILURE;
}
template <typename T>
void FRunHistogram::operator()(const T2DImage<T>& image)
{
m_sparse_histogram(image.begin(), image.end());
}
CSparseHistogram::Compressed FRunHistogram::get_histogram() const
{
return m_sparse_histogram.get_compressed_histogram();
}
FLocalCMeans::FLocalCMeans(float epsilon, const vector<double>& global_class_centers,
const C2DBounds& start, const C2DBounds& end,
const Probmap& global_probmap,
float rel_cluster_threshold,
const map<int, unsigned>& segmap,
vector<C2DFDatafield>& prob_buffer):
m_epsilon(epsilon),
m_global_class_centers(global_class_centers),
m_start(start),
m_end(end),
m_global_probmap(global_probmap),
m_rel_cluster_threshold(rel_cluster_threshold),
m_segmap(segmap),
m_prob_buffer(prob_buffer),
m_count((m_end - m_start).product())
{
}
template <typename T>
void FLocalCMeans::operator()(const T2DImage<T>& image)
{
cvmsg() << "Start subrange [" << m_start << "]-[" << m_end << "]\n";
// obtain the histogram for the current patch
CSparseHistogram histogram;
histogram(image.begin_range(m_start, m_end),
image.end_range(m_start, m_end));
auto ch = histogram.get_compressed_histogram();
// calculate the class avaliability in the patch
vector<double> partition(m_global_class_centers.size());
for (auto idx : ch) {
const double n = idx.second;
auto v = m_global_probmap.at(idx.first);
transform(partition.begin(), partition.end(), v.begin(),
partition.begin(), [n](double p, double value) {
return p + n * value;
});
}
auto part_thresh = std::accumulate(partition.begin(), partition.end(), 0.0) * m_rel_cluster_threshold;
cvinfo() << "Partition = " << partition << "\n";
// select the classes that should be used further on
vector<double> retained_class_centers;
vector<unsigned> used_classed;
for (unsigned i = 0; i < partition.size(); ++i) {
if (partition[i] >= part_thresh) {
retained_class_centers.push_back(m_global_class_centers[i]);
used_classed.push_back(i);
}
}
// prepare linear interpolation summing
auto center = C2DFVector((m_end + m_start)) / 2.0f;
auto max_distance = C2DFVector((m_end - m_start)) / 2.0f;
if (retained_class_centers.size() > 1) {
ostringstream cci_descr;
cci_descr << "predefined:cc=[" << retained_class_centers << "]";
cvinfo() << "Initializing local cmeans with '" << cci_descr.str()
<< " for retained classes " << used_classed << "'\n";
auto cci = CMeansInitializerPluginHandler::instance().produce(cci_descr.str());
// remove data that was globally assigned to now unused class
CSparseHistogram::Compressed cleaned_histogram;
cleaned_histogram.reserve(ch.size());
// copy used intensities
for (auto c : used_classed) {
for (auto ich : ch) {
if ( m_segmap.at(ich.first) == c) {
cleaned_histogram.push_back(ich);
}
}
}
// evluate the local c-means classification
CMeans local_cmeans(m_epsilon, cci);
auto local_map = local_cmeans.run(cleaned_histogram, retained_class_centers);
// create a lookup map intensity -> probability vector
map<unsigned short, CMeans::DVector> mapper;
for (auto i : local_map) {
mapper[i.first] = i.second;
}
// now add the new probabilities to the global maps.
auto ii = image.begin_range(m_start, m_end);
auto ie = image.end_range(m_start, m_end);
while (ii != ie) {
auto probs = mapper.find(*ii);
auto delta = (C2DFVector(ii.pos()) - center) / max_distance;
float lin_scale = (1.0 - std::fabs(delta.x)) * (1.0 - std::fabs(delta.y));
if (probs != mapper.end()) {
for (unsigned c = 0; c < used_classed.size(); ++c) {
m_prob_buffer[used_classed[c]](ii.pos()) += lin_scale * probs->second[c];
}
} else { // not in local map: retain global probabilities
auto v = m_global_probmap.at(*ii);
for (unsigned c = 0; c < v.size(); ++c) {
m_prob_buffer[c](ii.pos()) += lin_scale * v[c];
}
}
++ii;
}
} else { // only one class retained, add 1.0 to probabilities, linearly smoothed
cvdebug() << "Only one class used:" << used_classed[0] << "\n";
auto ii = m_prob_buffer[used_classed[0]].begin_range(m_start, m_end);
auto ie = m_prob_buffer[used_classed[0]].end_range(m_start, m_end);
while (ii != ie) {
auto delta = (C2DFVector(ii.pos()) - center) / max_distance;
*ii += (1.0 - std::fabs(delta.x)) * (1.0 - std::fabs(delta.y)); ;
++ii;
}
}
cvmsg() << "Done subrange [" << m_start << "]-[" << m_end << "]\n";
}
#include <mia/internal/main.hh>
MIA_MAIN(do_main);
|
gerddie/mia
|
src/2dsegment-local-cmeans.cc
|
C++
|
gpl-3.0
| 17,671 |
// sparkly effect for xmas stuff
// a blue icey glow with occasional sparkles
// sparkles
led.led_rnd(0, led.leds);
led.color(255, 255, 255);
led.fade_mode(2);
led.fade_speed(20);
led.draw();
//blue glow
led.repeat_begin_rnd(0,100);
led.led_rnd(0, led.leds);
led.color_rnd(0, 0, 0, 0, 100, 250);
led.fade_mode(1);
led.fade_speed(1);
led.draw();
led.delay(0);
led.repeat_end();
|
psy0rz/ledanim
|
web/repo/xmas/sparkle.js
|
JavaScript
|
gpl-3.0
| 390 |
<?php
/**
* Ini manipulation
*/
class Ini {
var $m_ini;
function Ini() {
$this->m_ini = Array();
}
function load($fn) {
$this->m_ini = Array();
$fh = fopen($fn, "r");
if (!$fh)
return false;
$section = "";
while (($line = fgets($fh)) !== false) {
$line = trim($line);
// ignore blank lines
if (strlen($line) == 0)
continue;
if (substr($line, 0, 1) == "[") {
if (substr($line, -1) != "]") {
fclose($fh);
return false;
}
$section = substr($line, 1, -1);
continue;
}
list($name, $value) = explode("=", $line, 2);
$name = trim($name);
// TODO: comma separated values?
$value = trim($value);
if (!$this->add($section, $name, $value)) {
fclose($fh);
return false;
}
}
fclose($fh);
return true;
}
function validate($section, $name) {
return $section != "" && $name != "";
}
function get($section, $name) {
if (!$this->validate($section, $name))
return false;
return $this->m_ini[$section][$name];
}
function set($section, $name, $value) {
if (!$this->validate($section, $name))
return false;
$this->m_ini[$section][$name] = $value;
return true;
}
function add($section, $name, $value) {
if (!$this->validate($section, $name))
return false;
if (isset($this->m_ini[$section][$name])) {
if (!is_array($this->m_ini[$section][$name])) {
$ovalue = $this->m_ini[$section][$name];
$this->m_ini[$section][$name] = array();
$this->m_ini[$section][$name][] = $ovalue;
}
$this->m_ini[$section][$name][] = $value;
} else {
$this->m_ini[$section][$name] = $value;
}
return true;
}
function dump($fn) {
$fh = fopen($fn, "w");
if (!$fh)
return false;
foreach (array_keys($this->m_ini) as $section) {
fwrite($fh, "[$section]\n");
foreach (array_keys($this->m_ini[$section]) as $name) {
if (is_array($this->m_ini[$section][$name])) {
foreach ($this->m_ini[$section][$name] as $value)
fwrite($fh, "$name=$value\n");
} else {
fwrite($fh, "$name=" . $this->m_ini[$section][$name] . "\n");
}
}
fwrite($fh, "\n");
}
fclose($fh);
}
function sections() {
return array_keys($this->m_ini);
}
function deleteSection($section) {
if ($section != "")
unset($this->m_ini[$section]);
}
}
/*
$ini = new Ini();
$ini->load("data/sip.conf");
var_dump($ini->get("general", "allow"));
var_dump($ini->get("general", "bindport"));
$ini->dump("sip.conf");
*/
?>
|
xiaosuo/voipconf
|
lib/ini.php
|
PHP
|
gpl-3.0
| 2,462 |
/*
* This file is part of CRISIS, an economics simulator.
*
* Copyright (C) 2015 AITIA International, Inc.
* Copyright (C) 2015 John Kieran Phillips
* Copyright (C) 2015 Ariel Y. Hoffman
*
* CRISIS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CRISIS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CRISIS. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.crisis_economics.abm.dashboard;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map.Entry;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import org.apache.log4j.Logger;
import ai.aitia.meme.gui.Wizard;
import ai.aitia.meme.gui.Wizard.Button;
import ai.aitia.meme.gui.Wizard.IWizardPage;
import aurelienribon.ui.css.Style;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import eu.crisis_economics.utilities.Pair;
/**
* @author Tamรกs Mรกhr
*
*/
public class Page_Model implements IWizardPage, IIconsInHeader {
private static final String CSS_CLASS_COMMON_PANEL = ".commonPanel";
private static final int DECORATION_IMAGE_WIDTH = 600;
private static final String DECORATION_IMAGE = "Decisions.png";
private static final String TITLE = "Model";
private static final String INFO_TEXT = "Please select the model to run!";
private static final int STARTBUTTON_HEIGHT = 50;
private static final int STARTBUTTON_WIDTH = 350;
private Wizard wizard;
private Dashboard dashboard;
private Container container;
public Page_Model(Wizard wizard, final Dashboard dashboard) {
this.wizard = wizard;
this.dashboard = dashboard;
container = initContainer();
}
@Override
public String getInfoText(Wizard wizard) {
return wizard.getArrowsHeader(INFO_TEXT);
}
@Override
public Icon getIcon() {
return new ImageIcon(getClass().getResource("icons/bank.png"));
}
@Override
public Container getPanel() {
// ImageIcon buttonIcon = new ImageIcon(getClass().getResource("white-background-gold-button-hi.png"));
// buttonIcon = new ImageIcon(buttonIcon.getImage().getScaledInstance(STARTBUTTON_WIDTH, -STARTBUTTON_HEIGHT, java.awt.Image.SCALE_SMOOTH));
//
// int buttonHeight = buttonIcon.getIconHeight();
// int buttonWidth = buttonIcon.getIconWidth();
return container;
}
private Container initContainer() {
// BufferedImage image = null;
// try {
// image = ImageIO.read(getClass().getResource(DECORATION_IMAGE));
// } catch (IOException e) {
// throw new IllegalStateException(e);
// }
//
// ImageIcon imageIcon = new ImageIcon(image.getScaledInstance(DECORATION_IMAGE_WIDTH, -1, BufferedImage.SCALE_SMOOTH));
JLabel label = null;
label = new JLabel(new ImageIcon(new ImageIcon(getClass().getResource(DECORATION_IMAGE)).getImage().getScaledInstance(DECORATION_IMAGE_WIDTH, -1, Image.SCALE_SMOOTH)));
// label = new JLabel(imageIcon);
// label.setOpaque(true);
final DefaultFormBuilder
buttonFormBuilder = FormsUtils.build("p ~ p", "");
for (final Entry<String, Pair<String, Color>> record :
Dashboard.availableModels.entrySet()) {
final String
modelURI = record.getKey(),
modelName = record.getValue().getFirst();
final Color
buttonColor = record.getValue().getSecond();
JButton button = new JButton(
"<html><p align='center'>" + modelName + "</html>");
button.setPreferredSize(new Dimension(STARTBUTTON_WIDTH, STARTBUTTON_HEIGHT));
button.setBackground(buttonColor);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
IModelHandler modelHandler = null;
try {
modelHandler = dashboard.createModelHandler(modelURI);
} catch (ClassNotFoundException e) {
Logger log = Logger.getLogger(getClass());
log.error("Could not load the model class!", e);
}
try {
modelHandler.getRecorderAnnotationValue();
} catch (Exception e) {
ErrorDialog errorDialog = new ErrorDialog(wizard, "No recorder specified", "The model does not have '@RecorderSource' annotation");
errorDialog.show();
return;
}
dashboard.setTitle(modelName.substring(modelName.lastIndexOf('.') + 1));
wizard.gotoPage(1);
}
});
}
});
buttonFormBuilder.append(button);
}
final JButton loadButton = new JButton("<html><p align='center'>Load model configuration..." + "</html>");
loadButton.setPreferredSize(new Dimension(STARTBUTTON_WIDTH, STARTBUTTON_HEIGHT));
loadButton.setBackground(new Color(60, 193, 250));
loadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent _) {
dashboard.loadConfiguration();
}
});
buttonFormBuilder.append(loadButton);
JPanel buttonPanel = buttonFormBuilder.getPanel();
Style.registerCssClasses(buttonPanel, CSS_CLASS_COMMON_PANEL);
JPanel panel = FormsUtils.build("p ~ f:p:g",
"01 f:p:g",
label, buttonPanel, CellConstraints.CENTER).getPanel();
// panel.setBackground(Color.WHITE);
Style.registerCssClasses(panel, CSS_CLASS_COMMON_PANEL);
final JScrollPane pageScrollPane = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pageScrollPane.setBorder(null);
pageScrollPane.setViewportBorder(null);
pageScrollPane.setViewportView(panel);
return pageScrollPane;
}
@Override
public boolean isEnabled(Button button) {
switch (button){
case BACK:
return false;
case NEXT:
return false;
case CANCEL: // this is the charts page
return true;
case FINISH:
return false;
case CUSTOM:
return false;
}
return false;
}
@Override
public boolean onButtonPress(Button button) {
return true;
}
@Override
public void onPageChange(boolean show) {
if (show){
dashboard.getSaveConfigMenuItem().setEnabled(false);
dashboard.setTitle(null);
} else {
IModelHandler modelHandler = dashboard.getModelHandler();
if (modelHandler != null){
dashboard.setTitle(modelHandler.getModelClassSimpleName());
}
}
}
@Override
public String getTitle() {
return TITLE;
}
}
|
crisis-economics/CRISIS
|
CRISIS/src/eu/crisis_economics/abm/dashboard/Page_Model.java
|
Java
|
gpl-3.0
| 7,152 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package SQL;
import java.util.ArrayList;
/**
*
* @author adam279
*/
public interface CustomerDAO {
public Customer getCustomer(int id);
public ArrayList<Customer> getCustomers();
public void addCustomer(Customer customer);
public void deleteCustomer(int id);
public void updateCustomer(Customer customer);
}
|
mda747/dtu_elec2_prog2_semester_project
|
Serial/src/SQL/CustomerDAO.java
|
Java
|
gpl-3.0
| 529 |
//------------------------------------------------------------------------------
//
// This file is part of AnandamideEditor
//
// copyright: (c) 2010 - 2016
// authors: Alexey Egorov (FadeToBlack aka EvilSpirit)
// Zakhar Shelkovnikov
// Georgiy Kostarev
//
// mailto: anandamide@mail.ru
// anandamide.script@gmail.com
//
// AnandamideEditor is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// AnandamideEditor is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with AnandamideEditor. If not, see <http://www.gnu.org/licenses/>.
//
//------------------------------------------------------------------------------
#include "AnandamideWorkspaceTree.h"
#include "MainWindow.h"
#include "Anandamide.h"
#include "AnandamideLibrary.h"
#include "AnandamideViewport.h"
#include "XmlSettings.h"
#include "AnandamideViewport.h"
#include "AnandamideLibraryWidget.h"
#include <QFileInfo>
#include <QDir>
//------------------------------------------------------------------------------
//
// TreeItemWorkspace
//
//------------------------------------------------------------------------------
void TreeItemWorkspace::setChanged(bool changed)
{
changeFlag = changed;
QString text = "Default workspace";
if(fileName != QString()) {
text = QFileInfo(fileName).baseName();
}
if(changeFlag)
text.append('*');
setText(text.toLocal8Bit().constData());
}
TreeItemWorkspace::TreeItemWorkspace(QTreeWidget *parent, MainWindow *main_window) : TreeItemBase(parent, main_window) {
setIcon(0, QIcon(":/icons/folder2.png"));
setExpanded(true);
setChanged(false);
}
bool TreeItemWorkspace::addScriptItem(Anandamide::Script *script, const QString& fileName, int tabIndex, EditorWidgetsCollection *collection) {
if(getScriptWorkspaceIndex(script) >= 0) return false;
clearSelection();
TreeItemDepProject* project = new TreeItemDepProject(script, fileName, tabIndex, this);
project->setCollection(collection);
project->setSelected(true);
setChanged(true);
return true;
}
bool TreeItemWorkspace::removeScriptItem(Anandamide::Script *script)
{
int idx = getScriptWorkspaceIndex(script);
if(idx < 0) return false;
QTreeWidgetItem* child = this->child(idx);
TreeItemDepProject* project = dynamic_cast<TreeItemDepProject*>(child);
if(project) {
QList<int> tabs = project->getChildsTabs();
qSort(tabs);
while(tabs.size())
main_window->on_tabWidgetViewports_tabCloseRequested(tabs.takeLast());
}
this->removeChild(child);
delete child;
setChanged(true);
return true;
}
bool TreeItemWorkspace::removeScriptProjectByIndex(int tabIndex)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* proj = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(proj == NULL) continue;
if(proj->getTabIndex() == tabIndex) {
QTreeWidgetItem* child = this->child(i);
this->removeChild(child);
delete child;
setChanged(true);
return true;
}
}
return false;
}
int TreeItemWorkspace::getScriptWorkspaceIndex(Anandamide::Script *script)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* proj = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(proj == NULL) continue;
if(proj->getScript() == script /*|| Anandamide::Str(proj->script->getName()) == Anandamide::Str(script->getName())*/)
return i;
}
return -1;
}
bool TreeItemWorkspace::updateProject(Anandamide::Script *script)
{
// int idx = getScriptWorkspaceIndex(script);
// if(idx < 0) return false;
// TreeItemDepProject* proj = dynamic_cast<TreeItemDepProject*>(this->child(idx));
// if(proj == NULL) return false;
// proj->updateChildren();
// return true;
bool res = false;
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* proj = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(proj == NULL) continue;
if(proj->updateProject(script)) res = true;
}
return res;
}
TreeItemDepProject *TreeItemWorkspace::getScriptProject(Anandamide::Script *script)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* proj = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(proj == NULL) continue;
TreeItemDepProject* res = proj->getScriptProject(script);
if(res != NULL) return res;
}
return NULL;
}
TreeItemDepProject *TreeItemWorkspace::getTabIndexProject(int tabIndex)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* proj = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(proj == NULL) continue;
TreeItemDepProject* res = proj->getTabIndexProject(tabIndex);
if(res != NULL) return res;
}
return NULL;
}
TreeItemDepProject *TreeItemWorkspace::getProjectByFilename(const QString &filename)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* proj = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(proj == NULL) continue;
if(filename == proj->info.fileName)
return proj;
}
return NULL;
}
void TreeItemWorkspace::updateChildren()
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemBase* item = dynamic_cast<TreeItemBase*>(this->child(i));
if(item == NULL) continue;
item->updateChildren();
}
}
EditorWidgetsCollection *TreeItemWorkspace::getCollection(int tabIndex)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
EditorWidgetsCollection* res = child->getCollection(tabIndex);
if(res != NULL) return res;
}
return NULL;
}
Anandamide::Script *TreeItemWorkspace::getScript(int tabIndex)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
Anandamide::Script* res = child->getScript(tabIndex);
if(res != NULL) return res;
}
return NULL;
}
void TreeItemWorkspace::selectByTabIndex(int tabIndex)
{
clearSelection();
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
if(child->selectByTabIndex(tabIndex)) return;
}
}
void TreeItemWorkspace::tabMoved(int from, int to)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
child->tabMoved(from, to);
}
}
void TreeItemWorkspace::resetTabIndex(int tabIndex)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
child->resetTabIndex(tabIndex);
}
}
QString TreeItemWorkspace::getFileName(int tabIndex)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
QString res = child->getFileName(tabIndex);
if(res != QString()) return res;
}
return QString();
}
bool TreeItemWorkspace::setFileName(const QString &filename, int tabIndex)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
if(child->setFileName(filename, tabIndex)) return true;
}
return false;
}
void TreeItemWorkspace::setShiftOnWheel(bool shift)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
child->setShiftOnWheel(shift);
}
}
void TreeItemWorkspace::clearSelection()
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
child->setSelected(false);
}
}
bool TreeItemWorkspace::saveWorkspace()
{
if(fileName == QString()) return false;
return saveWorkspace(fileName);
}
bool TreeItemWorkspace::saveWorkspace(const QString &filename)
{
if(filename == QString()) return false;
CXml_Settings sets;
sets.beginGroup("WorkSpace");
sets.beginGroup("Scripts");
int cntr = 0;
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
sets.beginGroup(QString("Script_%1").arg(cntr));
sets.setValue("filename", QFileInfo(filename).absoluteDir().relativeFilePath(child->info.fileName));
sets.endGroup();
child->setSelected(false);
cntr++;
}
sets.endGroup();
sets.setValue("ScriptsCount", cntr);
sets.endGroup();
QFile file( filename );
if ( !file.open(QIODevice::WriteOnly) )
return false;
sets.saveToIO(&file);
file.close();
fileName = filename;
setChanged(false);
return true;
}
bool TreeItemWorkspace::loadWorkspace(const QString &filename)
{
QFile file( filename );
if ( !file.open(QIODevice::ReadOnly) )
return false;
CXml_Settings sets;
if(!sets.loadFromIO(&file)) {
file.close();
return false;
}
file.close();
main_window->closeAllTabs(true, -1);
this->clearChildren();
sets.beginGroup("WorkSpace");
int n = sets.value("ScriptsCount").toInt();
sets.beginGroup("Scripts");
for(int i = 0; i < n; ++i) {
sets.beginGroup(QString("Script_%1").arg(i));
QString fn = sets.value("filename").toString();
sets.endGroup();
if(fn != QString()) {
fn = QFileInfo(filename).absoluteDir().absoluteFilePath(fn);
Anandamide::Script* scr = main_window->createScript();
EditorWidgetsCollection* coll = new EditorWidgetsCollection(main_window);
main_window->currentCollection = coll;
coll->createCollection(main_window);
coll->viewport->shiftFlag = main_window->getShiftFlag();
main_window->setMessangerView(coll);
scr->load(fn.toLocal8Bit().constData());
if(scr->getLogicsCount() <= 0) {
scr->destroy();
continue;
}
// main_window->createTestLibraryForScript(scr);
addScriptItem(scr, fn, -1, coll);
}
}
sets.endGroup();
sets.endGroup();
fileName = filename;
setChanged(false);
selectByTabIndex(-1);
return true;
}
bool TreeItemWorkspace::isWorkspaceChanged()
{
return changeFlag;
}
QTreeWidgetItem *TreeItemWorkspace::getLibraryItem(const QString &libraryName)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
QTreeWidgetItem* item = child->getLibraryItem(libraryName, main_window->currentCollection);
if(item != NULL) return item;
}
return NULL;
}
void TreeItemWorkspace::onStopExecuting()
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
child->onStopExecuting();
}
}
//------------------------------------------------------------------------------
//
// TreeItemDepProject
//
//------------------------------------------------------------------------------
void TreeItemDepProject::clearCache()
{
while(cache.size())
delete cache.takeFirst();
}
int TreeItemDepProject::getCacheIndex(Anandamide::Script *script)
{
for(int i = 0; i < cache.size(); ++i)
if(cache[i]->script == script)
return i;
return -1;
}
void TreeItemDepProject::saveToCache()
{
clearCache();
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
child->saveToCache();
cache.append(new DepProjectInfo());
cache.last()->script = child->info.script;
cache.last()->fileName = child->info.fileName;
cache.last()->tabIndex = child->info.tabIndex;
foreach (DepProjectInfo* cc, child->cache) {
cache.last()->childInfo.append(new DepProjectInfo(cc));
}
cache.last()->collection = child->getCollection();
cache.last()->selected = child->info.selected;
}
}
QList<int> TreeItemDepProject::restoreFromCache()
{
QSet<int> unused;
QList<int> tabIndexes;
for(int i = 0; i < cache.size(); ++i)
unused.insert(i);
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
int idx = getCacheIndex(child->info.script);
if(idx < 0) continue;
unused.remove(idx);
child->info.fileName = cache[idx]->fileName;
child->info.tabIndex = cache[idx]->tabIndex;
child->clearCache();
foreach (DepProjectInfo* cc, cache[idx]->childInfo) {
child->cache.append(new DepProjectInfo(cc));
}
child->setCollection(cache[idx]->collection);
child->setSelected(cache[idx]->selected);
child->restoreFromCache();
}
QList<int> unusedList = unused.toList();
foreach (int i, unusedList) {
if(cache[i]->tabIndex >= 0)
tabIndexes.append(cache[i]->tabIndex);
tabIndexes.append( cache[i]->getChildsTabs() );
}
clearCache();
return tabIndexes;
}
TreeItemDepProject::TreeItemDepProject(Anandamide::Script *script, const QString& fileName, int tabIndex, TreeItemBase *parent) : TreeItemBase(parent) {
info.script = script;
info.fileName = fileName;
info.tabIndex = tabIndex;
setIcon(0, QIcon(isTopLevelProject() ? ":/icons/blocks.png" : ":/icons/library.png"));
setExpanded(true);
updateChildren();
}
TreeItemDepProject::~TreeItemDepProject()
{
clearCache();
}
bool TreeItemDepProject::isTopLevelProject()
{
TreeItemDepProject* prg = dynamic_cast<TreeItemDepProject*>(this->parent());
return prg == NULL;
}
void TreeItemDepProject::updateChildren() {
if(Anandamide::Str(info.script->getName()) == Anandamide::Str())
setText("Unnamed Script");
else
setText(info.script->getName());
saveToCache();
clearChildren();
for(int i = 0; i < info.script->getLibraries()->getLibrariesCount(); ++i) {
Anandamide::ScriptLibrary* script_lib = dynamic_cast<Anandamide::ScriptLibrary*>(const_cast<Anandamide::Library*>(info.script->getLibraries()->getLibrary(i)));
if(script_lib == NULL) continue;
if(isScriptUsed(script_lib->getScript())) continue;
/*TreeItemDepProject *item = */new TreeItemDepProject(script_lib->getScript(), QString::fromLocal8Bit(script_lib->getFileName()), -1, this);
}
QList<int> tabIndexes = restoreFromCache();
qSort(tabIndexes);
while(tabIndexes.size()) {
main_window->on_tabWidgetViewports_tabCloseRequested(tabIndexes.takeLast());
}
}
bool TreeItemDepProject::isScriptUsed(Anandamide::Script *script) {
if(info.script == script/* || Anandamide::Str(info.script->getName()) == Anandamide::Str(script->getName())*/)
return true;
TreeItemDepProject* parent = dynamic_cast<TreeItemDepProject*>(this->parent());
if(parent == NULL) return false;
return parent->isScriptUsed(script);
}
Anandamide::Script *TreeItemDepProject::getScript() {return info.script;}
Anandamide::Script *TreeItemDepProject::getScript(int tabIndex)
{
if(info.tabIndex == tabIndex && tabIndex >= 0)
return info.script;
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
Anandamide::Script* res = child->getScript(tabIndex);
if(res != NULL) return res;
}
return NULL;
}
int TreeItemDepProject::getScriptIndex(Anandamide::Script *script)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
if(script = child->getScript()) return i;
}
return -1;
}
bool TreeItemDepProject::updateProject(Anandamide::Script *script)
{
bool res = false;
if(script == info.script) {
res = true;
updateChildren();
}
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
if(child->updateProject(script)) res = true;
}
return res;
}
EditorWidgetsCollection *TreeItemDepProject::getCollection() {return info.collection;}
EditorWidgetsCollection *TreeItemDepProject::getCollection(int tabIndex)
{
if(info.tabIndex == tabIndex && tabIndex >= 0)
return info.collection;
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
EditorWidgetsCollection* res = child->getCollection(tabIndex);
if(res != NULL) return res;
}
return NULL;
}
void TreeItemDepProject::setCollection(EditorWidgetsCollection *collection)
{
info.collection = collection;
}
int TreeItemDepProject::getTabIndex()
{
return info.tabIndex;
}
void TreeItemDepProject::setTabIndex(int tabIndex)
{
info.tabIndex = tabIndex;
}
void TreeItemDepProject::tabMoved(int from, int to)
{
if(info.tabIndex == from)
info.tabIndex = to;
else if(info.tabIndex == to)
info.tabIndex = from;
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
child->tabMoved(from, to);
}
}
void TreeItemDepProject::resetTabIndex(int tabIndex)
{
if(tabIndex >= 0) {
if(info.tabIndex == tabIndex)
info.tabIndex = -1;
else if(info.tabIndex > tabIndex)
info.tabIndex--;
}
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
child->resetTabIndex(tabIndex);
}
}
void TreeItemDepProject::setShiftOnWheel(bool shift)
{
if(info.collection != NULL)
if(info.collection->isCreated())
info.collection->viewport->shiftFlag = shift;
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
child->setShiftOnWheel(shift);
}
}
void TreeItemDepProject::setSelected(bool selected)
{
info.selected = selected;
QFont f;
if(selected)
f.setBold(true);
this->setFont(0, f);
this->setBackground(0, selected ? QBrush(QColor(230, 193, 193)) : QBrush());
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
child->setSelected(false);
}
}
bool TreeItemDepProject::selectByTabIndex(int tabIndex)
{
if(info.tabIndex == tabIndex && tabIndex >= 0) {
setSelected(true);
return true;
}
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
if(child->selectByTabIndex(tabIndex)) return true;
}
return false;
}
void TreeItemDepProject::createNewTab()
{
if(info.collection == NULL)
info.collection = new EditorWidgetsCollection(main_window);
main_window->currentCollection = info.collection;
if(!info.collection->isCreated())
info.collection->createCollection(main_window);
info.tabIndex = main_window->getTabsCount();
main_window->addCollection(info.collection, info.script->getName(), isTopLevelProject());
Anandamide::Logic *logic = info.script->getLogic(0);
info.collection->editor->setLogic(logic);
info.collection->editor->reset();
info.collection->project_tree->clear();
TreeItemScript *script_item = new TreeItemScript(info.collection->project_tree, main_window, info.script);
info.collection->project_tree->addTopLevelItem(script_item);
script_item->setExpanded(true);
info.collection->library_widget->invalidate();
info.collection->viewport->repaint();
}
QString TreeItemDepProject::getFileName(int tabIndex)
{
if(info.tabIndex == tabIndex && tabIndex >= 0)
return info.fileName;
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
QString res = child->getFileName(tabIndex);
if(res != QString()) return res;
}
return QString();
}
bool TreeItemDepProject::setFileName(const QString &filename, int tabIndex)
{
if(info.tabIndex == tabIndex && tabIndex >= 0) {
info.fileName = filename;
return true;
}
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
if(child->setFileName(filename, tabIndex)) return true;
}
return false;
}
QList<int> TreeItemDepProject::getChildsTabs() {
QList<int> res;
if(info.tabIndex >= 0)
res << info.tabIndex;
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
res << child->getChildsTabs();
}
return res;
}
QTreeWidgetItem *TreeItemDepProject::getLibraryItem(const QString &libraryName, EditorWidgetsCollection *collection)
{
if(info.collection == collection) {
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
if(QString::fromLocal8Bit( child->info.script->getName() ) == libraryName) return child;
}
}
else {
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
QTreeWidgetItem* item = child->getLibraryItem(libraryName, collection);
if(item != NULL) return item;
}
}
return NULL;
}
TreeItemDepProject *TreeItemDepProject::getChildByName(const QString &name)
{
return dynamic_cast<TreeItemDepProject*>(this->getChildByText(name));
}
void TreeItemDepProject::onStopExecuting()
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
child->onStopExecuting();
}
}
TreeItemDepProject *TreeItemDepProject::getScriptProject(Anandamide::Script *script)
{
if(info.script == script)
return this;
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
TreeItemDepProject* res = child->getScriptProject(script);
if(res != NULL) return res;
}
return NULL;
}
TreeItemDepProject *TreeItemDepProject::getTabIndexProject(int tabIndex)
{
if(info.tabIndex == tabIndex && tabIndex >= 0)
return this;
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
TreeItemDepProject* res = child->getTabIndexProject(tabIndex);
if(res != NULL) return res;
}
return NULL;
}
//------------------------------------------------------------------------------
//
// AnandamideWorkspaceTree
//
//------------------------------------------------------------------------------
AnandamideWorkspaceTree::AnandamideWorkspaceTree(QWidget *parent) :
QTreeWidget(parent)
{
root = new TreeItemWorkspace(this, main_window);
connect(this,
SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)),
SLOT(onItemDoubleClicked(QTreeWidgetItem*, int)));
}
bool AnandamideWorkspaceTree::addScriptProject(Anandamide::Script *script, const QString &fileName, int tabIndex, EditorWidgetsCollection *collection)
{
return root->addScriptItem(script, fileName, tabIndex, collection);
}
bool AnandamideWorkspaceTree::removeScriptProject(Anandamide::Script *script)
{
return root->removeScriptItem(script);
}
bool AnandamideWorkspaceTree::removeScriptProjectByIndex(int tabIndex)
{
return root->removeScriptProjectByIndex(tabIndex);
}
bool AnandamideWorkspaceTree::isScriptProject(Anandamide::Script *script)
{
return root->getScriptWorkspaceIndex(script) >= 0;
}
bool AnandamideWorkspaceTree::setScriptProject(const QString &fileName)
{
TreeItemDepProject* project = root->getProjectByFilename(fileName);
if(project == NULL) return false;
onItemDoubleClicked(project, 0);
return true;
}
bool AnandamideWorkspaceTree::updateProject(Anandamide::Script *script)
{
return root->updateProject(script);
}
void AnandamideWorkspaceTree::update()
{
root->updateChildren();
}
EditorWidgetsCollection *AnandamideWorkspaceTree::getCollection(int tabIndex)
{
return root->getCollection(tabIndex);
}
Anandamide::Script *AnandamideWorkspaceTree::getScript(int tabIndex)
{
return root->getScript(tabIndex);
}
QString AnandamideWorkspaceTree::getFileName(int tabIndex)
{
return root->getFileName(tabIndex);
}
bool AnandamideWorkspaceTree::setFileName(const QString &filename, int tabIndex)
{
return root->setFileName(filename, tabIndex);
}
void AnandamideWorkspaceTree::newWorkspace()
{
main_window->closeAllTabs(true, -1);
delete root;
root = new TreeItemWorkspace(this, main_window);
}
bool AnandamideWorkspaceTree::saveWorkspace()
{
return root->saveWorkspace();
}
bool AnandamideWorkspaceTree::saveWorkspace(const QString &filename)
{
return root->saveWorkspace(filename);
}
bool AnandamideWorkspaceTree::loadWorkspace(const QString &filename)
{
main_window->setCursorShape(Qt::WaitCursor);
bool res = root->loadWorkspace(filename);
main_window->setCursorShape(Qt::ArrowCursor);
return res;
}
bool AnandamideWorkspaceTree::isWorkspaceChanged()
{
return root->isWorkspaceChanged();
}
void AnandamideWorkspaceTree::clearChanges()
{
root->setChanged(false);
}
bool AnandamideWorkspaceTree::openLibrary(const QString &libraryName)
{
QTreeWidgetItem* item = root->getLibraryItem(libraryName);
if(item == NULL) return false;
onItemDoubleClicked(item, 0);
return true;
}
void AnandamideWorkspaceTree::onStopExecuting()
{
root->clearSelection();
root->onStopExecuting();
}
void AnandamideWorkspaceTree::setCurrentScript(QStringList &logicLibList)
{/*
if(logicLibList.takeLast() != QString()) return;
while(logicLibList.size() && project != NULL) {
project = project->getChildByName(logicLibList.takeLast());
}
onItemDoubleClicked(project, 0);
*/
}
void AnandamideWorkspaceTree::openScriptView(Anandamide::Script *script)
{
TreeItemDepProject* project = root->getScriptProject(script);
if(project == NULL) return;
if(project->getTabIndex() >= 0) {
main_window->setTabIndex(project->getTabIndex());
}
else {
project->createNewTab();
}
}
bool AnandamideWorkspaceTree::isProjectRunning(int tabIndex)
{
if(tabIndex < 0) return false;
TreeItemDepProject* project = root->getTabIndexProject(tabIndex);
while(project != NULL) {
project = dynamic_cast<TreeItemDepProject*>(project->parent());
}
return false;
}
void AnandamideWorkspaceTree::selectByTabIndex(int tabIndex)
{
root->selectByTabIndex(tabIndex);
}
void AnandamideWorkspaceTree::tabMoved(int from, int to)
{
root->tabMoved(from, to);
}
void AnandamideWorkspaceTree::resetTabIndex(int tabIndex)
{
root->resetTabIndex(tabIndex);
}
void AnandamideWorkspaceTree::setShiftOnWheel(bool shift)
{
root->setShiftOnWheel(shift);
}
void AnandamideWorkspaceTree::onItemDoubleClicked(QTreeWidgetItem *tree_item, int column)
{
Q_UNUSED(column);
TreeItemDepProject* project = dynamic_cast<TreeItemDepProject*>(tree_item);
if(project == NULL) return;
root->clearSelection();
project->setSelected(true);
if(project->getTabIndex() >= 0) {
main_window->setTabIndex(project->getTabIndex());
}
else {
project->createNewTab();
}
}
TreeItemDepProject::DepProjectInfo::DepProjectInfo() {
collection = NULL;
selected = false;
}
TreeItemDepProject::DepProjectInfo::DepProjectInfo(TreeItemDepProject::DepProjectInfo *other) {
script = other->script;
fileName = other->fileName;
tabIndex = other->tabIndex;
collection = other->collection;
selected = other->selected;
childCopy(other);
}
void TreeItemDepProject::DepProjectInfo::clear() {
while(childInfo.size()) {
delete childInfo.takeFirst();
}
}
void TreeItemDepProject::DepProjectInfo::childCopy(TreeItemDepProject::DepProjectInfo *other) {
clear();
foreach (DepProjectInfo* cc, other->childInfo) {
childInfo.append(new DepProjectInfo(cc));
}
}
QList<int> TreeItemDepProject::DepProjectInfo::getChildsTabs() {
QList<int> res;
foreach (DepProjectInfo* ci, childInfo) {
if(ci->tabIndex >= 0)
res.append(ci->tabIndex);
res.append( ci->getChildsTabs() );
}
return res;
}
|
Evil-Spirit/AnandamideEditor
|
src/AnandamideWorkspaceTree.cpp
|
C++
|
gpl-3.0
| 29,220 |
/** Unused, mostly useless, code. */
/// Computes circumcentre and circumradius of a [tetrahedron](@ref Tet).
/** NOTE: The tetrahedron's jacobian (2*volume) should be stored in [elem.D](&ref D) beforehand.
* The center and radius of the circumsphere are calculated as follows. The circumcenter is
* \f[ \mathbf{O} = \frac{|\mathbf{a}^2(\mathbf{b}\times \mathbf{c}) + \mathbf{b}^2(\mathbf{c}\times \mathbf{a}) + \mathbf{c}^2(\mathbf{a}\times \mathbf{b})|}{12 V} \f]
* and the radius \f$ R = |\mathbf{O}|\f$.
*/
void Delaunay3d::compute_circumsphere2(Tet& elem)
{
vector<double> a(ndim), b(ndim), c(ndim), n1(ndim), n2(ndim), n3(ndim), fin(ndim);
for(int idim = 0; idim < ndim; idim++)
{
a[idim] = nodes[elem.p[0]][idim]-nodes[elem.p[3]][idim];
b[idim] = nodes[elem.p[1]][idim]-nodes[elem.p[3]][idim];
c[idim] = nodes[elem.p[2]][idim]-nodes[elem.p[3]][idim];
}
cross_product3(n1,b,c);
cross_product3(n2,c,a);
cross_product3(n3,a,b);
for(int idim = 0; idim < ndim; idim++)
{
fin[idim] = dot(a,a)*n1[idim] + dot(b,b)*n2[idim] + dot(c,c)*n3[idim];
fin[idim] /= 2.0*elem.D;
elem.centre[idim] = fin[idim];
}
elem.radius = l2norm(fin);
cout << "Circumsphere data: centre " << elem.centre[0] << "," << elem.centre[1] << "," << elem.centre[2] << ", radius " << elem.radius << ", elem jacobian " << elem.D << endl;
}
/// Computes circumcentre and circumradius of a [tetrahedron](@ref Tet).
/** NOTE: The tetrahedron's jacobian (6*volume) should be stored in [elem.D](@ref elem::D) beforehand.
* Reference: [Weisstein, Eric W. "Circumsphere." From MathWorld--A Wolfram Web Resource.](@ref http://mathworld.wolfram.com/Circumsphere.html)
* \note Probably wrong!
*/
void Delaunay3d::compute_circumsphere3(Tet& elem)
{
Matrix<double> dx(nnode,nnode), dy(nnode,nnode), dz(nnode,nnode), cc(nnode,nnode);
double a = elem.D, c, d_x, d_y, d_z;
#if DEBUGW==1
if(fabs(a) < ZERO_TOL) cout << "Delaunay3d: compute_circumcircle(): ! Jacobian of the element is zero!!" << endl;
#endif
dx(0,0) = nodes[elem.p[0]][0]*nodes[elem.p[0]][0] + nodes[elem.p[0]][1]*nodes[elem.p[0]][1] + nodes[elem.p[0]][2]*nodes[elem.p[0]][2];
dx(0,1) = nodes[elem.p[0]][1]; dx(0,2) = nodes[elem.p[0]][2]; dx(0,3) = 1;
dx(1,0) = nodes[elem.p[1]][0]*nodes[elem.p[1]][0] + nodes[elem.p[1]][1]*nodes[elem.p[1]][1] + nodes[elem.p[1]][2]*nodes[elem.p[1]][2];
dx(1,1) = nodes[elem.p[1]][1]; dx(1,2) = nodes[elem.p[1]][2]; dx(1,3) = 1;
dx(2,0) = nodes[elem.p[2]][0]*nodes[elem.p[2]][0] + nodes[elem.p[2]][1]*nodes[elem.p[2]][1] + nodes[elem.p[2]][2]*nodes[elem.p[2]][2];
dx(2,1) = nodes[elem.p[2]][1]; dx(2,2) = nodes[elem.p[2]][2]; dx(2,3) = 1;
dx(3,0) = nodes[elem.p[3]][0]*nodes[elem.p[3]][0] + nodes[elem.p[3]][1]*nodes[elem.p[3]][1] + nodes[elem.p[3]][2]*nodes[elem.p[3]][2];
dx(3,1) = nodes[elem.p[3]][1]; dx(3,2) = nodes[elem.p[3]][2]; dx(3,3) = 1;
dy(0,0) = nodes[elem.p[0]][0]*nodes[elem.p[0]][0] + nodes[elem.p[0]][1]*nodes[elem.p[0]][1] + nodes[elem.p[0]][2]*nodes[elem.p[0]][2];
dy(0,1) = nodes[elem.p[0]][0]; dy(0,2) = nodes[elem.p[0]][2]; dy(0,3) = 1;
dy(1,0) = nodes[elem.p[1]][0]*nodes[elem.p[1]][0] + nodes[elem.p[1]][1]*nodes[elem.p[1]][1] + nodes[elem.p[1]][2]*nodes[elem.p[1]][2];
dy(1,1) = nodes[elem.p[1]][0]; dy(1,2) = nodes[elem.p[1]][2]; dy(1,3) = 1;
dy(2,0) = nodes[elem.p[2]][0]*nodes[elem.p[2]][0] + nodes[elem.p[2]][1]*nodes[elem.p[2]][1] + nodes[elem.p[2]][2]*nodes[elem.p[2]][2];
dy(2,1) = nodes[elem.p[2]][0]; dy(2,2) = nodes[elem.p[2]][2]; dy(2,3) = 1;
dy(3,0) = nodes[elem.p[3]][0]*nodes[elem.p[3]][0] + nodes[elem.p[3]][1]*nodes[elem.p[3]][1] + nodes[elem.p[3]][2]*nodes[elem.p[3]][2];
dy(3,1) = nodes[elem.p[3]][0]; dy(3,2) = nodes[elem.p[3]][2]; dy(3,3) = 1;
dz(0,0) = nodes[elem.p[0]][0]*nodes[elem.p[0]][0] + nodes[elem.p[0]][1]*nodes[elem.p[0]][1] + nodes[elem.p[0]][2]*nodes[elem.p[0]][2];
dz(0,1) = nodes[elem.p[0]][0]; dz(0,2) = nodes[elem.p[0]][1]; dz(0,3) = 1;
dz(1,0) = nodes[elem.p[1]][0]*nodes[elem.p[1]][0] + nodes[elem.p[1]][1]*nodes[elem.p[1]][1] + nodes[elem.p[1]][2]*nodes[elem.p[1]][2];
dz(1,1) = nodes[elem.p[1]][0]; dz(1,2) = nodes[elem.p[1]][1]; dz(1,3) = 1;
dz(2,0) = nodes[elem.p[2]][0]*nodes[elem.p[2]][0] + nodes[elem.p[2]][1]*nodes[elem.p[2]][1] + nodes[elem.p[2]][2]*nodes[elem.p[2]][2];
dz(2,1) = nodes[elem.p[2]][0]; dz(2,2) = nodes[elem.p[2]][1]; dz(2,3) = 1;
dz(3,0) = nodes[elem.p[3]][0]*nodes[elem.p[3]][0] + nodes[elem.p[3]][1]*nodes[elem.p[3]][1] + nodes[elem.p[3]][2]*nodes[elem.p[3]][2];
dz(3,1) = nodes[elem.p[3]][0]; dz(3,2) = nodes[elem.p[3]][1]; dz(3,3) = 1;
cc(0,0) = nodes[elem.p[0]][0]*nodes[elem.p[0]][0] + nodes[elem.p[0]][1]*nodes[elem.p[0]][1] + nodes[elem.p[0]][2]*nodes[elem.p[0]][2];
cc(0,1) = nodes[elem.p[0]][0]; cc(0,2) = nodes[elem.p[0]][1]; cc(0,3) = nodes[elem.p[0]][2];
cc(1,0) = nodes[elem.p[1]][0]*nodes[elem.p[1]][0] + nodes[elem.p[1]][1]*nodes[elem.p[1]][1] + nodes[elem.p[1]][2]*nodes[elem.p[1]][2];
cc(1,1) = nodes[elem.p[1]][0]; cc(1,2) = nodes[elem.p[1]][1]; cc(1,3) = nodes[elem.p[1]][2];
cc(2,0) = nodes[elem.p[2]][0]*nodes[elem.p[2]][0] + nodes[elem.p[2]][1]*nodes[elem.p[2]][1] + nodes[elem.p[2]][2]*nodes[elem.p[2]][2];
cc(2,1) = nodes[elem.p[2]][0]; cc(2,2) = nodes[elem.p[2]][1]; cc(2,3) = nodes[elem.p[2]][2];
cc(3,0) = nodes[elem.p[3]][0]*nodes[elem.p[3]][0] + nodes[elem.p[3]][1]*nodes[elem.p[3]][1] + nodes[elem.p[3]][2]*nodes[elem.p[3]][2];
cc(3,1) = nodes[elem.p[3]][0]; cc(3,2) = nodes[elem.p[3]][1]; cc(3,3) = nodes[elem.p[3]][2];
d_x = determinant(dx);
d_y = determinant(dy);
d_z = determinant(dz);
c = determinant(cc);
elem.centre[0] = d_x/a*0.5;
elem.centre[1] = d_y/a*0.5;
elem.centre[2] = d_z/a*0.5;
elem.radius = sqrt(d_x*d_x + d_y*d_y + d_z*d_z - 4.0*a*c)/2*fabs(a);
cout << "Circumcircle data: centre " << elem.centre[0] << "," << elem.centre[1] << "," << elem.centre[2] << ", radius " << elem.radius << ", elem jacobian " << a << endl;
}
/// Calculates the jacobian of the tetrahedron formed by point r and a face of tetrahedron ielem.
/** The face is selected by i between 0 and 3. Face i is the face opposite to local node i of the tetrahedron.
*/
double Delaunay3d::det4(int ielem, int i, const vector<double>& r) const
{
#if DEBUGW==1
if(i > 3) {
std::cout << "Delaunay3D: det4(): ! Second argument is greater than 3!" << std::endl;
return 0;
}
#endif
Tet elem = elems[ielem];
double ret = 0;
switch(i)
{
case(0):
ret = r[0] * ( nodes[elem.p[1]][1]*(nodes[elem.p[2]][2]-nodes[elem.p[3]][2]) -nodes[elem.p[1]][2]*(nodes[elem.p[2]][1]-nodes[elem.p[3]][1]) + nodes[elem.p[2]][1]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][1] );
ret -= r[1] * (nodes[elem.p[1]][0]*(nodes[elem.p[2]][2]-nodes[elem.p[3]][2]) -nodes[elem.p[1]][2]*(nodes[elem.p[2]][0]-nodes[elem.p[3]][0]) + nodes[elem.p[2]][0]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][0] );
ret += r[2] * (nodes[elem.p[1]][0]*(nodes[elem.p[2]][1]-nodes[elem.p[3]][1]) -nodes[elem.p[1]][1]*(nodes[elem.p[2]][0]-nodes[elem.p[3]][0]) + nodes[elem.p[2]][0]*nodes[elem.p[3]][1] - nodes[elem.p[2]][1]*nodes[elem.p[3]][0] );
ret -= nodes[elem.p[1]][0]*( nodes[elem.p[2]][1]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][1] ) -nodes[elem.p[1]][1]*( nodes[elem.p[2]][0]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][0] ) +nodes[elem.p[1]][2]*( nodes[elem.p[2]][0]*nodes[elem.p[3]][1] - nodes[elem.p[2]][1]*nodes[elem.p[3]][0] );
break;
case(1):
ret = nodes[elem.p[0]][0] * ( r[1]*(nodes[elem.p[2]][2]-nodes[elem.p[3]][2]) -r[2]*(nodes[elem.p[2]][1]-nodes[elem.p[3]][1]) + nodes[elem.p[2]][1]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][1] );
ret -= nodes[elem.p[0]][1] * (r[0]*(nodes[elem.p[2]][2]-nodes[elem.p[3]][2]) -r[2]*(nodes[elem.p[2]][0]-nodes[elem.p[3]][0]) + nodes[elem.p[2]][0]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][0] );
ret += nodes[elem.p[0]][2] * (r[0]*(nodes[elem.p[2]][1]-nodes[elem.p[3]][1]) -r[1]*(nodes[elem.p[2]][0]-nodes[elem.p[3]][0]) + nodes[elem.p[2]][0]*nodes[elem.p[3]][1] - nodes[elem.p[2]][1]*nodes[elem.p[3]][0] );
ret -= r[0]*( nodes[elem.p[2]][1]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][1] ) -r[1]*( nodes[elem.p[2]][0]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][0] ) +r[2]*( nodes[elem.p[2]][0]*nodes[elem.p[3]][1] - nodes[elem.p[2]][1]*nodes[elem.p[3]][0] );
break;
case(2):
ret = nodes[elem.p[0]][0] * ( nodes[elem.p[1]][1]*(r[2]-nodes[elem.p[3]][2]) -nodes[elem.p[1]][2]*(r[1]-nodes[elem.p[3]][1]) + r[1]*nodes[elem.p[3]][2] - r[2]*nodes[elem.p[3]][1] );
ret -= nodes[elem.p[0]][1] * (nodes[elem.p[1]][0]*(r[2]-nodes[elem.p[3]][2]) -nodes[elem.p[1]][2]*(r[0]-nodes[elem.p[3]][0]) + r[0]*nodes[elem.p[3]][2] - r[2]*nodes[elem.p[3]][0] );
ret += nodes[elem.p[0]][2] * (nodes[elem.p[1]][0]*(r[1]-nodes[elem.p[3]][1]) -nodes[elem.p[1]][1]*(r[0]-nodes[elem.p[3]][0]) + r[0]*nodes[elem.p[3]][1] - r[1]*nodes[elem.p[3]][0] );
ret -= nodes[elem.p[1]][0]*( r[1]*nodes[elem.p[3]][2] - r[2]*nodes[elem.p[3]][1] ) -nodes[elem.p[1]][1]*( r[0]*nodes[elem.p[3]][2] - r[2]*nodes[elem.p[3]][0] ) +nodes[elem.p[1]][2]*( r[0]*nodes[elem.p[3]][1] - r[1]*nodes[elem.p[3]][0] );
break;
case(3):
ret = nodes[elem.p[0]][0] * ( nodes[elem.p[1]][1]*(nodes[elem.p[2]][2]-r[2]) -nodes[elem.p[1]][2]*(nodes[elem.p[2]][1]-r[1]) + nodes[elem.p[2]][1]*r[2] - nodes[elem.p[2]][2]*r[1] );
ret -= nodes[elem.p[0]][1] * (nodes[elem.p[1]][0]*(nodes[elem.p[2]][2]-r[2]) -nodes[elem.p[1]][2]*(nodes[elem.p[2]][0]-r[0]) + nodes[elem.p[2]][0]*r[2] - nodes[elem.p[2]][2]*r[0] );
ret += nodes[elem.p[0]][2] * (nodes[elem.p[1]][0]*(nodes[elem.p[2]][1]-r[1]) -nodes[elem.p[1]][1]*(nodes[elem.p[2]][0]-r[0]) + nodes[elem.p[2]][0]*r[1] - nodes[elem.p[2]][1]*r[0] );
ret -= nodes[elem.p[1]][0] *( nodes[elem.p[2]][1]*r[2] - nodes[elem.p[2]][2]*r[1] ) -nodes[elem.p[1]][1]*( nodes[elem.p[2]][0]*r[2] - nodes[elem.p[2]][2]*r[0] ) + nodes[elem.p[1]][2]*( nodes[elem.p[2]][0]*r[1] - nodes[elem.p[2]][1]*r[0] );
break;
default:
cout << "Delaunay3D: det4(): ! Invalid argument i! Should be between 0 and 3 inclusive." << endl;
ret = -1;
}
return ret;
}
|
Slaedr/amovemesh
|
src/unused/extra_code.hpp
|
C++
|
gpl-3.0
| 10,133 |
//package org.aksw.autosparql.tbsl.algorithm.util;
//
//import java.util.Comparator;
//import java.util.HashMap;
//import java.util.Map;
//
//import org.dllearner.common.index.IndexResultItem;
//
//public class IndexResultItemComparator implements Comparator<IndexResultItem>{
// private String s;
// private Map<String, Double> cache;
//
// public IndexResultItemComparator(String s) {
// this.s = s;
// cache = new HashMap<String, Double>();
// }
//
// @Override
// public int compare(IndexResultItem item1, IndexResultItem item2) {
//
// double sim1 = 0;
// if(cache.containsKey(item1.getLabel())){
// sim1 = cache.get(item1.getLabel());
// } else {
// sim1 = Similarity.getSimilarity(s, item1.getLabel());
// cache.put(item1.getLabel(), sim1);
// }
// double sim2 = 0;
// if(cache.containsKey(item2.getLabel())){
// sim2 = cache.get(item2.getLabel());
// } else {
// sim2 = Similarity.getSimilarity(s, item2.getLabel());
// cache.put(item2.getLabel(), sim2);
// }
//
// if(sim1 < sim2){
// return 1;
// } else if(sim1 > sim2){
// return -1;
// } else {
// int val = item1.getLabel().compareTo(item2.getLabel());
// if(val == 0){
// return item1.getUri().compareTo(item2.getUri());
// }
// return val;
// }
// }
//}
|
AKSW/AutoSPARQL
|
algorithm-tbsl/src/main/java/org/aksw/autosparql/tbsl/algorithm/util/IndexResultItemComparator.java
|
Java
|
gpl-3.0
| 1,260 |
import {Logger, getLogger} from '../utils/logger';
import fs = require('fs');
import {Observable} from 'rxjs/Observable';
import {Subscriber} from 'rxjs/Subscriber';
import {Direction, AbstractAIN, AbstractGPIO, AbstractLED} from './abstract-ports';
export class GPIO extends AbstractGPIO {
public static readonly VALID_IDS: number[] = [2, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 20, 26, 27, 44, 45, 46, 47, 48, 49, 60, 61, 65, 66, 69, 115];
private static readonly logger: Logger = getLogger('GPIO');
private static readonly ROOT = '/sys/class/gpio/';
private static readonly UNEXPORT = GPIO.ROOT + 'unexport';
private static readonly EXPORT = GPIO.ROOT + 'export';
private static readonly BASE_NAME = 'gpio';
private outputObs: Observable<boolean> = null;
private intervalId: any = null;
private prevValue: number = 48; // ascii 0
constructor(protected id: number, private direction: Direction) {
super(id);
if (GPIO.VALID_IDS.filter(vid => vid != id).length === 0) {
throw new Error(`GPIO id ${id} is not valid!`);
}
let portName: string = this.getName();
// activate port if not yet done
if (!fs.existsSync(portName)) {
let cmd: string = `${GPIO.EXPORT}`;
fs.writeFileSync(cmd, id);
GPIO.logger.debug(`enable port id ${id}`);
}
// set port direction
let cmd = `${portName}/direction`;
fs.writeFileSync(cmd, this.directionVerb());
GPIO.logger.debug(`port ${id} direction ${this.directionVerb()}`);
// if output then set mode to edge
if (this.direction === Direction.INPUT) {
cmd = `${portName}/edge`;
fs.writeFileSync(cmd, 'none');
GPIO.logger.debug(`port ${id} edge on both`);
} else {
this.setState(false);
}
}
getName(): string {
return `${GPIO.ROOT}${GPIO.BASE_NAME}${this.id}`;
}
directionVerb(): string {
switch (this.direction) {
case Direction.INPUT:
return 'in';
case Direction.OUTPUT:
return 'out';
default:
return null;
}
}
setState(on: boolean): void {
if (this.direction === Direction.OUTPUT) {
let cmd: string = `${this.getName()}/value`;
let state: number = on ? 0 : 1; // on = 0, off = 1, i.e. inverted
GPIO.logger.debug(`setState ${cmd} to ${state}`);
if (fs.existsSync(cmd)) {
fs.writeFileSync(cmd, state);
GPIO.logger.debug('done');
} else {
GPIO.logger.error(`setState failed: ${cmd} does not exit`);
}
} else {
GPIO.logger.error(`setState ${this.getName()} not allowed for input pin`);
}
}
watch(): Observable<boolean> {
if (this.direction === Direction.INPUT) {
if (this.outputObs === null) {
this.outputObs = Observable.create((subscriber: Subscriber<boolean>) => {
let cmd: string = `${this.getName()}/value`;
GPIO.logger.debug(`watch ${cmd}`);
if (fs.existsSync(cmd)) {
this.read(subscriber, cmd);
} else {
subscriber.error(`watch failed: ${cmd} does not exist`);
subscriber.complete();
}
});
}
return this.outputObs;
} else {
GPIO.logger.error(`watch ${this.getName()} not allowed for output pin`);
}
}
private read(subscriber: Subscriber<boolean>, cmd: string, value?: boolean): void {
this.intervalId = setInterval(() => {
let data: Buffer = fs.readFileSync(cmd);
if (data) {
let val: number = data.readUInt8(0); // ascii value of 0 = 48, of 1 = 49
if (val !== this.prevValue) {
GPIO.logger.debug(`${this.getName()} input is ${val !== 48}`);
subscriber.next(val !== 48);
this.prevValue = val;
}
} else {
let errStr: string = `read ${cmd} failed with no data`;
GPIO.logger.error(errStr);
subscriber.error(errStr);
subscriber.complete();
clearInterval(this.intervalId);
}
}, 100);
}
reset(): void {
GPIO.logger.debug(`reset ${this.getName()} --> ${GPIO.UNEXPORT} for gpio${this.id}`);
if (fs.existsSync(this.getName())) {
if (this.intervalId !== null) {
clearInterval(this.intervalId);
}
fs.writeFileSync(GPIO.UNEXPORT, this.id);
GPIO.logger.debug('done');
} else {
GPIO.logger.error(`Reset failed: ${this.getName()} does not exit`);
}
}
toString(): string {
let portName: string = `${this.getName()}`;
if (fs.existsSync(portName)) {
let direction = fs.readFileSync(`${portName}}/direction`);
let edge = fs.readFileSync(`${portName}}/edge`);
let str = `${portName}: direction ${direction} [${this.directionVerb()}]`;
if (this.direction === Direction.OUTPUT) {
str += `, edge on ${edge} [none]`;
}
return str;
} else {
return `Unexpected: ${portName} does not exist!`;
}
}
}
export class AIN extends AbstractAIN {
public static readonly VALID_IDS: number[] = [0, 1, 2, 3, 4, 5, 6];
public static readonly MAX_VALUE: number = 4096;
private static readonly logger: Logger = getLogger('AIN');
private static readonly ROOT = '/sys/bus/iio/devices/iio:device0/';
private static readonly BASE_NAME = 'in_voltage';
private static readonly POST_FIX = '_raw';
private outputObs: Observable<number> = null;
private intervalId: any = null;
private doPoll: boolean = true;
constructor(protected id: number) {
super(id);
if (AIN.VALID_IDS.filter(vid => vid != id).length === 0) {
throw new Error(`AIN id ${id} is not valid!`);
}
}
getName(): string {
return `${AIN.ROOT}${AIN.BASE_NAME}${this.id}${AIN.POST_FIX}`;
}
poll(intervalSeconds: number): Observable<number> {
if (this.outputObs === null) {
this.outputObs = Observable.create((subscriber: Subscriber<number>) => {
AIN.logger.debug(`poll ${this.getName()} every ${intervalSeconds} second(s)`);
if (fs.existsSync(this.getName())) {
this.readInitialValue(subscriber);
this.doPoll = true;
this.intervalId = setInterval(() => {
if (this.doPoll) {
this.subscribeReadValue(subscriber);
} else {
subscriber.complete();
}
}, intervalSeconds * 1000);
} else {
subscriber.error(`poll failed: ${this.getName()} does not exist`);
subscriber.complete();
}
});
}
return this.outputObs;
}
private readInitialValue(subscriber: Subscriber<number>) {
this.subscribeReadValue(subscriber);
}
private subscribeReadValue(subscriber: Subscriber<number>) {
fs.readFile(this.getName(), (err, data) => {
if (err) {
subscriber.error(`read ${this.getName()} failed with ${err}`);
} else {
let val: number = Number(data.toString());
AIN.logger.debug(`${this.getName()}: value ${val}`);
subscriber.next(val);
}
});
}
stopPolling(): void {
AIN.logger.debug(`stopPolling ${this.getName()}`);
clearInterval(this.intervalId);
this.doPoll = false;
}
}
export class LED extends AbstractLED {
public static readonly VALID_IDS: number[] = [0, 1, 2, 3];
private static readonly logger: Logger = getLogger('SimulatedGPIO');
private static readonly ROOT = '/sys/class/leds/';
private static readonly BASE_NAME = 'beaglebone:green:usr';
constructor(protected id: number) {
super(id);
if (LED.VALID_IDS.filter(vid => vid != id).length === 0) {
throw new Error(`LED id ${id} is not valid!`);
}
this.setState(0);
}
getName(): string {
return `${LED.ROOT}${LED.BASE_NAME}${this.id}`;
}
setState(state: number): void {
let cmd: string = `${this.getName()}/brightness`;
LED.logger.debug(`setState ${cmd} to ${state}`);
if (fs.existsSync(cmd)) {
fs.writeFileSync(cmd, state);
} else {
LED.logger.error(`setState ${state} failed: ${cmd} does not exist`);
}
}
blink(delayOn: number, delayOff: number): void {
let cmdTimer: string = `${this.getName()}/trigger`;
let cmdOn: string = `${this.getName()}/delay_on`;
let cmdOff: string = `${this.getName()}/delay_off`;
LED.logger.debug(`blink ${cmdTimer} with ${delayOn}-${delayOff}`);
if (fs.existsSync(cmdTimer)) {
fs.writeFileSync(cmdTimer, 'timer');
fs.writeFileSync(cmdOn, delayOn);
fs.writeFileSync(cmdOff, delayOff);
} else {
LED.logger.error(`blink ${delayOn}-${delayOff} failed: ${cmdTimer} does not exist`);
}
}
heartbeat(): void {
let cmd: string = `${this.getName()}/trigger`;
let value: string = 'heartbeat';
LED.logger.debug(`heartbeat ${cmd} to ${value}`);
if (fs.existsSync(cmd)) {
fs.writeFileSync(cmd, value);
} else {
LED.logger.error(`heatbeat ${value} failed: ${cmd} does not exist`);
}
}
}
|
dleuenbe/project2
|
server/hardware/beaglebone-ports.ts
|
TypeScript
|
gpl-3.0
| 8,864 |
/* Copyright (C) 2003-2013 Runtime Revolution Ltd.
This file is part of LiveCode.
LiveCode is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License v3 as published by the Free
Software Foundation.
LiveCode is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with LiveCode. If not see <http://www.gnu.org/licenses/>. */
#include <foundation.h>
#include <foundation-auto.h>
#include "foundation-private.h"
////////////////////////////////////////////////////////////////////////////////
// This method ensures there is 'count' bytes of empty space starting at 'at'
// in 'r_data'. It returns false if allocation fails.
static bool __MCDataExpandAt(MCDataRef r_data, uindex_t at, uindex_t count);
// This method removes 'count' bytes from byte sequence starting at 'at'.
static void __MCDataShrinkAt(MCDataRef r_data, uindex_t at, uindex_t count);
// This method clamps the given range to the valid limits for the byte sequence.
static void __MCDataClampRange(MCDataRef r_data, MCRange& x_range);
static bool __MCDataMakeImmutable(__MCData *self);
////////////////////////////////////////////////////////////////////////////////
bool MCDataCreateWithBytes(const byte_t *p_bytes, uindex_t p_byte_count, MCDataRef& r_data)
{
bool t_success;
t_success = true;
__MCData *self;
self = nil;
if (t_success)
t_success = __MCValueCreate(kMCValueTypeCodeData, self);
if (t_success)
t_success = MCMemoryNewArray(p_byte_count, self -> bytes);
if (t_success)
{
MCMemoryCopy(self -> bytes, p_bytes, p_byte_count);
self -> byte_count = p_byte_count;
r_data = self;
}
else
{
if (self != nil)
MCMemoryDeleteArray(self -> bytes);
MCMemoryDelete(self);
}
return t_success;
}
bool MCDataCreateWithBytesAndRelease(byte_t *p_bytes, uindex_t p_byte_count, MCDataRef& r_data)
{
if (MCDataCreateWithBytes(p_bytes, p_byte_count, r_data))
{
MCMemoryDeallocate(p_bytes);
return true;
}
return false;
}
bool MCDataIsEmpty(MCDataRef p_data)
{
return p_data -> byte_count == 0;
}
uindex_t MCDataGetLength(MCDataRef p_data)
{
return p_data->byte_count;
}
const byte_t *MCDataGetBytePtr(MCDataRef p_data)
{
return p_data->bytes;
}
byte_t MCDataGetByteAtIndex(MCDataRef p_data, uindex_t p_index)
{
return p_data->bytes[p_index];
}
hash_t MCDataHash(MCDataRef p_data);
bool MCDataIsEqualTo(MCDataRef p_left, MCDataRef p_right)
{
if (p_left -> byte_count != p_right -> byte_count)
return false;
return MCMemoryCompare(p_left -> bytes, p_right -> bytes, p_left -> byte_count) == 0;
}
compare_t MCDataCompareTo(MCDataRef p_left, MCDataRef p_right);
// Mutable data methods
bool MCDataCreateMutable(uindex_t p_initial_capacity, MCDataRef& r_data)
{
bool t_success;
t_success = true;
__MCData *self;
self = nil;
if (t_success)
t_success = __MCValueCreate(kMCValueTypeCodeData, self);
if (t_success)
t_success = __MCDataExpandAt(self, 0, p_initial_capacity);
if (t_success)
{
self->flags |= kMCDataFlagIsMutable;
r_data = self;
}
return t_success;
}
bool MCDataCopy(MCDataRef p_data, MCDataRef& r_new_data)
{
if (!MCDataIsMutable(p_data))
{
MCValueRetain(p_data);
r_new_data = p_data;
return true;
}
return MCDataCreateWithBytes(p_data->bytes, p_data->byte_count, r_new_data);
}
bool MCDataCopyAndRelease(MCDataRef p_data, MCDataRef& r_new_data)
{
// If the MCData is immutable we just pass it through (as we are releasing it).
if (!MCDataIsMutable(p_data))
{
r_new_data = p_data;
return true;
}
// If the reference is 1, convert it to an immutable MCData
if (p_data->references == 1)
{
__MCDataMakeImmutable(p_data);
p_data->flags &= ~kMCDataFlagIsMutable;
r_new_data = p_data;
return true;
}
// Otherwise make a copy of the data and then release the original
bool t_success;
t_success = MCDataCreateWithBytes(p_data->bytes, p_data->byte_count, r_new_data);
MCValueRelease(p_data);
return t_success;
}
bool MCDataMutableCopy(MCDataRef p_data, MCDataRef& r_mutable_data)
{
MCDataRef t_mutable_data;
if (!MCDataCreateMutable(p_data->byte_count, t_mutable_data))
return false;
MCMemoryCopy(t_mutable_data->bytes, p_data->bytes, p_data->byte_count);
t_mutable_data->byte_count = p_data->byte_count;
r_mutable_data = t_mutable_data;
return true;
}
bool MCDataMutableCopyAndRelease(MCDataRef p_data, MCDataRef& r_mutable_data)
{
if (MCDataMutableCopy(p_data, r_mutable_data))
{
MCValueRelease(p_data);
return true;
}
return false;
}
bool MCDataCopyRange(MCDataRef self, MCRange p_range, MCDataRef& r_new_data)
{
__MCDataClampRange(self, p_range);
return MCDataCreateWithBytes(self -> bytes + p_range . offset, p_range . length, r_new_data);
}
bool MCDataCopyRangeAndRelease(MCDataRef self, MCRange p_range, MCDataRef& r_new_data)
{
if (MCDataCopyRange(self, p_range, r_new_data))
{
MCValueRelease(self);
return true;
}
return false;
}
bool MCDataIsMutable(const MCDataRef p_data)
{
return (p_data->flags & kMCDataFlagIsMutable) != 0;
}
bool MCDataAppend(MCDataRef r_data, MCDataRef p_suffix)
{
MCAssert(MCDataIsMutable(r_data));
if (r_data == p_suffix)
{
// Must copy first the suffix
MCDataRef t_suffix_copy;
if(!MCDataCopy(r_data, t_suffix_copy))
return false;
// Copy succeeded: can process recursively the appending, and then release the newly created suffix.
bool t_success = MCDataAppend(r_data, t_suffix_copy);
MCValueRelease(t_suffix_copy);
return t_success;
}
if (!__MCDataExpandAt(r_data, r_data->byte_count, p_suffix->byte_count))
return false;
MCMemoryCopy(r_data->bytes + r_data->byte_count - p_suffix->byte_count, p_suffix->bytes, p_suffix->byte_count);
return true;
}
bool MCDataAppendBytes(MCDataRef r_data, const byte_t *p_bytes, uindex_t p_byte_count)
{
MCAssert(MCDataIsMutable(r_data));
// Expand the capacity if necessary
if (!__MCDataExpandAt(r_data, r_data->byte_count, p_byte_count))
return false;
MCMemoryCopy(r_data->bytes + r_data->byte_count - p_byte_count, p_bytes, p_byte_count);
return true;
}
bool MCDataAppendByte(MCDataRef r_data, byte_t p_byte)
{
MCAssert(MCDataIsMutable(r_data));
return MCDataAppendBytes(r_data, &p_byte, 1);
}
bool MCDataPrepend(MCDataRef r_data, MCDataRef p_prefix)
{
MCAssert(MCDataIsMutable(r_data));
if (r_data == p_prefix)
{
// Must copy first the prefix
MCDataRef t_prefix_copy;
if(!MCDataCopy(r_data, t_prefix_copy))
return false;
// Copy succeeded: can process recursively the appending, and then release the newly created suffix.
bool t_success = MCDataPrepend(r_data, t_prefix_copy);
MCValueRelease(t_prefix_copy);
return t_success;
}
// Ensure there is room enough to copy the prefix
if (!__MCDataExpandAt(r_data, 0, p_prefix->byte_count))
return false;
MCMemoryCopy(r_data->bytes, p_prefix->bytes, p_prefix->byte_count);
return true;
}
bool MCDataPrependBytes(MCDataRef r_data, const byte_t *p_bytes, uindex_t p_byte_count)
{
MCAssert(MCDataIsMutable(r_data));
// Ensure there is room enough to copy the prefix
if (!__MCDataExpandAt(r_data, 0, p_byte_count))
return false;
MCMemoryCopy(r_data->bytes, p_bytes, p_byte_count);
return true;
}
bool MCDataPrependByte(MCDataRef r_data, byte_t p_byte)
{
return MCDataPrependBytes(r_data, &p_byte, 1);
}
bool MCDataInsert(MCDataRef r_data, uindex_t p_at, MCDataRef p_new_data)
{
MCAssert(MCDataIsMutable(r_data));
if (r_data == p_new_data)
{
// Must copy first the prefix
MCDataRef t_new_data_copy;
if(!MCDataCopy(r_data, t_new_data_copy))
return false;
// Copy succeeded: can process recursively the appending, and then release the newly created suffix.
bool t_success = MCDataPrepend(r_data, t_new_data_copy);
MCValueRelease(t_new_data_copy);
return t_success;
}
// Ensure there is room enough to copy the prefix
if (!__MCDataExpandAt(r_data, p_at, p_new_data->byte_count))
return false;
MCMemoryCopy(r_data->bytes, p_new_data->bytes, p_new_data->byte_count);
return true;
}
bool MCDataRemove(MCDataRef r_data, MCRange p_range)
{
MCAssert(MCDataIsMutable(r_data));
__MCDataClampRange(r_data, p_range);
// Copy down the bytes above
__MCDataShrinkAt(r_data, p_range.offset, p_range.length);
// We succeeded.
return true;
}
bool MCDataReplace(MCDataRef r_data, MCRange p_range, MCDataRef p_new_data)
{
MCAssert(MCDataIsMutable(r_data));
if (r_data == p_new_data)
{
MCDataRef t_new_data;
if (!MCDataCopy(p_new_data, t_new_data))
return false;
bool t_success = MCDataReplace(r_data, p_range, t_new_data);
MCValueRelease(t_new_data);
return t_success;
}
__MCDataClampRange(r_data, p_range);
// Work out the new size of the string.
uindex_t t_new_char_count;
t_new_char_count = r_data->byte_count - p_range.length + p_new_data->byte_count;
if (t_new_char_count > r_data->byte_count)
{
// Expand the string at the end of the range by the amount extra we
// need.
if (!__MCDataExpandAt(r_data, p_range.offset + p_range.length, t_new_char_count - r_data->byte_count))
return false;
}
else if (t_new_char_count < r_data->byte_count)
{
// Shrink the last part of the range by the amount less we need.
__MCDataShrinkAt(r_data, p_range.offset + (p_range.length - (r_data->byte_count - t_new_char_count)), (r_data->byte_count - t_new_char_count));
}
// Copy across the replacement chars.
MCMemoryCopy(r_data->bytes + p_range.offset, p_new_data->bytes, p_new_data->byte_count);
// We succeeded.
return true;
}
bool MCDataPad(MCDataRef p_data, byte_t p_byte, uindex_t p_count)
{
if (!__MCDataExpandAt(p_data, p_data -> byte_count, p_count))
return false;
memset(p_data -> bytes + p_data -> byte_count - p_count, p_byte, p_count);
return true;
}
compare_t MCDataCompareTo(MCDataRef p_left, MCDataRef p_right)
{
compare_t t_result;
t_result = memcmp(p_left -> bytes, p_right -> bytes, MCMin(p_left -> byte_count, p_right -> byte_count));
if (t_result != 0)
return t_result;
return p_left -> byte_count - p_right -> byte_count;
}
#if defined(__MAC__) || defined (__IOS__)
bool MCDataConvertToCFDataRef(MCDataRef p_data, CFDataRef& r_cfdata)
{
r_cfdata = CFDataCreate(nil, MCDataGetBytePtr(p_data), MCDataGetLength(p_data));
return r_cfdata != nil;
}
#endif
static void __MCDataClampRange(MCDataRef p_data, MCRange& x_range)
{
uindex_t t_left, t_right;
t_left = MCMin(x_range . offset, p_data -> byte_count);
t_right = MCMin(x_range . offset + MCMin(x_range . length, UINDEX_MAX - x_range . offset), p_data->byte_count);
x_range . offset = t_left;
x_range . length = t_right - t_left;
}
static void __MCDataShrinkAt(MCDataRef r_data, uindex_t p_at, uindex_t p_count)
{
// Shift the bytes above 'at' down to remove 'count'
MCMemoryMove(r_data->bytes + p_at, r_data->bytes + (p_at + p_count), r_data->byte_count - (p_at + p_count));
// Now adjust the length of the string.
r_data->byte_count -= p_count;
// TODO: Shrink the buffer if its too big.
}
static bool __MCDataExpandAt(MCDataRef r_data, uindex_t p_at, uindex_t p_count)
{
// Fetch the capacity.
uindex_t t_capacity;
t_capacity = r_data->capacity;
// The capacity field stores the total number of chars that could fit not
// including the implicit NUL, so if we fit, we can fast-track.
if (t_capacity != 0 && r_data->byte_count + p_count <= t_capacity)
{
// Shift up the bytes above
MCMemoryMove(r_data->bytes + p_at + p_count,r_data->bytes + p_at, r_data->byte_count - p_at);
// Increase the byte_count.
r_data->byte_count += p_count;
// We succeeded.
return true;
}
// If we get here then we need to reallocate first.
// Base capacity - current length + inserted length
uindex_t t_new_capacity;
t_new_capacity = r_data->byte_count + p_count;
// Capacity rounded up to a suitable boundary (at some point this should
// be a function of the string's size).
t_new_capacity = (t_new_capacity + 63) & ~63;
// Reallocate.
if (!MCMemoryReallocate(r_data->bytes, t_new_capacity, r_data->bytes))
return false;
// Shift up the bytes above
MCMemoryMove(r_data->bytes + p_at + p_count, r_data->bytes + p_at, r_data->byte_count - p_at);
// Increase the byte_count.
r_data->byte_count += p_count;
// Update the capacity
r_data -> capacity = t_new_capacity;
// We succeeded.
return true;
}
static bool __MCDataMakeImmutable(__MCData *self)
{
if (!MCMemoryResizeArray(self -> byte_count, self -> bytes, self -> byte_count))
return false;
return true;
}
////////////////////////////////////////////////////////////////////////////////
MCDataRef kMCEmptyData;
bool __MCDataInitialize(void)
{
if (!MCDataCreateWithBytes(nil, 0, kMCEmptyData))
return false;
return true;
}
void __MCDataFinalize(void)
{
MCValueRelease(kMCEmptyData);
}
void __MCDataDestroy(__MCData *self)
{
if (self -> bytes != nil)
MCMemoryDeleteArray(self -> bytes);
}
bool __MCDataImmutableCopy(__MCData *self, bool p_release, __MCData *&r_immutable_value)
{
if (!p_release)
return MCDataCopy(self, r_immutable_value);
return MCDataCopyAndRelease(self, r_immutable_value);
}
bool __MCDataIsEqualTo(__MCData *self, __MCData *p_other_data)
{
return MCDataIsEqualTo(self, p_other_data);
}
hash_t __MCDataHash(__MCData *self)
{
return MCHashBytes(self -> bytes, self -> byte_count);
}
bool __MCDataCopyDescription(__MCData *self, MCStringRef &r_description)
{
return false;
}
|
livecodefraser/livecode
|
libfoundation/src/foundation-data.cpp
|
C++
|
gpl-3.0
| 14,664 |
/*
* Copyright (C) 2015 Lenny Knockaert <lknockx@gmail.com>
*
* This file is part of ZetCam
*
* ZetCam is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ZetCam is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.maksvzw.zetcam.core.audio.buffers;
import com.xuggle.xuggler.IAudioSamples;
/**
*
* @author Lenny Knockaert
*/
public abstract class ByteSampleBuffer extends AudioSampleBuffer<Byte>
{
private final byte[] tempBuf;
private byte[] mixBuf;
protected ByteSampleBuffer(IAudioSamples samples)
{
super(samples);
this.tempBuf = new byte[1024];
}
@Override
protected final Byte getSample(IAudioSamples samples, int index)
{
samples.get(index, this.tempBuf, 0, 1);
return this.tempBuf[0];
}
@Override
protected final void putSample(IAudioSamples samples, int index, Byte sample)
{
this.tempBuf[0] = sample;
samples.put(this.tempBuf, 0, index, 1);
}
@Override
protected final void copySamples(IAudioSamples src, int srcIndex, IAudioSamples dst, int dstIndex, int length)
{
int tempLength;
while(length > 0) {
tempLength = Math.min(this.tempBuf.length, length);
src.get(srcIndex, this.tempBuf, 0, tempLength);
dst.put(this.tempBuf, 0, dstIndex, tempLength);
srcIndex += tempLength;
dstIndex += tempLength;
length -= tempLength;
}
}
@Override
protected final void mixSamples(IAudioSamples src, int srcIndex, IAudioSamples dst, int dstIndex, int length)
{
if (this.mixBuf == null)
this.mixBuf = new byte[this.tempBuf.length];
int tempLength;
while(length > 0) {
tempLength = Math.min(this.tempBuf.length, length);
src.get(srcIndex, this.tempBuf, 0, tempLength);
dst.get(srcIndex, this.mixBuf, 0, tempLength);
for(int i = 0; i < tempLength; i++)
this.mixBuf[i] = this.mixSample(this.tempBuf[i], this.mixBuf[i]);
dst.put(this.mixBuf, 0, dstIndex, tempLength);
srcIndex += tempLength;
dstIndex += tempLength;
length -= tempLength;
}
}
@Override
protected final void scaleSamples(IAudioSamples samples, int index, int length, double scale)
{
int tempLength;
while(length > 0) {
tempLength = Math.min(length, this.tempBuf.length);
samples.get(index, this.tempBuf, 0, tempLength);
for(int i = 0; i < tempLength; i++)
this.tempBuf[i] = this.scaleSample(this.tempBuf[i], scale);
samples.put(this.tempBuf, 0, index, tempLength);
length -= tempLength;
index += tempLength;
}
}
@Override
protected final void fillSamples(IAudioSamples samples, int index, int length, Byte sample)
{
int tempLength;
while(length > 0) {
tempLength = Math.min(length, this.tempBuf.length);
samples.get(index, this.tempBuf, 0, tempLength);
for(int i = 0; i < tempLength; i++)
this.tempBuf[i] = sample;
samples.put(this.tempBuf, 0, index, tempLength);
length -= tempLength;
index += tempLength;
}
}
}
|
maksvzw/zetcam
|
src/main/java/org/maksvzw/zetcam/core/audio/buffers/ByteSampleBuffer.java
|
Java
|
gpl-3.0
| 3,890 |
package me.staartvin.statz.datamanager.player.specification;
import java.util.UUID;
public class EnteredBedsSpecification extends PlayerStatSpecification {
public EnteredBedsSpecification(UUID uuid, int value, String worldName) {
super();
this.putInData(Keys.UUID.toString(), uuid);
this.putInData(Keys.VALUE.toString(), value);
this.putInData(Keys.WORLD.toString(), worldName);
}
@Override
public boolean hasWorldSupport() {
return true;
}
public enum Keys {UUID, VALUE, WORLD}
}
|
Staartvin/Statz
|
src/me/staartvin/statz/datamanager/player/specification/EnteredBedsSpecification.java
|
Java
|
gpl-3.0
| 551 |
export default {
div: 'Div',
aside: 'Aside',
main: 'Main',
h1: 'Heading',
h2: 'Heading',
h3: 'Heading',
h4: 'Heading',
h5: 'Heading',
h6: 'Heading',
p: 'Paragraph',
span: 'Span',
ul: 'Unordered List',
li: 'List Item',
img: 'Image',
strong: 'Strong Text',
em: 'Emphasised Text',
i: 'Icon',
a: 'Link',
input: 'Input',
blockquote: 'Quote',
figcaption: 'Caption',
button: 'Button',
header: 'Header',
footer: 'Footer'
};
|
builify/builify
|
src/javascript/components/canvas/click-toolbox/html-tagnames.js
|
JavaScript
|
gpl-3.0
| 512 |
// watch
"use strict";
module.exports = {
options: {
livereload: false
},
// docs: {
// files: [
// "<%= pkg.source %>" + "/javascript/**/*.js"
// ],
// tasks: [
// "docs"
// ]
// },
js: {
files: [
"<%= pkg.source %>" + "/javascript/**/*.js"
],
tasks: [
// 'clean:js',
"newer:copy:js",
"newer:copy:libs"
]
},
html: {
files: [
"<%= pkg.source %>" + "/html/**/*.html"
],
tasks: [
// 'clean:html',
"newer:copy:html"
]
},
less: {
files: [
"<%= pkg.source %>" + "/css/**/*.less"
],
tasks: [
"less:dev",
"postcss:dev"
]
},
images: {
files: [
"<%= pkg.source %>" + "/images/**/*.{png,jpg,jpeg,gif}"
],
tasks: [
"newer:imagemin:dev"
]
},
livereload: {
options: {
livereload: true
},
files: [
"<%= pkg.development %>" + "/**/*"
]
}
};
|
LOA-SEAD/cuidando-bem
|
grunt/options/watch.js
|
JavaScript
|
gpl-3.0
| 1,178 |
/*===========================================================================*\
* *
* OpenFlipper *
* Copyright (C) 2001-2014 by Computer Graphics Group, RWTH Aachen *
* www.openflipper.org *
* *
*--------------------------------------------------------------------------- *
* This file is part of OpenFlipper. *
* *
* OpenFlipper is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenFlipper is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU LesserGeneral Public *
* License along with OpenFlipper. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision$ *
* $LastChangedBy$ *
* $Date$ *
* *
\*===========================================================================*/
#ifdef ENABLE_OPENVOLUMEMESH_SUPPORT
#define OVM_PROPERTY_VISUALIZER_CC
#ifdef ENABLE_OPENVOLUMEMESH_POLYHEDRAL_SUPPORT
#include <ObjectTypes/PolyhedralMesh/PolyhedralMesh.hh>
#endif
#ifdef ENABLE_OPENVOLUMEMESH_HEXAHEDRAL_SUPPORT
#include <ObjectTypes/HexahedralMesh/HexahedralMesh.hh>
#endif
#include "OVMPropertyVisualizer.hh"
template <typename MeshT>
template <typename InnerType>
QString OVMPropertyVisualizer<MeshT>::getPropertyText_(unsigned int index)
{
if (PropertyVisualizer::propertyInfo.isCellProp())
{
OpenVolumeMesh::CellPropertyT<InnerType> prop = OVMPropertyVisualizer<MeshT>::mesh->template request_cell_property<InnerType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
return PropertyVisualizer::toStr(prop[OpenVolumeMesh::CellHandle(index)]);
}
else if (PropertyVisualizer::propertyInfo.isFaceProp())
{
OpenVolumeMesh::FacePropertyT<InnerType> prop = OVMPropertyVisualizer<MeshT>::mesh->template request_face_property<InnerType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
return PropertyVisualizer::toStr(prop[OpenVolumeMesh::FaceHandle(index)]);
}
else if (PropertyVisualizer::propertyInfo.isHalffaceProp())
{
OpenVolumeMesh::HalfFacePropertyT<InnerType> prop = OVMPropertyVisualizer<MeshT>::mesh->template request_halfface_property<InnerType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
return PropertyVisualizer::toStr(prop[OpenVolumeMesh::HalfFaceHandle(index)]);
}
else if (PropertyVisualizer::propertyInfo.isEdgeProp())
{
OpenVolumeMesh::EdgePropertyT<InnerType> prop = OVMPropertyVisualizer<MeshT>::mesh->template request_edge_property<InnerType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
return PropertyVisualizer::toStr(prop[OpenVolumeMesh::EdgeHandle(index)]);
}
else if (PropertyVisualizer::propertyInfo.isHalfedgeProp())
{
OpenVolumeMesh::HalfEdgePropertyT<InnerType> prop = OVMPropertyVisualizer<MeshT>::mesh->template request_halfedge_property<InnerType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
return PropertyVisualizer::toStr(prop[OpenVolumeMesh::HalfEdgeHandle(index)]);
}
else //if (propertyInfo.isVertexProp())
{
OpenVolumeMesh::VertexPropertyT<InnerType> prop = OVMPropertyVisualizer<MeshT>::mesh->template request_vertex_property<InnerType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
return PropertyVisualizer::toStr(prop[OpenVolumeMesh::VertexHandle(index)]);
}
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::setPropertyFromText(unsigned int index, QString text)
{
if (propertyInfo.isCellProp())
setCellPropertyFromText(index, text);
else if (propertyInfo.isFaceProp())
setFacePropertyFromText(index, text);
else if (propertyInfo.isHalffaceProp())
setHalffacePropertyFromText(index, text);
else if (propertyInfo.isEdgeProp())
setEdgePropertyFromText(index, text);
else if (propertyInfo.isHalfedgeProp())
setHalfedgePropertyFromText(index, text);
else //if (propertyInfo.isVertexProp())
setVertexPropertyFromText(index, text);
}
template <typename MeshT>
int OVMPropertyVisualizer<MeshT>::getEntityCount()
{
if (propertyInfo.isCellProp())
return mesh->n_cells();
if (propertyInfo.isFaceProp())
return mesh->n_faces();
if (propertyInfo.isHalffaceProp())
return mesh->n_halffaces();
else if (propertyInfo.isEdgeProp())
return mesh->n_edges();
else if (propertyInfo.isHalfedgeProp())
return mesh->n_halfedges();
else //if (propertyInfo.isVertexProp())
return mesh->n_vertices();
}
template <typename MeshT>
QString OVMPropertyVisualizer<MeshT>::getHeader()
{
//Header: headerVersion, numberOfEntities, typeOfEntites, typeOfProperty, propertyName
QString header = QObject::tr("1"); //version
header.append(QObject::tr(", %1").arg(getEntityCount())); //number of entities
header.append(QObject::tr(", %1").arg(propertyInfo.entityType())); //type of entities
header.append(", ").append(propertyInfo.friendlyTypeName()); //type of property
header.append(", ").append(propertyInfo.propName().c_str()); // name of property
return header;
}
template <typename MeshT>
unsigned int OVMPropertyVisualizer<MeshT>::getClosestPrimitiveId(unsigned int _face, ACG::Vec3d& _hitPoint)
{
if (propertyInfo.isHalffaceProp())
return getClosestHalffaceId(_face, _hitPoint);
else// if (propertyInfo.isHalfedgeProp())
return getClosestHalfedgeId(_face, _hitPoint);
}
template <typename MeshT>
unsigned int OVMPropertyVisualizer<MeshT>::getClosestHalffaceId(unsigned int _face, ACG::Vec3d& _hitPoint)
{
ACG::Vec3d direction = PluginFunctions::viewingDirection();
OpenVolumeMesh::HalfFaceHandle hfh = mesh->halfface_handle(OpenVolumeMesh::FaceHandle(_face), 0);
OpenVolumeMesh::HalfFaceVertexIter hfv_it = mesh->hfv_iter(hfh);
ACG::Vec3d p1 = mesh->vertex(*(hfv_it+0));
ACG::Vec3d p2 = mesh->vertex(*(hfv_it+1));
ACG::Vec3d p3 = mesh->vertex(*(hfv_it+2));
ACG::Vec3d normal = (p2-p1)%(p3-p1);
if ((direction | normal) < 0)
return hfh.idx();
else
return mesh->halfface_handle(OpenVolumeMesh::FaceHandle(_face), 1).idx();
}
template <typename MeshT>
unsigned int OVMPropertyVisualizer<MeshT>::getClosestHalfedgeId(unsigned int _face, ACG::Vec3d& _hitPoint)
{
unsigned int halfface = getClosestHalffaceId(_face, _hitPoint);
OpenVolumeMesh::OpenVolumeMeshFace face = mesh->halfface(halfface);
const std::vector<OpenVolumeMesh::HalfEdgeHandle> & halfedges = face.halfedges();
double min_distance = DBL_MAX;
OpenVolumeMesh::HalfEdgeHandle closestHalfEdgeHandle;
for (std::vector<OpenVolumeMesh::HalfEdgeHandle>::const_iterator he_it = halfedges.begin(); he_it != halfedges.end(); ++he_it)
{
OpenVolumeMesh::OpenVolumeMeshEdge edge = OVMPropertyVisualizer<MeshT>::mesh->halfedge(*he_it);
ACG::Vec3d v1 = mesh->vertex(edge.from_vertex());
ACG::Vec3d v2 = mesh->vertex(edge.to_vertex());
ACG::Vec3d p = 0.5 * (v1+v2);
double distance = (p-_hitPoint).length();
if (distance < min_distance)
{
min_distance = distance;
closestHalfEdgeHandle = *he_it;
}
}
return closestHalfEdgeHandle.idx();
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::visualize(bool _setDrawMode)
{
if (propertyInfo.isCellProp())
visualizeCellProp(_setDrawMode);
else if (propertyInfo.isFaceProp())
visualizeFaceProp(_setDrawMode);
else if (propertyInfo.isHalffaceProp())
visualizeHalffaceProp(_setDrawMode);
else if (propertyInfo.isEdgeProp())
visualizeEdgeProp(_setDrawMode);
else if (propertyInfo.isHalfedgeProp())
visualizeHalfedgeProp(_setDrawMode);
else if (propertyInfo.isVertexProp())
visualizeVertexProp(_setDrawMode);
}
template <typename MeshT>
OpenMesh::Vec4f OVMPropertyVisualizer<MeshT>::convertColor(const QColor _color){
OpenMesh::Vec4f color;
color[0] = _color.redF();
color[1] = _color.greenF();
color[2] = _color.blueF();
color[3] = _color.alphaF();
return color;
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::visualizeFaceProp(bool /*_setDrawMode*/)
{
emit log(LOGERR, "Visualizing FaceProp not implemented");
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::visualizeEdgeProp(bool /*_setDrawMode*/)
{
emit log(LOGERR, "Visualizing EdgeProp not implemented");
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::visualizeHalfedgeProp(bool /*_setDrawMode*/)
{
emit log(LOGERR, "Visualizing HalfedgeProp not implemented");
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::visualizeVertexProp(bool /*_setDrawMode*/)
{
emit log(LOGERR, "Visualizing VertexProp not implemented");
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::visualizeCellProp(bool /*_setDrawMode*/)
{
emit log(LOGERR, "Visualizing CellProp not implemented");
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::visualizeHalffaceProp(bool /*_setDrawMode*/)
{
emit log(LOGERR, "Visualizing HalffaceProp not implemented");
}
template<typename MeshT>
template<typename PropType>
inline void OVMPropertyVisualizer<MeshT>::duplicateProperty_stage1() {
std::string newPropertyName;
for (int i = 1;; ++i) {
std::ostringstream oss;
oss << propertyInfo.propName() << " Copy " << i;
newPropertyName = oss.str();
if (propertyInfo.isCellProp())
{
if(!mesh->template cell_property_exists<PropType>(newPropertyName)) break;
}
else if (propertyInfo.isFaceProp())
{
if(!mesh->template face_property_exists<PropType>(newPropertyName)) break;
}
else if (propertyInfo.isHalffaceProp())
{
if(!mesh->template halfface_property_exists<PropType>(newPropertyName)) break;
}
else if (propertyInfo.isEdgeProp())
{
if(!mesh->template edge_property_exists<PropType>(newPropertyName)) break;
}
else if (propertyInfo.isHalfedgeProp())
{
if(!mesh->template halfedge_property_exists<PropType>(newPropertyName)) break;
}
else if (propertyInfo.isVertexProp())
{
if(!mesh->template vertex_property_exists<PropType>(newPropertyName)) break;
}
}
if (propertyInfo.isCellProp())
{
OpenVolumeMesh::CellPropertyT<PropType> prop = mesh->template request_cell_property<PropType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
OpenVolumeMesh::CellPropertyT<PropType> newProp = mesh->template request_cell_property< PropType >(newPropertyName);
mesh->set_persistent(newProp, true);
std::for_each(mesh->cells_begin(), mesh->cells_end(), CopyProperty<OpenVolumeMesh::CellPropertyT<PropType> >(newProp, prop, mesh));
}
else if (propertyInfo.isFaceProp())
{
OpenVolumeMesh::FacePropertyT<PropType> prop = mesh->template request_face_property<PropType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
OpenVolumeMesh::FacePropertyT<PropType> newProp = mesh->template request_face_property< PropType >(newPropertyName);
mesh->set_persistent(newProp, true);
std::for_each(mesh->faces_begin(), mesh->faces_end(), CopyProperty<OpenVolumeMesh::FacePropertyT<PropType> >(newProp, prop, mesh));
}
else if (propertyInfo.isHalffaceProp())
{
OpenVolumeMesh::HalfFacePropertyT<PropType> prop = mesh->template request_halfface_property<PropType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
OpenVolumeMesh::HalfFacePropertyT<PropType> newProp = mesh->template request_halfface_property< PropType >(newPropertyName);
mesh->set_persistent(newProp, true);
std::for_each(mesh->halffaces_begin(), mesh->halffaces_end(), CopyProperty<OpenVolumeMesh::HalfFacePropertyT<PropType> >(newProp, prop, mesh));
}
else if (propertyInfo.isEdgeProp())
{
OpenVolumeMesh::EdgePropertyT<PropType> prop = mesh->template request_edge_property<PropType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
OpenVolumeMesh::EdgePropertyT<PropType> newProp = mesh->template request_edge_property< PropType >(newPropertyName);
mesh->set_persistent(newProp, true);
std::for_each(mesh->edges_begin(), mesh->edges_end(), CopyProperty<OpenVolumeMesh::EdgePropertyT<PropType> >(newProp, prop, mesh));
}
else if (propertyInfo.isHalfedgeProp())
{
OpenVolumeMesh::HalfEdgePropertyT<PropType> prop = mesh->template request_halfedge_property<PropType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
OpenVolumeMesh::HalfEdgePropertyT<PropType> newProp = mesh->template request_halfedge_property< PropType >(newPropertyName);
mesh->set_persistent(newProp, true);
std::for_each(mesh->halfedges_begin(), mesh->halfedges_end(), CopyProperty<OpenVolumeMesh::HalfEdgePropertyT<PropType> >(newProp, prop, mesh));
}
else if (propertyInfo.isVertexProp())
{
OpenVolumeMesh::VertexPropertyT<PropType> prop = mesh->template request_vertex_property<PropType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
OpenVolumeMesh::VertexPropertyT<PropType> newProp = mesh->template request_vertex_property< PropType >(newPropertyName);
mesh->set_persistent(newProp, true);
std::for_each(mesh->vertices_begin(), mesh->vertices_end(), CopyProperty<OpenVolumeMesh::VertexPropertyT<PropType> >(newProp, prop, mesh));
}
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::clear()
{
VolumeMeshObject<MeshT>* object;
PluginFunctions::getObject(OVMPropertyVisualizer<MeshT>::mObjectID, object);
if (propertyInfo.isCellProp())
object->colors().clear_cell_colors();
else if (propertyInfo.isFaceProp())
object->colors().clear_face_colors();
else if (propertyInfo.isHalffaceProp())
object->colors().clear_halfface_colors();
else if (propertyInfo.isEdgeProp())
object->colors().clear_edge_colors();
else if (propertyInfo.isHalfedgeProp())
object->colors().clear_halfedge_colors();
else if (propertyInfo.isVertexProp())
object->colors().clear_vertex_colors();
object->setObjectDrawMode(drawModes.cellsFlatShaded);
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::setCellPropertyFromText(unsigned int /*index*/, QString /*text*/)
{
emit log(LOGERR, "Setting CellProp not implemented for this property type");
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::setFacePropertyFromText(unsigned int /*index*/, QString /*text*/)
{
emit log(LOGERR, "Setting FaceProp not implemented for this property type");
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::setHalffacePropertyFromText(unsigned int /*index*/, QString /*text*/)
{
emit log(LOGERR, "Setting HalffaceProp not implemented for this property type");
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::setEdgePropertyFromText(unsigned int /*index*/, QString /*text*/)
{
emit log(LOGERR, "Setting EdgeProp not implemented for this property type");
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::setHalfedgePropertyFromText(unsigned int /*index*/, QString /*text*/)
{
emit log(LOGERR, "Setting HalfedgeProp not implemented for this property type");
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::setVertexPropertyFromText(unsigned int /*index*/, QString /*text*/)
{
emit log(LOGERR, "Setting VertexProp not implemented for this property type");
}
#endif /* ENABLE_OPENVOLUMEMESH_SUPPORT */
|
heartvalve/OpenFlipper
|
Plugin-PropertyVis/OpenVolumeMesh/OVMPropertyVisualizerT.cc
|
C++
|
gpl-3.0
| 18,016 |
///**
// * This file is part of FXL GUI API.
// *
// * FXL GUI API is free software: you can redistribute it and/or modify
// * it under the terms of the GNU General Public License as published by
// * the Free Software Foundation, either version 3 of the License, or
// * (at your option) any later version.
// *
// * FXL GUI API is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with FXL GUI API. If not, see <http://www.gnu.org/licenses/>.
// *
// * Copyright (c) 2010-2015 Dangelmayr IT GmbH. All rights reserved.
// */
//package co.fxl.gui.style.gplus;
//
//import co.fxl.gui.api.ILabel;
//import co.fxl.gui.api.IPanel;
//import co.fxl.gui.style.api.IStyle.ITable;
//
//public class GPlusTable implements ITable {
//
// @Override
// public IColumnSelection columnSelection() {
// return new IColumnSelection() {
//
// @Override
// public IColumnSelection panel(IPanel<?> b, boolean visible) {
// if (visible)
// b.color().gray();
// else
// b.color().white();
// return this;
// }
//
// @Override
// public IColumnSelection label(ILabel b, boolean visible) {
// if (visible)
// b.font().color().white();
// else
// b.font().color().gray();
// return this;
// }
//
// };
// }
//
// @Override
// public ITable statusPanel(IPanel<?> statusPanel) {
// statusPanel.color().remove().white();
// // statusPanel.border().remove();
// return this;
// }
//
// @Override
// public ITable topPanel(IPanel<?> topPanel) {
// topPanel.color().remove().white();
// topPanel.border().remove();
// return this;
// }
//
// }
|
Letractively/fxlgui
|
co.fxl.gui.style.gplus/src/main/java/co/fxl/gui/style/gplus/GPlusTable.java
|
Java
|
gpl-3.0
| 1,909 |
๏ปฟnamespace Tower_Unite_Instrument_Autoplayer.Core
{
/// <summary>
/// This interface is a set of rules that all notes has to follow
/// in order to qualify as a note
/// </summary>
interface INote
{
/// <summary>
/// This method is invoked when the note is reached in the song
/// </summary>
void Play();
}
}
|
Sejemus/Tower-Unite-Piano-Bot
|
Tower Unite Instrument Autoplayer/Core/Interfaces/INote.cs
|
C#
|
gpl-3.0
| 371 |
import libtcodpy as libtcod
#globs are imported almost everywhere, so unnecessary libtcod imports should be omitted
##########################################################
# Options
##########################################################
#it's better to pack them into separate file
LIMIT_FPS = 20
#size of the map
MAP_WIDTH = 100
MAP_HEIGHT = 80
#size of the camera screen
CAMERA_WIDTH = 80
CAMERA_HEIGHT = 43
#size of the window
SCREEN_WIDTH = 80
SCREEN_HEIGHT = 50
#map generating settings
MAX_ROOM_ENEMIES = 3
MAX_ROOM_ITEMS = 3
#BSP options
DEPTH = 10 #number of node splittings
ROOM_MIN_SIZE = 6
FULL_ROOMS = False
#sizes and coordinates for GUI
PANEL_HEIGHT = 7
BAR_WIDTH = 20
PANEL_Y = SCREEN_HEIGHT - PANEL_HEIGHT
MESSAGE_X = BAR_WIDTH + 2
MESSAGE_WIDTH = SCREEN_WIDTH - BAR_WIDTH - 2
MESSAGE_HEIGHT = PANEL_HEIGHT - 1
#inventory properties
MAX_INVENTORY_SIZE = 26
INVENTORY_WIDTH = 50
#item properties
STIM_HEAL_AMOUNT = 50
DISCHARGE_DAMAGE = 100
ITEM_USING_RANGE = 5
CONFUSE_TURNS = 10
GRENADE_DAMAGE = 30
GRENADE_RADIUS = 3
#weapon properties
WEAPON_RANGE = 5
LASER_PISTOL_DAMAGE = 20
LASER_RIFLE_DAMAGE = 50
#experience properties
LEVEL_UP_BASE = 100
LEVEL_UP_FACTOR = 150
#FOV properties
FOV_ALGO = 0
FOV_LIGHT_WALLS = True
TORCH_RADIUS = 10
##########################################################
#colors of invisible tiles
c_hid_wall = libtcod.Color(22, 7, 115)
c_hid_floor = libtcod.Color(55, 46, 133)
#colors of visible tiles
c_vis_wall = libtcod.Color(148, 122, 23)
c_vis_floor = libtcod.Color(180, 155, 58)
#colors of highlighted tiles
c_hi_wall = libtcod.Color(67, 128, 211)
c_hi_floor = libtcod.Color(105, 150, 211)
#possible tile types
#properties description:
# title - just a name for a specific terrain, also used as key for a corresponding tile type in 'TYLE_TYPES' dict
# walkable - indicates, if tiles of this type can hold an object (character, item and so on) on the top of itself
# transparent - indicates, whether the tile blocks line of sight during calculating FOV for characters or not
# vis_color, hid_color, hi_color - visible color, hidden color, highlighted color respectively; used in 'calculate_color' function
#
#current types: 'floor', 'wall'
#
#in order to add new type, just create additional dict holding its properties as shown below and append it to 'TYLE_TYPES'
#'tile_type' used in 'Tile.set_type' is the keyword of a corresponding type in 'TILE_TYPES'
floor = {'title': 'f1loor', 'walkable': True, 'transparent': True, 'vis_color': c_vis_floor, 'hid_color': c_hid_floor, 'hi_color': c_hi_floor}
wall = {'title': 'metal wall', 'walkable': False, 'transparent': False, 'vis_color': c_vis_wall, 'hid_color': c_hid_wall, 'hi_color': c_hi_wall}
TILE_TYPES = {'floor': floor, 'wall': wall}
#variables for input handling
#they are kept here, as they don't hold any used information outside input-handling functions
#it doesn't matter, if they are constantly reinitializing
key = libtcod.Key()
mouse = libtcod.Mouse()
##########################################################
|
MaxGavr/breakdown_game
|
globs.py
|
Python
|
gpl-3.0
| 3,049 |
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class AutoRevealStatListener : gameScriptStatsListener
{
[Ordinal(0)] [RED("owner")] public wCHandle<gameObject> Owner { get; set; }
public AutoRevealStatListener(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
|
Traderain/Wolven-kit
|
CP77.CR2W/Types/cp77/AutoRevealStatListener.cs
|
C#
|
gpl-3.0
| 381 |
from .main import create_random_key, vigenere, otp
|
D-Vaillant/julius
|
julius/__init__.py
|
Python
|
gpl-3.0
| 51 |
package vinamax
import (
"log"
)
var (
//These variables can be set in the input files
B_ext func(t float64) (float64, float64, float64) // External applied field in T
B_ext_space func(t, x, y, z float64) (float64, float64, float64) // External applied field in T
Dt float64 = -1 // Timestep in s
Mindt float64 = 1e-20 //smallest allowed timestep
Maxdt float64 = 1 //largest allowed timestep
T float64 // Time in s
Alpha float64 = -1 // Gilbert damping constant
gammaoveralpha float64 //g/1+alfa^2
Temp float64 = -1 // Temperature in K
Ku1 float64 = 0 // Uniaxial anisotropy constant in J/m**3
Kc1 float64 = 0 // Cubic anisotropy constant in J/m**3
Errortolerance float64 = 1e-5
Thresholdbeta float64 = 0.3 // The threshold value for the FMM
demagtime float64
universe node // The entire universe of the simulation
FMM bool = false // Calculate demag with FMM method
Demag bool = true // Calculate demag
demagevery bool = false // Calculate demag only after certain interval
Adaptivestep bool = false
outdir string // The output directory
solver string = "dopri" // The solver used
outputinterval float64
maxtauwitht float64 = 0. //maximum torque during the simulations with temperature
// suggest_timestep bool = false
order int = 5 //the order of the solver
constradius float64
logradius_m float64
logradius_s float64
Tau0 float64 =1e-8
msatcalled bool = false
radiuscalled bool = false
constradiuscalled bool = false
logradiuscalled bool = false
uaniscalled bool = false
c1called bool = false
c2called bool = false
worldcalled bool = false
magnetisationcalled bool = false
treecalled bool = false
outputcalled bool = false
randomseedcalled bool = false
tableaddcalled bool = false
Jumpnoise bool = false
Brown bool = false
)
//initialised B_ext functions
func init() {
B_ext = func(t float64) (float64, float64, float64) { return 0, 0, 0 } // External applied field in T
B_ext_space = func(t, x, y, z float64) (float64, float64, float64) { return 0, 0, 0 } // External applied field in T
}
//demag every interval
func Demagevery(t float64) {
demagevery = true
demagtime = t
}
//test the inputvalues for unnatural things
func testinput() {
if Demag == true && demagevery == true {
log.Fatal("You cannot call both Demagevery and Demag, pick one")
}
if Dt < 0 {
log.Fatal("Dt cannot be smaller than 0, did you forget to initialise?")
}
if Alpha < 0 {
log.Fatal("Alpha cannot be smaller than 0, did you forget to initialise?")
}
if Temp < 0 {
log.Fatal("Temp cannot be smaller than 0, did you forget to initialise?")
}
if universe.number == 0 {
log.Fatal("There are no particles in the geometry")
}
}
//checks the inputfiles for functions that should have been called but weren't
func syntaxrun() {
if msatcalled == false {
log.Fatal("You have to specify msat")
}
if radiuscalled == false {
log.Fatal("You have to specify the size of the particles")
}
if uaniscalled == false && Ku1 != 0 {
log.Fatal("You have to specify the uniaxial anisotropy-axis")
}
if (c1called == false || c2called == false) && Kc1 != 0 {
log.Fatal("You have to specify the cubic anisotropy-axes")
}
if worldcalled == false {
log.Fatal("You have define a \"World\"")
}
if magnetisationcalled == false {
log.Fatal("You have specify the initial magnetisation")
}
if treecalled == false && FMM == true {
log.Fatal("You have to run Maketree() as last command in front of Run() when using the FMM method")
}
if Temp != 0 && randomseedcalled == false {
log.Fatal("You have to run Setrandomseed() when using nonzero temperatures")
}
if tableaddcalled == true && outputcalled == false {
log.Fatal("You have to run Output(interval) when calling tableadd")
}
if Brown == true && Adaptivestep == true {
log.Fatal("Brown Temperature can only be used with fixed timestep")
}
if Jumpnoise == true {
resetswitchtimes(universe.lijst)
}
if Temp != 0 && Brown == false && Jumpnoise == false {
log.Fatal("You have to specify which temperature you want to use: \"Jumpnoise\" or \"Brown\"")
}
if Brown {
calculatetempnumbers(universe.lijst)
}
}
|
acoene/vinamax
|
var.go
|
GO
|
gpl-3.0
| 4,996 |
#include <DefenseManager.h>
#include <BorderManager.h>
using namespace BWAPI;
DefenseManager::DefenseManager(Arbitrator::Arbitrator<BWAPI::Unit*,double>* arbitrator)
{
firsss2 = false; //chc
very_early_rush = false;
early_attack_assimi = true;
very_early_attack_gate = true;
early_attack_gate = true;
early_rush =false;
firsss=false;
lastFrameCheck = 0;
this->arbitrator = arbitrator;
}
void DefenseManager::setBorderManager(BorderManager* borderManager)
{
this->borderManager=borderManager;
}
void DefenseManager::setBaseManager(BaseManager *baseManager)
{
this->baseManager = baseManager;
}
void DefenseManager::setInformationManager(InformationManager *informationManager)
{
this->informationManager = informationManager;
}
std::set<BWAPI::Unit*>& DefenseManager::getIdleDefenders()
{
idleDefenders.clear();
for (std::map<BWAPI::Unit*, DefenseData>::iterator it = defenders.begin(); it != defenders.end(); it++)
{
if ((it->second.mode == DefenseData::Idle) || (it->second.mode == DefenseData::Moving))
idleDefenders.insert(it->first);
}
return idleDefenders;
}
void DefenseManager::onOffer(std::set<BWAPI::Unit*> units)
{
for(std::set<BWAPI::Unit*>::iterator u = units.begin(); u != units.end(); u++)
{
if (defenders.find(*u) == defenders.end())
{
arbitrator->accept(this, *u);
DefenseData temp;
defenders.insert(std::make_pair(*u, temp));
}
}
}
void DefenseManager::onRevoke(BWAPI::Unit* unit, double bid)
{
defenders.erase(unit);
}
void DefenseManager::onRemoveUnit(BWAPI::Unit* unit)
{
defenders.erase(unit);
}
void DefenseManager::update()
{
//chc
int enemy_assimilator = 0;
int enemy_gateway = 0;
for (std::set<BWAPI::Unit *>::const_iterator en = Broodwar->enemy()->getUnits().begin(); en != BWAPI::Broodwar->enemy()->getUnits().end(); ++en)
{
if((*en)->getType() == BWAPI::UnitTypes::Protoss_Assimilator)
enemy_assimilator++;
if((*en)->getType() == BWAPI::UnitTypes::Protoss_Gateway)
enemy_gateway++;
}
if(enemy_assimilator == 0)
early_attack_assimi = false;
if(enemy_gateway >= 2)
early_attack_gate = false;
if(enemy_gateway >=3)
very_early_attack_gate = false;
if(!very_early_rush && !firsss2)
{
if(BWAPI::Broodwar->self()->allUnitCount(BWAPI::UnitTypes::Protoss_Cybernetics_Core) == 1)
{
if(Broodwar->self()->incompleteUnitCount(UnitTypes::Protoss_Cybernetics_Core) != 1) // ยปรงรรยนรถ ยณรยฝยบรยฝรรยพรฎยฐยก รรถยพรฎรรถยฐรญ รรยดร ยตยตรรรร ยพรยดรยถรณยธรฉ
firsss2 = true; //ยดรต รรยปรณ รร ifยนยฎรยธยทร ยธรธยตรฉยพรฎยฟร.
if(!very_early_attack_gate && early_attack_assimi == false)
very_early_rush = true;
}
}
if ((lastFrameCheck == 0) || (BWAPI::Broodwar->getFrameCount() > lastFrameCheck + 10))
{
lastFrameCheck = BWAPI::Broodwar->getFrameCount();
// Bid on all completed military units
std::set<BWAPI::Unit*> myPlayerUnits=BWAPI::Broodwar->self()->getUnits();
for (std::set<BWAPI::Unit*>::iterator u = myPlayerUnits.begin(); u != myPlayerUnits.end(); u++)
{
if ((*u)->isCompleted() &&
!(*u)->getType().isWorker() &&
!(*u)->getType().isBuilding() &&
(*u)->getType().canAttack() &&
(*u)->getType() != BWAPI::UnitTypes::Zerg_Egg &&
(*u)->getType() != BWAPI::UnitTypes::Zerg_Larva)
{
arbitrator->setBid(this, *u, 20);
}
}
bool borderUpdated=false;
if (myBorder!=borderManager->getMyBorder())
{
myBorder=borderManager->getMyBorder();
borderUpdated=true;
}
//search among our bases which ones are in a border region
std::vector<Base*> borderBases;
for each (Base *base in baseManager->getAllBases())
{
bool isBorderBase = false;
for each (BWTA::Chokepoint *c in base->getBaseLocation()->getRegion()->getChokepoints())
{
if (myBorder.find(c) != myBorder.end())
{
isBorderBase = true;
break;
}
}
if (isBorderBase)
borderBases.push_back(base);
}
std::set<BWTA::BaseLocation*> enemyBasesLocation = informationManager->getEnemyBases();
myBorderVector.clear();
for(int i=0; i < (int)borderBases.size(); i++)
{
//search the nearest enemy base from current borderBases[i]
BWTA::BaseLocation *nearestEnemyBaseLocation;
double shortestDistance = 9999999;
for each (BWTA::BaseLocation *bl in enemyBasesLocation)
{
double distance = borderBases[i]->getBaseLocation()->getGroundDistance(bl);
if (distance < shortestDistance)
{
shortestDistance = distance;
nearestEnemyBaseLocation = bl;
}
}
if (nearestEnemyBaseLocation == NULL)
nearestEnemyBaseLocation = informationManager->getEnemyStartLocation();
//now search the nearest choke of borderBases[i] from the enemy base
BWTA::Chokepoint *bestChoke;
shortestDistance = 9999999;
for each(BWTA::Chokepoint *c in borderBases[i]->getBaseLocation()->getRegion()->getChokepoints())
{
double distance = nearestEnemyBaseLocation->getPosition().getApproxDistance(c->getCenter());
if (distance < shortestDistance)
{
shortestDistance = distance;
bestChoke = c;
}
}
myBorderVector.push_back(bestChoke);
}
//Order all units to choke
/*
int i=0;
if (!myBorder.empty())
{
for (std::map<BWAPI::Unit*,DefenseData>::iterator u = defenders.begin(); u != defenders.end(); u++)
{
if ((*u).second.mode == DefenseData::Idle || borderUpdated)
{
BWAPI::Position chokePosition=myBorderVector[i]->getCenter();
i++;
if (i>=(int)myBorderVector.size())
i=0;
(*u).first->attack(chokePosition);
(*u).second.mode = DefenseData::Moving;
}
}
}
*/
/*
//รรป รรร
ยฉรรทรรรยฎร
รยฝยบรยฎ
if (enemyBorder!=borderManager->getEnemyBorder())
{
enemyBorder=borderManager->getEnemyBorder();
enemyBorderVector.clear();
for(std::set<BWTA::Chokepoint*>::iterator i=enemyBorder.begin();i!=enemyBorder.end();i++)
enemyBorderVector.push_back(*i);
//borderUpdated=true;
}
//Order all units to choke
int i=0;
if (!enemyBorder.empty())
{
for (std::map<BWAPI::Unit*,DefenseData>::iterator u = defenders.begin(); u != defenders.end(); u++)
{
BWAPI::Position chokePosition2=enemyBorderVector[i]->getCenter();
i++;
if (i>=(int)myBorderVector.size())
i=0;
// (*u).first->attackMove(chokePosition);
// (*u).second.mode = DefenseData::Moving;
} }
*/
//////////////////
//รรยทรร
รคยฝยบรรยธรฉ
if((Broodwar->enemy()->getRace() == Races::Protoss || Broodwar->enemy()->getRace() == Races::Zerg || Broodwar->enemy()->getRace() == Races::Terran) && very_early_rush == false) //chcยผรถรยค
{
round = (int)myBorderVector.size() - 1;
if (!myBorder.empty())
{
for (std::map<BWAPI::Unit*,DefenseData>::iterator u = defenders.begin(); u != defenders.end(); u++)
{
if (u->first->isIdle())
{
u->second.mode = DefenseData::Idle;
}
if (u->second.mode == DefenseData::Idle || borderUpdated)
{
BWAPI::Position chokePosition=myBorderVector[round]->getCenter();
round--;
if (round < 0)
round = (int)myBorderVector.size() - 1;
//wait to the 2/3 between your current position and the center of the choke to protect
int borderBasesSize = (int)borderBases.size();
BWAPI::Position lastBase = borderBases[borderBasesSize - round - 1]->getBaseLocation()->getPosition();
int x_wait = chokePosition.x() - lastBase.x();
int y_wait = chokePosition.y() - lastBase.y();
x_wait = (x_wait / 4) * 3;
y_wait = (y_wait / 4) * 3;
x_wait += lastBase.x();
y_wait += lastBase.y();
BWAPI::Position waitPosition(x_wait, y_wait);
(*u).first->attack(waitPosition);
(*u).second.mode = DefenseData::Moving;
}
if (u->first->isUnderAttack())
{
std::set<BWAPI::Unit *> backup = this->getIdleDefenders();
for each (BWAPI::Unit *bck in backup)
{
bck->attack(u->first->getPosition());
defenders[bck].mode = DefenseData::Defending;
}
}
}
}
}
// round = (int)myBorderVector.size() - 1;
else
{
int i=0;
if (!myBorder.empty())
{
for (std::map<BWAPI::Unit*,DefenseData>::iterator u = defenders.begin(); u != defenders.end(); u++)
{
if (u->first->isIdle())
{
u->second.mode = DefenseData::Idle;
}
if (u->second.mode == DefenseData::Idle || borderUpdated)
{
BWAPI::Position chokePosition=myBorderVector[i]->getCenter();
i++;
if (i>=(int)myBorderVector.size())
i=0;
(*u).first->attack(chokePosition);
(*u).second.mode = DefenseData::Moving;
}
if (u->first->isUnderAttack())
{
std::set<BWAPI::Unit *> backup = this->getIdleDefenders();
for each (BWAPI::Unit *bck in backup)
{
bck->attack(u->first->getPosition());
defenders[bck].mode = DefenseData::Defending;
}
}
}
}
}
}
}
std::string DefenseManager::getName() const
{
return "Defense Manager";
}
std::string DefenseManager::getShortName() const
{
return "Def";
}
|
chc2212/Xelnaga-Starcraft-game-AI-bot-AIIDE2014
|
src/src/DefenseManager.cpp
|
C++
|
gpl-3.0
| 9,063 |
<?php
namespace OCAX\Backup;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class BackupBundle extends Bundle
{
}
|
omgslinux/oc2
|
src/OCAX/Backup/BackupBundle.php
|
PHP
|
gpl-3.0
| 118 |
/*
libSDL2pp - C++11 bindings/wrapper for SDL2
Copyright (C) 2015 Dmitry Marakasov <amdmi3@amdmi3.ru>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_mixer.h>
#include <SDL2pp/SDL.hh>
#include <SDL2pp/SDLMixer.hh>
#include <SDL2pp/Mixer.hh>
#include <SDL2pp/Chunk.hh>
using namespace SDL2pp;
int main(int, char*[]) try {
SDL sdl(SDL_INIT_AUDIO);
SDLMixer mixerlib(MIX_INIT_OGG);
Mixer mixer(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 4096);
Chunk sound(TESTDATA_DIR "/test.ogg");
mixer.SetChannelFinishedHandler([](int channel){
std::cerr << "Channel " << channel << " finished playback" << std::endl;
});
int chan;
// Fade in
chan = mixer.FadeInChannel(-1, sound, 0, 1000);
std::cerr << "Fading sound in on channel " << chan << "\n";
SDL_Delay(2000);
// Mix 3 sounds
chan = mixer.PlayChannel(-1, sound);
std::cerr << "Playing sound on channel " << chan << "\n";
SDL_Delay(250);
chan = mixer.PlayChannel(-1, sound);
std::cerr << "Playing sound on channel " << chan << "\n";
SDL_Delay(250);
chan = mixer.PlayChannel(-1, sound);
std::cerr << "Playing sound on channel " << chan << "\n";
SDL_Delay(2000);
// Fade out
chan = mixer.PlayChannel(-1, sound);
std::cerr << "Fading out sound on channel " << chan << "\n";
mixer.FadeOutChannel(chan, 2000);
SDL_Delay(2000);
return 0;
} catch (std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
|
manuporto/megaman
|
extern/libSDL2pp/examples/mixer.cc
|
C++
|
gpl-3.0
| 2,304 |
/*
* Copyright (C) 2011-2012 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptPCH.h"
#include "ruby_sanctum.h"
enum Texts
{
SAY_AGGRO = 0, // You will sssuffer for this intrusion! (17528)
SAY_CONFLAGRATION = 1, // Burn in the master's flame! (17532)
EMOTE_ENRAGED = 2, // %s becomes enraged!
SAY_KILL = 3, // Halion will be pleased. (17530) - As it should be.... (17529)
};
enum Spells
{
SPELL_CONFLAGRATION = 74452,
SPELL_FLAME_BEACON = 74453,
SPELL_CONFLAGRATION_2 = 74454, // Unknown dummy effect
SPELL_ENRAGE = 78722,
SPELL_FLAME_BREATH = 74403,
};
enum Events
{
EVENT_ENRAGE = 1,
EVENT_FLIGHT = 2,
EVENT_FLAME_BREATH = 3,
EVENT_CONFLAGRATION = 4,
// Event group
EVENT_GROUP_LAND_PHASE = 1,
};
enum MovementPoints
{
POINT_FLIGHT = 1,
POINT_LAND = 2,
};
enum Misc
{
SOUND_ID_DEATH = 17531,
};
Position const SavianaRagefireFlyPos = {3155.51f, 683.844f, 95.20f, 4.69f};
Position const SavianaRagefireLandPos = {3151.07f, 636.443f, 79.54f, 4.69f};
class boss_saviana_ragefire : public CreatureScript
{
public:
boss_saviana_ragefire() : CreatureScript("boss_saviana_ragefire") { }
struct boss_saviana_ragefireAI : public BossAI
{
boss_saviana_ragefireAI(Creature* creature) : BossAI(creature, DATA_SAVIANA_RAGEFIRE)
{
}
void Reset()
{
_Reset();
me->SetReactState(REACT_AGGRESSIVE);
}
void EnterCombat(Unit* /*who*/)
{
_EnterCombat();
Talk(SAY_AGGRO);
events.Reset();
events.ScheduleEvent(EVENT_ENRAGE, 20000, EVENT_GROUP_LAND_PHASE);
events.ScheduleEvent(EVENT_FLAME_BREATH, 14000, EVENT_GROUP_LAND_PHASE);
events.ScheduleEvent(EVENT_FLIGHT, 60000);
}
void JustDied(Unit* /*killer*/)
{
_JustDied();
me->PlayDirectSound(SOUND_ID_DEATH);
}
void MovementInform(uint32 type, uint32 point)
{
if (type != POINT_MOTION_TYPE)
return;
switch (point)
{
case POINT_FLIGHT:
events.ScheduleEvent(EVENT_CONFLAGRATION, 1000);
Talk(SAY_CONFLAGRATION);
break;
case POINT_LAND:
me->SetFlying(false);
me->SetLevitate(false);
me->SetReactState(REACT_AGGRESSIVE);
if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() == POINT_MOTION_TYPE)
me->GetMotionMaster()->MovementExpired();
DoStartMovement(me->getVictim());
break;
default:
break;
}
}
void JustReachedHome()
{
_JustReachedHome();
me->SetFlying(false);
me->SetLevitate(false);
}
void KilledUnit(Unit* victim)
{
if (victim->GetTypeId() == TYPEID_PLAYER)
Talk(SAY_KILL);
}
void UpdateAI(uint32 const diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_FLIGHT:
{
me->SetFlying(true);
me->SetLevitate(true);
me->SetReactState(REACT_PASSIVE);
me->GetMotionMaster()->MovePoint(POINT_FLIGHT, SavianaRagefireFlyPos);
events.ScheduleEvent(EVENT_FLIGHT, 50000);
events.DelayEvents(12500, EVENT_GROUP_LAND_PHASE);
break;
}
case EVENT_CONFLAGRATION:
DoCast(me, SPELL_CONFLAGRATION, true);
break;
case EVENT_ENRAGE:
DoCast(me, SPELL_ENRAGE);
Talk(EMOTE_ENRAGED);
events.ScheduleEvent(EVENT_ENRAGE, urand(15000, 20000), EVENT_GROUP_LAND_PHASE);
break;
case EVENT_FLAME_BREATH:
DoCastVictim(SPELL_FLAME_BREATH);
events.ScheduleEvent(EVENT_FLAME_BREATH, urand(20000, 30000), EVENT_GROUP_LAND_PHASE);
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const
{
return GetRubySanctumAI<boss_saviana_ragefireAI>(creature);
}
};
class ConflagrationTargetSelector
{
public:
ConflagrationTargetSelector() { }
bool operator()(Unit* unit)
{
return unit->GetTypeId() != TYPEID_PLAYER;
}
};
class spell_saviana_conflagration_init : public SpellScriptLoader
{
public:
spell_saviana_conflagration_init() : SpellScriptLoader("spell_saviana_conflagration_init") { }
class spell_saviana_conflagration_init_SpellScript : public SpellScript
{
PrepareSpellScript(spell_saviana_conflagration_init_SpellScript);
void FilterTargets(std::list<Unit*>& unitList)
{
unitList.remove_if (ConflagrationTargetSelector());
uint8 maxSize = uint8(GetCaster()->GetMap()->GetSpawnMode() & 1 ? 6 : 3);
if (unitList.size() > maxSize)
Trinity::RandomResizeList(unitList, maxSize);
}
void HandleDummy(SpellEffIndex effIndex)
{
PreventHitDefaultEffect(effIndex);
GetCaster()->CastSpell(GetHitUnit(), SPELL_FLAME_BEACON, true);
GetCaster()->CastSpell(GetHitUnit(), SPELL_CONFLAGRATION_2, false);
}
void Register()
{
OnUnitTargetSelect += SpellUnitTargetFn(spell_saviana_conflagration_init_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY);
OnEffectHitTarget += SpellEffectFn(spell_saviana_conflagration_init_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_saviana_conflagration_init_SpellScript();
}
};
class spell_saviana_conflagration_throwback : public SpellScriptLoader
{
public:
spell_saviana_conflagration_throwback() : SpellScriptLoader("spell_saviana_conflagration_throwback") { }
class spell_saviana_conflagration_throwback_SpellScript : public SpellScript
{
PrepareSpellScript(spell_saviana_conflagration_throwback_SpellScript);
void HandleScript(SpellEffIndex effIndex)
{
PreventHitDefaultEffect(effIndex);
GetHitUnit()->CastSpell(GetCaster(), uint32(GetEffectValue()), true);
GetHitUnit()->GetMotionMaster()->MovePoint(POINT_LAND, SavianaRagefireLandPos);
}
void Register()
{
OnEffectHitTarget += SpellEffectFn(spell_saviana_conflagration_throwback_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const
{
return new spell_saviana_conflagration_throwback_SpellScript();
}
};
void AddSC_boss_saviana_ragefire()
{
new boss_saviana_ragefire();
new spell_saviana_conflagration_init();
new spell_saviana_conflagration_throwback();
}
|
Zapuss/ZapekFapeCore
|
src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_saviana_ragefire.cpp
|
C++
|
gpl-3.0
| 8,541 |
/*
* SOS
* Copyright (C) 2016 zDuo (Adithya J, Vazbloke)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.zduo.sos.activity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;
import android.widget.Toast;
import com.zduo.sos.R;
import com.zduo.sos.db.HB1ACReading;
import com.zduo.sos.presenter.AddA1CPresenter;
import com.zduo.sos.tools.FormatDateTime;
import java.util.Calendar;
public class AddA1CActivity extends AddReadingActivity {
private TextView readingTextView;
private TextView unitTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_hb1ac);
Toolbar toolbar = (Toolbar) findViewById(R.id.activity_main_toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setElevation(2);
}
this.retrieveExtra();
AddA1CPresenter presenter = new AddA1CPresenter(this);
setPresenter(presenter);
presenter.setReadingTimeNow();
readingTextView = (TextView) findViewById(R.id.hb1ac_add_value);
unitTextView = (TextView) findViewById(R.id.hb1ac_unit);
this.createDateTimeViewAndListener();
this.createFANViewAndListener();
if (!"percentage".equals(presenter.getA1CUnitMeasuerement())) {
unitTextView.setText(getString(R.string.mmol_mol));
}
// If an id is passed, open the activity in edit mode
FormatDateTime formatDateTime = new FormatDateTime(getApplicationContext());
if (this.isEditing()) {
setTitle(R.string.title_activity_add_hb1ac_edit);
HB1ACReading readingToEdit = presenter.getHB1ACReadingById(getEditId());
readingTextView.setText(readingToEdit.getReading() + "");
Calendar cal = Calendar.getInstance();
cal.setTime(readingToEdit.getCreated());
this.getAddDateTextView().setText(formatDateTime.getDate(cal));
this.getAddTimeTextView().setText(formatDateTime.getTime(cal));
presenter.updateReadingSplitDateTime(readingToEdit.getCreated());
} else {
this.getAddDateTextView().setText(formatDateTime.getCurrentDate());
this.getAddTimeTextView().setText(formatDateTime.getCurrentTime());
}
}
@Override
protected void dialogOnAddButtonPressed() {
AddA1CPresenter presenter = (AddA1CPresenter) getPresenter();
if (this.isEditing()) {
presenter.dialogOnAddButtonPressed(this.getAddTimeTextView().getText().toString(),
this.getAddDateTextView().getText().toString(), readingTextView.getText().toString(), this.getEditId());
} else {
presenter.dialogOnAddButtonPressed(this.getAddTimeTextView().getText().toString(),
this.getAddDateTextView().getText().toString(), readingTextView.getText().toString());
}
}
public void showErrorMessage() {
Toast.makeText(getApplicationContext(), getString(R.string.dialog_error2), Toast.LENGTH_SHORT).show();
}
}
|
adithya321/SOS-The-Healthcare-Companion
|
app/src/main/java/com/zduo/sos/activity/AddA1CActivity.java
|
Java
|
gpl-3.0
| 3,876 |
<header>
<!--Navigation-->
<nav id="menu" class="navbar container">
<div class="navbar-header">
<button type="button" class="btn btn-navbar navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"><i class="fa fa-bars"></i></button>
<a class="navbar-brand" href="#">
<div class="logo"><span>Newspaper</span></div>
</a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li><a href="index.html">Home</a></li>
<li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Login <i class="fa fa-arrow-circle-o-down"></i></a>
<div class="dropdown-menu">
<div class="dropdown-inner">
<ul class="list-unstyled">
<li><a href="archive.html">Text 101</a></li>
<li><a href="archive.html">Text 102</a></li>
</ul>
</div>
</div>
</li>
<li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Video <i class="fa fa-arrow-circle-o-down"></i></a>
<div class="dropdown-menu">
<div class="dropdown-inner">
<ul class="list-unstyled">
<li><a href="archive.html">Text 201</a></li>
<li><a href="archive.html">Text 202</a></li>
<li><a href="archive.html">Text 203</a></li>
<li><a href="archive.html">Text 204</a></li>
<li><a href="archive.html">Text 205</a></li>
</ul>
</div>
</div>
</li>
<li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Category <i class="fa fa-arrow-circle-o-down"></i></a>
<div class="dropdown-menu" style="margin-left: -203.625px;">
<div class="dropdown-inner">
<ul class="list-unstyled">
<li><a href="archive.html">Text 301</a></li>
<li><a href="archive.html">Text 302</a></li>
<li><a href="archive.html">Text 303</a></li>
<li><a href="archive.html">Text 304</a></li>
<li><a href="archive.html">Text 305</a></li>
</ul>
<ul class="list-unstyled">
<li><a href="archive.html">Text 306</a></li>
<li><a href="archive.html">Text 307</a></li>
<li><a href="archive.html">Text 308</a></li>
<li><a href="archive.html">Text 309</a></li>
<li><a href="archive.html">Text 310</a></li>
</ul>
<ul class="list-unstyled">
<li><a href="archive.html">Text 311</a></li>
<li><a href="archive.html">Text 312</a></li>
<li><a href="archive.html#">Text 313</a></li>
<li><a href="archive.html#">Text 314</a></li>
<li><a href="archive.html">Text 315</a></li>
</ul>
</div>
</div>
</li>
<li><a href="archive.html"><i class="fa fa-cubes"></i> Blocks</a></li>
<li><a href="contact.html"><i class="fa fa-envelope"></i> Contact</a></li>
</ul>
<ul class="list-inline navbar-right top-social">
<li><a href="#"><i class="fa fa-facebook"></i></a></li>
<li><a href="#"><i class="fa fa-twitter"></i></a></li>
<li><a href="#"><i class="fa fa-pinterest"></i></a></li>
<li><a href="#"><i class="fa fa-google-plus-square"></i></a></li>
<li><a href="#"><i class="fa fa-youtube"></i></a></li>
</ul>
</div>
</nav>
</header>
|
normeno/laravel-blog
|
resources/views/layouts/partials/frontendhead.blade.php
|
PHP
|
gpl-3.0
| 4,423 |
/*
* _____ _ _ _____ _
* | __ \| | | | / ____| | |
* | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| |
* | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` |
* | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| |
* |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_|
* | |
* |_|
* PlotSquared plot management system for Minecraft
* Copyright (C) 2014 - 2022 IntellectualSites
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.core.plot.flag.implementations;
import com.plotsquared.core.configuration.caption.TranslatableCaption;
import com.plotsquared.core.plot.flag.FlagParseException;
import com.plotsquared.core.plot.flag.types.ListFlag;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class BlockedCmdsFlag extends ListFlag<String, BlockedCmdsFlag> {
public static final BlockedCmdsFlag BLOCKED_CMDS_FLAG_NONE =
new BlockedCmdsFlag(Collections.emptyList());
protected BlockedCmdsFlag(List<String> valueList) {
super(valueList, TranslatableCaption.of("flags.flag_category_string_list"),
TranslatableCaption.of("flags.flag_description_blocked_cmds")
);
}
@Override
public BlockedCmdsFlag parse(@NonNull String input) throws FlagParseException {
return flagOf(Arrays.asList(input.split(",")));
}
@Override
public String getExample() {
return "gamemode survival, spawn";
}
@Override
protected BlockedCmdsFlag flagOf(@NonNull List<String> value) {
return new BlockedCmdsFlag(value);
}
}
|
IntellectualSites/PlotSquared
|
Core/src/main/java/com/plotsquared/core/plot/flag/implementations/BlockedCmdsFlag.java
|
Java
|
gpl-3.0
| 2,524 |
๏ปฟusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Linq;
using Microsoft.VisualBasic.FileIO;
using Telerik.WinControls.UI;
namespace StockControl
{
public partial class Types : Telerik.WinControls.UI.RadRibbonForm
{
public Types()
{
InitializeComponent();
}
//private int RowView = 50;
//private int ColView = 10;
DataTable dt = new DataTable();
private void radMenuItem2_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
HistoryView hw = new HistoryView(this.Name);
this.Cursor = Cursors.Default;
hw.ShowDialog();
}
private void radRibbonBar1_Click(object sender, EventArgs e)
{
}
private void GETDTRow()
{
dt.Columns.Add(new DataColumn("GroupCode", typeof(string)));
dt.Columns.Add(new DataColumn("TypeCode", typeof(string)));
dt.Columns.Add(new DataColumn("TypeDetail", typeof(string)));
dt.Columns.Add(new DataColumn("TypeActive", typeof(bool)));
}
private void Unit_Load(object sender, EventArgs e)
{
RMenu3.Click += RMenu3_Click;
RMenu4.Click += RMenu4_Click;
RMenu5.Click += RMenu5_Click;
RMenu6.Click += RMenu6_Click;
radGridView1.ReadOnly = true;
radGridView1.AutoGenerateColumns = false;
GETDTRow();
DataLoad();
LoadDefualt();
}
private void RMenu6_Click(object sender, EventArgs e)
{
DeleteUnit();
DataLoad();
}
private void RMenu5_Click(object sender, EventArgs e)
{
EditClick();
}
private void RMenu4_Click(object sender, EventArgs e)
{
ViewClick();
}
private void RMenu3_Click(object sender, EventArgs e)
{
NewClick();
}
private void LoadDefualt()
{
try
{
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
var gt = (from ix in db.tb_GroupTypes where ix.GroupActive == true select ix).ToList();
GridViewComboBoxColumn comboBoxColumn = this.radGridView1.Columns["GroupCode"] as GridViewComboBoxColumn;
comboBoxColumn.DisplayMember = "GroupCode";
comboBoxColumn.ValueMember = "GroupCode";
comboBoxColumn.DataSource = gt;
//comboBoxColumn.DataSource= new string[] { "INSERT","Mr.", "Mrs.", "Dr.", "Ms." };
//GridViewComboBoxColumn lookUpColumn = new GridViewComboBoxColumn();
//lookUpColumn.FieldName = "GroupCode1";
//lookUpColumn.Name = "GroupCode1";
//lookUpColumn.HeaderText = "GroupCode";
//lookUpColumn.DataSource = new string[] { "Mr.", "Mrs.", "Dr.", "Ms." };
//lookUpColumn.Width = 100;
//lookUpColumn.IsVisible = true;
//this.radGridView1.Columns.Add(lookUpColumn);
}
}catch(Exception ex) {
MessageBox.Show(ex.Message);
dbClss.AddError("เนเธเธดเนเธกเธเธฃเนเธ เธ", ex.Message, this.Name);
}
}
private void DataLoad()
{
//dt.Rows.Clear();
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
//dt = ClassLib.Classlib.LINQToDataTable(db.tb_Units.ToList());
radGridView1.DataSource = db.tb_Types.ToList();
int ck = 0;
foreach(var x in radGridView1.Rows)
{
x.Cells["dgvCodeTemp"].Value = x.Cells["GroupCode"].Value.ToString();
x.Cells["dgvCodeTemp2"].Value = x.Cells["TypeCode"].Value.ToString();
x.Cells["dgvOldDetail"].Value= x.Cells["TypeDetail"].Value.ToString();
x.Cells["GroupCode"].ReadOnly = true;
x.Cells["TypeCode"].ReadOnly = true;
x.Cells["GroupCode"].Style.ForeColor = Color.MidnightBlue;
x.Cells["TypeCode"].Style.ForeColor = Color.MidnightBlue;
if (row >= 0 && row == ck)
{
x.ViewInfo.CurrentRow = x;
}
ck += 1;
}
}
// radGridView1.DataSource = dt;
}
private bool CheckDuplicate(string code,string Typecode)
{
bool ck = false;
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
int i = (from ix in db.tb_Types where ix.GroupCode == code && ix.TypeCode==Typecode select ix).Count();
if (i > 0)
ck = false;
else
ck = true;
}
return ck;
}
private bool AddUnit()
{
bool ck = false;
int C = 0;
try
{
radGridView1.EndEdit();
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
foreach (var g in radGridView1.Rows)
{
if (!Convert.ToString(g.Cells["GroupCode"].Value).Equals("")
&& !Convert.ToString(g.Cells["TypeCode"].Value).Equals(""))
{
if (Convert.ToString(g.Cells["dgvC"].Value).Equals("T"))
{
if (Convert.ToString(g.Cells["dgvCodeTemp"].Value).Equals("")
&& Convert.ToString(g.Cells["dgvCodeTemp2"].Value).Equals("")
)
{
// MessageBox.Show("11");
tb_Type gy = new tb_Type();
gy.GroupCode = Convert.ToString(g.Cells["GroupCode"].Value);
gy.TypeCode= Convert.ToString(g.Cells["TypeCode"].Value);
gy.TypeActive = Convert.ToBoolean(g.Cells["TypeActive"].Value);
gy.TypeDetail= Convert.ToString(g.Cells["TypeDetail"].Value);
db.tb_Types.InsertOnSubmit(gy);
db.SubmitChanges();
C += 1;
dbClss.AddHistory(this.Name, "เนเธเธดเนเธกเธเธฃเธฐเนเธ เธ", "Insert Type Code [" + gy.TypeCode+ "]","");
}
else
{
var unit1 = (from ix in db.tb_Types
where ix.GroupCode == Convert.ToString(g.Cells["dgvCodeTemp"].Value)
&& ix.TypeCode == Convert.ToString(g.Cells["dgvCodeTemp2"].Value)
select ix).First();
unit1.TypeDetail = Convert.ToString(g.Cells["TypeDetail"].Value);
unit1.TypeActive = Convert.ToBoolean(g.Cells["TypeActive"].Value);
C += 1;
db.SubmitChanges();
dbClss.AddHistory(this.Name, "เนเธเนเนเธ", "Update Type Code [" + unit1.TypeCode+ "]","");
}
}
}
}
}
}
catch (Exception ex) { MessageBox.Show(ex.Message);
dbClss.AddError("เนเธเธดเนเธกเธเธฃเนเธ เธ", ex.Message, this.Name);
}
if (C > 0)
MessageBox.Show("เธเธฑเธเธเธถเธเธชเธณเนเธฃเนเธ!");
return ck;
}
private bool DeleteUnit()
{
bool ck = false;
int C = 0;
try
{
if (row >= 0)
{
string CodeDelete = Convert.ToString(radGridView1.Rows[row].Cells["GroupCode"].Value);
string CodeDelete2 = Convert.ToString(radGridView1.Rows[row].Cells["TypeCode"].Value);
string CodeTemp = Convert.ToString(radGridView1.Rows[row].Cells["dgvCodeTemp"].Value);
string CodeTemp2 = Convert.ToString(radGridView1.Rows[row].Cells["dgvCodeTemp2"].Value);
radGridView1.EndEdit();
if (MessageBox.Show("เธเนเธญเธเธเธฒเธฃเธฅเธเธฃเธฒเธขเธเธฒเธฃ ( "+ CodeDelete+" ) เธซเธฃเธทเธญเนเธกเน ?", "เธฅเธเธฃเธฒเธขเธเธฒเธฃ", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
if (!CodeDelete.Equals("") && !CodeDelete2.Equals(""))
{
if (!CodeTemp.Equals("") && !CodeTemp2.Equals(""))
{
var unit1 = (from ix in db.tb_Types
where ix.GroupCode == CodeDelete
&& ix.TypeCode == CodeDelete2
select ix).ToList();
foreach (var d in unit1)
{
db.tb_Types.DeleteOnSubmit(d);
dbClss.AddHistory(this.Name, "เธฅเธเธเธฃเธฐเนเธ เธ", "Delete Type Code ["+d.TypeCode+"]","");
}
C += 1;
db.SubmitChanges();
}
}
}
}
}
}
catch (Exception ex) { MessageBox.Show(ex.Message);
dbClss.AddError("เธฅเธเธเธฃเธฐเนเธ เธ", ex.Message, this.Name);
}
if (C > 0)
{
row = row - 1;
MessageBox.Show("เธฅเธเธฃเธฒเธขเธเธฒเธฃ เธชเธณเนเธฃเนเธ!");
}
return ck;
}
private void btnCancel_Click(object sender, EventArgs e)
{
DataLoad();
}
private void NewClick()
{
radGridView1.ReadOnly = false;
radGridView1.AllowAddNewRow = false;
btnEdit.Enabled = false;
btnView.Enabled = true;
radGridView1.Rows.AddNew();
}
private void EditClick()
{
radGridView1.ReadOnly = false;
btnEdit.Enabled = false;
btnView.Enabled = true;
radGridView1.AllowAddNewRow = false;
}
private void ViewClick()
{
radGridView1.ReadOnly = true;
btnView.Enabled = false;
btnEdit.Enabled = true;
radGridView1.AllowAddNewRow = false;
DataLoad();
}
private void btnNew_Click(object sender, EventArgs e)
{
NewClick();
}
private void btnView_Click(object sender, EventArgs e)
{
ViewClick();
}
private void btnEdit_Click(object sender, EventArgs e)
{
EditClick();
}
private void btnSave_Click(object sender, EventArgs e)
{
if(MessageBox.Show("เธเนเธญเธเธเธฒเธฃเธเธฑเธเธเธถเธ ?","เธเธฑเธเธเธถเธ",MessageBoxButtons.YesNo,MessageBoxIcon.Question)==DialogResult.Yes)
{
AddUnit();
DataLoad();
}
}
private void radGridView1_CellEndEdit(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e)
{
try
{
radGridView1.Rows[e.RowIndex].Cells["dgvC"].Value = "T";
string check1 = Convert.ToString(radGridView1.Rows[e.RowIndex].Cells["GroupCode"].Value);
string check2 = Convert.ToString(radGridView1.Rows[e.RowIndex].Cells["TypeCode"].Value);
string TM= Convert.ToString(radGridView1.Rows[e.RowIndex].Cells["dgvCodeTemp"].Value);
if (!check1.Trim().Equals("") && !check2.Trim().Equals("") && TM.Equals(""))
{
if (!CheckDuplicate(check1.Trim(), check2.Trim()))
{
MessageBox.Show("เธเนเธญเธกเธนเธฅ เธฃเธซเธฑเธชเธเธฃเนเธ เธ เธเนเธณ");
radGridView1.Rows[e.RowIndex].Cells["TypeCode"].Value = "";
radGridView1.Rows[e.RowIndex].Cells["GroupCode"].IsSelected = true;
}
}
}
catch { }
}
private void Unit_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
// MessageBox.Show(e.KeyCode.ToString());
}
private void radGridView1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
// MessageBox.Show(e.KeyCode.ToString());
if(e.KeyData==(Keys.Control|Keys.S))
{
if (MessageBox.Show("เธเนเธญเธเธเธฒเธฃเธเธฑเธเธเธถเธ ?", "เธเธฑเธเธเธถเธ", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
AddUnit();
DataLoad();
}
}
else if (e.KeyData == (Keys.Control | Keys.N))
{
if (MessageBox.Show("เธเนเธญเธเธเธฒเธฃเธชเธฃเนเธฒเธเนเธซเธกเน ?", "เธชเธฃเนเธฒเธเนเธซเธกเน", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
NewClick();
}
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
DeleteUnit();
DataLoad();
}
int row = -1;
private void radGridView1_CellClick(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e)
{
row = e.RowIndex;
}
private void btnExport_Click(object sender, EventArgs e)
{
//dbClss.ExportGridCSV(radGridView1);
dbClss.ExportGridXlSX(radGridView1);
}
private void btnImport_Click(object sender, EventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.Filter = "Spread Sheet files (*.csv)|*.csv|All files (*.csv)|*.csv";
if (op.ShowDialog() == DialogResult.OK)
{
using (TextFieldParser parser = new TextFieldParser(op.FileName))
{
dt.Rows.Clear();
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
int a = 0;
int c = 0;
while (!parser.EndOfData)
{
//Processing row
a += 1;
DataRow rd = dt.NewRow();
// MessageBox.Show(a.ToString());
string[] fields = parser.ReadFields();
c = 0;
foreach (string field in fields)
{
c += 1;
//TODO: Process field
//MessageBox.Show(field);
if (a>1)
{
if(c==1)
rd["GroupCode"] = Convert.ToString(field);
else if(c==2)
rd["Typecode"] = Convert.ToString(field);
else if(c==3)
rd["TypeDetail"] = Convert.ToString(field);
else if (c == 4)
rd["TypeActive"] = Convert.ToBoolean(field);
}
else
{
if (c == 1)
rd["GroupCode"] = "";
else if (c == 2)
rd["Typecode"] = "";
else if (c == 3)
rd["TypeDetail"] = "";
else if (c == 4)
rd["TypeActive"] = false;
}
//
//rd[""] = "";
//rd[""]
}
dt.Rows.Add(rd);
}
}
if(dt.Rows.Count>0)
{
dbClss.AddHistory(this.Name, "Import [Type]", "Import file CSV in to System", "");
ImportData();
MessageBox.Show("Import Completed.");
DataLoad();
}
}
}
private void ImportData()
{
try
{
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
foreach (DataRow rd in dt.Rows)
{
if (!rd["GroupCode"].ToString().Equals("") && !rd["TypeCode"].ToString().Equals(""))
{
var x = (from ix in db.tb_Types
where ix.GroupCode.ToLower().Trim() == rd["GroupCode"].ToString().ToLower().Trim()
&& ix.TypeCode.ToLower().Trim() == rd["TypeCode"].ToString().ToLower().Trim()
select ix).FirstOrDefault();
if(x==null)
{
tb_Type ts = new tb_Type();
ts.GroupCode= Convert.ToString(rd["GroupCode"].ToString());
ts.TypeCode = Convert.ToString(rd["TypeCode"].ToString());
ts.TypeDetail= Convert.ToString(rd["TypeDetail"].ToString());
ts.TypeActive = Convert.ToBoolean(rd["TypeActive"].ToString());
db.tb_Types.InsertOnSubmit(ts);
db.SubmitChanges();
}
else
{
x.TypeDetail= Convert.ToString(rd["TypeDetail"].ToString());
x.TypeActive = Convert.ToBoolean(rd["TypeActive"].ToString());
db.SubmitChanges();
}
}
}
}
}
catch(Exception ex) { MessageBox.Show(ex.Message);
dbClss.AddError("InportData", ex.Message, this.Name);
}
}
private void btnFilter1_Click(object sender, EventArgs e)
{
radGridView1.EnableFiltering = true;
}
private void btnUnfilter1_Click(object sender, EventArgs e)
{
radGridView1.EnableFiltering = false;
}
private void radMenuItem1_Click(object sender, EventArgs e)
{
this.Close();
}
private void radGridView1_CellFormatting(object sender, CellFormattingEventArgs e)
{
if (e.CellElement.ColumnInfo.HeaderText == "เธฃเธซเธฑเธชเธเธฃเธฐเนเธ เธเธเธฅเธธเนเธก" )
{
if (e.CellElement.RowInfo.Cells["GroupCode"].Value != null)
{
if (!e.CellElement.RowInfo.Cells["GroupCode"].Value.Equals(""))
{
e.CellElement.DrawFill = true;
// e.CellElement.ForeColor = Color.Blue;
e.CellElement.NumberOfColors = 1;
e.CellElement.BackColor = Color.WhiteSmoke;
}
//else
//{
// e.CellElement.DrawFill = true;
// //e.CellElement.ForeColor = Color.Yellow;
// e.CellElement.NumberOfColors = 1;
// e.CellElement.BackColor = Color.WhiteSmoke;
//}
}
}
}
}
}
|
Tay-nakub/Stockcontrol
|
StockControl/Process/Types.cs
|
C#
|
gpl-3.0
| 21,576 |
/*
* MicroJIAC - A Lightweight Agent Framework
* This file is part of Example: PingPong.
*
* Copyright (c) 2007-2011 DAI-Labor, Technische Universitรคt Berlin
*
* This library includes software developed at DAI-Labor, Technische
* Universitรคt Berlin (http://www.dai-labor.de)
*
* This library is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* $Id$
*/
package de.jiac.micro.examples.pingpong;
import de.jiac.micro.internal.ApplicationLauncher;
/**
* @author Marcel Patzlaff
* @version $Revision:$
*/
public class PingNodeLauncher {
public static void main(String[] args) {
ApplicationLauncher.main(new String[] {"config.ping"});
}
}
|
mcpat/microjiac-examples-public
|
pingpong/src/main/java/de/jiac/micro/examples/pingpong/PingNodeLauncher.java
|
Java
|
gpl-3.0
| 1,256 |
/*
Copyright 2010-2012 Infracom & Eurotechnia (support@webcampak.com)
This file is part of the Webcampak project.
Webcampak is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License,
or (at your option) any later version.
Webcampak is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with Webcampak.
If not, see http://www.gnu.org/licenses/.
*/
console.log('Log: Load: Webcampak.controller.dashboard.SourceDiskUsage');
Ext.define('Webcampak.controller.dashboard.SourceDiskUsage', {
extend: 'Ext.app.Controller',
stores: [
'dashboard.SourceDiskUsage',
'permissions.sources.Sources'
],
models: [
'dashboard.SourceDiskUsage'
],
views: [
'dashboard.sourcediskusage.SourceDiskUsageWindow',
'dashboard.sourcediskusage.SourceDiskUsage',
'dashboard.sourcediskusage.SourcesList'
],
refs: [
{ref: 'sourcediskusagewindow', selector: 'sourcediskusagewindow', xtype: 'sourcediskusagewindow'},
{ref: 'sourcediskusage', selector: 'sourcediskusage', xtype: 'sourcediskusage'},
{ref: 'statssourceslist', selector: 'statssourceslist', xtype: 'statssourceslist'}
],
onLaunch: function() {
console.log('Log: Controller->Dashboard->SourceDiskUsage: Controller onLaunch: function()');
/*
//Show Files Graph window (stats about size of pictures per day)
if(!this.getSourcediskusagewindow().isVisible()) {
this.getSourcediskusagewindow().show();
console.log('Log: Controller->Menu: openPhotos - getSourcepicturefileswindow().show()');
//Load the sources store
this.getPermissionsSourcesSourcesStore().on('load',this.loadGraphContent,this,{single:true});
this.getPermissionsSourcesSourcesStore().load();
} else {
this.getSourcediskusagewindow().hide();
console.log('Log: Controller->Menu: openPhotos - getSourcepicturefileswindow().hide()');
}
*/
},
init: function() {
console.log('Log: Controller->Dashboard->SourceDiskUsage: Controller init: function()');
// Start listening for events on views
this.control({
'sourcediskusagewindow button[action=reload]': {click: this.reloadGraph},
'sourcediskusagewindow button[action=save]': {click: this.saveGraph},
'statssourceslist': {select: this.onSourceSelected},
'sourcediskusagewindow combo[action=updateRange]': {select: this.onUpdateRange},
'sourcediskusagewindow': {resize: this.windowResize}
});
},
loadGraphContent: function() {
console.log('Log: Controller->Dashboard->SourceDiskUsage: loadGraphContent: function()');
},
windowResize: function() {
console.log('Log: Controller->Dashboard->SourceDiskUsage: windowResize: function()');
this.getSourcediskusage().axes.items[1].setTitle(Ext.getStore('permissions.sources.Sources').first().get('name'));
Ext.getStore('dashboard.SourceDiskUsage').getProxy().setExtraParam('sourceid', Ext.getStore('permissions.sources.Sources').first().get('sourceid'));
//Load the latest picture for the selected source
this.getDashboardSourceDiskUsageStore().on('load',this.loadGraphContent,this,{single:true});
this.getDashboardSourceDiskUsageStore().load();
},
onUpdateRange: function(selModel, selection) {
console.log('Log: Controller->Dashboard->SourceDiskUsage: onUpdateRange: function()');
console.log('Log: Controller->Dashboard->SourceDiskUsage: onUpdateRange: Selected range is:' + selection[0].get('name'));
Ext.getStore('dashboard.SourceDiskUsage').getProxy().setExtraParam('range', selection[0].get('value'));
//Load the latest picture for the selected source
this.getDashboardSourceDiskUsageStore().on('load',this.loadGraphContent,this,{single:true});
this.getDashboardSourceDiskUsageStore().load();
},
onSourceSelected: function(selModel, selection) {
console.log('Log: Controller->Dashboard->SourceDiskUsage: onSourceSelected: function()');
console.log('Log: Controller->Dashboard->SourceDiskUsage: onSourceSelected: Selected name is:' + selection[0].get('name'));
console.log('Log: Controller->Dashboard->SourceDiskUsage: onSourceSelected: Selected Sourceid is:' + selection[0].get('sourceid'));
Ext.getStore('dashboard.SourceDiskUsage').getProxy().setExtraParam('sourceid', selection[0].get('sourceid'));
//Set Sourcename as the title
// this.getSourcediskusagewindow().setTitle(i18n.gettext('Graph: Disk usage per source') + " (" + selection[0].get('name') + ")");
this.getSourcediskusage().axes.items[1].setTitle(selection[0].get('name'));
//Load the latest picture for the selected source
this.getDashboardSourceDiskUsageStore().on('load',this.loadGraphContent,this,{single:true});
this.getDashboardSourceDiskUsageStore().load();
},
reloadGraph: function() {
console.log('Log: Controller->Dashboard->SourceDiskUsage: Controller reloadGraph: function()');
this.getDashboardSourceDiskUsageStore().load();
},
saveGraph: function() {
console.log('Log: Controller->Dashboard->SourceDiskUsage: Controller saveGraph: function()');
currentChart = this.getSourcediskusage();
Ext.MessageBox.confirm(i18n.gettext('Confirm Download'), i18n.gettext('Would you like to download the chart as an image?'), function(choice){
if(choice == 'yes'){
currentChart.save({
type: 'image/png'
});
}
});
}
});
|
Webcampak/v2.0
|
src/www/interface/dev/app/controller/dashboard/SourceDiskUsage.js
|
JavaScript
|
gpl-3.0
| 5,637 |
<?php
/**
* @auther Saurabh Chandra Patel
* @link https://github.com/saurabhaec/PHPLogger/ for PHP Log report
* @license https://github.com/saurabhaec/PHPLogger/blob/master/LICENSE GNU GENERAL PUBLIC LICENSE
*/
class PHPLogger implements \SplSubject {
/**
* [$name log file name ]
* @var [type]
*/
private $filename;
/**
* [$observers description]
* @var array
*/
private $observers = array();
/**
* [$content description]
* @var [type]
*/
private $content;
/**
* [$path description]
* @var [type]
*/
private $path = '/var/log/';
/**
* [__construct description]
* @param [type] $name [description]
*/
public function __construct($path) {
$this->filename = date('y-m-d') . '.log';
$this->path = $path;
}
public function __get($pro) {
return $this->$pro;
}
/**
* [__set description]
* @param [string] $pro [description]
* @param [string] $value [description]
*/
public function __set($pro, $value) {
return $this->$pro = $value;
}
//add observer
/**
* [attach description]
* @param \SplObserver $observer [description]
* @return [null] [description]
*/
public function attach(\SplObserver $observer) {
$this->observers[] = $observer;
}
//remove observer
/**
* [detach description]
* @param \SplObserver $observer [description]
* @return [null] [description]
*/
public function detach(\SplObserver $observer) {
$key = array_search($observer, $this->observers, true);
if ($key) {
unset($this->observers[$key]);
}
}
public function getContent() {
return $this->content . " ({$this->filename})";
}
//notify observers(or some of them)
/**
* [notify description]
* @return [null] [description]
*/
public function notify() {
foreach ($this->observers as $value) {
$value->update($this);
}
}
public function writeLog() {
$this->notify();
}
}
class Reportlog implements SplObserver {
private $action;
/**
* [__construct description]
* @param $action [report identifiers]
*/
public function __construct($action) {
$this->action = $action;
}
/**
* [update description]
* @param \SplSubject $subject [description]
* @return [type] [description]
*/
public function update(\SplSubject $subject) {
$msg = date('y-m-d H:i:s') . "\t" . $this->action . "\n";
$path = $subject->__get('path') . '' . $subject->__get('filename');
error_log($msg, 3, $path);
}
}
?>
|
saurabhaec/PHPLogger
|
PHPLogger.php
|
PHP
|
gpl-3.0
| 2,465 |
/* Copyright 2012, mokasin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package database
import (
"database/sql"
"errors"
"fmt"
_ "github.com/mattn/go-sqlite3"
"os"
"time"
)
var (
ErrNoOpenTransaction = errors.New("No open transaction.")
ErrExistingTransaction = errors.New("There is an existing transaction.")
ErrDatabaseExists = errors.New("Can't create new database. A database already exists.")
)
type CreateTableFunc func(db *Database) error
// A Result is a mapping from column name to its value.
type Result map[string]interface{}
type Database struct {
Filename string
db *sql.DB
mtime int64
tx *sql.Tx // global transaction
txOpen bool // flag true, when exists an open transaction
fctables []CreateTableFunc
newDB bool
}
// Creates a new Database struct and connects it to the database at filename.
// Needs to be closed with method Close()!
func NewDatabase(filename string) (*Database, error) {
_, err := os.Stat(filename)
newdatabase := os.IsNotExist(err)
db, err := sql.Open("sqlite3", filename)
if err != nil {
return nil, err
}
datab := &Database{Filename: filename, db: db, newDB: newdatabase}
// Make it nosync and disable the journal
if _, err := db.Exec("PRAGMA synchronous=OFF"); err != nil {
return nil, err
}
if _, err := db.Exec("PRAGMA journal_mode=OFF"); err != nil {
return nil, err
}
//if _, err := db.Exec("PRAGMA case_sensitive_like=TRUE"); err != nil {
// return nil, err
//}
return datab, nil
}
func (self *Database) Mtime() int64 {
return self.mtime
}
// Closes the opened database.
func (self *Database) Close() {
self.db.Close()
}
// Creates the basic database structure.
func (self *Database) CreateDatabase() error {
if !self.newDB {
return ErrDatabaseExists
}
if len(self.fctables) == 0 {
return fmt.Errorf("Can't create database. " +
"No functions to create the tables are registered.")
}
if err := self.BeginTransaction(); err != nil {
return err
}
defer self.EndTransaction()
for _, t := range self.fctables {
err := t(self)
if err != nil {
return err
}
}
return nil
}
// Add registers a new function to create a table.
func (self *Database) Register(m CreateTableFunc) {
self.fctables = append(self.fctables, m)
}
// BeginTransaction starts a new database transaction.
func (self *Database) BeginTransaction() (err error) {
if self.txOpen {
return ErrExistingTransaction
}
self.tx, err = self.db.Begin()
if err != nil {
return err
}
self.txOpen = true
// Updating mtime when something has changed
self.mtime = time.Now().Unix()
return nil
}
// EndTransaction closes a opened database transaction.
func (self *Database) EndTransaction() error {
if !self.txOpen {
return ErrNoOpenTransaction
}
self.txOpen = false
return self.tx.Commit()
}
// Execute just executes sql query in global transaction.
func (self *Database) Execute(sql string, args ...interface{}) (res sql.Result, err error) {
if !self.txOpen {
err = self.BeginTransaction()
if err != nil {
return nil, err
}
defer self.EndTransaction()
}
res, err = self.tx.Exec(sql, args...)
return res, err
}
// QueryDB queries the database with a given SQL-string and arguments args and
// returns the result as a map from column name to its value.
func (self *Database) Query(sql string, args ...interface{}) ([]Result, error) {
if !self.txOpen {
err := self.BeginTransaction()
if err != nil {
return nil, err
}
defer self.EndTransaction()
}
// do the actual query
rows, err := self.tx.Query(sql, args...)
if err != nil {
return nil, err
}
defer rows.Close()
// find out about the columns in the database
columns, err := rows.Columns()
if err != nil {
return nil, err
}
// prepare result
var result []Result
// stupid trick, because rows.Scan will not take []interface as args
col_vals := make([]interface{}, len(columns))
col_args := make([]interface{}, len(columns))
// initialize col_args
for i := 0; i < len(columns); i++ {
col_args[i] = &col_vals[i]
}
// read out columns and save them in a Result map
for rows.Next() {
if err := rows.Scan(col_args...); err != nil {
return nil, err
}
res := make(Result)
for i := 0; i < len(columns); i++ {
res[columns[i]] = col_vals[i]
}
result = append(result, res)
}
return result, rows.Err()
}
|
mokasin/musicrawler
|
lib/database/database.go
|
GO
|
gpl-3.0
| 4,976 |
<?php
// Exit if accessed directly
if ( !defined('ABSPATH')) exit;
/**
* Main Widget Template
*
*
* @file sidebar.php
* @package Responsive
* @author Emil Uzelac
* @copyright 2003 - 2013 ThemeID
* @license license.txt
* @version Release: 1.0
* @filesource wp-content/themes/responsive/sidebar.php
* @link http://codex.wordpress.org/Theme_Development#Widgets_.28sidebar.php.29
* @since available since Release 1.0
*/
?>
<div id="widgets" class="grid col-300 fit">
<?php responsive_widgets(); // above widgets hook ?>
<?php if (!dynamic_sidebar('bbpress')) : ?>
<div class="widget-wrapper">
<div class="widget-title"><?php _e('In Archive', 'responsive'); ?></div>
<ul>
<?php wp_get_archives( array( 'type' => 'monthly' ) ); ?>
</ul>
</div><!-- end of .widget-wrapper -->
<?php endif; //end of main-sidebar ?>
<?php responsive_widgets_end(); // after widgets hook ?>
</div><!-- end of #widgets -->
|
mhawksey/moocinabox
|
oocinabox/responsive-child-octel/sidebar-bbpress.php
|
PHP
|
gpl-3.0
| 1,109 |
var NAVTREEINDEX1 =
{
"var__init_8h.html#a0764b32f40bbe284b6ba2a1fee678d6c":[2,0,0,16,4],
"var__init_8h.html#a2fd24bcbadb8b59c176dccc6f13250e9":[2,0,0,16,3],
"var__init_8h.html#a3482785bd2a4c8b307f9e0b6f54e2c36":[2,0,0,16,8],
"var__init_8h.html#a6b57f01d3c576db5368dd0efc2f435a4":[2,0,0,16,1],
"var__init_8h.html#a78fa3957d73de49cb81d047857504218":[2,0,0,16,5],
"var__init_8h.html#a8194731fdeea643e725e3a89d2f7ec59":[2,0,0,16,6],
"var__init_8h.html#ab454541ae58bcf6555e8d723b1eb95e7":[2,0,0,16,7],
"var__init_8h.html#abe06f96c5aeacdb02e4b66e34e609982":[2,0,0,16,2],
"var__init_8h.html#ae86e3a2639bfd6cac9c94470ec2825c8":[2,0,0,16,9],
"var__init_8h_source.html":[2,0,0,16]
};
|
SimonItaly/duckhunt
|
doc/html/navtreeindex1.js
|
JavaScript
|
gpl-3.0
| 675 |
var a00572 =
[
[ "Nrf_bootloader", "a00573.html", null ],
[ "Nrf_dfu", "a00574.html", null ],
[ "Nrf_dfu_transport", "a00575.html", null ],
[ "Nrf_bootloader_util", "a00576.html", null ],
[ "Ble_sdk_app_bootloader_main", "a00577.html", null ]
];
|
DroneBucket/Drone_Bucket_CrazyFlie2_NRF_Firmware
|
nrf51_sdk/Documentation/s120/html/a00572.js
|
JavaScript
|
gpl-3.0
| 265 |
package greymerk.roguelike.dungeon.segment;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import greymerk.roguelike.dungeon.IDungeonLevel;
import greymerk.roguelike.theme.ITheme;
import greymerk.roguelike.util.WeightedChoice;
import greymerk.roguelike.util.WeightedRandomizer;
import greymerk.roguelike.worldgen.Cardinal;
import greymerk.roguelike.worldgen.Coord;
import greymerk.roguelike.worldgen.IStair;
import greymerk.roguelike.worldgen.IWorldEditor;
public class SegmentGenerator implements ISegmentGenerator{
protected Segment arch;
protected WeightedRandomizer<Segment> segments;
public SegmentGenerator(){
this(Segment.ARCH);
}
public SegmentGenerator(Segment arch){
this.segments = new WeightedRandomizer<Segment>();
this.arch = arch;
}
public SegmentGenerator(SegmentGenerator toCopy){
this.arch = toCopy.arch;
this.segments = new WeightedRandomizer<Segment>(toCopy.segments);
}
public SegmentGenerator(JsonObject json){
String archType = json.get("arch").getAsString();
arch = Segment.valueOf(archType);
this.segments = new WeightedRandomizer<Segment>();
JsonArray segmentList = json.get("segments").getAsJsonArray();
for(JsonElement e : segmentList){
JsonObject segData = e.getAsJsonObject();
this.add(segData);
}
}
public void add(JsonObject entry){
String segType = entry.get("type").getAsString();
Segment type = Segment.valueOf(segType);
if(entry.has("arch")){
boolean a = entry.get("arch").getAsBoolean();
if(a) this.arch = type;
return;
}
int weight = entry.has("weight") ? entry.get("weight").getAsInt() : 1;
this.segments.add(new WeightedChoice<Segment>(type, weight));
}
public void add(Segment toAdd, int weight){
this.segments.add(new WeightedChoice<Segment>(toAdd, weight));
}
@Override
public List<ISegment> genSegment(IWorldEditor editor, Random rand, IDungeonLevel level, Cardinal dir, Coord pos) {
int x = pos.getX();
int y = pos.getY();
int z = pos.getZ();
List<ISegment> segs = new ArrayList<ISegment>();
for(Cardinal orth : Cardinal.orthogonal(dir)){
ISegment seg = pickSegment(editor, rand, level, dir, pos);
if(seg == null) return segs;
seg.generate(editor, rand, level, orth, level.getSettings().getTheme(), new Coord(pos));
segs.add(seg);
}
if(!level.hasNearbyNode(pos) && rand.nextInt(3) == 0) addSupport(editor, rand, level.getSettings().getTheme(), x, y, z);
return segs;
}
private ISegment pickSegment(IWorldEditor editor, Random rand, IDungeonLevel level, Cardinal dir, Coord pos){
int x = pos.getX();
int z = pos.getZ();
if((dir == Cardinal.NORTH || dir == Cardinal.SOUTH) && z % 3 == 0){
if(z % 6 == 0) return Segment.getSegment(arch);
return this.segments.isEmpty()
? Segment.getSegment(Segment.WALL)
: Segment.getSegment(this.segments.get(rand));
}
if((dir == Cardinal.WEST || dir == Cardinal.EAST) && x % 3 == 0){
if(x % 6 == 0) return Segment.getSegment(arch);
return this.segments.isEmpty()
? Segment.getSegment(Segment.WALL)
: Segment.getSegment(this.segments.get(rand));
}
return null;
}
private void addSupport(IWorldEditor editor, Random rand, ITheme theme, int x, int y, int z){
if(!editor.isAirBlock(new Coord(x, y - 2, z))) return;
editor.fillDown(rand, new Coord(x, y - 2, z), theme.getPrimary().getPillar());
IStair stair = theme.getPrimary().getStair();
stair.setOrientation(Cardinal.WEST, true);
stair.set(editor, new Coord(x - 1, y - 2, z));
stair.setOrientation(Cardinal.EAST, true);
stair.set(editor, new Coord(x + 1, y - 2, z));
stair.setOrientation(Cardinal.SOUTH, true);
stair.set(editor, new Coord(x, y - 2, z + 1));
stair.setOrientation(Cardinal.NORTH, true);
stair.set(editor, new Coord(x, y - 2, z - 1));
}
public static SegmentGenerator getRandom(Random rand, int count) {
SegmentGenerator segments = new SegmentGenerator(Segment.ARCH);
for(int i = 0; i < count; ++i){
segments.add(Segment.getRandom(rand), 1);
}
return segments;
}
}
|
Greymerk/minecraft-roguelike
|
src/main/java/greymerk/roguelike/dungeon/segment/SegmentGenerator.java
|
Java
|
gpl-3.0
| 4,198 |
<?php
/**
* Belgian Police Web Platform - Signatures Component
*
* @copyright Copyright (C) 2012 - 2013 Timble CVBA. (http://www.timble.net)
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link https://github.com/belgianpolice/internet-platform
*/
use Nooku\Library;
class SignaturesViewSignatureHtml extends SignaturesViewHtml
{
public function render()
{
//Get the article
$signature = $this->getModel()->getData();
$category = $this->getCategory();
//Set the pathway
$this->getObject('application')->getPathway()->addItem($category->title, $this->getTemplate()->getHelper('route')->category(array('row' => $category)));
$this->getObject('application')->getPathway()->addItem($signature->title, '');
// Get the zone
$this->zone = $this->getObject('com:police.model.zone')->id($this->getObject('application')->getCfg('site' ))->getRow();
//Get the attachments
if ($signature->id && $signature->isAttachable()) {
$this->attachments($signature->getAttachments());
}
return parent::render();
}
public function getCategory()
{
//Get the category
$category = $this->getObject('com:signatures.model.categories')
->table('signatures')
->slug($this->getModel()->getState()->category)
->getRow();
return $category;
}
}
|
yiendos/snowsport
|
application/site/component/signatures/view/signature/html.php
|
PHP
|
gpl-3.0
| 1,434 |
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "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 Nokia Corporation and its Subsidiary(-ies) 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."
** $QT_END_LICENSE$
**
****************************************************************************/
//! [0]
#include "stdafx.h"
#include <QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
Q_INIT_RESOURCE(application);
QApplication app(argc, argv);
app.setOrganizationName("Trolltech");
app.setApplicationName("Application Example");
MainWindow mainWin;
mainWin.show();
return app.exec();
}
//! [0]
|
austin98x/cross-platform-desktop-app
|
gui/qt-demo/main.cpp
|
C++
|
gpl-3.0
| 2,452 |
// Copyright 2015 The go-ethereum Authors
// This file is part of go-ethereum.
//
// go-ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// go-ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
// +build !evmjit
package vm
import "fmt"
func NewJitVm(env Environment) VirtualMachine {
fmt.Printf("Warning! EVM JIT not enabled.\n")
return New(env)
}
|
tgerring/go-ethereum
|
core/vm/vm_jit_fake.go
|
GO
|
gpl-3.0
| 906 |
/*
* Copyright (C) 2016 - 2017 Aurum
*
* Mystery is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Mystery is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.aurum.mystery2.game;
import com.aurum.mystery2.BitConverter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.aurum.mystery2.ByteBuffer;
import com.aurum.mystery2.ByteOrder;
import com.aurum.mystery2.Lists;
public class DungeonPokemon implements Cloneable {
// Entry fields
public List<Entry> entries;
// Other fields
public int offset;
// Static fields
public static final int SIZE = 0x8;
private static final byte[] NULL = new byte[SIZE];
public static class Entry implements Cloneable {
public int species, level, probability;
@Override
public String toString() {
return Lists.pokemon.get(species) + ": Lv. " + level + " (" + probability + ")";
}
@Override
public Object clone() {
try {
return super.clone();
}
catch (CloneNotSupportedException ex) {
return null;
}
}
}
@Override
public Object clone() {
try {
DungeonPokemon clone = (DungeonPokemon) super.clone();
clone.entries = new ArrayList();
for (Entry entry : entries)
clone.entries.add((Entry) entry.clone());
return clone;
}
catch (CloneNotSupportedException ex) {
return null;
}
}
public boolean checkProbabilitySum() {
int sum = 0;
for (Entry entry : entries)
sum += entry.probability;
return sum != 10000;
}
public static DungeonPokemon unpack(ByteBuffer buffer) {
DungeonPokemon pokemon = new DungeonPokemon();
pokemon.offset = buffer.position();
pokemon.entries = new ArrayList();
int storedoffset = buffer.position();
int diff = 0;
while(!Arrays.equals(buffer.readBytes(SIZE), NULL)) {
buffer.seek(storedoffset);
Entry entry = new Entry();
int mask = buffer.readUnsignedShort();
entry.level = (mask ^ 0x1A8) / 0x200;
entry.species = mask - 0x200 * entry.level;
entry.probability = buffer.readUnsignedShort();
int val = entry.probability;
if (val != 0) {
val -= diff;
diff = entry.probability;
}
entry.probability = val;
pokemon.entries.add(entry);
buffer.skip(0x4);
storedoffset = buffer.position();
}
return pokemon;
}
public static byte[] pack(DungeonPokemon pokemon) {
ByteBuffer buffer = new ByteBuffer(pokemon.entries.size() * 8 + 8, ByteOrder.LITTLE_ENDIAN);
int sum = 0;
for (Entry entry : pokemon.entries) {
buffer.writeUnsignedShort(entry.species + entry.level * 0x200);
if (sum < 10000) {
int val = (entry.probability != 0) ? sum += entry.probability : 0;
buffer.writeUnsignedShort(val);
buffer.writeUnsignedShort(val);
}
else {
buffer.writeUnsignedShort(0);
buffer.writeUnsignedShort(0);
}
buffer.writeUnsignedShort(0);
}
buffer.writeBytes(NULL);
return buffer.getBuffer();
}
}
|
SunakazeKun/PMDe
|
src/com/aurum/mystery2/game/DungeonPokemon.java
|
Java
|
gpl-3.0
| 4,157 |
/**
* JSkat - A skat program written in Java
* by Jan Schรคfer, Markus J. Luzius and Daniel Loreck
*
* Version 0.11.0
* Copyright (C) 2012-08-28
*
* Licensed under the Apache License, Version 2.0. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jskat.gui.action.iss;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import org.jskat.gui.action.AbstractJSkatAction;
import org.jskat.gui.action.JSkatAction;
import org.jskat.gui.img.JSkatGraphicRepository.Icon;
import org.jskat.util.JSkatResourceBundle;
/**
* Implements the action for showing about dialog
*/
public class ShowLoginPanelAction extends AbstractJSkatAction {
private static final long serialVersionUID = 1L;
/**
* @see AbstractJSkatAction#AbstractJSkatAction()
*/
public ShowLoginPanelAction() {
putValue(Action.NAME,
JSkatResourceBundle.instance().getString("play_on_iss")); //$NON-NLS-1$
setActionCommand(JSkatAction.SHOW_ISS_LOGIN);
setIcon(Icon.CONNECT_ISS);
}
/**
* @see AbstractAction#actionPerformed(ActionEvent)
*/
@Override
public void actionPerformed(final ActionEvent e) {
jskat.getIssController().showISSLoginPanel();
}
}
|
mfrasca/jskat-gui
|
src/main/java/org/jskat/gui/action/iss/ShowLoginPanelAction.java
|
Java
|
gpl-3.0
| 1,581 |
/*
Copyright (C) 1996-2017 John W. Eaton
This file is part of Octave.
Octave is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
Octave is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with Octave; see the file COPYING. If not, see
<http://www.gnu.org/licenses/>.
*/
#if defined (HAVE_CONFIG_H)
# include "config.h"
#endif
#include "Array-util.h"
#include "errwarn.h"
#include "ovl.h"
#include "ov.h"
#include "ov-scalar.h"
#include "ov-float.h"
#include "ov-flt-re-mat.h"
#include "ov-typeinfo.h"
#include "ov-null-mat.h"
#include "ops.h"
#include "xdiv.h"
#include "xpow.h"
// scalar unary ops.
DEFUNOP (not, float_scalar)
{
const octave_float_scalar& v = dynamic_cast<const octave_float_scalar&> (a);
float x = v.float_value ();
if (octave::math::isnan (x))
octave::err_nan_to_logical_conversion ();
return octave_value (x == 0.0f);
}
DEFUNOP_OP (uplus, float_scalar, /* no-op */)
DEFUNOP_OP (uminus, float_scalar, -)
DEFUNOP_OP (transpose, float_scalar, /* no-op */)
DEFUNOP_OP (hermitian, float_scalar, /* no-op */)
DEFNCUNOP_METHOD (incr, float_scalar, increment)
DEFNCUNOP_METHOD (decr, float_scalar, decrement)
// float by float ops.
DEFBINOP_OP (add, float_scalar, float_scalar, +)
DEFBINOP_OP (sub, float_scalar, float_scalar, -)
DEFBINOP_OP (mul, float_scalar, float_scalar, *)
DEFBINOP (div, float_scalar, float_scalar)
{
const octave_float_scalar& v1 = dynamic_cast<const octave_float_scalar&> (a1);
const octave_float_scalar& v2 = dynamic_cast<const octave_float_scalar&> (a2);
float d = v2.float_value ();
if (d == 0.0)
warn_divide_by_zero ();
return octave_value (v1.float_value () / d);
}
DEFBINOP_FN (pow, float_scalar, float_scalar, xpow)
DEFBINOP (ldiv, float_scalar, float_scalar)
{
const octave_float_scalar& v1 = dynamic_cast<const octave_float_scalar&> (a1);
const octave_float_scalar& v2 = dynamic_cast<const octave_float_scalar&> (a2);
float d = v1.float_value ();
if (d == 0.0)
warn_divide_by_zero ();
return octave_value (v2.float_value () / d);
}
DEFBINOP_OP (lt, float_scalar, float_scalar, <)
DEFBINOP_OP (le, float_scalar, float_scalar, <=)
DEFBINOP_OP (eq, float_scalar, float_scalar, ==)
DEFBINOP_OP (ge, float_scalar, float_scalar, >=)
DEFBINOP_OP (gt, float_scalar, float_scalar, >)
DEFBINOP_OP (ne, float_scalar, float_scalar, !=)
DEFBINOP_OP (el_mul, float_scalar, float_scalar, *)
DEFBINOP (el_div, float_scalar, float_scalar)
{
const octave_float_scalar& v1 = dynamic_cast<const octave_float_scalar&> (a1);
const octave_float_scalar& v2 = dynamic_cast<const octave_float_scalar&> (a2);
float d = v2.float_value ();
if (d == 0.0)
warn_divide_by_zero ();
return octave_value (v1.float_value () / d);
}
DEFBINOP_FN (el_pow, float_scalar, float_scalar, xpow)
DEFBINOP (el_ldiv, float_scalar, float_scalar)
{
const octave_float_scalar& v1 = dynamic_cast<const octave_float_scalar&> (a1);
const octave_float_scalar& v2 = dynamic_cast<const octave_float_scalar&> (a2);
float d = v1.float_value ();
if (d == 0.0)
warn_divide_by_zero ();
return octave_value (v2.float_value () / d);
}
DEFSCALARBOOLOP_OP (el_and, float_scalar, float_scalar, &&)
DEFSCALARBOOLOP_OP (el_or, float_scalar, float_scalar, ||)
DEFNDCATOP_FN (fs_fs, float_scalar, float_scalar, float_array, float_array,
concat)
DEFNDCATOP_FN (s_fs, scalar, float_scalar, float_array, float_array, concat)
DEFNDCATOP_FN (fs_s, float_scalar, scalar, float_array, float_array, concat)
void
install_fs_fs_ops (void)
{
INSTALL_UNOP (op_not, octave_float_scalar, not);
INSTALL_UNOP (op_uplus, octave_float_scalar, uplus);
INSTALL_UNOP (op_uminus, octave_float_scalar, uminus);
INSTALL_UNOP (op_transpose, octave_float_scalar, transpose);
INSTALL_UNOP (op_hermitian, octave_float_scalar, hermitian);
INSTALL_NCUNOP (op_incr, octave_float_scalar, incr);
INSTALL_NCUNOP (op_decr, octave_float_scalar, decr);
INSTALL_BINOP (op_add, octave_float_scalar, octave_float_scalar, add);
INSTALL_BINOP (op_sub, octave_float_scalar, octave_float_scalar, sub);
INSTALL_BINOP (op_mul, octave_float_scalar, octave_float_scalar, mul);
INSTALL_BINOP (op_div, octave_float_scalar, octave_float_scalar, div);
INSTALL_BINOP (op_pow, octave_float_scalar, octave_float_scalar, pow);
INSTALL_BINOP (op_ldiv, octave_float_scalar, octave_float_scalar, ldiv);
INSTALL_BINOP (op_lt, octave_float_scalar, octave_float_scalar, lt);
INSTALL_BINOP (op_le, octave_float_scalar, octave_float_scalar, le);
INSTALL_BINOP (op_eq, octave_float_scalar, octave_float_scalar, eq);
INSTALL_BINOP (op_ge, octave_float_scalar, octave_float_scalar, ge);
INSTALL_BINOP (op_gt, octave_float_scalar, octave_float_scalar, gt);
INSTALL_BINOP (op_ne, octave_float_scalar, octave_float_scalar, ne);
INSTALL_BINOP (op_el_mul, octave_float_scalar, octave_float_scalar, el_mul);
INSTALL_BINOP (op_el_div, octave_float_scalar, octave_float_scalar, el_div);
INSTALL_BINOP (op_el_pow, octave_float_scalar, octave_float_scalar, el_pow);
INSTALL_BINOP (op_el_ldiv, octave_float_scalar, octave_float_scalar, el_ldiv);
INSTALL_BINOP (op_el_and, octave_float_scalar, octave_float_scalar, el_and);
INSTALL_BINOP (op_el_or, octave_float_scalar, octave_float_scalar, el_or);
INSTALL_CATOP (octave_float_scalar, octave_float_scalar, fs_fs);
INSTALL_CATOP (octave_scalar, octave_float_scalar, s_fs);
INSTALL_CATOP (octave_float_scalar, octave_scalar, fs_s);
INSTALL_ASSIGNCONV (octave_float_scalar, octave_float_scalar,
octave_float_matrix);
INSTALL_ASSIGNCONV (octave_scalar, octave_float_scalar, octave_matrix);
INSTALL_ASSIGNCONV (octave_float_scalar, octave_null_matrix,
octave_float_matrix);
INSTALL_ASSIGNCONV (octave_float_scalar, octave_null_str,
octave_float_matrix);
INSTALL_ASSIGNCONV (octave_float_scalar, octave_null_sq_str,
octave_float_matrix);
}
|
xmjiao/octave-debian
|
libinterp/operators/op-fs-fs.cc
|
C++
|
gpl-3.0
| 6,381 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration | Version: 3.2
\\ / A nd | Web: http://www.foam-extend.org
\\/ M anipulation | For copyright notice see file Copyright
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
foam-extend is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with foam-extend. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::vanAlbadaLimiter
Description
Class with limiter function which returns the limiter for the
vanAlbada differencing scheme based on r obtained from the LimiterFunc
class.
Used in conjunction with the template class LimitedScheme.
SourceFiles
vanAlbada.C
\*---------------------------------------------------------------------------*/
#ifndef vanAlbada_H
#define vanAlbada_H
#include "vector.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class vanAlbadaLimiter Declaration
\*---------------------------------------------------------------------------*/
template<class LimiterFunc>
class vanAlbadaLimiter
:
public LimiterFunc
{
public:
vanAlbadaLimiter(Istream&)
{}
scalar limiter
(
const scalar cdWeight,
const scalar faceFlux,
const typename LimiterFunc::phiType& phiP,
const typename LimiterFunc::phiType& phiN,
const typename LimiterFunc::gradPhiType& gradcP,
const typename LimiterFunc::gradPhiType& gradcN,
const vector& d
) const
{
scalar r = LimiterFunc::r
(
faceFlux, phiP, phiN, gradcP, gradcN, d
);
// New formulation. Oliver Borm and Aleks Jemcov
// HJ, 13/Jan/2011
return max((r + 1)/(r + 1/stabilise(r, SMALL)), 0);
}
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
|
Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2
|
src/finiteVolume/interpolation/surfaceInterpolation/limitedSchemes/vanAlbada/vanAlbada.H
|
C++
|
gpl-3.0
| 2,902 |
<?php
/*
EINSATZZWECK / USE CASE
* Auslesen der Statistik aus der Datenbank
* Schreiben der Ergebnisse in eine Textdatei
* Die Textdatei kann dann von RESULTS.HTML und RESULTS.JS ausgelesen werden
* Read statistics from database
* Write results into text-file
* The text-file can be accessed via RESULTS.HTML and RESULTS.JS.
*/
$filename = 'results_db.txt';
$somecontent = "";
echo "<p>Current file path and file: <strong>".$_SERVER['SCRIPT_FILENAME']."</strong></p>";
// https://www.w3schools.com/php/php_mysql_select.asp
// Include Database Settings
echo "<p> Loading DB-Settings ... </p>";
include "../statistics/db_settings.php";
// Establish Connection
echo "<p> Establishing Connection ... </p>";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
echo "<p> Checking Connection ... </p>";
if ($conn->connect_error) {
die("Mat-o-Wahl: Connection failed: " . $conn->connect_error);
}
echo "<p> Query SQL ... </p>";
$sql = "SELECT ip, timestamp, personal, parties FROM `$tablename` ";
$result = $conn->query($sql);
$counter = 0;
if ($result->num_rows > 0) {
// output data of each row
echo "<p> Reading data for file ".$filename." ... </p>";
while($row = $result->fetch_assoc()) {
$counter++;
$ip = $row["ip"];
$timestamp = $row["timestamp"];
$mowpersonal = $row["personal"];
$mowparties = $row["parties"];
echo $counter." ip: " .$ip. " - Date: " .$timestamp. " Personal: " .$mowpersonal. " Parties: " .$mowparties. "<br /> ";
$somecontent .= "".$ip." ".$timestamp." ".$mowpersonal." ".$mowparties."\n";
}
}
else {
echo "<p> Error: 0 results </p>";
}
echo "<p> Closing Connection. </p>";
$conn->close();
// DE: Sichergehen, dass die Datei existiert und beschreibbar ist
// EN: Let's make sure the file exists and is writable first.
if (is_writable($filename)) {
// DE: Wir รถffnen $filename im "WRITE" - Modus, so dass die Datei neu geschrieben wird.
// EN: In our example we're opening $filename in WRITE mode to write it new.
if (!$handle = fopen($filename, "w")) {
print "<strong> Cannot open file ($filename) </strong> ";
exit;
}
// DE: Schreibe $somecontent in die geรถffnete Datei.
// EN: Write $somecontent to our opened file.
if (!fwrite($handle, $somecontent)) {
print "<strong> Cannot write to file $filename </strong> ";
exit;
}
print "Success! <br /> wrote: ($somecontent) <br />to file ($filename)";
fclose($handle);
} else {
print "<strong> The file $filename is not writable </strong> ";
}
echo "<p> You can now change the <strong>`var fileResults`</strong> in <strong>/SYSTEM/RESULTS.JS</strong> to <strong>".$filename."</strong> "
?>
|
msteudtn/Mat-O-Wahl
|
extras/statistics_db/read_db_write_text.php
|
PHP
|
gpl-3.0
| 2,864 |
/**********************************************************
* Version $Id$
*********************************************************/
//#include "..\stdafx.h"
#include <iostream>
#include <vector>
#include <functional>
#include "ausdruck.h"
#include "funktion.h"
using namespace std;
class compare_BB_Funktion : public greater<BBFunktion *>
{
public:
bool operator()(const BBFunktion * &x, const BBFunktion * &y) const
{
return x->name < y->name;
};
};
BBBaumInteger::BBBaumInteger()
{
typ = NoOp;
memset(&k, 0, sizeof(BBKnoten));
}
BBBaumInteger::~BBBaumInteger()
{
if (typ == NoOp)
return;
switch(typ)
{
case BIOperator:
if (k.BiOperator.links != NULL)
delete k.BiOperator.links;
if (k.BiOperator.rechts != NULL)
delete k.BiOperator.rechts;
break;
case UniOperator:
if (k.UniOperator.rechts != NULL)
delete k.UniOperator.rechts;
break;
case MIndex:
if (k.MatrixIndex.P != NULL)
delete k.MatrixIndex.P;
break;
case Funktion:
if (k.func != NULL)
delete k.func;
break;
case IZahl:
case FZahl:
case IVar:
case FVar:
break;
}
memset(&k, 0, sizeof(BBKnoten));
}
BBBaumMatrixPoint::BBBaumMatrixPoint() : typ(NoOp) , isMatrix(true)
{
memset(&k, 0, sizeof(BBKnoten));
}
BBBaumMatrixPoint::~BBBaumMatrixPoint()
{
if (typ == NoOp)
return;
switch(typ)
{
case BIOperator:
if (k.BiOperator.links != NULL)
delete k.BiOperator.links;
if (k.BiOperator.rechts != NULL)
delete k.BiOperator.rechts;
break;
case UniOperator:
if (k.UniOperator.rechts != NULL)
delete k.UniOperator.rechts;
break;
case IFAusdruck:
if (k.IntFloatAusdruck.b != NULL)
delete k.IntFloatAusdruck.b;
break;
case MVar:
case PVar:
break;
}
memset(&k, 0, sizeof(BBKnoten));
}
bool getFirstCharKlammer(const string& statement, const string& cmp, char& c, int& pos)
{
if (statement.empty())
return false;
int klammer_ebene = 0, klammerE_ebene = 0;
for (int i=0; i<statement.size()-1; i++)
{
if (statement[i] == '(')
klammer_ebene++;
if (statement[i] == ')')
klammer_ebene--;
if (statement[i] == '[')
klammerE_ebene++;
if (statement[i] == ']')
klammerE_ebene--;
if (klammer_ebene == 0 && klammerE_ebene == 0 && i != statement.size() -1 && i != 0)
{
//int p = cmp.find_first_of(statement[i]);
//if (cmp.find_first_of(statement[i]) >= 0)
int j;
for (j=0; j<cmp.size(); j++)
if (cmp[j] == statement[i])
break;
if (j < cmp.size())
{
c = statement[i];
pos = i;
return true;
}
}
}
return false;
}
bool getLastCharKlammer(const string& statement, const string& cmp, char& c, int& pos)
{
if (statement.empty())
return false;
int char_found = -1;
int klammer_ebene = 0, klammerE_ebene = 0;
for (int i=0; i<statement.size()-1; i++)
{
if (statement[i] == '(')
klammer_ebene++;
if (statement[i] == ')')
klammer_ebene--;
if (statement[i] == '[')
klammerE_ebene++;
if (statement[i] == ']')
klammerE_ebene--;
if (klammer_ebene == 0 && klammerE_ebene == 0 && i != statement.size() -1 && i != 0)
{
int j;
for (j=0; j<cmp.size(); j++)
if (cmp[j] == statement[i])
char_found = i;
}
}
if (char_found > 0)
{
c = statement[char_found];
pos = char_found;
return true;
}
return false;
}
bool isKlammer(const string& statement)
{
// klammer-Level zรคhlen
if (statement.empty())
return false;
if (statement[0] != '(' || statement[statement.size()-1] != ')')
return false;
int klammer_ebene = 0;
for (int i=0; i<statement.size()-1; i++)
{
if (statement[i] == '(')
klammer_ebene++;
if (statement[i] == ')')
klammer_ebene--;
if (klammer_ebene == 0 && i != statement.size() -1)
return false;
}
return true;
}
//++++++++++++++ Integer/ Float ++++++++++++++++++++++++++
bool isBiOperator(const string& statement, char& c, int& pos)
{
// Klammern zรคhlen, da nur zwischen Klammer-Level NULL
// ein Operator stehen darf
// den Operator mit der niedrigsten Prioritรคt zuerst ausfรผhren, da er
// in der Baum-Struktur "oben" stehen muร !
if (getFirstCharKlammer(statement, "+", c, pos))
return true;
if (getLastCharKlammer(statement, "-", c, pos))
return true;
if (getFirstCharKlammer(statement, "*", c, pos))
return true;
if (getLastCharKlammer(statement, "/", c, pos))
return true;
if (getFirstCharKlammer(statement, "^", c, pos))
return true;
//-->
if (getFirstCharKlammer(statement, "%", c, pos))
return true;
//<--
return false;
}
bool isUniOperator(const string& statement, char& c)
{
c = statement[0];
return (c == '-' || c == '+');
}
bool isMatrixIndex(const string& statement, BBMatrix *& bm, BBBaumMatrixPoint *& bp, bool getMem /* = true */)
{
// wenn X[p] enthรคlt und X = Matrix und p = Point
if (statement.empty())
return false;
string s(statement);
int pos1, pos2;
pos1 = s.find('[');
if (pos1 > 0)
{
pos2 = s.find(']');
if ( pos2 > pos1 && pos2 == s.size()-1 )
{
// ersten Teil
string m, p;
m = s.substr(0, pos1);
p = s.substr(pos1+1, pos2-pos1-1);
BBTyp *tm;
BBBaumMatrixPoint *bmp;
if (isMVar(m, tm))
{
try
{
// erst Testen
pars_matrix_point(p, bmp, false, false);
}
catch (BBFehlerException)
{
return false;
}
if (!getMem) // falls nichts allokieren -> test erfolgreich
return true;
try
{
// dann allokieren
pars_matrix_point(p, bmp, false);
}
catch (BBFehlerException)
{
return false;
}
bm = (BBMatrix *) tm;
bp = bmp;
return true;
}
/* if (isMVar(m, tm) && isPVar(p, tp))
{
bm = (BBMatrix *) tm;
bp = (BBPoint *) tp;
return true;
}
*/
}
}
return false;
}
bool isFZahl(const string& statement)
{
// Format: [+-]d[d][.[d[dd]][e|E +|- d[d]]]
if (statement .size() > 50)
return false;
char buff[100];
double f;
int anz = sscanf(statement.data(), "%f%s", &f, buff);
return (anz == 1);
}
bool isIZahl(const string& statement)
{
if (statement.empty())
return false;
string s(statement);
// eventuel voranstehenden +-
if (s[0] == '+')
s.erase(s.begin());
else if (s[0] == '-')
s.erase(s.begin());
if (s.empty())
return false;
int p = s.find_first_not_of("1234567890");
if (p >= 0)
return false;
return true;
}
bool isFVar(const string& statement, BBTyp * & b)
{
b = isVar(statement);
if (b == NULL)
return false;
if (b->type == BBTyp::FType)
return true;
return false;
}
bool isIVar(const string& statement, BBTyp * & b)
{
b = isVar(statement);
if (b == NULL)
return false;
if (b->type == BBTyp::IType)
return true;
return false;
}
bool isPVar(const string& statement, BBTyp * & b)
{
b = isVar(statement);
if (b == NULL)
return false;
if (b->type == BBTyp::PType)
return true;
return false;
}
bool isMVar(const string& statement, BBTyp * & b)
{
b = isVar(statement);
if (b == NULL)
return false;
if (b->type == BBTyp::MType)
return true;
return false;
}
BBFunktion *isFktName(const string& s)
{
if (FunktionList.empty())
return NULL;
T_FunktionList::iterator it;
for (it = FunktionList.begin(); it != FunktionList.end(); it++)
{
if ((*it)->name == s)
return (*it);
}
return NULL;
}
bool getNextFktToken(const string& s, int& pos, string& erg)
{
// Syntax xx[,xx[,xx...]]
if (pos >= s.size())
return false;
string ss(s.substr(pos));
int pos1 = ss.find_first_of(',');
if (pos1 >= 0)
{
erg = ss.substr(0, pos1);
pos += pos1;
}
else
{
erg = ss;
pos = s.size();
}
if (erg.empty())
return false;
return true;
}
bool isFunktion (const string& statement, BBFktExe * & fktexe, bool getMem /* = true */, bool AlleFunktionen /* = true */)
{
// Syntax: fktname([arg1[, arg2]])
string s(statement);
int pos1, pos2;
pos1 = s.find_first_of('(');
pos2 = s.find_last_of(')');
if (pos1 <= 0 || pos2 != s.size()-1)
return false;
// Variablen-Name
string sub1, sub2;
sub1 = s.substr(0, pos1);
trim(sub1);
sub2 = s.substr(pos1+1, pos2-pos1-1);
trim(sub2);
if (sub1.empty())
return false;
BBFunktion *fkt = isFktName(sub1);
if (fkt == NULL)
return false;
if (!AlleFunktionen)
{ // nur diejenigen Funktionen mit Return-Typ
if (fkt->ret.typ == BBArgumente::NoOp) // kein Return-Typ
return false;
}
if (sub2.empty()) // keine Argumente
{
if (!fkt->args.empty())
return false;
if (getMem)
{
fktexe = new BBFktExe;
fktexe->args = fkt->args;
fktexe->f = fkt; // vorher ... = NULL;
}
return true;
}
else
{
// Argumente zรคhlen
// 1. Float/Integer lassen sich konvertieren
// 2. Matrix
// 3. Point
if (getMem)
{
fktexe = new BBFktExe;
fktexe->args = fkt->args; // vector kopieren
fktexe->f = fkt;
}
int anz = fkt->args.size();
int possub2 = 0;
for (int i=0; i<anz; i++)
{
// finde Token
string ss;
if (!getNextFktToken(sub2, possub2, ss))
return false;
// BBTyp *bt = isVar(ss);
// if (bt == NULL)
// return false;
if (fkt->args[i].typ == BBArgumente::ITyp ||
fkt->args[i].typ == BBArgumente::FTyp)
{
// if (bt->type != BBTyp::IType ||
// bt->type != BBTyp::FType)
// return false;
try
{
BBBaumInteger *b;
pars_integer_float(ss, b, getMem);
if (getMem)
fktexe->args[i].ArgTyp.IF = b;
}
catch (BBFehlerException)
{
if (getMem)
delete fktexe;
return false;
}
}
else
{
/* if (fkt->args[i].typ == BBArgumente::MTyp &&
bt->type != BBTyp::MType)
return false;
if (fkt->args[i].typ == BBArgumente::PTyp &&
bt->type != BBTyp::PType)
return false;
*/
try
{
BBBaumMatrixPoint *b;
pars_matrix_point(ss, b, fkt->args[i].typ == BBArgumente::MTyp, getMem);
if (getMem)
fktexe->args[i].ArgTyp.MP = b;
}
catch (BBFehlerException)
{
if (getMem)
delete fktexe;
return false;
}
}
possub2++; // Komma entfernen
}
if (possub2 < sub2.size()) // zuviel Parameter angegeben
{
if (getMem)
delete fktexe;
return false;
}
}
return true;
}
// ------------- Hauptroutine -------------------
static char c;
static BBTyp *b;
static BBMatrix *bm;
static BBPoint *bp;
static BBBaumMatrixPoint *bmp;
static int pos;
static BBFktExe *bfkt;
void pars_integer_float(const string& statement, BBBaumInteger * & Knoten, int getMem /* = true */)
{
string s(statement);
trim(s);
if (s.empty())
throw BBFehlerException();
if (isKlammer(s))
{
s.erase(s.begin());
s.erase(s.end()-1);
pars_integer_float(s, Knoten, getMem);
}
else if (isMatrixIndex(s, bm, bmp, getMem!=0))
{
if (getMem)
{
Knoten = new BBBaumInteger;
Knoten->typ = BBBaumInteger::MIndex;
Knoten->k.MatrixIndex.M = bm;
Knoten->k.MatrixIndex.P = bmp;
}
}
else if (isBiOperator(s, c, pos))
{
string links = s.substr(0, pos);
string rechts = s.substr(pos+1, s.size()-pos-1);
if (links.empty() || rechts.empty())
throw BBFehlerException();
if (getMem)
{
Knoten = new BBBaumInteger;
Knoten->typ = BBBaumInteger::BIOperator;
switch(c)
{
case '+':
Knoten->k.BiOperator.OpTyp = BBBaumInteger::BBKnoten::BBBiOperator::Plus;
break;
case '-':
Knoten->k.BiOperator.OpTyp = BBBaumInteger::BBKnoten::BBBiOperator::Minus;
break;
case '*':
Knoten->k.BiOperator.OpTyp = BBBaumInteger::BBKnoten::BBBiOperator::Mal;
break;
case '/':
Knoten->k.BiOperator.OpTyp = BBBaumInteger::BBKnoten::BBBiOperator::Geteilt;
break;
case '^':
Knoten->k.BiOperator.OpTyp = BBBaumInteger::BBKnoten::BBBiOperator::Hoch;
break;
//-->
case '%':
Knoten->k.BiOperator.OpTyp = BBBaumInteger::BBKnoten::BBBiOperator::Modulo;
break;
//<--
}
pars_integer_float(links, Knoten->k.BiOperator.links);
pars_integer_float(rechts, Knoten->k.BiOperator.rechts);
}
else
{
pars_integer_float(links, Knoten, getMem);
pars_integer_float(rechts, Knoten, getMem);
}
}
else if (isUniOperator(s, c))
{
s.erase(s.begin());
if (getMem)
{
Knoten = new BBBaumInteger;
Knoten->typ = BBBaumInteger::UniOperator;
Knoten->k.UniOperator.OpTyp = (c == '+' ? BBBaumInteger::BBKnoten::BBUniOperator::Plus : BBBaumInteger::BBKnoten::BBUniOperator::Minus);
pars_integer_float(s, Knoten->k.UniOperator.rechts);
}
else
pars_integer_float(s, Knoten->k.UniOperator.rechts, getMem);
}
else if (isFZahl(s))
{
if (getMem)
{
Knoten = new BBBaumInteger;
Knoten->typ = BBBaumInteger::FZahl;
Knoten->k.FZahl = atof(s.data());
}
}
else if (isIZahl(s))
{
if (getMem)
{
Knoten = new BBBaumInteger;
Knoten->typ = BBBaumInteger::IZahl;
Knoten->k.IZahl = (int)atof(s.data());
}
}
else if (isFVar(s, b))
{
if (getMem)
{
Knoten = new BBBaumInteger;
Knoten->typ = BBBaumInteger::FVar;
Knoten->k.FVar = getVarF(b);
}
}
else if (isIVar(s, b))
{
if (getMem)
{
Knoten = new BBBaumInteger;
Knoten->typ = BBBaumInteger::IVar;
Knoten->k.IVar = getVarI(b);
}
}
else if (isFunktion (s, bfkt, getMem!=0, false)) // nur die Funktionen mit Return-Typ
{
if (getMem)
{
Knoten = new BBBaumInteger;
Knoten->typ = BBBaumInteger::Funktion;
Knoten->k.func = bfkt;
}
}
else
throw BBFehlerException();
}
bool isIntFloatAusdruck(const string& s)
{
try
{
BBBaumInteger *knoten = NULL;
pars_integer_float(s, knoten, false);
}
catch (BBFehlerException)
{
return false;
}
return true;
}
//++++++++++++++ Point ++++++++++++++++++++++++++
// Operator p/p + -
// Operator p/i i/p p/f f/p * /
//++++++++++++++ Matrix ++++++++++++++++++++++++++
// Operator M/M + -
// Operator M/i i/M M/f f/M * /
void pars_matrix_point(const string& statement, BBBaumMatrixPoint * &Knoten, bool matrix, bool getMem /* = true */)
{
string s(statement);
trim(s);
if (s.empty())
throw BBFehlerException();
if (isKlammer(s))
{
s.erase(s.begin());
s.erase(s.end()-1);
pars_matrix_point(s, Knoten, matrix, getMem);
}
else if (isUniOperator(s, c))
{
s.erase(s.begin());
if (getMem)
{
Knoten = new BBBaumMatrixPoint;
Knoten->typ = BBBaumMatrixPoint::UniOperator;
Knoten->k.UniOperator.OpTyp = (c == '+' ? BBBaumMatrixPoint::BBKnoten::BBUniOperator::Plus : BBBaumMatrixPoint::BBKnoten::BBUniOperator::Minus);
Knoten->isMatrix = matrix;
pars_matrix_point(s, Knoten->k.UniOperator.rechts, matrix);
}
else
pars_matrix_point(s, Knoten, matrix, getMem);
}
else if (isBiOperator(s, c, pos))
{
string links = s.substr(0, pos);
string rechts = s.substr(pos+1, s.size()-pos-1);
if (links.empty() || rechts.empty())
throw BBFehlerException();
if (getMem)
{
Knoten = new BBBaumMatrixPoint;
Knoten->typ = BBBaumMatrixPoint::BIOperator;
Knoten->isMatrix = matrix;
switch(c)
{
case '+':
Knoten->k.BiOperator.OpTyp = BBBaumMatrixPoint::BBKnoten::BBBiOperator::Plus;
break;
case '-':
Knoten->k.BiOperator.OpTyp = BBBaumMatrixPoint::BBKnoten::BBBiOperator::Minus;
break;
case '*':
Knoten->k.BiOperator.OpTyp = BBBaumMatrixPoint::BBKnoten::BBBiOperator::Mal;
break;
case '/':
Knoten->k.BiOperator.OpTyp = BBBaumMatrixPoint::BBKnoten::BBBiOperator::Geteilt;
break;
case '^':
throw BBFehlerException();
break;
case '%':
throw BBFehlerException();
break;
}
pars_matrix_point(links, Knoten->k.BiOperator.links, matrix);
pars_matrix_point(rechts, Knoten->k.BiOperator.rechts, matrix);
if (c == '+' || c == '-')
{
// Operator nur zwischen zwei Points
if (matrix && ( (Knoten->k.BiOperator.rechts)->typ != BBBaumMatrixPoint::MVar ||
(Knoten->k.BiOperator.links )->typ != BBBaumMatrixPoint::MVar ))
{
throw BBFehlerException();
}
if (!matrix && ((Knoten->k.BiOperator.rechts)->typ != BBBaumMatrixPoint::PVar ||
(Knoten->k.BiOperator.links )->typ != BBBaumMatrixPoint::PVar ))
{
throw BBFehlerException();
}
}
if (c == '*' || c == '/')
{
// Operator nur zwischen i/f und p, Reihenfolge egal
int pvar = 0;
int mvar = 0;
if ((Knoten->k.BiOperator.rechts)->typ == BBBaumMatrixPoint::PVar)
pvar++;
if ((Knoten->k.BiOperator.rechts)->typ == BBBaumMatrixPoint::MVar)
mvar++;
if ((Knoten->k.BiOperator.links)->typ == BBBaumMatrixPoint::PVar)
pvar++;
if ((Knoten->k.BiOperator.links)->typ == BBBaumMatrixPoint::MVar)
mvar++;
if (matrix && (mvar != 1 || pvar != 0))
throw BBFehlerException();
if (!matrix && (pvar != 1 || mvar != 0))
throw BBFehlerException();
}
}
else
{
pars_matrix_point(links, Knoten, matrix, getMem);
pars_matrix_point(rechts, Knoten, matrix, getMem);
}
}
else if (matrix && isMVar(s, b))
{
if (getMem)
{
Knoten = new BBBaumMatrixPoint;
Knoten->typ = BBBaumMatrixPoint::MVar;
Knoten->k.M = getVarM(b);
Knoten->isMatrix = matrix;
}
}
else if (!matrix && isPVar(s, b))
{
if (getMem)
{
Knoten = new BBBaumMatrixPoint;
Knoten->typ = BBBaumMatrixPoint::PVar;
Knoten->k.P = getVarP(b);
Knoten->isMatrix = matrix;
}
}
else if (isIntFloatAusdruck(s))
{
if (getMem)
{
Knoten = new BBBaumMatrixPoint;
Knoten->typ = BBBaumMatrixPoint::IFAusdruck;
Knoten->isMatrix = matrix;
pars_integer_float(s, Knoten->k.IntFloatAusdruck.b);
}
else
{
BBBaumInteger *k = NULL;
pars_integer_float(s, k, getMem);
}
}
else
throw BBFehlerException();
}
|
UoA-eResearch/saga-gis
|
saga-gis/src/modules/grid/grid_calculus_bsl/ausdruck.cpp
|
C++
|
gpl-3.0
| 17,374 |
# Rewritten by RayzoR
import sys
from com.l2scoria.gameserver.model.quest import State
from com.l2scoria.gameserver.model.quest import QuestState
from com.l2scoria.gameserver.model.quest.jython import QuestJython as JQuest
qn = "112_WalkOfFate"
# ~~~~~ npcId list: ~~~~~
Livina = 30572
Karuda = 32017
# ~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~ itemId list: ~~~~~~
EnchantD = 956
# ~~~~~~~~~~~~~~~~~~~~~~~~~~
class Quest (JQuest) :
def __init__(self,id,name,descr): JQuest.__init__(self,id,name,descr)
def onAdvEvent (self,event,npc,player) :
st = player.getQuestState(qn)
if not st: return
htmltext = event
cond = st.getInt("cond")
if event == "32017-02.htm" and cond == 1 :
st.giveItems(57,22308)
st.giveItems(EnchantD,1)
st.addExpAndSp(112876,5774)
st.exitQuest(False)
st.playSound("ItemSound.quest_finish")
elif event == "30572-02.htm" :
st.playSound("ItemSound.quest_accept")
st.setState(STARTED)
st.set("cond","1")
return htmltext
def onTalk (self,npc,player):
htmltext = "<html><head><body>You are either not on a quest that involves this NPC, or you don't meet this NPC's minimum quest requirements.</body></html>"
st = player.getQuestState(qn)
if not st : return htmltext
state = st.getState()
npcId = npc.getNpcId()
cond = st.getInt("cond")
if state == COMPLETED :
htmltext = "<html><body>This quest has already been completed.</body></html>"
elif state == CREATED :
if npcId == Livina :
if player.getLevel() >= 20 :
htmltext = "30572-01.htm"
else:
htmltext = "30572-00.htm"
st.exitQuest(1)
elif state == STARTED :
if npcId == Livina :
htmltext = "30572-03.htm"
elif npcId == Karuda :
htmltext = "32017-01.htm"
return htmltext
QUEST = Quest(112,qn,"Walk of Fate")
CREATED = State('Start', QUEST)
STARTED = State('Started', QUEST)
COMPLETED = State('Completed', QUEST)
QUEST.setInitialState(CREATED)
QUEST.addStartNpc(Livina)
QUEST.addTalkId(Livina)
QUEST.addTalkId(Karuda)
|
zenn1989/scoria-interlude
|
L2Jscoria-Game/data/scripts/quests/112_WalkOfFate/__init__.py
|
Python
|
gpl-3.0
| 2,208 |
#include "reversead/algorithm/base_reverse_tensor.hpp"
#include "reversead/forwardtype/single_forward.hpp"
template class ReverseAD::BaseReverseTensor<double>;
template class ReverseAD::BaseReverseTensor<ReverseAD::SingleForward>;
|
wangmu0701/ReverseAD
|
ReverseAD/src/algorithm/base_reverse_tensor.cpp
|
C++
|
gpl-3.0
| 232 |
package com.aepronunciation.ipa;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import androidx.appcompat.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import java.util.ArrayList;
import static android.content.Context.MODE_PRIVATE;
import static com.aepronunciation.ipa.MainActivity.PRACTICE_MODE_IS_SINGLE_KEY;
import static com.aepronunciation.ipa.MainActivity.PREFS_NAME;
public class SelectSoundDialogFragment extends DialogFragment {
public interface SelectSoundDialogListener {
void onDialogPositiveClick(
SoundMode numberSounds,
ArrayList<String> chosenVowels,
ArrayList<String> chosenConsonants);
void onDialogNegativeClick(DialogFragment dialog);
}
static final String KEY_DIALOG_IS_SINGLE_MODE = "isSingleMode";
static final String KEY_DIALOG_VOWEL_LIST = "vowels";
static final String KEY_DIALOG_CONSONANT_LIST = "consonants";
private SelectSoundDialogListener mListener;
private RadioButton rbSingle;
private RadioButton rbDouble;
private CheckBox cbVowelsCategory;
private CheckBox cbConsonantsCategory;
private CheckBox[] checkBoxesVowels;
private CheckBox[] checkBoxesConsonants;
private CheckBox cbSchwa;
private CheckBox cbUnstressedEr;
private CheckBox cbGlottalStop;
private CheckBox cbFlapT;
private Button positiveButton;
private boolean listenerDisabled = false;
@Override
@NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_select_sound, null);
rbSingle = view.findViewById(R.id.radio_single);
rbDouble = view.findViewById(R.id.radio_double);
cbSchwa = view.findViewById(R.id.cb_shwua);
cbUnstressedEr = view.findViewById(R.id.cb_er_unstressed);
cbGlottalStop = view.findViewById(R.id.cb_glottal_stop);
cbFlapT = view.findViewById(R.id.cb_flap_t);
// get saved practice mode
SharedPreferences settings = getActivity().getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
boolean isSingle = settings.getBoolean(PRACTICE_MODE_IS_SINGLE_KEY, true);
if (isSingle) {
rbSingle.setChecked(true);
} else {
rbDouble.setChecked(true);
cbSchwa.setVisibility(View.GONE);
cbUnstressedEr.setVisibility(View.GONE);
cbGlottalStop.setVisibility(View.GONE);
cbFlapT.setVisibility(View.GONE);
}
initializeCheckBoxes(view);
final RadioGroup rg = view.findViewById(R.id.select_sounds_radio_group);
rg.setOnCheckedChangeListener(radioGroupListener);
// disable the OK button
view.post(new Runnable() {
@Override
public void run() {
AlertDialog dialog = (AlertDialog) getDialog();
positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
}
});
// build the alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AlertDialogTheme);
builder.setView(view)
.setTitle(getString(R.string.select_sounds_title))
.setPositiveButton(R.string.select_sounds_positive_button, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
SoundMode soundType = SoundMode.Double;
//RadioButton single = (RadioButton) rg.findViewById(R.id.radio_single);
if (rbSingle.isChecked()) {
soundType = SoundMode.Single;
}
// get all chosen sounds
ArrayList<String> chosenVowels = new ArrayList<>();
for (CheckBox cb : checkBoxesVowels) {
if (cb.isChecked() & cb.getVisibility() == View.VISIBLE) {
chosenVowels.add(cb.getText().toString());
}
}
ArrayList<String> chosenConsonants = new ArrayList<>();
for (CheckBox cb : checkBoxesConsonants) {
if (cb.isChecked() & cb.getVisibility() == View.VISIBLE) {
chosenConsonants.add(cb.getText().toString());
}
}
// TODO: save single/double state to user preferences
// report back to parent fragment
mListener.onDialogPositiveClick(soundType, chosenVowels, chosenConsonants);
}
})
.setNegativeButton(R.string.dialog_cancel_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mListener.onDialogNegativeClick(SelectSoundDialogFragment.this);
}
});
return builder.create();
}
@Override
public void onResume() {
super.onResume();
final AlertDialog alertDialog = (AlertDialog) getDialog();
Button okButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
okButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SoundMode soundType = SoundMode.Double;
RadioButton single = alertDialog.findViewById(R.id.radio_single);
if (single != null && single.isChecked()) {
soundType = SoundMode.Single;
}
// get all chosen sounds
ArrayList<String> chosenVowels = new ArrayList<>();
for (CheckBox cb : checkBoxesVowels) {
if (cb.isChecked() & cb.getVisibility() == View.VISIBLE) {
chosenVowels.add(cb.getText().toString());
}
}
ArrayList<String> chosenConsonants = new ArrayList<>();
for (CheckBox cb : checkBoxesConsonants) {
if (cb.isChecked() & cb.getVisibility() == View.VISIBLE) {
chosenConsonants.add(cb.getText().toString());
}
}
mListener.onDialogPositiveClick(soundType, chosenVowels, chosenConsonants);
dismiss();
}
});
}
private void initializeCheckBoxes(View layout) {
checkBoxesVowels = new CheckBox[]{
layout.findViewById(R.id.cb_i),
layout.findViewById(R.id.cb_i_short),
layout.findViewById(R.id.cb_e_short),
layout.findViewById(R.id.cb_ae),
layout.findViewById(R.id.cb_a),
layout.findViewById(R.id.cb_c_backwards),
layout.findViewById(R.id.cb_u_short),
layout.findViewById(R.id.cb_u),
layout.findViewById(R.id.cb_v_upsidedown),
cbSchwa,
layout.findViewById(R.id.cb_ei),
layout.findViewById(R.id.cb_ai),
layout.findViewById(R.id.cb_au),
layout.findViewById(R.id.cb_oi),
layout.findViewById(R.id.cb_ou),
layout.findViewById(R.id.cb_er_stressed),
cbUnstressedEr,
layout.findViewById(R.id.cb_ar),
layout.findViewById(R.id.cb_er),
layout.findViewById(R.id.cb_ir),
layout.findViewById(R.id.cb_or)
};
checkBoxesConsonants = new CheckBox[]{
layout.findViewById(R.id.cb_p),
layout.findViewById(R.id.cb_b),
layout.findViewById(R.id.cb_t),
layout.findViewById(R.id.cb_d),
layout.findViewById(R.id.cb_k),
layout.findViewById(R.id.cb_g),
layout.findViewById(R.id.cb_ch),
layout.findViewById(R.id.cb_dzh),
layout.findViewById(R.id.cb_f),
layout.findViewById(R.id.cb_v),
layout.findViewById(R.id.cb_th_voiceless),
layout.findViewById(R.id.cb_th_voiced),
layout.findViewById(R.id.cb_s),
layout.findViewById(R.id.cb_z),
layout.findViewById(R.id.cb_sh),
layout.findViewById(R.id.cb_zh),
layout.findViewById(R.id.cb_m),
layout.findViewById(R.id.cb_n),
layout.findViewById(R.id.cb_ng),
layout.findViewById(R.id.cb_l),
layout.findViewById(R.id.cb_w),
layout.findViewById(R.id.cb_j),
layout.findViewById(R.id.cb_h),
layout.findViewById(R.id.cb_r),
cbGlottalStop,
cbFlapT
};
if (checkBoxesConsonants.length != Ipa.NUMBER_OF_CONSONANTS ||
checkBoxesVowels.length != Ipa.NUMBER_OF_VOWELS) {
throw new RuntimeException("update number of checkboxes if vowels or consonant number changes");
}
cbVowelsCategory = layout.findViewById(R.id.cbVowels);
cbConsonantsCategory = layout.findViewById(R.id.cbConsonants);
// get saved settings
Bundle mArgs = getArguments();
// FIXME use getSerializable to pass SoundMode enum directly
boolean isSingleMode = mArgs.getBoolean(KEY_DIALOG_IS_SINGLE_MODE);
SoundMode mode = SoundMode.Double;
if (isSingleMode) {
mode = SoundMode.Single;
}
ArrayList<String> vowelSounds = mArgs.getStringArrayList(KEY_DIALOG_VOWEL_LIST);
ArrayList<String> consonantSounds = mArgs.getStringArrayList(KEY_DIALOG_CONSONANT_LIST);
updateCheckedState(mode, vowelSounds, consonantSounds);
// set listeners on the IPA checkboxes so that OK button can be disabled
for (CheckBox cb : checkBoxesVowels) {
cb.setOnCheckedChangeListener(checkBoxListener);
}
for (CheckBox cb : checkBoxesConsonants) {
cb.setOnCheckedChangeListener(checkBoxListener);
}
cbVowelsCategory.setOnCheckedChangeListener(checkBoxListener);
cbConsonantsCategory.setOnCheckedChangeListener(checkBoxListener);
}
// allow calling fragment to set state
private void updateCheckedState(SoundMode mode, ArrayList<String> vowelSounds, ArrayList<String> consonantSounds) {
if (mode == null || vowelSounds == null || consonantSounds == null) {
return;
}
// radio group
if (mode == SoundMode.Single) {
rbSingle.setChecked(true);
} else {
rbDouble.setChecked(true);
}
// uncheck the vowel/consonant boxes if some of the small boxes are unchecked
listenerDisabled = true;
cbVowelsCategory.setChecked(checkBoxesVowels.length == vowelSounds.size());
cbConsonantsCategory.setChecked(checkBoxesConsonants.length == consonantSounds.size());
listenerDisabled = false;
// check individual boxes
String currentCbString;
boolean found;
for (CheckBox cb : checkBoxesVowels) {
currentCbString = cb.getText().toString();
found = false;
for (String sound : vowelSounds) {
if (currentCbString.equals(sound)) {
found = true;
}
}
cb.setChecked(found);
}
for (CheckBox cb : checkBoxesConsonants) {
currentCbString = cb.getText().toString();
found = false;
for (String sound : consonantSounds) {
if (currentCbString.equals(sound)) {
found = true;
}
}
cb.setChecked(found);
}
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
// check if parent Fragment implements listener
if (getParentFragment() instanceof SelectSoundDialogListener) {
mListener = (SelectSoundDialogListener) getParentFragment();
} else {
throw new RuntimeException("Parent fragment must implement SelectSoundDialogListener");
}
}
private RadioGroup.OnCheckedChangeListener radioGroupListener = new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
switch (checkedId) {
case R.id.radio_single:
// show optional sounds (unstressed er, shwua, glottal stop and flap t)
cbSchwa.setVisibility(View.VISIBLE);
cbUnstressedEr.setVisibility(View.VISIBLE);
cbGlottalStop.setVisibility(View.VISIBLE);
cbFlapT.setVisibility(View.VISIBLE);
break;
case R.id.radio_double:
// hide optional sounds
cbSchwa.setVisibility(View.GONE);
cbUnstressedEr.setVisibility(View.GONE);
cbGlottalStop.setVisibility(View.GONE);
cbFlapT.setVisibility(View.GONE);
break;
}
// disable/enable OK button if needed
boolean enabledState = getButtonShouldBeEnabledState();
if (positiveButton.isEnabled() != enabledState) {
positiveButton.setEnabled(enabledState);
}
}
};
private CompoundButton.OnCheckedChangeListener checkBoxListener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (listenerDisabled) {
return;
}
switch (compoundButton.getId()) {
case R.id.cbVowels:
for (CheckBox cb : checkBoxesVowels) {
cb.setChecked(isChecked);
}
break;
case R.id.cbConsonants:
for (CheckBox cb : checkBoxesConsonants) {
cb.setChecked(isChecked);
}
break;
default:
// all other check boxes are individual sounds
// set the enabled state of the OK button
boolean enabledState = getButtonShouldBeEnabledState();
if (positiveButton.isEnabled() != enabledState) {
positiveButton.setEnabled(enabledState);
}
break;
}
}
};
private boolean getButtonShouldBeEnabledState() {
// count the number of checked boxes for consonants and vowels
int vowelsChecked = 0;
for (CheckBox cb : checkBoxesVowels) {
if (cb.isChecked() && cb.getVisibility() == View.VISIBLE) {
vowelsChecked++;
if (vowelsChecked > 1) break;
}
}
int consonantsChecked = 0;
for (CheckBox cb : checkBoxesConsonants) {
if (cb.isChecked() && cb.getVisibility() == View.VISIBLE) {
consonantsChecked++;
if (consonantsChecked > 1) break;
}
}
// There must be at least two sounds for single or one for double
if (rbSingle.isChecked()) {
if (vowelsChecked + consonantsChecked <= 1) {
return false;
}
} else { // Double
if (vowelsChecked + consonantsChecked < 1) {
return false;
}
}
return true;
}
}
|
suragch/aePronunciation
|
app/src/main/java/com/aepronunciation/ipa/SelectSoundDialogFragment.java
|
Java
|
gpl-3.0
| 16,390 |
/*
Wgs.h - Custom library for wintergarden.
Created by Felix Neubauer, August 12, 2016.
*/
#include "Arduino.h"
#include "Wgs.h"
const int STATE_UNKNOWN = 0;
const int STATE_ENABLED = 1;
const int STATE_DISABLING = 2;
const int STATE_DISABLED = 3;
const int STATE_ENABLING = 4;
Wgs::Wgs(int pin_on, int pin_down, long duration)
{
//pinMode(pin, OUTPUT);
_pin_on = pin_on;
_pin_down = pin_down;
_duration = duration;
_disable = false;
}
void Wgs::loop(bool button_disable, bool button_enable)
{
//debug("Loop. Button enable: "+button_enable);
//debug("Button disable: "+button_disable);
//debug("State: "+_state);
if(_mute_time > millis()){
debug("Muted");
return;
}
if(_disable){
debug("Detected rain!!!!!!!!!!!!!!!!!!!!!!!!!!");
button_disable = true;
}
if(button_disable){
if(_state == STATE_DISABLED || _state == STATE_DISABLING){ //Already disabled/disabling
debug("Already disabling/disabled");
return;
}
if(_state == STATE_ENABLING){
debug("Stop enabling");
_mute_time = millis() + 400;
stopMovement(STATE_UNKNOWN);
return;
}
debug("Start disabling");
startMovement(STATE_DISABLING);
}else if(button_enable){
if(_state == STATE_ENABLED || _state == STATE_ENABLING){ //Already enabled/enabling
debug("Already enabling/enabled");
return;
}
if(_state == STATE_DISABLING){
debug("Stop disabling");
_mute_time = millis() + 400;
stopMovement(STATE_UNKNOWN);
return;
}
debug("Start enabling");
startMovement(STATE_ENABLING);
}
if (_finish_time <= millis() && _finish_time > 0) {
debug("reached finish time");
switch (_state) {
case STATE_DISABLING:
stopMovement(STATE_DISABLED);
break;
case STATE_ENABLING:
stopMovement(STATE_ENABLED);
break;
}
}
}
void Wgs::setDisable(boolean b)
{
_disable = b;
}
void Wgs::stopMovement(int state) {
_finish_time = 0; //Set destination time to 0 -> it's not active anymore
digitalWrite(_pin_on, HIGH);
delay(150);
digitalWrite(_pin_down, HIGH);
_state = state;
}
void Wgs::debug(String text) {
/*String prefix = String();
prefix = "["+ _pin_on;
prefix = prefix+" ";
prefix = prefix + _pin_down;
prefix = prefix +"] ";
String goal = String();
goal = prefix + text;*/
Serial.println(_pin_on + text);
}
void Wgs::startMovement(int state)
{
setState(state);
if(_state == STATE_DISABLING){
digitalWrite(_pin_down, HIGH);//Activate relais and make it ready to disable this component
}else if(_state == STATE_ENABLING){
digitalWrite(_pin_down, LOW); //Activate relais and make it ready to enable this component
}
delay(150);
digitalWrite(_pin_on, LOW); //Activate motor
_finish_time = millis() + _duration; //Set destination time
}
void Wgs::setState(int i) //-1 = unknown. 0 = enabled; 1 = move_disable; 2 = disabled; 3 = move_enable;
{
_state = i;
}
|
ranseyer/blind-control
|
arduino/Wintergartensteuerung/lib/Wgs.cpp
|
C++
|
gpl-3.0
| 3,018 |
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package dk.apaq.peers.sip.transactionuser;
import java.util.Collection;
import java.util.Hashtable;
import dk.apaq.peers.sip.RFC3261;
import dk.apaq.peers.sip.syntaxencoding.SipHeaderFieldName;
import dk.apaq.peers.sip.syntaxencoding.SipHeaderFieldValue;
import dk.apaq.peers.sip.syntaxencoding.SipHeaderParamName;
import dk.apaq.peers.sip.syntaxencoding.SipHeaders;
import dk.apaq.peers.sip.transport.SipMessage;
import dk.apaq.peers.sip.transport.SipResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DialogManager {
private static final Logger LOG = LoggerFactory.getLogger(DialogManager.class);
private Hashtable<String, Dialog> dialogs;
public DialogManager() {
dialogs = new Hashtable<String, Dialog>();
}
/**
* @param sipResponse sip response must contain a To tag, a
* From tag and a Call-ID
* @return the new Dialog created
*/
public synchronized Dialog createDialog(SipResponse sipResponse) {
SipHeaders sipHeaders = sipResponse.getSipHeaders();
String callID = sipHeaders.get(new SipHeaderFieldName(RFC3261.HDR_CALLID)).toString();
SipHeaderFieldValue from = sipHeaders.get(new SipHeaderFieldName(RFC3261.HDR_FROM));
SipHeaderFieldValue to = sipHeaders.get(new SipHeaderFieldName(RFC3261.HDR_TO));
String fromTag = from.getParam(new SipHeaderParamName(RFC3261.PARAM_TAG));
String toTag = to.getParam(new SipHeaderParamName(RFC3261.PARAM_TAG));
Dialog dialog;
if (sipHeaders.get(new SipHeaderFieldName(RFC3261.HDR_VIA)) == null) {
//createDialog is called from UAS side, in layer Transaction User
dialog = new Dialog(callID, toTag, fromTag);
} else {
//createDialog is called from UAC side, in syntax encoding layer
dialog = new Dialog(callID, fromTag, toTag);
}
dialogs.put(dialog.getId(), dialog);
return dialog;
}
public void removeDialog(String dialogId) {
dialogs.remove(dialogId);
}
public synchronized Dialog getDialog(SipMessage sipMessage) {
SipHeaders sipHeaders = sipMessage.getSipHeaders();
String callID = sipHeaders.get(new SipHeaderFieldName(RFC3261.HDR_CALLID)).toString();
SipHeaderFieldValue from = sipHeaders.get(new SipHeaderFieldName(RFC3261.HDR_FROM));
SipHeaderFieldValue to = sipHeaders.get(new SipHeaderFieldName(RFC3261.HDR_TO));
SipHeaderParamName tagName = new SipHeaderParamName(RFC3261.PARAM_TAG);
String fromTag = from.getParam(tagName);
String toTag = to.getParam(tagName);
Dialog dialog = dialogs.get(getDialogId(callID, fromTag, toTag));
if (dialog != null) {
return dialog;
}
return dialogs.get(getDialogId(callID, toTag, fromTag));
}
public synchronized Dialog getDialog(String callId) {
for (Dialog dialog : dialogs.values()) {
if (dialog.getCallId().equals(callId)) {
return dialog;
}
}
return null;
}
private String getDialogId(String callID, String localTag, String remoteTag) {
StringBuffer buf = new StringBuffer();
buf.append(callID);
buf.append(Dialog.ID_SEPARATOR);
buf.append(localTag);
buf.append(Dialog.ID_SEPARATOR);
buf.append(remoteTag);
return buf.toString();
}
public Collection<Dialog> getDialogCollection() {
return dialogs.values();
}
}
|
Apaq/peers
|
peers-lib/src/main/java/dk/apaq/peers/sip/transactionuser/DialogManager.java
|
Java
|
gpl-3.0
| 4,300 |
package cz.cvut.fit.ddw.project.subprocess;
import cz.cvut.fit.ddw.project.enums.News;
import com.rometools.rome.feed.synd.SyndEntry;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.FeedException;
import com.rometools.rome.io.SyndFeedInput;
import com.rometools.rome.io.XmlReader;
import cz.cvut.fit.ddw.project.entity.NewsArticle;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
/**
*
* @author Tomรกลก Duda <dudatom2@fit.cvut.cz>
*/
public class RSSFetcher {
private static final Logger logger = Logger.getLogger(RSSFetcher.class);
private final News news;
private final SyndFeedInput input;
private final SyndFeed feed;
public RSSFetcher(News news) throws IllegalArgumentException, FeedException, IOException {
logger.info("Inicializuji spojeni s " + news.name());
this.news = news;
this.input = new SyndFeedInput();
this.feed = input.build(new XmlReader(new URL(news.getUrl())));
}
public List<NewsArticle> getCurrentFeed() throws IOException {
List<NewsArticle> articles = new ArrayList<>();
// 3 pokusy na navazani spojeni
List<SyndEntry> entries = null;
for (int i = 0; i < 3; i++) {
try {
logger.info("Pokus " + (i + 1) + "/" + 3 + " navazat spojeni s " + news.name());
entries = feed.getEntries();
logger.info("Pokus uspesny.");
break;
} catch (Exception ste) {
logger.info("Pokus neuspesny.");
if (i == 2) {
return articles;
}
}
}
for (SyndEntry se : entries) {
String title = se.getTitle();
String link = se.getLink();
String content;
try {
logger.debug("Pokousim se ziskat obsah clanku ze zpravodajskeho webu.");
Document doc = Jsoup.connect(link).get();
Elements elements = doc.getElementsByClass(news.getClassContentName());
if (!elements.isEmpty()) {
content = elements.get(0).text();
} else {
content = "";
}
} catch (IOException ioe) {
logger.warn("Ziskani clanku z webu nebylo uspesne, preskakuji.", ioe);
continue;
}
if (!content.isEmpty()) {
NewsArticle na = new NewsArticle(news, link, title, content);
articles.add(na);
} else {
logger.info("Vyrazuji clanek bez textoveho obsahu (video, galerie, infografika, livefeed ...): " + link);
continue;
}
logger.debug("Clanek uspesne zpracovan.");
}
return articles;
}
}
|
tomas-duda/ddw
|
src/main/java/cz/cvut/fit/ddw/project/subprocess/RSSFetcher.java
|
Java
|
gpl-3.0
| 2,999 |
/*
* Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.ksenechal.javafx.bootstrapfx.skin;
import com.sun.javafx.scene.control.behavior.MenuButtonBehaviorBase;
import com.sun.javafx.scene.control.skin.MenuButtonSkinBase;
import javafx.scene.control.MenuButton;
/**
* Base class for MenuButtonSkin and SplitMenuButtonSkin. It consists of the
* label, the arrowButton with its arrow shape, and the popup.
*/
public abstract class BootstrapMenuButtonSkinBase<C extends MenuButton, B extends MenuButtonBehaviorBase<C>> extends MenuButtonSkinBase<C, B> {
public BootstrapMenuButtonSkinBase(C c, B b) {
super(c, b);
popup.getStyleClass().add("bootstrap-context-menu");
}
}
|
ksenechal/BootstrapFX
|
src/main/java/com/ksenechal/javafx/bootstrapfx/skin/BootstrapMenuButtonSkinBase.java
|
Java
|
gpl-3.0
| 1,850 |
import React from 'react';
import Grafico from './Grafico';
class Grafici extends React.Component {
render() {
return (
<div>
<h5 className="mt-3">Grafici</h5>
<Grafico titolo="Latenza" xtitle="Misurazioni" ytitle="ms" label="Ping" data={this.props.dataPing} colors={["#ffc107"]}/>
<Grafico titolo="Download" xtitle="Misurazioni" ytitle="kb/s" label="Banda" data={this.props.dataDownload} colors={["#007bff"]}/>
<Grafico titolo="Upload" xtitle="Misurazioni" ytitle="kb/s" label="Banda" data={this.props.dataUpload} colors={["#28a745"]}/>
</div>
)
}
}
export default Grafici;
|
fondazionebordoni/misurainternet-ui
|
src/Grafici.js
|
JavaScript
|
gpl-3.0
| 633 |
/*
* ThreadPool.java
*
* This file is part of the IHMC Util Library
* Copyright (c) 1993-2016 IHMC.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 (GPLv3) as published by the Free Software Foundation.
*
* U.S. Government agencies and organizations may redistribute
* and/or modify this program under terms equivalent to
* "Government Purpose Rights" as defined by DFARS
* 252.227-7014(a)(12) (February 2014).
*
* Alternative licenses that allow for use within commercial products may be
* available. Contact Niranjan Suri at IHMC (nsuri@ihmc.us) for details.
*/
/**
* ThreadPool
*
* @author Marco Arguedas <marguedas@ihmc.us>
*
* @version $Revision$
* $Date$
*/
package us.ihmc.util;
import java.util.ArrayList;
import java.util.List;
/**
*
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public class ThreadPool
{
public ThreadPool (int maxNumWorkers)
{
if (maxNumWorkers <= 0) {
throw new IllegalArgumentException ("maxNumWorker cannot be <= 0");
}
_maxNumWorkers = maxNumWorkers;
_workers = new ArrayList<ThreadPoolWorker>();
_tasks = new ArrayList<ThreadPoolTask>();
}
/**
*
*/
public void enqueue (Runnable runnable, ThreadPoolMonitor tpm)
{
ThreadPoolTask tpt = new ThreadPoolTask (runnable, tpm);
this.checkAndActivateThreads();
synchronized (_tasks) {
_tasks.add (tpt);
_tasks.notifyAll();
}
} //enqueue()
/**
*
*/
public void enqueue (Runnable runnable)
{
this.enqueue (runnable, null);
}
// /////////////////////////////////////////////////////////////////////////
// PRIVATE METHODS /////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////
/**
*
*/
private ThreadPoolTask dequeueTask()
{
ThreadPoolTask task = null;
synchronized (_tasks) {
while (_tasks.isEmpty()) {
try {
_tasks.wait();
}
catch (Exception ex) {
ex.printStackTrace();
}
} //while()
task = _tasks.remove (0);
}
return task;
} //dequeueTask()
/**
*
*/
private void threadBusyStatusChanged (boolean threadIsBusy)
{
synchronized (this) {
if (threadIsBusy) {
_numBusyWorkers++;
}
else {
_numBusyWorkers--;
}
}
} //threadBusyStatusChanged()
/**
*
*/
private void checkAndActivateThreads()
{
int numWorkers = _workers.size();
if (numWorkers >= _maxNumWorkers) {
return;
}
synchronized (this) {
int numIdleWorkers = numWorkers - _numBusyWorkers;
if (numIdleWorkers == 0) {
ThreadPoolWorker tpt = new ThreadPoolWorker (this);
_workers.add (tpt);
tpt.start();
}
}
} //checkAndActivateThreads()
// /////////////////////////////////////////////////////////////////////////
// INTERNAL CLASSES ////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////
/**
*
*/
private class ThreadPoolTask
{
public ThreadPoolTask (Runnable r, ThreadPoolMonitor tpm)
{
runnable = r;
tpMon = tpm;
}
Runnable runnable = null;
ThreadPoolMonitor tpMon = null;
} //class ThreadPoolTask
/**
*
*/
private static class ThreadPoolWorker extends Thread
{
ThreadPoolWorker (ThreadPool tp)
{
setName ("ThreadPoolWorker" + (_tpwInstanceCounter++) + "-[" + getName() + "]");
_threadPool = tp;
}
/**
*
*/
public void run()
{
while (true) {
ThreadPoolTask tpt = _threadPool.dequeueTask();
Exception runnableEx = null;
_threadPool.threadBusyStatusChanged (true);
try {
tpt.runnable.run();
}
catch (Exception ex) {
runnableEx = ex;
}
if (tpt.tpMon != null) {
try {
tpt.tpMon.runFinished (tpt.runnable, runnableEx);
}
catch (Exception ex) {
} //intentionally left blank.
}
_threadPool.threadBusyStatusChanged (false);
}
} //run()
private ThreadPool _threadPool = null;
private static int _tpwInstanceCounter = 0;
} // class ThreadPoolWorker
/**
*
*/
public interface ThreadPoolMonitor
{
public void runFinished (Runnable runnable, Exception exception);
} //interface ThreadPoolMonitor
// /////////////////////////////////////////////////////////////////////////
private int _maxNumWorkers = 0;
private int _numBusyWorkers = 0;
private final List<ThreadPoolWorker> _workers;
private final List<ThreadPoolTask> _tasks;
} //class ThreadPool
|
ihmc/nomads
|
util/java/us/ihmc/util/ThreadPool.java
|
Java
|
gpl-3.0
| 5,504 |
/**
* ShapeChange - processing application schemas for geographic information
*
* This file is part of ShapeChange. ShapeChange takes a ISO 19109
* Application Schema from a UML model and translates it into a
* GML Application Schema or other implementation representations.
*
* Additional information about the software can be found at
* http://shapechange.net/
*
* (c) 2002-2019 interactive instruments GmbH, Bonn, Germany
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact:
* interactive instruments GmbH
* Trierer Strasse 70-72
* 53115 Bonn
* Germany
*/
package de.interactive_instruments.ShapeChange.scxmltest;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import de.interactive_instruments.ShapeChange.TestInstance;
import de.interactive_instruments.ShapeChange.Util.XMLUtil;
/**
* @author Johannes Echterhoff (echterhoff at interactive-instruments dot
* de)
*
*/
public class SCXMLTestResourceConverter {
/**
* Name of the VM argument / system property to indicate that unit tests shall
* be executed using the original configuration (by setting the value of the
* system property to 'true'), for unit tests with tag SCXML.
*/
public static final String RUN_ORIGINAL_CONFIGURATIONS_SYSTEM_PROPERTY_NAME = "runOriginalConfigurations";
/**
* Name of the VM argument / system property to indicate that the model
* resources and ShapeChange configuration of SCXML-tagged unit tests shall be
* updated (by setting the value of the system property to 'true') based upon
* the original model and configuration files - or created, if they do not exist
* yet. The only exception are tests which already solely rely on SCXML models.
*/
public static final String UPDATE_OR_CREATE_SCXML_RESOURCES_SYSTEM_PROPERTY_NAME = "updateOrCreateScxmlResources";
String suffix_configToExportModel = "_exportModel";
String suffix_configRunWithSCXML = "_runWithSCXML";
File tmpDir = new File("scxmlTmpDir");
public String updateSCXMLTestResources(String configPath) throws Exception {
if ("true".equalsIgnoreCase(System.getProperty(RUN_ORIGINAL_CONFIGURATIONS_SYSTEM_PROPERTY_NAME))) {
return configPath;
} else {
if (!tmpDir.exists()) {
tmpDir.mkdir();
}
// load original config, for creation of SCXML export configs
/*
* WARNING: The in-memory document will be updated if SCXML really is created!
* log, transformers, and targets from the original config will be removed, only
* the input will be kept and a new model export target section added.
*/
Document doc1 = XMLUtil.loadXml(configPath);
boolean notPureScxmlTest = hasModelTypeOtherThanSCXML(doc1);
if ("true".equalsIgnoreCase(System.getProperty(UPDATE_OR_CREATE_SCXML_RESOURCES_SYSTEM_PROPERTY_NAME))
&& notPureScxmlTest) {
// create SCXML based models
createScxml(doc1, configPath);
/*
* Load original config again (it would be incorrect to use doc1, because it may
* have been updated and used as export configuration).
*/
Document doc2 = XMLUtil.loadXml(configPath);
switchModelsToScxml(doc2, configPath);
}
String pathToRelevantConfig;
if (notPureScxmlTest) {
pathToRelevantConfig = getFileForScxmlBasedConfiguration(configPath).getPath();
System.out.println("Unit test execution uses SCXML based configuration " + pathToRelevantConfig);
} else {
pathToRelevantConfig = configPath;
System.out.println(
"Unit test execution uses (original) SCXML based configuration " + pathToRelevantConfig);
}
return pathToRelevantConfig;
}
}
private void switchModelsToScxml(Document configDoc, String configPath) throws Exception {
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList modelTypeNodes = (NodeList) xpath.evaluate(
"//*[(@name = 'inputModelType' or @name = 'referenceModelType') and @value != 'SCXML']", configDoc,
XPathConstants.NODESET);
for (int idx = 0; idx < modelTypeNodes.getLength(); idx++) {
Node modelTypeNode = modelTypeNodes.item(idx);
// set the model type
modelTypeNode.getAttributes().getNamedItem("value").setTextContent("SCXML");
// now also get the node with the model file path
Node modelPathNode = getModelFilePathNode(modelTypeNode);
if (modelPathNode == null) {
System.out.println("Model path node not found!");
} else {
String modelFilePath = modelPathNode.getAttributes().getNamedItem("value").getTextContent();
String newModelFilePath = getScxmlFilePathForModel(modelFilePath);
modelPathNode.getAttributes().getNamedItem("value").setTextContent(newModelFilePath);
}
}
// store updated config
File updatedConfig = getFileForScxmlBasedConfiguration(configPath);
XMLUtil.writeXml(configDoc, updatedConfig);
System.out.println("SCXML based config created: " + updatedConfig.getPath());
}
private Node getModelFilePathNode(Node modelTypeNode) throws Exception {
XPath xpath = XPathFactory.newInstance().newXPath();
Node modelPathNode = (Node) xpath.evaluate(
"./preceding-sibling::*[@name = 'inputFile' or @name = 'repositoryFileNameOrConnectionString' or @name = 'referenceModelFileNameOrConnectionString']",
modelTypeNode, XPathConstants.NODE);
if (modelPathNode == null) {
modelPathNode = (Node) xpath.evaluate(
"./following-sibling::*[@name = 'inputFile' or @name = 'repositoryFileNameOrConnectionString' or @name = 'referenceModelFileNameOrConnectionString']",
modelTypeNode, XPathConstants.NODE);
}
return modelPathNode;
}
//
// private File getScxmlFileForModel(String modelFilePath) {
// return new File(getScxmlFilePathForModel(modelFilePath));
// }
private File getFileForScxmlBasedConfiguration(String configPath) {
return new File(FilenameUtils.getPath(configPath) + FilenameUtils.getBaseName(configPath)
+ suffix_configRunWithSCXML + ".xml");
}
private String getScxmlFilePathForModel(String modelFilePath) {
return modelFilePath.subSequence(0, modelFilePath.lastIndexOf(".")).toString() + ".zip";
}
private boolean hasModelTypeOtherThanSCXML(Document doc) throws Exception {
return !findNonScxmlModelOccurrences(doc).isEmpty();
}
/**
* @param configPath
* @throws Exception
*/
private void createScxml(Document doc, String configPath) throws Exception {
// identify all model files that need to be converted to SCXML; for each such
// file we also need to know the model type
/*
* key: model file path, value: model type
*/
SortedMap<String, String> nonScxmlModelMap = findNonScxmlModelOccurrences(doc);
/*
* now remove the log, transformation and target elements of the configuration
* document
*/
NodeList logNodes = doc.getElementsByTagName("log");
for (int idx = 0; idx < logNodes.getLength(); idx++) {
Node ln = logNodes.item(idx);
ln.getParentNode().removeChild(ln);
}
NodeList transformersNodes = doc.getElementsByTagName("transformers");
for (int idx = 0; idx < transformersNodes.getLength(); idx++) {
Node tn = transformersNodes.item(idx);
tn.getParentNode().removeChild(tn);
}
NodeList targetsNodes = doc.getElementsByTagName("targets");
for (int idx = 0; idx < targetsNodes.getLength(); idx++) {
Node tn = targetsNodes.item(idx);
tn.getParentNode().removeChild(tn);
}
// now add the model export target configuration
Node scConfigNode = doc.getElementsByTagName("ShapeChangeConfiguration").item(0);
String scNs = scConfigNode.getNamespaceURI();
String scNsPrefix = scConfigNode.getPrefix();
Node inputNode = doc.getElementsByTagName("input").item(0);
Node inputIdAttributeNode = inputNode.getAttributes().getNamedItem("id");
String inputIdAttribute = inputIdAttributeNode == null ? null : inputIdAttributeNode.getTextContent();
Element targetsE = doc.createElementNS(scNs, qname(scNsPrefix, "targets"));
scConfigNode.appendChild(targetsE);
Element targetE = doc.createElementNS(scNs, qname(scNsPrefix, "Target"));
targetsE.appendChild(targetE);
targetE.setAttribute("class", "de.interactive_instruments.ShapeChange.Target.ModelExport.ModelExport");
targetE.setAttribute("mode", "enabled");
if (inputIdAttribute != null) {
targetE.setAttribute("inputs", inputIdAttribute);
}
Element outputDirE = doc.createElementNS(scNs, qname(scNsPrefix, "targetParameter"));
targetE.appendChild(outputDirE);
outputDirE.setAttribute("name", "outputDirectory");
// value will be set per relevant non-scxml model
Element outputFilenameE = doc.createElementNS(scNs, qname(scNsPrefix, "targetParameter"));
targetE.appendChild(outputFilenameE);
outputFilenameE.setAttribute("name", "outputFilename");
// value will be set per relevant non-scxml model
Element sortedOutputE = doc.createElementNS(scNs, qname(scNsPrefix, "targetParameter"));
targetE.appendChild(sortedOutputE);
sortedOutputE.setAttribute("name", "sortedOutput");
sortedOutputE.setAttribute("value", "true");
Element exportProfilesFromWholeModelE = doc.createElementNS(scNs, qname(scNsPrefix, "targetParameter"));
targetE.appendChild(exportProfilesFromWholeModelE);
exportProfilesFromWholeModelE.setAttribute("name", "exportProfilesFromWholeModel");
exportProfilesFromWholeModelE.setAttribute("value", "true");
Element zipOutputE = doc.createElementNS(scNs, qname(scNsPrefix, "targetParameter"));
targetE.appendChild(zipOutputE);
zipOutputE.setAttribute("name", "zipOutput");
zipOutputE.setAttribute("value", "true");
Element ignoreTaggedValuesRegexE = doc.createElementNS(scNs, qname(scNsPrefix, "targetParameter"));
targetE.appendChild(ignoreTaggedValuesRegexE);
ignoreTaggedValuesRegexE.setAttribute("name", "ignoreTaggedValuesRegex");
ignoreTaggedValuesRegexE.setAttribute("value", "^$");
// TBD: maybe profilesInModelSetExplicitly needs to be configured per unit test
Element defaultEncodingRuleE = doc.createElementNS(scNs, qname(scNsPrefix, "targetParameter"));
targetE.appendChild(defaultEncodingRuleE);
defaultEncodingRuleE.setAttribute("name", "defaultEncodingRule");
defaultEncodingRuleE.setAttribute("value", "export");
Element rulesE = doc.createElementNS(scNs, qname(scNsPrefix, "rules"));
targetE.appendChild(rulesE);
Element encodingRuleE = doc.createElementNS(scNs, qname(scNsPrefix, "EncodingRule"));
rulesE.appendChild(encodingRuleE);
encodingRuleE.setAttribute("name", "export");
Element ruleE = doc.createElementNS(scNs, qname(scNsPrefix, "rule"));
encodingRuleE.appendChild(ruleE);
ruleE.setAttribute("name", "rule-exp-pkg-allPackagesAreEditable");
XPath xpath = XPathFactory.newInstance().newXPath();
Node inputModelTypeNode = (Node) xpath.evaluate(
"/*/*[local-name() = 'input']/*[local-name() = 'parameter' and @name = 'inputModelType']", doc,
XPathConstants.NODE);
Node inputFileNode = (Node) xpath.evaluate(
"/*/*[local-name() = 'input']/*[local-name() = 'parameter' and (@name = 'inputFile' or @name = 'repositoryFileNameOrConnectionString')]",
doc, XPathConstants.NODE);
// create SCXML for each non-scxml model
for (Entry<String, String> entry : nonScxmlModelMap.entrySet()) {
String modelType = entry.getValue();
String modelFilePath = entry.getKey();
((Element) inputModelTypeNode).setAttribute("value", modelType);
((Element) inputFileNode).setAttribute("value", modelFilePath);
File exportDirectory = new File(tmpDir, "export" + File.separator + FilenameUtils.getBaseName(configPath));
outputDirE.setAttribute("value", exportDirectory.getPath());
outputFilenameE.setAttribute("value", FilenameUtils.getBaseName(modelFilePath));
// config document in temporรคres Verzeichnis speichern
File exportConfig = new File(tmpDir,
FilenameUtils.getBaseName(configPath) + suffix_configToExportModel + ".xml");
XMLUtil.writeXml(doc, exportConfig);
System.out.println("Export config created: " + exportConfig.getPath());
// execute export config
System.out.println("Running export config ...");
@SuppressWarnings("unused")
TestInstance test = new TestInstance(exportConfig.getPath());
System.out.println("... export done");
// get SCXML file that was produced
List<Path> scxmlFilePaths = null;
try (Stream<Path> files = Files.walk(Paths.get(exportDirectory.toURI()))) {
scxmlFilePaths = files.filter(
f -> f.getFileName().toString().equals(FilenameUtils.getBaseName(modelFilePath) + ".zip"))
.collect(Collectors.toList());
}
File scxmlFile = scxmlFilePaths.get(0).toFile();
FileUtils.copyFile(scxmlFile,
new File(FilenameUtils.getPath(modelFilePath) + FilenameUtils.getBaseName(modelFilePath) + ".zip"));
}
}
private String qname(String prefix, String name) {
return prefix == null ? name : prefix + ":" + name;
}
// /**
// * @param configDoc
// * @return can be empty but not <code>null</code>
// * @throws Exception
// */
// private SortedMap<String, String> findRelevantNonScxmlModelOccurrences(Document configDoc, String configPath)
// throws Exception {
//
// SortedMap<String, String> result = new TreeMap<>();
//
// SortedMap<String, String> modelTypeByFilePath = findNonScxmlModelOccurrences(configDoc);
//
// /*
// * Now determine which of these models has an SCXML file that is younger than
// * both the original model AND the ShapeChange configuration (because the
// * configuration influences the way that a model is loaded, and thus how the
// * exported SCXML looks like).
// */
//
// File configFile = new File(configPath);
//
// for (Entry<String, String> e : modelTypeByFilePath.entrySet()) {
//
// String modelFilePath = e.getKey();
// String modelType = e.getValue();
//
// File modelFile = new File(modelFilePath);
// File scxmlFile = getScxmlFileForModel(modelFilePath);
//
// if (!scxmlFile.exists() || FileUtils.isFileOlder(scxmlFile, modelFile)
// || FileUtils.isFileOlder(scxmlFile, configFile)) {
// result.put(modelFilePath, modelType);
// }
// }
//
// return result;
// }
/**
* @param configDoc
* @return map with model file path as key and model type as value; can be empty
* but not <code>null</code>
* @throws Exception
*/
private SortedMap<String, String> findNonScxmlModelOccurrences(Document configDoc) throws Exception {
SortedMap<String, String> modelTypeByFilePath = new TreeMap<>();
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList modelTypeNodes = (NodeList) xpath.evaluate(
"//*[(@name = 'inputModelType' or @name = 'referenceModelType') and @value != 'SCXML']", configDoc,
XPathConstants.NODESET);
for (int idx = 0; idx < modelTypeNodes.getLength(); idx++) {
Node modelTypeNode = modelTypeNodes.item(idx);
// identify the model type
String modelType = modelTypeNode.getAttributes().getNamedItem("value").getTextContent();
// now also get the model file path
Node modelPathNode = (Node) xpath.evaluate(
"./preceding-sibling::*[@name = 'inputFile' or @name = 'repositoryFileNameOrConnectionString' or @name = 'referenceModelFileNameOrConnectionString']",
modelTypeNode, XPathConstants.NODE);
if (modelPathNode == null) {
modelPathNode = (Node) xpath.evaluate(
"./following-sibling::*[@name = 'inputFile' or @name = 'repositoryFileNameOrConnectionString' or @name = 'referenceModelFileNameOrConnectionString']",
modelTypeNode, XPathConstants.NODE);
}
if (modelPathNode == null) {
System.out.println("Model path node not found!");
} else {
String modelFilePath = modelPathNode.getAttributes().getNamedItem("value").getTextContent();
modelTypeByFilePath.put(modelFilePath, modelType);
}
}
return modelTypeByFilePath;
}
}
|
ShapeChange/ShapeChange
|
src/test/java/de/interactive_instruments/ShapeChange/scxmltest/SCXMLTestResourceConverter.java
|
Java
|
gpl-3.0
| 16,951 |
package com.lamer.rc_model_car;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.os.ParcelUuid;
import android.util.Log;
import android.widget.Toast;
public class ArduinoModule implements Runnable {
//Context mComtext=null;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
private Context mComtext;
public int create(Context context){
mComtext=context;
return 0;
}
private int findBT() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null) {
Log.v("Arduino BT","Bluetooth null !");
Toast.makeText(mComtext, "Bluetooth is not available", Toast.LENGTH_LONG).show();
return 0;
}
if(!mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
return 0;
//startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0) {
for(BluetoothDevice device : pairedDevices) {
if(device.getName().equals("HC-06")) {
mmDevice = device;
Log.v("Arduino BT","Bluetooth Device Found");
return 1;
}
}
}
return 0;
}
private int openBT() {
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard //SerialPortService ID
//final String PBAP_UUID = "0000112f-0000-1000-8000-00805f9b34fb"; //standard pbap uuid
//UUID uuid = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
//mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
try {
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
} catch (Exception e) {Log.e("Arduino BT","Error creating socket");}
try {
mmSocket.connect();
Log.e("Arduino BT","Connected");
} catch (IOException e) {
Log.e("Arduino BT",e.getMessage());
try {
Log.v("Arduino BT","trying fallback...");
//mmSocket =(BluetoothSocket) mmDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(mmDevice,uuid);
Method m = mmDevice.getClass().getMethod("createRfcommSocket", int.class);
mmSocket = (BluetoothSocket)m.invoke(mmDevice, 1);
mmSocket.connect();
Log.v("Arduino BT","Connected");
}
catch (Exception e2) {
e2.printStackTrace();
try {
mmSocket.close();
Log.v("Arduino BT","Couldn't establish Bluetooth connection! (1)");
} catch (IOException closeException) {
closeException.printStackTrace();
Log.v("Arduino BT","Couldn't establish Bluetooth connection! (2)");
}
return 0;
}
}
if(mmSocket==null)return 0;
//mmSocket.connect();
try{
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
connecting=false;
}catch (NullPointerException e){
connecting=false;
mmSocket=null;
mmOutputStream=null;
mmInputStream=null;
return 0;
} catch (IOException e) {
e.printStackTrace();
closeBT();
}
return 1;
}
void beginListenForData() {
//final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
new Thread(this).start();
//workerThread.start();
}
boolean connecting=false;
public int tryConnect(){
if(connecting)return 2;
connecting=true;
if(findBT()>0){
int ret = openBT();
connecting=false;
return ret;
}
connecting=false;
return 0;
}
void sendData(String string){
try{
if(!stopWorker && mmOutputStream!=null && isConnected()) {
mmOutputStream.write(string.getBytes());
mmOutputStream.flush();
}else{
if(tryConnect()>0) {
mmOutputStream.write(string.getBytes());
mmOutputStream.flush();
}
}
} catch (IOException e) {
closeBT();
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void closeBT(){
stopWorker = true;
try{
mmSocket.close();
mmSocket=null;
if(mmOutputStream!=null)
mmOutputStream.close();
if(mmInputStream!=null)
mmInputStream.close();
mmOutputStream=null;
mmInputStream=null;
mmDevice=null;
}catch(NullPointerException e){
Log.v("Arduino BT","Bluetooth Bad close");
mmSocket=null;
mmDevice=null;
mmOutputStream=null;
mmInputStream=null;
}catch (IOException e) {
Log.v("Arduino BT","Bluetooth IO Bad close");
mmSocket=null;
mmDevice=null;
mmOutputStream=null;
mmInputStream=null;
}
Log.v("Arduino BT","Bluetooth Closed");
}
public boolean isConnected(){
try{
boolean a=mmSocket.isConnected();
return a;
}catch (NullPointerException e){
return false;
}
//return mmOutputStream!=null;
}
@Override
public void run() {
// final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
while(!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0) {
Log.v("Arduino BT","Bluetooth bytesAvailable:"+bytesAvailable);
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
StringBuilder byStr = new StringBuilder();
for(int i=0;i<bytesAvailable;i++) {
byte b = packetBytes[i];
byStr.append( (char)b);
/*if(b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
/*handler.post(new Runnable() {
public void run() {
myLabel.setText(data);
}
});/
}
else {
readBuffer[readBufferPosition++] = b;
}*/
}
Log.v("Arduino BT","Bluetooth:"+byStr.toString());
}
}
catch (IOException ex) {
stopWorker = true;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
stopWorker = true;
}
}
}
}
|
whitelamer/android-bt-rc-car
|
src/com/lamer/rc_model_car/ArduinoModule.java
|
Java
|
gpl-3.0
| 8,713 |
/*
Copyright ยฉ 2014, Ryan Pavlik
This file is part of xleapmouse.
xleapmouse is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
xleapmouse is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with xleapmouse. If not, see <http://www.gnu.org/licenses/>.
*/
void get_xy(Display *dpy, Window &root, int &x, int &y) {
Window r_root, r_child;
int winx, winy;
unsigned int mask;
XQueryPointer(dpy, root, &r_root, &r_child, &x, &y,
&winx, &winy, &mask);
}
|
rpav/xleapmouse
|
src/util.cpp
|
C++
|
gpl-3.0
| 931 |
from django.urls import path
from .views import redirect_to_archive
urlpatterns = [path("<str:media_id>/", redirect_to_archive)]
|
whav/hav
|
src/hav/apps/media/urls.py
|
Python
|
gpl-3.0
| 130 |
package com.megathirio.shinsei.item.powder;
import com.megathirio.shinsei.item.PowderShinsei;
import com.megathirio.shinsei.reference.Names;
public class ItemBariumPowder extends PowderShinsei {
public ItemBariumPowder(){
super();
this.setUnlocalizedName(Names.Powders.BARIUM_POWDER);
}
}
|
Mrkwtkr/shinsei
|
src/main/java/com/megathirio/shinsei/item/powder/ItemBariumPowder.java
|
Java
|
gpl-3.0
| 315 |
import numpy as np
from scipy import constants
from scipy.integrate import quad
# Boltzmann constant in eV/K
k = constants.value('Boltzmann constant in eV/K')
class Flux() :
"""
This class evaluates the neutron spectrum. The thermal cutoff is treated
as a variable parameter to ensure a specific fast-to-thermal ratio.
At thermal energy range (e < e1 eV), the flux is approximated by Maxwellian
distribution (D&H book Eq.(9-6)).
At fast energy range (e2 MeV < e < 20MeV), the flux is approximated by U-235
chi-spectrum (D&H book Eq.(2-112)).
At epithermal energies (e1 eV < e < e2 MeV), flux = 1/e
ratio : fast-to-thermal flux ratio
"""
def __init__(self, ratio = 2, thermal_temp = 600.0):
self.e2 = 1e6
self.thermal_temp = thermal_temp
# Maxwellian distribution, Eq.(9-6)
self.m = lambda x : x ** 0.5 * np.exp(-x/(k*self.thermal_temp))
# U235 chi distribution, Eq.(2-112)
self.chi = lambda x : np.exp(-1.036e-6*x)*np.sinh((2.29e-6 * x)**0.5)
# Middle energy range
self.f = lambda x : 1 / x
# Compute ratio as a function of thermal cutoff
E = np.logspace(-4, 0.1, 200)
R = np.array([self.compute_ratio(e1) for e1 in E])
# Compute thermal cutoff for given ratio
self.e1 = np.interp(1.0/ratio, R, E)
print 'Thermal cutoff is {} eV'.format(self.e1)
# Compute constants for each part of the spectrum
self.c1 = 1.0
self.c2 = self.m(self.e1) / self.f(self.e1)
self.c3 = self.c2 * self.f(self.e2) / self.chi(self.e2)
def compute_ratio(self, e1):
A = quad(self.m, 0, e1)[0]
C2 = self.m(e1) / self.f(e1)
C3 = self.f(self.e2) / self.chi(self.e2)
B = C2 * quad(self.f, e1, self.e2)[0]
C = C2 * C3 * quad(self.chi, self.e2, 2e7)[0]
r = A / (B + C)
return r
def evaluate(self, e):
# Evaluate flux at Energy e in eV
return (e<=self.e1) * self.c1*self.m(e) + \
(e>self.e1)*(e<=self.e2) * (self.c2 / e) + \
(e>self.e2) * self.c3*self.chi(e)
if __name__ == "__main__" :
import matplotlib.pyplot as plt
from multigroup_utilities import *
from nice_plots import init_nice_plots
init_nice_plots()
# PWR-like and TRIGA-like spectra
pwr = Flux(7.0, 600.0)
triga = Flux(1.0, 600.0)
# Evaluate the flux
E = np.logspace(-5, 7, 1000)
phi_pwr = pwr.evaluate(E)
phi_triga = triga.evaluate(E)
# Collapse the flux and flux per unit lethargy onto WIMS 69-group structure
bounds = energy_groups(structure='wims69')
pwr_mg = collapse(bounds, phi_pwr, E)
triga_mg = collapse(bounds, phi_triga, E)
phi_mg_pul = collapse(bounds, E*phi_pwr, E)
triga_mg_pul = collapse(bounds, E*phi_triga, E)
# Produce step-plot data for each spectrum
E_mg, phi_mg = plot_multigroup_data(bounds, pwr_mg)
_, triga_mg = plot_multigroup_data(bounds, triga_mg)
_, phi_mg_pul = plot_multigroup_data(bounds, phi_mg_pul)
_, triga_mg_pul = plot_multigroup_data(bounds, triga_mg_pul)
plt.figure(1)
plt.loglog(E, phi_pwr, 'k', E_mg, phi_mg, 'k--',
E, phi_triga, 'b', E_mg, triga_mg, 'b:')
plt.xlabel('$E$ (eV)')
plt.ylabel('$\phi(E)$')
plt.figure(2)
plt.loglog(E, E*phi_pwr, 'k', E_mg, phi_mg_pul, 'k--',
E, E*phi_triga, 'b', E_mg, triga_mg_pul, 'b:')
plt.xlabel('$E$ (eV)')
plt.ylabel('$E\phi(E)$')
plt.show()
|
corps-g/flux_spectrum
|
flux_spectrum.py
|
Python
|
gpl-3.0
| 3,697 |
<script>
function puntuar(valor){
$(function(){
form = document.forms["form1"];
cr = form.elements["critica"].value;
ju = form.elements["juego"].value;
us = form.elements["usuario"].value;
destino = "<?= base_url('index.php/criticas/puntuar') ?>";
$.post(destino,{critica: cr, juego: ju, usuario: us, confirmar: valor},function(respuesta){
$("#contenido").html(respuesta);
});
});
}
</script>
<div id="contenido">
<?php if (isset($mensaje)): ?>
<div id="mensaje">
<p><?= $mensaje ?></p>
</div>
<?php endif; ?>
<?php if ($usuario == $this->session->userdata('id')): ?>
<h1>Crรญtica de <?= anchor('juegos/index/'.$juego, $nombrejuego) ?> por tรญ</h1>
<?php else: ?>
<h1>Crรญtica de <?= anchor('juegos/index/'.$juego, $nombrejuego) ?> por
<?= anchor("usuarios/index/".$usuario, $nombreusuario) ?></h1>
<?php endif;?>
<div class="capa">
<table>
<tr>
<td>
<?= anchor("usuarios/index/".$usuario, "<img class='avatar' src=".base_url('imagenes/'.$avatar)." />") ?>
</td>
<td class="celda_descripcion">
<h3 <?= ($karma < 0) ? "class='negativo'" : "class='positivo'" ?>>
Karma del autor: <?= $karma ?> punto<?php if ($karma != 1 && $karma != -1) echo "s"; ?>
</h3>
</td>
</tr>
<tr>
<td>
<?= anchor('juegos/index/'.$juego, "<img class='caratula_pequeรฑa' src=".base_url('imagenes/'.$caratula)." />") ?>
</td>
<td class="celda_descripcion">
<h3 <?= ($media < 5) ? "class='negativo'" : "class='positivo'" ?>>
Nota media del juego: <?= $media ?>
</h3>
</td>
</tr>
</table>
</div>
<fieldset><legend>Contenido</legend>
<span id="capa_nota">
<h2 <?= ($nota < 5) ? "class='negativo'" : "class='positivo'" ?>>
Nota: <?= $nota ?>
</h2>
</span>
<br/><br/>
<div class="capa">
<?= $contenido ?>
</div>
<br/>
<div style="text-align: right;">
<em style="font-size: small;">Realizado el <?= date("d-m-Y", strtotime($fecha)) ?></em> <br/>
</div>
</fieldset>
<div class="capa">
<br/>
<div>
<?php if ($votos == 0): ?>
Aรบn no han valorado esta crรญtica
<?php else: ?>
<div class="caja_de_barra">
<div id="barra_positiva" style="width: <?= $positivos ?>%;"><?= $positivos ?>%</div>
Valoraciones positivas
</div>
<br/>
<div class="caja_de_barra">
<div id="barra_negativa" style="width: <?= (100 - $positivos) ?>%;"><?= (100 - $positivos) ?>%</div>
Valoraciones negativas
</div>
<br/>
<?php endif; ?>
</div>
<?php if ($this->session->userdata('id')): ?>
<?php if ($usuario != $this->session->userdata('id')): ?>
<div id="capa_valoracion">
<form name="form1" id="form1">
<?= form_hidden('critica', $id) ?>
<?= form_hidden('juego', $juego) ?>
<?= form_hidden('usuario', $usuario) ?>
<?php if (!isset($valoracion)): ?>
<input type="button" name="confirmar" class="boton" value="Dar punto positivo"
onClick="puntuar('Dar punto positivo');"/>
<input type="button" name="confirmar" class="boton" value="Dar punto negativo"
onClick="puntuar('Dar punto negativo');"/>
<?php elseif ($valoracion == 1): ?>
<em class="positivo">Has puntuado positivamente esta crรญtica</em>
<input type="button" name="confirmar" class="boton" value="Retirar punto"
onClick="puntuar('Retirar punto');"/>
<input type="button" name="confirmar" class="boton" value="Dar punto negativo"
onClick="puntuar('Dar punto negativo');"/>
<?php elseif ($valoracion == -1): ?>
<em class="negativo">Has puntuado negativamente esta crรญtica</em>
<input type="button" name="confirmar" class="boton" value="Retirar punto"
onClick="puntuar('Retirar punto');"/>
<input type="button" name="confirmar" class="boton" value="Dar punto positivo"
onClick="puntuar('Dar punto positivo');"/>
<?php endif; ?>
</form>
</div>
<?php else: ?>
<?= form_open('criticas/editar/'.$juego) ?>
<?= form_hidden('critica', $id) ?>
<?= form_submit('editar', 'Editar crรญtica', "class='boton'") ?>
<?= form_close() ?>
<?php endif; ?>
<br/>
<?php if ($votos == 0): ?>
<?php elseif ($votos == 1 && isset($valoracion)): ?>
Solamente tรบ has puntuado esta crรญtica
<?php elseif ($votos == 2 && isset($valoracion)): ?>
<?= anchor('usuarios/listar/critica/'.$id, 'Otra persona') ?> mรกs ha puntuado esta crรญtica
<?php elseif ($votos == 1 && !isset($valoracion)): ?>
<?= anchor('usuarios/listar/critica/'.$id, 'Una persona') ?> ha puntuado esta crรญtica
<?php elseif ($votos > 1 && !isset($valoracion)): ?>
<?= anchor('usuarios/listar/critica/'.$id, "$votos personas") ?> puntuaron esta crรญtica
<?php else: ?>
<?= anchor('usuarios/listar/critica/'.$id, "Otras ".($votos-1)." personas") ?> mรกs puntuaron esta crรญtica
<?php endif; ?>
<?php endif; ?>
</div>
</div>
|
tonigallego/gamerland
|
application/views/criticas/index.php
|
PHP
|
gpl-3.0
| 5,024 |
/*
*
* This file is part of Genome Artist.
*
* Genome Artist is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Genome Artist is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Genome Artist. If not, see <http://www.gnu.org/licenses/>.
*
*/
package ro.genomeartist.components.utils;
import java.util.Arrays;
/**
*
* @author iulian
*/
public class StringUtilities {
/** Test whether a given string is a valid Java identifier.
* @param id string which should be checked
* @return <code>true</code> if a valid identifier
*/
public static boolean isJavaIdentifier(String id) {
if (id == null) return false;
if (id.equals("")) return false; // NOI18N
if (!(java.lang.Character.isJavaIdentifierStart(id.charAt(0))) )
return false;
for (int i = 1; i < id.length(); i++) {
if (!(java.lang.Character.isJavaIdentifierPart(id.charAt(i))) )
return false;
}
return Arrays.binarySearch(keywords, id) < 0;
}
/**
* Vector cu identificatorii java
*/
private static final String[] keywords = new String[] {
//If adding to this, insert in alphabetical order!
"abstract","assert","boolean","break","byte","case", //NOI18N
"catch","char","class","const","continue","default", //NOI18N
"do","double","else","extends","false","final", //NOI18N
"finally","float","for","goto","if","implements", //NOI18N
"import","instanceof","int","interface","long", //NOI18N
"native","new","null","package","private", //NOI18N
"protected","public","return","short","static", //NOI18N
"strictfp","super","switch","synchronized","this", //NOI18N
"throw","throws","transient","true","try","void", //NOI18N
"volatile","while" //NOI18N
};
/**
* Fac escape la un string pentru a-l afisa in XML
* @param text
* @return
*/
public static String removeWindowsCarriageReturn(String text){
return text.replaceAll("\\r", "");
}
}
|
genomeartist/genomeartist
|
sources_java/Components/src/ro/genomeartist/components/utils/StringUtilities.java
|
Java
|
gpl-3.0
| 2,529 |
package etomica.normalmode.nptdemo;
import java.awt.Color;
import etomica.api.IAtom;
import etomica.api.IAtomList;
import etomica.api.IBoundary;
import etomica.api.IBox;
import etomica.api.IVector;
import etomica.api.IVectorMutable;
import etomica.graphics.ColorSchemeCollectiveAgent;
import etomica.nbr.list.NeighborListManager;
import etomica.nbr.list.PotentialMasterList;
import etomica.normalmode.CoordinateDefinition;
import etomica.space.ISpace;
/**
* Color atoms based on being neighbors of the reference atom
*
* @author Andrew Schultz
*/
public class ColorSchemeScaledOverlap extends ColorSchemeCollectiveAgent {
public ColorSchemeScaledOverlap(ISpace space, PotentialMasterList potentialMaster, CoordinateDefinition coordinateDefinition) {
super(coordinateDefinition.getBox());
this.coordinateDefinition = coordinateDefinition;
IBox box = coordinateDefinition.getBox();
nOverlaps = new int[box.getLeafList().getAtomCount()];
neighborManager = potentialMaster.getNeighborManager(box);
pi = space.makeVector();
pj = space.makeVector();
dr = space.makeVector();
}
public void setPressure(double newPressure) {
pressure = newPressure;
}
public double getPressure() {
return pressure;
}
public void setDisplayDensity(double newDisplayDensity) {
displayDensity = newDisplayDensity;
}
public double getDisplayDensity() {
return displayDensity;
}
public synchronized void colorAllAtoms() {
IBox box = coordinateDefinition.getBox();
IAtomList leafList = box.getLeafList();
double vOld = box.getBoundary().volume();
int nAtoms = box.getLeafList().getAtomCount();
double vNew = nAtoms/displayDensity;
double rScale = Math.sqrt(vNew/vOld);
double latticeScale = Math.exp((pressure*(vNew-vOld))/((nAtoms-1)*1*2))/rScale;
// T=1, D=2
double sigma = 1.0;
double scaledSig = sigma/rScale;
double sig2 = scaledSig*scaledSig;
//color all atoms according to their type
int nLeaf = leafList.getAtomCount();
for (int iLeaf=0; iLeaf<nLeaf; iLeaf++) {
nOverlaps[iLeaf] = 0;
}
IBoundary boundary = box.getBoundary();
for (int i=0; i<leafList.getAtomCount(); i++) {
//color blue the neighbor atoms in same group
IAtom atom = leafList.getAtom(i);
pi.E(atom.getPosition());
IVector l = coordinateDefinition.getLatticePosition(atom);
pi.ME(l);
pi.TE(latticeScale);
pi.PE(l);
IAtomList list = neighborManager.getDownList(atom)[0];
for (int j=0; j<list.getAtomCount(); j++) {
IAtom jAtom = list.getAtom(j);
pj.E(jAtom.getPosition());
IVector lj = coordinateDefinition.getLatticePosition(jAtom);
pj.ME(lj);
pj.TE(latticeScale);
pj.PE(lj);
dr.Ev1Mv2(pi, pj);
boundary.nearestImage(dr);
double r2 = dr.squared();
if (r2 < sig2) {
nOverlaps[i]++;
nOverlaps[jAtom.getLeafIndex()]++;
}
}
}
for (int i=0; i<leafList.getAtomCount(); i++) {
//color green the target atom
agentManager.setAgent(leafList.getAtom(i), colors[nOverlaps[i]]);
}
}
private static final long serialVersionUID = 1L;
private final NeighborListManager neighborManager;
protected final IVectorMutable dr;
protected final IVectorMutable pi, pj;
protected final int[] nOverlaps;
protected double pressure, displayDensity;
protected final CoordinateDefinition coordinateDefinition;
protected Color[] colors = new Color[]{Color.RED, Color.BLUE, Color.GREEN, Color.BLACK, Color.CYAN, Color.PINK, new Color(0.5f, 0.0f, 0.5f)};
}
|
ajschult/etomica
|
etomica-apps/src/main/java/etomica/normalmode/nptdemo/ColorSchemeScaledOverlap.java
|
Java
|
mpl-2.0
| 4,038 |
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.javascript.orginal.ast;
import org.mozilla.javascript.orginal.Token;
/**
* AST node representing unary operators such as {@code ++},
* {@code ~}, {@code typeof} and {@code delete}. The type field
* is set to the appropriate Token type for the operator. The node length spans
* from the operator to the end of the operand (for prefix operators) or from
* the start of the operand to the operator (for postfix).<p>
*
* The {@code default xml namespace = <expr>} statement in E4X
* (JavaScript 1.6) is represented as a {@code UnaryExpression} of node
* type {@link Token#DEFAULTNAMESPACE}, wrapped with an
* {@link ExpressionStatement}.
*/
public class UnaryExpression extends AstNode {
private AstNode operand;
private boolean isPostfix;
public UnaryExpression() {
}
public UnaryExpression(int pos) {
super(pos);
}
/**
* Constructs a new postfix UnaryExpression
*/
public UnaryExpression(int pos, int len) {
super(pos, len);
}
/**
* Constructs a new prefix UnaryExpression.
*/
public UnaryExpression(int operator, int operatorPosition,
AstNode operand) {
this(operator, operatorPosition, operand, false);
}
/**
* Constructs a new UnaryExpression with the specified operator
* and operand. It sets the parent of the operand, and sets its own bounds
* to encompass the operator and operand.
* @param operator the node type
* @param operatorPosition the absolute position of the operator.
* @param operand the operand expression
* @param postFix true if the operator follows the operand. Int
* @throws IllegalArgumentException} if {@code operand} is {@code null}
*/
public UnaryExpression(int operator, int operatorPosition,
AstNode operand, boolean postFix) {
assertNotNull(operand);
int beg = postFix ? operand.getPosition() : operatorPosition;
// JavaScript only has ++ and -- postfix operators, so length is 2
int end = postFix
? operatorPosition + 2
: operand.getPosition() + operand.getLength();
setBounds(beg, end);
setOperator(operator);
setOperand(operand);
isPostfix = postFix;
}
/**
* Returns operator token – alias for {@link #getType}
*/
public int getOperator() {
return type;
}
/**
* Sets operator – same as {@link #setType}, but throws an
* exception if the operator is invalid
* @throws IllegalArgumentException if operator is not a valid
* Token code
*/
public void setOperator(int operator) {
if (!Token.isValidToken(operator))
throw new IllegalArgumentException("Invalid token: " + operator);
setType(operator);
}
public AstNode getOperand() {
return operand;
}
/**
* Sets the operand, and sets its parent to be this node.
* @throws IllegalArgumentException} if {@code operand} is {@code null}
*/
public void setOperand(AstNode operand) {
assertNotNull(operand);
this.operand = operand;
operand.setParent(this);
}
/**
* Returns whether the operator is postfix
*/
public boolean isPostfix() {
return isPostfix;
}
/**
* Returns whether the operator is prefix
*/
public boolean isPrefix() {
return !isPostfix;
}
/**
* Sets whether the operator is postfix
*/
public void setIsPostfix(boolean isPostfix) {
this.isPostfix = isPostfix;
}
@Override
public String toSource(int depth) {
StringBuilder sb = new StringBuilder();
sb.append(makeIndent(depth));
int type = getType();
if (!isPostfix) {
sb.append(operatorToString(type));
if (type == Token.TYPEOF || type == Token.DELPROP || type == Token.VOID) {
sb.append(" ");
}
}
sb.append(operand.toSource());
if (isPostfix) {
sb.append(operatorToString(type));
}
return sb.toString();
}
/**
* Visits this node, then the operand.
*/
@Override
public void visit(NodeVisitor v) {
if (v.visit(this)) {
operand.visit(v);
}
}
}
|
WolframG/Rhino-Prov-Mod
|
src/org/mozilla/javascript/orginal/ast/UnaryExpression.java
|
Java
|
mpl-2.0
| 4,690 |
/*~
* Copyright (C) 2013 - 2016 George Makrydakis <george@irrequietus.eu>
*
* This file is part of 'clause', a highly generic C++ meta-programming library,
* subject to the terms and conditions of the Mozilla Public License v 2.0. If
* a copy of the MPLv2 license text was not distributed with this file, you can
* obtain it at: http://mozilla.org/MPL/2.0/.
*
* The 'clause' library is an experimental library in active development with
* a source code repository at: https://github.com/irrequietus/clause.git and
* issue tracker at https://github.com/irrequietus/clause/issues.
*
*/
/*~
* @warn This file should not be included directly in code deploying library
* constructs from 'clause'; it is part of a high level meta-macro
* construct where multiple #if directives control its actual inclusion.
*/
#undef PPMPF_VXPP_S7F34
#undef PPMPF_VXPP_S7F33
#undef PPMPF_VXPP_S7F32
#undef PPMPF_VXPP_S7F31
#undef PPMPF_VXPP_S7F30
#if (_PPMPF_FARG73() / 10000) % 10 == 0
#define PPMPF_VXPP_S7F34 0
#elif (_PPMPF_FARG73() / 10000) % 10 == 1
#define PPMPF_VXPP_S7F34 1
#elif (_PPMPF_FARG73() / 10000) % 10 == 2
#define PPMPF_VXPP_S7F34 2
#elif (_PPMPF_FARG73() / 10000) % 10 == 3
#define PPMPF_VXPP_S7F34 3
#elif (_PPMPF_FARG73() / 10000) % 10 == 4
#define PPMPF_VXPP_S7F34 4
#elif (_PPMPF_FARG73() / 10000) % 10 == 5
#define PPMPF_VXPP_S7F34 5
#elif (_PPMPF_FARG73() / 10000) % 10 == 6
#define PPMPF_VXPP_S7F34 6
#elif (_PPMPF_FARG73() / 10000) % 10 == 7
#define PPMPF_VXPP_S7F34 7
#elif (_PPMPF_FARG73() / 10000) % 10 == 8
#define PPMPF_VXPP_S7F34 8
#elif (_PPMPF_FARG73() / 10000) % 10 == 9
#define PPMPF_VXPP_S7F34 9
#endif
#if (_PPMPF_FARG73() / 1000) % 10 == 0
#define PPMPF_VXPP_S7F33 0
#elif (_PPMPF_FARG73() / 1000) % 10 == 1
#define PPMPF_VXPP_S7F33 1
#elif (_PPMPF_FARG73() / 1000) % 10 == 2
#define PPMPF_VXPP_S7F33 2
#elif (_PPMPF_FARG73() / 1000) % 10 == 3
#define PPMPF_VXPP_S7F33 3
#elif (_PPMPF_FARG73() / 1000) % 10 == 4
#define PPMPF_VXPP_S7F33 4
#elif (_PPMPF_FARG73() / 1000) % 10 == 5
#define PPMPF_VXPP_S7F33 5
#elif (_PPMPF_FARG73() / 1000) % 10 == 6
#define PPMPF_VXPP_S7F33 6
#elif (_PPMPF_FARG73() / 1000) % 10 == 7
#define PPMPF_VXPP_S7F33 7
#elif (_PPMPF_FARG73() / 1000) % 10 == 8
#define PPMPF_VXPP_S7F33 8
#elif (_PPMPF_FARG73() / 1000) % 10 == 9
#define PPMPF_VXPP_S7F33 9
#endif
#if (_PPMPF_FARG73() / 100) % 10 == 0
#define PPMPF_VXPP_S7F32 0
#elif (_PPMPF_FARG73() / 100) % 10 == 1
#define PPMPF_VXPP_S7F32 1
#elif (_PPMPF_FARG73() / 100) % 10 == 2
#define PPMPF_VXPP_S7F32 2
#elif (_PPMPF_FARG73() / 100) % 10 == 3
#define PPMPF_VXPP_S7F32 3
#elif (_PPMPF_FARG73() / 100) % 10 == 4
#define PPMPF_VXPP_S7F32 4
#elif (_PPMPF_FARG73() / 100) % 10 == 5
#define PPMPF_VXPP_S7F32 5
#elif (_PPMPF_FARG73() / 100) % 10 == 6
#define PPMPF_VXPP_S7F32 6
#elif (_PPMPF_FARG73() / 100) % 10 == 7
#define PPMPF_VXPP_S7F32 7
#elif (_PPMPF_FARG73() / 100) % 10 == 8
#define PPMPF_VXPP_S7F32 8
#elif (_PPMPF_FARG73() / 100) % 10 == 9
#define PPMPF_VXPP_S7F32 9
#endif
#if (_PPMPF_FARG73() / 10) % 10 == 0
#define PPMPF_VXPP_S7F31 0
#elif (_PPMPF_FARG73() / 10) % 10 == 1
#define PPMPF_VXPP_S7F31 1
#elif (_PPMPF_FARG73() / 10) % 10 == 2
#define PPMPF_VXPP_S7F31 2
#elif (_PPMPF_FARG73() / 10) % 10 == 3
#define PPMPF_VXPP_S7F31 3
#elif (_PPMPF_FARG73() / 10) % 10 == 4
#define PPMPF_VXPP_S7F31 4
#elif (_PPMPF_FARG73() / 10) % 10 == 5
#define PPMPF_VXPP_S7F31 5
#elif (_PPMPF_FARG73() / 10) % 10 == 6
#define PPMPF_VXPP_S7F31 6
#elif (_PPMPF_FARG73() / 10) % 10 == 7
#define PPMPF_VXPP_S7F31 7
#elif (_PPMPF_FARG73() / 10) % 10 == 8
#define PPMPF_VXPP_S7F31 8
#elif (_PPMPF_FARG73() / 10) % 10 == 9
#define PPMPF_VXPP_S7F31 9
#endif
#if _PPMPF_FARG73() % 10 == 0
#define PPMPF_VXPP_S7F30 0
#elif _PPMPF_FARG73() % 10 == 1
#define PPMPF_VXPP_S7F30 1
#elif _PPMPF_FARG73() % 10 == 2
#define PPMPF_VXPP_S7F30 2
#elif _PPMPF_FARG73() % 10 == 3
#define PPMPF_VXPP_S7F30 3
#elif _PPMPF_FARG73() % 10 == 4
#define PPMPF_VXPP_S7F30 4
#elif _PPMPF_FARG73() % 10 == 5
#define PPMPF_VXPP_S7F30 5
#elif _PPMPF_FARG73() % 10 == 6
#define PPMPF_VXPP_S7F30 6
#elif _PPMPF_FARG73() % 10 == 7
#define PPMPF_VXPP_S7F30 7
#elif _PPMPF_FARG73() % 10 == 8
#define PPMPF_VXPP_S7F30 8
#elif _PPMPF_FARG73() % 10 == 9
#define PPMPF_VXPP_S7F30 9
#endif
|
irrequietus/clause
|
clause/ppmpf/vxpp/slots/func/arty/arty74.hh
|
C++
|
mpl-2.0
| 4,493 |
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/*
* Copyright (c) 2019, Joyent, Inc.
*/
var mod_fs = require('fs');
var mod_path = require('path');
var mod_assert = require('assert-plus');
var DEFAULT_DEBOUNCE_TIME = 600;
var DEFAULT_RETAIN_TIME = 0;
var LOGSETS;
function
load_logsets()
{
var NAMES_SEEN = [];
LOGSETS = JSON.parse(mod_fs.readFileSync(mod_path.join(__dirname,
'..', 'etc', 'logsets.json'), 'utf8'));
for (var i = 0; i < LOGSETS.length; i++) {
var ls = LOGSETS[i];
ls.regex = new RegExp(ls.regex);
mod_assert.optionalString(
ls.search_dirs_pattern,
'search_dirs_pattern');
mod_assert.arrayOfString(ls.search_dirs, 'search_dirs');
mod_assert.optionalBool(ls.no_upload, 'no_upload');
mod_assert.string(ls.manta_path, 'manta_path');
mod_assert.optionalNumber(ls.debounce_time, 'debounce_time');
if (!ls.debounce_time)
ls.debounce_time = DEFAULT_DEBOUNCE_TIME;
mod_assert.optionalNumber(ls.retain_time, 'retain_time');
if (!ls.retain_time)
ls.retain_time = DEFAULT_RETAIN_TIME;
mod_assert.ok(NAMES_SEEN.indexOf(ls.name) === -1,
'duplicate logset name');
NAMES_SEEN.push(ls.name);
}
}
var COPY_FIELDS = [
'search_dirs',
'search_dirs_pattern',
'manta_path',
'date_string',
'date_adjustment',
'debounce_time',
'retain_time',
'customer_uuid',
'no_upload'
];
/*
* Create a JSON-safe object for transport across the wire to the actor:
*/
function
format_logset(logset, zonename, zonerole)
{
var o = {
name: logset.name + (zonename ? '@' + zonename : ''),
zonename: zonename || 'global',
zonerole: zonerole || 'global',
regex: logset.regex.source
};
for (var i = 0; i < COPY_FIELDS.length; i++) {
var cf = COPY_FIELDS[i];
o[cf] = logset[cf];
}
return (o);
}
function
logsets_for_server(zone_list_for_server)
{
var out = [];
for (var i = 0; i < LOGSETS.length; i++) {
var ls = LOGSETS[i];
/*
* This logset applies to the global zone:
*/
if (ls.zones.indexOf('global') !== -1) {
out.push(format_logset(ls));
}
for (var j = 0; j < zone_list_for_server.length; j++) {
var zz = zone_list_for_server[j];
if (ls.zones.indexOf(zz.role) !== -1) {
out.push(format_logset(ls, zz.uuid, zz.role));
}
}
}
return (out);
}
/*
* Initialisation:
*/
load_logsets();
/*
* API:
*/
module.exports = {
logsets_for_server: logsets_for_server
};
/* vim: set syntax=javascript ts=8 sts=8 sw=8 noet: */
|
joyent/sdc-hermes
|
lib/logsets.js
|
JavaScript
|
mpl-2.0
| 2,593 |
/*
* Copyright ยฉ 2016 Mathias Doenitz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package swave.core.impl;
final class Statics {
static final Integer _0 = 0;
static final Integer _1 = 1;
static final Integer _2 = 2;
static final Integer _3 = 3;
static final Integer _4 = 4;
static final Integer _5 = 5;
static final Integer _6 = 6;
static final Integer _7 = 7;
static final Integer _8 = 8;
static final Integer _9 = 9;
static final Integer _10 = 10;
static final Integer _11 = 11;
static final Integer _12 = 12;
static final java.lang.Integer[] NEG_INTS = {
-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16,
-17, -18, -19, -20, -21, -22, -23, -24, -25, -26, -27, -28, -29, -30, -31, -32
};
static final java.lang.Integer[] INTS_PLUS_100 = {
101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116,
117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132
};
}
|
sirthias/swave
|
core/src/main/java/swave/core/impl/Statics.java
|
Java
|
mpl-2.0
| 1,574 |
// Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved.
// Licensed under the Mozilla Public License v2.0
package oci
import (
"context"
"fmt"
"testing"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/terraform"
"github.com/oracle/oci-go-sdk/v46/common"
oci_kms "github.com/oracle/oci-go-sdk/v46/keymanagement"
"github.com/terraform-providers/terraform-provider-oci/httpreplay"
)
var (
KeyRequiredOnlyResource = KeyResourceDependencies +
generateResourceFromRepresentationMap("oci_kms_key", "test_key", Required, Create, keyRepresentation)
KeyResourceConfig = KeyResourceDependencies +
generateResourceFromRepresentationMap("oci_kms_key", "test_key", Optional, Update, keyRepresentation)
keySingularDataSourceRepresentation = map[string]interface{}{
"key_id": Representation{repType: Required, create: `${oci_kms_key.test_key.id}`},
"management_endpoint": Representation{repType: Required, create: `${data.oci_kms_vault.test_vault.management_endpoint}`},
}
keyDataSourceRepresentation = map[string]interface{}{
"compartment_id": Representation{repType: Required, create: `${var.compartment_id}`},
"management_endpoint": Representation{repType: Required, create: `${data.oci_kms_vault.test_vault.management_endpoint}`},
"protection_mode": Representation{repType: Optional, create: `SOFTWARE`},
"algorithm": Representation{repType: Optional, create: `AES`},
"length": Representation{repType: Optional, create: `16`},
"filter": RepresentationGroup{Required, keyDataSourceFilterRepresentation}}
keyDataSourceFilterRepresentation = map[string]interface{}{
"name": Representation{repType: Required, create: `id`},
"values": Representation{repType: Required, create: []string{`${oci_kms_key.test_key.id}`}},
}
deletionTime = time.Now().UTC().AddDate(0, 0, 8).Truncate(time.Millisecond)
keyRepresentation = map[string]interface{}{
"compartment_id": Representation{repType: Required, create: `${var.compartment_id}`},
"display_name": Representation{repType: Required, create: `Key C`, update: `displayName2`},
"key_shape": RepresentationGroup{Required, keyKeyShapeRepresentation},
"management_endpoint": Representation{repType: Required, create: `${data.oci_kms_vault.test_vault.management_endpoint}`},
"desired_state": Representation{repType: Optional, create: `ENABLED`, update: `DISABLED`},
"freeform_tags": Representation{repType: Optional, create: map[string]string{"Department": "Finance"}, update: map[string]string{"Department": "Accounting"}},
"protection_mode": Representation{repType: Optional, create: `SOFTWARE`},
"time_of_deletion": Representation{repType: Required, create: deletionTime.Format(time.RFC3339Nano)},
}
keyKeyShapeRepresentation = map[string]interface{}{
"algorithm": Representation{repType: Required, create: `AES`},
"length": Representation{repType: Required, create: `16`},
}
kmsVaultId = getEnvSettingWithBlankDefault("kms_vault_ocid")
KmsVaultIdVariableStr = fmt.Sprintf("variable \"kms_vault_id\" { default = \"%s\" }\n", kmsVaultId)
kmsKeyIdForCreate = getEnvSettingWithBlankDefault("key_ocid_for_create")
kmsKeyIdCreateVariableStr = fmt.Sprintf("variable \"kms_key_id_for_create\" { default = \"%s\" }\n", kmsKeyIdForCreate)
kmsKeyIdForUpdate = getEnvSettingWithBlankDefault("key_ocid_for_update")
kmsKeyIdUpdateVariableStr = fmt.Sprintf("variable \"kms_key_id_for_update\" { default = \"%s\" }\n", kmsKeyIdForUpdate)
kmsKeyCompartmentId = getEnvSettingWithBlankDefault("compartment_ocid")
kmsKeyCompartmentIdVariableStr = fmt.Sprintf("variable \"kms_key_compartment_id\" { default = \"%s\" }\n", kmsKeyCompartmentId)
// Should deprecate use of tenancy level resources
KeyResourceDependencies = KmsVaultIdVariableStr + `
data "oci_kms_vault" "test_vault" {
#Required
vault_id = "${var.kms_vault_id}"
}
`
KeyResourceDependencyConfig = KeyResourceDependencies + `
data "oci_kms_keys" "test_keys_dependency" {
#Required
compartment_id = "${var.tenancy_ocid}"
management_endpoint = "${data.oci_kms_vault.test_vault.management_endpoint}"
algorithm = "AES"
filter {
name = "state"
values = ["ENABLED", "UPDATING"]
}
}
data "oci_kms_keys" "test_keys_dependency_RSA" {
#Required
compartment_id = "${var.tenancy_ocid}"
management_endpoint = "${data.oci_kms_vault.test_vault.management_endpoint}"
algorithm = "RSA"
filter {
name = "state"
values = ["ENABLED", "UPDATING"]
}
}
`
KeyResourceDependencyConfig2 = KeyResourceDependencies + kmsKeyCompartmentIdVariableStr + `
data "oci_kms_keys" "test_keys_dependency" {
#Required
compartment_id = "${var.kms_key_compartment_id}"
management_endpoint = "${data.oci_kms_vault.test_vault.management_endpoint}"
algorithm = "AES"
filter {
name = "state"
values = ["ENABLED", "UPDATING"]
}
}
data "oci_kms_keys" "test_keys_dependency_RSA" {
#Required
compartment_id = "${var.kms_key_compartment_id}"
management_endpoint = "${data.oci_kms_vault.test_vault.management_endpoint}"
algorithm = "RSA"
filter {
name = "state"
values = ["ENABLED", "UPDATING"]
}
}
`
)
// issue-routing-tag: kms/default
func TestKmsKeyResource_basic(t *testing.T) {
httpreplay.SetScenario("TestKmsKeyResource_basic")
defer httpreplay.SaveScenario()
provider := testAccProvider
config := testProviderConfig()
compartmentId := getEnvSettingWithBlankDefault("compartment_ocid")
compartmentIdVariableStr := fmt.Sprintf("variable \"compartment_id\" { default = \"%s\" }\n", compartmentId)
compartmentIdU := getEnvSettingWithDefault("compartment_id_for_update", compartmentId)
compartmentIdUVariableStr := fmt.Sprintf("variable \"compartment_id_for_update\" { default = \"%s\" }\n", compartmentIdU)
resourceName := "oci_kms_key.test_key"
datasourceName := "data.oci_kms_keys.test_keys"
singularDatasourceName := "data.oci_kms_key.test_key"
var resId, resId2 string
// Save TF content to create resource with optional properties. This has to be exactly the same as the config part in the "create with optionals" step in the test.
saveConfigContent(config+compartmentIdVariableStr+KeyResourceDependencies+
generateResourceFromRepresentationMap("oci_kms_key", "test_key", Optional, Create, keyRepresentation), "keymanagement", "key", t)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
CheckDestroy: testAccCheckKMSKeyDestroy,
Providers: map[string]terraform.ResourceProvider{
"oci": provider,
},
Steps: []resource.TestStep{
// verify create
{
Config: config + compartmentIdVariableStr + KeyResourceDependencies + DefinedTagsDependencies +
generateResourceFromRepresentationMap("oci_kms_key", "test_key", Required, Create, keyRepresentation),
Check: ComposeAggregateTestCheckFuncWrapper(
resource.TestCheckResourceAttr(resourceName, "compartment_id", compartmentId),
resource.TestCheckResourceAttr(resourceName, "display_name", "Key C"),
resource.TestCheckResourceAttr(resourceName, "key_shape.#", "1"),
resource.TestCheckResourceAttr(resourceName, "key_shape.0.algorithm", "AES"),
resource.TestCheckResourceAttr(resourceName, "key_shape.0.length", "16"),
func(s *terraform.State) (err error) {
resId, err = fromInstanceState(s, resourceName, "id")
return err
},
),
},
// delete before next create
{
Config: config + compartmentIdVariableStr + KeyResourceDependencies,
},
// verify create with optionals
{
Config: config + compartmentIdVariableStr + KeyResourceDependencies + DefinedTagsDependencies +
generateResourceFromRepresentationMap("oci_kms_key", "test_key", Optional, Create, keyRepresentation),
Check: ComposeAggregateTestCheckFuncWrapper(
resource.TestCheckResourceAttr(resourceName, "compartment_id", compartmentId),
resource.TestCheckResourceAttrSet(resourceName, "current_key_version"),
resource.TestCheckResourceAttr(resourceName, "display_name", "Key C"),
resource.TestCheckResourceAttr(resourceName, "freeform_tags.%", "1"),
resource.TestCheckResourceAttrSet(resourceName, "id"),
resource.TestCheckResourceAttr(resourceName, "key_shape.#", "1"),
resource.TestCheckResourceAttr(resourceName, "key_shape.0.algorithm", "AES"),
resource.TestCheckResourceAttr(resourceName, "key_shape.0.length", "16"),
resource.TestCheckResourceAttrSet(resourceName, "management_endpoint"),
resource.TestCheckResourceAttr(resourceName, "protection_mode", "SOFTWARE"),
resource.TestCheckResourceAttrSet(resourceName, "state"),
resource.TestCheckResourceAttrSet(resourceName, "time_created"),
resource.TestCheckResourceAttrSet(resourceName, "vault_id"),
func(s *terraform.State) (err error) {
resId, err = fromInstanceState(s, resourceName, "id")
return err
},
),
},
// verify update to the compartment (the compartment will be switched back in the next step)
{
Config: config + compartmentIdVariableStr + compartmentIdUVariableStr + KeyResourceDependencies + DefinedTagsDependencies +
generateResourceFromRepresentationMap("oci_kms_key", "test_key", Optional, Create,
representationCopyWithNewProperties(keyRepresentation, map[string]interface{}{
"compartment_id": Representation{repType: Required, create: `${var.compartment_id_for_update}`},
})),
Check: ComposeAggregateTestCheckFuncWrapper(
resource.TestCheckResourceAttr(resourceName, "compartment_id", compartmentIdU),
resource.TestCheckResourceAttrSet(resourceName, "current_key_version"),
resource.TestCheckResourceAttr(resourceName, "display_name", "Key C"),
resource.TestCheckResourceAttr(resourceName, "freeform_tags.%", "1"),
resource.TestCheckResourceAttrSet(resourceName, "id"),
resource.TestCheckResourceAttr(resourceName, "key_shape.#", "1"),
resource.TestCheckResourceAttr(resourceName, "key_shape.0.algorithm", "AES"),
resource.TestCheckResourceAttr(resourceName, "key_shape.0.length", "16"),
resource.TestCheckResourceAttr(resourceName, "protection_mode", "SOFTWARE"),
resource.TestCheckResourceAttrSet(resourceName, "state"),
resource.TestCheckResourceAttrSet(resourceName, "time_created"),
resource.TestCheckResourceAttrSet(resourceName, "vault_id"),
func(s *terraform.State) (err error) {
resId2, err = fromInstanceState(s, resourceName, "id")
if resId != resId2 {
return fmt.Errorf("resource recreated when it was supposed to be updated")
}
return err
},
),
},
// verify updates to updatable parameters
{
Config: config + compartmentIdVariableStr + KeyResourceDependencies + DefinedTagsDependencies +
generateResourceFromRepresentationMap("oci_kms_key", "test_key", Optional, Update, keyRepresentation),
Check: ComposeAggregateTestCheckFuncWrapper(
resource.TestCheckResourceAttr(resourceName, "compartment_id", compartmentId),
resource.TestCheckResourceAttrSet(resourceName, "current_key_version"),
resource.TestCheckResourceAttr(resourceName, "display_name", "displayName2"),
resource.TestCheckResourceAttr(resourceName, "freeform_tags.%", "1"),
resource.TestCheckResourceAttrSet(resourceName, "id"),
resource.TestCheckResourceAttr(resourceName, "key_shape.#", "1"),
resource.TestCheckResourceAttr(resourceName, "key_shape.0.algorithm", "AES"),
resource.TestCheckResourceAttr(resourceName, "key_shape.0.length", "16"),
resource.TestCheckResourceAttr(resourceName, "protection_mode", "SOFTWARE"),
resource.TestCheckResourceAttrSet(resourceName, "state"),
resource.TestCheckResourceAttrSet(resourceName, "time_created"),
resource.TestCheckResourceAttrSet(resourceName, "vault_id"),
func(s *terraform.State) (err error) {
resId2, err = fromInstanceState(s, resourceName, "id")
if resId != resId2 {
return fmt.Errorf("Resource recreated when it was supposed to be updated.")
}
return err
},
),
},
// verify datasource
{
Config: config +
generateDataSourceFromRepresentationMap("oci_kms_keys", "test_keys", Optional, Update, keyDataSourceRepresentation) +
compartmentIdVariableStr + KeyResourceDependencies + DefinedTagsDependencies +
generateResourceFromRepresentationMap("oci_kms_key", "test_key", Optional, Update, keyRepresentation),
Check: ComposeAggregateTestCheckFuncWrapper(
resource.TestCheckResourceAttr(datasourceName, "algorithm", "AES"),
resource.TestCheckResourceAttr(datasourceName, "compartment_id", compartmentId),
resource.TestCheckResourceAttrSet(datasourceName, "management_endpoint"),
resource.TestCheckResourceAttr(datasourceName, "protection_mode", "SOFTWARE"),
resource.TestCheckResourceAttr(datasourceName, "length", "16"),
resource.TestCheckResourceAttr(datasourceName, "keys.#", "1"),
resource.TestCheckResourceAttr(datasourceName, "keys.0.compartment_id", compartmentId),
resource.TestCheckResourceAttr(datasourceName, "keys.0.display_name", "displayName2"),
resource.TestCheckResourceAttr(datasourceName, "keys.0.freeform_tags.%", "1"),
resource.TestCheckResourceAttrSet(datasourceName, "keys.0.id"),
resource.TestCheckResourceAttr(datasourceName, "keys.0.protection_mode", "SOFTWARE"),
resource.TestCheckResourceAttrSet(datasourceName, "keys.0.state"),
resource.TestCheckResourceAttrSet(datasourceName, "keys.0.time_created"),
resource.TestCheckResourceAttrSet(datasourceName, "keys.0.vault_id"),
),
},
// verify singular datasource
{
Config: config +
generateDataSourceFromRepresentationMap("oci_kms_key", "test_key", Required, Create, keySingularDataSourceRepresentation) +
compartmentIdVariableStr + KeyResourceConfig + DefinedTagsDependencies,
Check: ComposeAggregateTestCheckFuncWrapper(
resource.TestCheckResourceAttrSet(singularDatasourceName, "key_id"),
resource.TestCheckResourceAttr(singularDatasourceName, "compartment_id", compartmentId),
resource.TestCheckResourceAttrSet(singularDatasourceName, "current_key_version"),
resource.TestCheckResourceAttr(singularDatasourceName, "display_name", "displayName2"),
resource.TestCheckResourceAttr(singularDatasourceName, "freeform_tags.%", "1"),
resource.TestCheckResourceAttrSet(singularDatasourceName, "id"),
resource.TestCheckResourceAttrSet(singularDatasourceName, "is_primary"),
resource.TestCheckResourceAttr(singularDatasourceName, "key_shape.#", "1"),
resource.TestCheckResourceAttr(singularDatasourceName, "key_shape.0.algorithm", "AES"),
resource.TestCheckResourceAttr(singularDatasourceName, "key_shape.0.length", "16"),
resource.TestCheckResourceAttr(singularDatasourceName, "protection_mode", "SOFTWARE"),
resource.TestCheckResourceAttrSet(singularDatasourceName, "state"),
resource.TestCheckResourceAttrSet(singularDatasourceName, "time_created"),
resource.TestCheckResourceAttrSet(singularDatasourceName, "vault_id"),
),
},
// remove singular datasource from previous step so that it doesn't conflict with import tests
{
Config: config + compartmentIdVariableStr + KeyResourceConfig + DefinedTagsDependencies,
},
// revert the updates
{
Config: config + compartmentIdVariableStr + KeyResourceDependencies + DefinedTagsDependencies +
generateResourceFromRepresentationMap("oci_kms_key", "test_key", Optional, Create, keyRepresentation),
Check: ComposeAggregateTestCheckFuncWrapper(
resource.TestCheckResourceAttr(resourceName, "display_name", "Key C"),
resource.TestCheckResourceAttr(resourceName, "state", "ENABLED"),
func(s *terraform.State) (err error) {
resId2, err = fromInstanceState(s, resourceName, "id")
if resId != resId2 {
return fmt.Errorf("Resource recreated when it was supposed to be updated.")
}
return err
},
),
},
// verify resource import
{
Config: config,
ImportState: true,
ImportStateVerify: true,
ImportStateIdFunc: keyImportId,
ImportStateVerifyIgnore: []string{
"desired_state",
"time_of_deletion",
"replica_details",
},
ResourceName: resourceName,
},
},
})
}
func testAccCheckKMSKeyDestroy(s *terraform.State) error {
noResourceFound := true
for _, rs := range s.RootModule().Resources {
if rs.Type == "oci_kms_key" {
client, err := testAccProvider.Meta().(*OracleClients).KmsManagementClient(rs.Primary.Attributes["management_endpoint"])
if err != nil {
return err
}
noResourceFound = false
request := oci_kms.GetKeyRequest{}
tmp := rs.Primary.ID
request.KeyId = &tmp
request.RequestMetadata.RetryPolicy = getRetryPolicy(true, "kms")
response, err := client.GetKey(context.Background(), request)
if err == nil {
deletedLifecycleStates := map[string]bool{
string(oci_kms.KeyLifecycleStateSchedulingDeletion): true,
string(oci_kms.KeyLifecycleStatePendingDeletion): true,
}
if _, ok := deletedLifecycleStates[string(response.LifecycleState)]; !ok {
//resource lifecycle state is not in expected deleted lifecycle states.
return fmt.Errorf("resource lifecycle state: %s is not in expected deleted lifecycle states", response.LifecycleState)
}
if !response.TimeOfDeletion.Equal(deletionTime) && !httpreplay.ModeRecordReplay() {
return fmt.Errorf("resource time_of_deletion: %s is not set to %s", response.TimeOfDeletion.Format(time.RFC3339Nano), deletionTime.Format(time.RFC3339Nano))
}
//resource lifecycle state is in expected deleted lifecycle states. continue with next one.
continue
}
//Verify that exception is for '404 not found'.
if failure, isServiceError := common.IsServiceError(err); !isServiceError || failure.GetHTTPStatusCode() != 404 {
return err
}
}
}
if noResourceFound {
return fmt.Errorf("at least one resource was expected from the state file, but could not be found")
}
return nil
}
func keyImportId(state *terraform.State) (string, error) {
for _, rs := range state.RootModule().Resources {
if rs.Type == "oci_kms_key" {
return fmt.Sprintf("managementEndpoint/%s/keys/%s", rs.Primary.Attributes["management_endpoint"], rs.Primary.ID), nil
}
}
return "", fmt.Errorf("unable to create import id as no resource of type oci_kms_key in state")
}
|
oracle/terraform-provider-baremetal
|
oci/kms_key_test.go
|
GO
|
mpl-2.0
| 18,702 |
package org.bear.bookstore.concurrent;
import java.util.PriorityQueue;
public class PriorityQueueTest {
public static void main(String[] args) {
PriorityQueue<String> queue = new PriorityQueue<>((a,b)->{
return a.compareTo(b);
});
queue.add("a");
queue.add("x");
queue.add("c");
queue.add("e");
queue.add("a");
System.out.println(queue.poll());
System.out.println(queue.poll());
System.out.println(queue.poll());
int x = 15 & (("abcd".hashCode()) ^ ("abcd".hashCode() >>> 16));
System.out.println(Integer.toBinaryString("abcd".hashCode()));
System.out.println(Integer.toBinaryString("abcd".hashCode() >>> 16));
System.out.println(Integer.toBinaryString(("abcd".hashCode()) ^ ("abcd".hashCode() >>> 16)));
System.out.println(Integer.toBinaryString(15));
System.out.println(x);
}
}
|
zhougithui/bookstore-single
|
src/test/java/org/bear/bookstore/concurrent/PriorityQueueTest.java
|
Java
|
mpl-2.0
| 831 |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.22.0
// protoc v3.11.2
// source: google/monitoring/v3/alert.proto
package monitoring
import (
reflect "reflect"
sync "sync"
proto "github.com/golang/protobuf/proto"
duration "github.com/golang/protobuf/ptypes/duration"
wrappers "github.com/golang/protobuf/ptypes/wrappers"
_ "google.golang.org/genproto/googleapis/api/annotations"
status "google.golang.org/genproto/googleapis/rpc/status"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// This is a compile-time assertion that a sufficiently up-to-date version
// of the legacy proto package is being used.
const _ = proto.ProtoPackageIsVersion4
// Operators for combining conditions.
type AlertPolicy_ConditionCombinerType int32
const (
// An unspecified combiner.
AlertPolicy_COMBINE_UNSPECIFIED AlertPolicy_ConditionCombinerType = 0
// Combine conditions using the logical `AND` operator. An
// incident is created only if all the conditions are met
// simultaneously. This combiner is satisfied if all conditions are
// met, even if they are met on completely different resources.
AlertPolicy_AND AlertPolicy_ConditionCombinerType = 1
// Combine conditions using the logical `OR` operator. An incident
// is created if any of the listed conditions is met.
AlertPolicy_OR AlertPolicy_ConditionCombinerType = 2
// Combine conditions using logical `AND` operator, but unlike the regular
// `AND` option, an incident is created only if all conditions are met
// simultaneously on at least one resource.
AlertPolicy_AND_WITH_MATCHING_RESOURCE AlertPolicy_ConditionCombinerType = 3
)
// Enum value maps for AlertPolicy_ConditionCombinerType.
var (
AlertPolicy_ConditionCombinerType_name = map[int32]string{
0: "COMBINE_UNSPECIFIED",
1: "AND",
2: "OR",
3: "AND_WITH_MATCHING_RESOURCE",
}
AlertPolicy_ConditionCombinerType_value = map[string]int32{
"COMBINE_UNSPECIFIED": 0,
"AND": 1,
"OR": 2,
"AND_WITH_MATCHING_RESOURCE": 3,
}
)
func (x AlertPolicy_ConditionCombinerType) Enum() *AlertPolicy_ConditionCombinerType {
p := new(AlertPolicy_ConditionCombinerType)
*p = x
return p
}
func (x AlertPolicy_ConditionCombinerType) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (AlertPolicy_ConditionCombinerType) Descriptor() protoreflect.EnumDescriptor {
return file_google_monitoring_v3_alert_proto_enumTypes[0].Descriptor()
}
func (AlertPolicy_ConditionCombinerType) Type() protoreflect.EnumType {
return &file_google_monitoring_v3_alert_proto_enumTypes[0]
}
func (x AlertPolicy_ConditionCombinerType) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use AlertPolicy_ConditionCombinerType.Descriptor instead.
func (AlertPolicy_ConditionCombinerType) EnumDescriptor() ([]byte, []int) {
return file_google_monitoring_v3_alert_proto_rawDescGZIP(), []int{0, 0}
}
// A description of the conditions under which some aspect of your system is
// considered to be "unhealthy" and the ways to notify people or services about
// this state. For an overview of alert policies, see
// [Introduction to Alerting](https://cloud.google.com/monitoring/alerts/).
type AlertPolicy struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// Required if the policy exists. The resource name for this policy. The
// format is:
//
// projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[ALERT_POLICY_ID]
//
// `[ALERT_POLICY_ID]` is assigned by Stackdriver Monitoring when the policy
// is created. When calling the
// [alertPolicies.create][google.monitoring.v3.AlertPolicyService.CreateAlertPolicy]
// method, do not include the `name` field in the alerting policy passed as
// part of the request.
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
// A short name or phrase used to identify the policy in dashboards,
// notifications, and incidents. To avoid confusion, don't use the same
// display name for multiple policies in the same project. The name is
// limited to 512 Unicode characters.
DisplayName string `protobuf:"bytes,2,opt,name=display_name,json=displayName,proto3" json:"display_name,omitempty"`
// Documentation that is included with notifications and incidents related to
// this policy. Best practice is for the documentation to include information
// to help responders understand, mitigate, escalate, and correct the
// underlying problems detected by the alerting policy. Notification channels
// that have limited capacity might not show this documentation.
Documentation *AlertPolicy_Documentation `protobuf:"bytes,13,opt,name=documentation,proto3" json:"documentation,omitempty"`
// User-supplied key/value data to be used for organizing and
// identifying the `AlertPolicy` objects.
//
// The field can contain up to 64 entries. Each key and value is limited to
// 63 Unicode characters or 128 bytes, whichever is smaller. Labels and
// values can contain only lowercase letters, numerals, underscores, and
// dashes. Keys must begin with a letter.
UserLabels map[string]string `protobuf:"bytes,16,rep,name=user_labels,json=userLabels,proto3" json:"user_labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
// A list of conditions for the policy. The conditions are combined by AND or
// OR according to the `combiner` field. If the combined conditions evaluate
// to true, then an incident is created. A policy can have from one to six
// conditions.
// If `condition_time_series_query_language` is present, it must be the only
// `condition`.
Conditions []*AlertPolicy_Condition `protobuf:"bytes,12,rep,name=conditions,proto3" json:"conditions,omitempty"`
// How to combine the results of multiple conditions to determine if an
// incident should be opened.
// If `condition_time_series_query_language` is present, this must be
// `COMBINE_UNSPECIFIED`.
Combiner AlertPolicy_ConditionCombinerType `protobuf:"varint,6,opt,name=combiner,proto3,enum=google.monitoring.v3.AlertPolicy_ConditionCombinerType" json:"combiner,omitempty"`
// Whether or not the policy is enabled. On write, the default interpretation
// if unset is that the policy is enabled. On read, clients should not make
// any assumption about the state if it has not been populated. The
// field should always be populated on List and Get operations, unless
// a field projection has been specified that strips it out.
Enabled *wrappers.BoolValue `protobuf:"bytes,17,opt,name=enabled,proto3" json:"enabled,omitempty"`
// Read-only description of how the alert policy is invalid. OK if the alert
// policy is valid. If not OK, the alert policy will not generate incidents.
Validity *status.Status `protobuf:"bytes,18,opt,name=validity,proto3" json:"validity,omitempty"`
// Identifies the notification channels to which notifications should be sent
// when incidents are opened or closed or when new violations occur on
// an already opened incident. Each element of this array corresponds to
// the `name` field in each of the
// [`NotificationChannel`][google.monitoring.v3.NotificationChannel]
// objects that are returned from the [`ListNotificationChannels`]
// [google.monitoring.v3.NotificationChannelService.ListNotificationChannels]
// method. The format of the entries in this field is:
//
// projects/[PROJECT_ID_OR_NUMBER]/notificationChannels/[CHANNEL_ID]
NotificationChannels []string `protobuf:"bytes,14,rep,name=notification_channels,json=notificationChannels,proto3" json:"notification_channels,omitempty"`
// A read-only record of the creation of the alerting policy. If provided
// in a call to create or update, this field will be ignored.
CreationRecord *MutationRecord `protobuf:"bytes,10,opt,name=creation_record,json=creationRecord,proto3" json:"creation_record,omitempty"`
// A read-only record of the most recent change to the alerting policy. If
// provided in a call to create or update, this field will be ignored.
MutationRecord *MutationRecord `protobuf:"bytes,11,opt,name=mutation_record,json=mutationRecord,proto3" json:"mutation_record,omitempty"`
}
func (x *AlertPolicy) Reset() {
*x = AlertPolicy{}
if protoimpl.UnsafeEnabled {
mi := &file_google_monitoring_v3_alert_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AlertPolicy) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AlertPolicy) ProtoMessage() {}
func (x *AlertPolicy) ProtoReflect() protoreflect.Message {
mi := &file_google_monitoring_v3_alert_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AlertPolicy.ProtoReflect.Descriptor instead.
func (*AlertPolicy) Descriptor() ([]byte, []int) {
return file_google_monitoring_v3_alert_proto_rawDescGZIP(), []int{0}
}
func (x *AlertPolicy) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *AlertPolicy) GetDisplayName() string {
if x != nil {
return x.DisplayName
}
return ""
}
func (x *AlertPolicy) GetDocumentation() *AlertPolicy_Documentation {
if x != nil {
return x.Documentation
}
return nil
}
func (x *AlertPolicy) GetUserLabels() map[string]string {
if x != nil {
return x.UserLabels
}
return nil
}
func (x *AlertPolicy) GetConditions() []*AlertPolicy_Condition {
if x != nil {
return x.Conditions
}
return nil
}
func (x *AlertPolicy) GetCombiner() AlertPolicy_ConditionCombinerType {
if x != nil {
return x.Combiner
}
return AlertPolicy_COMBINE_UNSPECIFIED
}
func (x *AlertPolicy) GetEnabled() *wrappers.BoolValue {
if x != nil {
return x.Enabled
}
return nil
}
func (x *AlertPolicy) GetValidity() *status.Status {
if x != nil {
return x.Validity
}
return nil
}
func (x *AlertPolicy) GetNotificationChannels() []string {
if x != nil {
return x.NotificationChannels
}
return nil
}
func (x *AlertPolicy) GetCreationRecord() *MutationRecord {
if x != nil {
return x.CreationRecord
}
return nil
}
func (x *AlertPolicy) GetMutationRecord() *MutationRecord {
if x != nil {
return x.MutationRecord
}
return nil
}
// A content string and a MIME type that describes the content string's
// format.
type AlertPolicy_Documentation struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// The text of the documentation, interpreted according to `mime_type`.
// The content may not exceed 8,192 Unicode characters and may not exceed
// more than 10,240 bytes when encoded in UTF-8 format, whichever is
// smaller.
Content string `protobuf:"bytes,1,opt,name=content,proto3" json:"content,omitempty"`
// The format of the `content` field. Presently, only the value
// `"text/markdown"` is supported. See
// [Markdown](https://en.wikipedia.org/wiki/Markdown) for more information.
MimeType string `protobuf:"bytes,2,opt,name=mime_type,json=mimeType,proto3" json:"mime_type,omitempty"`
}
func (x *AlertPolicy_Documentation) Reset() {
*x = AlertPolicy_Documentation{}
if protoimpl.UnsafeEnabled {
mi := &file_google_monitoring_v3_alert_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AlertPolicy_Documentation) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AlertPolicy_Documentation) ProtoMessage() {}
func (x *AlertPolicy_Documentation) ProtoReflect() protoreflect.Message {
mi := &file_google_monitoring_v3_alert_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AlertPolicy_Documentation.ProtoReflect.Descriptor instead.
func (*AlertPolicy_Documentation) Descriptor() ([]byte, []int) {
return file_google_monitoring_v3_alert_proto_rawDescGZIP(), []int{0, 0}
}
func (x *AlertPolicy_Documentation) GetContent() string {
if x != nil {
return x.Content
}
return ""
}
func (x *AlertPolicy_Documentation) GetMimeType() string {
if x != nil {
return x.MimeType
}
return ""
}
// A condition is a true/false test that determines when an alerting policy
// should open an incident. If a condition evaluates to true, it signifies
// that something is wrong.
type AlertPolicy_Condition struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// Required if the condition exists. The unique resource name for this
// condition. Its format is:
//
// projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[POLICY_ID]/conditions/[CONDITION_ID]
//
// `[CONDITION_ID]` is assigned by Stackdriver Monitoring when the
// condition is created as part of a new or updated alerting policy.
//
// When calling the
// [alertPolicies.create][google.monitoring.v3.AlertPolicyService.CreateAlertPolicy]
// method, do not include the `name` field in the conditions of the
// requested alerting policy. Stackdriver Monitoring creates the
// condition identifiers and includes them in the new policy.
//
// When calling the
// [alertPolicies.update][google.monitoring.v3.AlertPolicyService.UpdateAlertPolicy]
// method to update a policy, including a condition `name` causes the
// existing condition to be updated. Conditions without names are added to
// the updated policy. Existing conditions are deleted if they are not
// updated.
//
// Best practice is to preserve `[CONDITION_ID]` if you make only small
// changes, such as those to condition thresholds, durations, or trigger
// values. Otherwise, treat the change as a new condition and let the
// existing condition be deleted.
Name string `protobuf:"bytes,12,opt,name=name,proto3" json:"name,omitempty"`
// A short name or phrase used to identify the condition in dashboards,
// notifications, and incidents. To avoid confusion, don't use the same
// display name for multiple conditions in the same policy.
DisplayName string `protobuf:"bytes,6,opt,name=display_name,json=displayName,proto3" json:"display_name,omitempty"`
// Only one of the following condition types will be specified.
//
// Types that are assignable to Condition:
// *AlertPolicy_Condition_ConditionThreshold
// *AlertPolicy_Condition_ConditionAbsent
Condition isAlertPolicy_Condition_Condition `protobuf_oneof:"condition"`
}
func (x *AlertPolicy_Condition) Reset() {
*x = AlertPolicy_Condition{}
if protoimpl.UnsafeEnabled {
mi := &file_google_monitoring_v3_alert_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AlertPolicy_Condition) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AlertPolicy_Condition) ProtoMessage() {}
func (x *AlertPolicy_Condition) ProtoReflect() protoreflect.Message {
mi := &file_google_monitoring_v3_alert_proto_msgTypes[2]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AlertPolicy_Condition.ProtoReflect.Descriptor instead.
func (*AlertPolicy_Condition) Descriptor() ([]byte, []int) {
return file_google_monitoring_v3_alert_proto_rawDescGZIP(), []int{0, 1}
}
func (x *AlertPolicy_Condition) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *AlertPolicy_Condition) GetDisplayName() string {
if x != nil {
return x.DisplayName
}
return ""
}
func (m *AlertPolicy_Condition) GetCondition() isAlertPolicy_Condition_Condition {
if m != nil {
return m.Condition
}
return nil
}
func (x *AlertPolicy_Condition) GetConditionThreshold() *AlertPolicy_Condition_MetricThreshold {
if x, ok := x.GetCondition().(*AlertPolicy_Condition_ConditionThreshold); ok {
return x.ConditionThreshold
}
return nil
}
func (x *AlertPolicy_Condition) GetConditionAbsent() *AlertPolicy_Condition_MetricAbsence {
if x, ok := x.GetCondition().(*AlertPolicy_Condition_ConditionAbsent); ok {
return x.ConditionAbsent
}
return nil
}
type isAlertPolicy_Condition_Condition interface {
isAlertPolicy_Condition_Condition()
}
type AlertPolicy_Condition_ConditionThreshold struct {
// A condition that compares a time series against a threshold.
ConditionThreshold *AlertPolicy_Condition_MetricThreshold `protobuf:"bytes,1,opt,name=condition_threshold,json=conditionThreshold,proto3,oneof"`
}
type AlertPolicy_Condition_ConditionAbsent struct {
// A condition that checks that a time series continues to
// receive new data points.
ConditionAbsent *AlertPolicy_Condition_MetricAbsence `protobuf:"bytes,2,opt,name=condition_absent,json=conditionAbsent,proto3,oneof"`
}
func (*AlertPolicy_Condition_ConditionThreshold) isAlertPolicy_Condition_Condition() {}
func (*AlertPolicy_Condition_ConditionAbsent) isAlertPolicy_Condition_Condition() {}
// Specifies how many time series must fail a predicate to trigger a
// condition. If not specified, then a `{count: 1}` trigger is used.
type AlertPolicy_Condition_Trigger struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// A type of trigger.
//
// Types that are assignable to Type:
// *AlertPolicy_Condition_Trigger_Count
// *AlertPolicy_Condition_Trigger_Percent
Type isAlertPolicy_Condition_Trigger_Type `protobuf_oneof:"type"`
}
func (x *AlertPolicy_Condition_Trigger) Reset() {
*x = AlertPolicy_Condition_Trigger{}
if protoimpl.UnsafeEnabled {
mi := &file_google_monitoring_v3_alert_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AlertPolicy_Condition_Trigger) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AlertPolicy_Condition_Trigger) ProtoMessage() {}
func (x *AlertPolicy_Condition_Trigger) ProtoReflect() protoreflect.Message {
mi := &file_google_monitoring_v3_alert_proto_msgTypes[4]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AlertPolicy_Condition_Trigger.ProtoReflect.Descriptor instead.
func (*AlertPolicy_Condition_Trigger) Descriptor() ([]byte, []int) {
return file_google_monitoring_v3_alert_proto_rawDescGZIP(), []int{0, 1, 0}
}
func (m *AlertPolicy_Condition_Trigger) GetType() isAlertPolicy_Condition_Trigger_Type {
if m != nil {
return m.Type
}
return nil
}
func (x *AlertPolicy_Condition_Trigger) GetCount() int32 {
if x, ok := x.GetType().(*AlertPolicy_Condition_Trigger_Count); ok {
return x.Count
}
return 0
}
func (x *AlertPolicy_Condition_Trigger) GetPercent() float64 {
if x, ok := x.GetType().(*AlertPolicy_Condition_Trigger_Percent); ok {
return x.Percent
}
return 0
}
type isAlertPolicy_Condition_Trigger_Type interface {
isAlertPolicy_Condition_Trigger_Type()
}
type AlertPolicy_Condition_Trigger_Count struct {
// The absolute number of time series that must fail
// the predicate for the condition to be triggered.
Count int32 `protobuf:"varint,1,opt,name=count,proto3,oneof"`
}
type AlertPolicy_Condition_Trigger_Percent struct {
// The percentage of time series that must fail the
// predicate for the condition to be triggered.
Percent float64 `protobuf:"fixed64,2,opt,name=percent,proto3,oneof"`
}
func (*AlertPolicy_Condition_Trigger_Count) isAlertPolicy_Condition_Trigger_Type() {}
func (*AlertPolicy_Condition_Trigger_Percent) isAlertPolicy_Condition_Trigger_Type() {}
// A condition type that compares a collection of time series
// against a threshold.
type AlertPolicy_Condition_MetricThreshold struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// A [filter](https://cloud.google.com/monitoring/api/v3/filters) that
// identifies which time series should be compared with the threshold.
//
// The filter is similar to the one that is specified in the
// [`ListTimeSeries`
// request](https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list)
// (that call is useful to verify the time series that will be retrieved /
// processed) and must specify the metric type and optionally may contain
// restrictions on resource type, resource labels, and metric labels.
// This field may not exceed 2048 Unicode characters in length.
Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"`
// Specifies the alignment of data points in individual time series as
// well as how to combine the retrieved time series together (such as
// when aggregating multiple streams on each resource to a single
// stream for each resource or when aggregating streams across all
// members of a group of resrouces). Multiple aggregations
// are applied in the order specified.
//
// This field is similar to the one in the [`ListTimeSeries`
// request](https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list).
// It is advisable to use the `ListTimeSeries` method when debugging this
// field.
Aggregations []*Aggregation `protobuf:"bytes,8,rep,name=aggregations,proto3" json:"aggregations,omitempty"`
// A [filter](https://cloud.google.com/monitoring/api/v3/filters) that
// identifies a time series that should be used as the denominator of a
// ratio that will be compared with the threshold. If a
// `denominator_filter` is specified, the time series specified by the
// `filter` field will be used as the numerator.
//
// The filter must specify the metric type and optionally may contain
// restrictions on resource type, resource labels, and metric labels.
// This field may not exceed 2048 Unicode characters in length.
DenominatorFilter string `protobuf:"bytes,9,opt,name=denominator_filter,json=denominatorFilter,proto3" json:"denominator_filter,omitempty"`
// Specifies the alignment of data points in individual time series
// selected by `denominatorFilter` as
// well as how to combine the retrieved time series together (such as
// when aggregating multiple streams on each resource to a single
// stream for each resource or when aggregating streams across all
// members of a group of resources).
//
// When computing ratios, the `aggregations` and
// `denominator_aggregations` fields must use the same alignment period
// and produce time series that have the same periodicity and labels.
DenominatorAggregations []*Aggregation `protobuf:"bytes,10,rep,name=denominator_aggregations,json=denominatorAggregations,proto3" json:"denominator_aggregations,omitempty"`
// The comparison to apply between the time series (indicated by `filter`
// and `aggregation`) and the threshold (indicated by `threshold_value`).
// The comparison is applied on each time series, with the time series
// on the left-hand side and the threshold on the right-hand side.
//
// Only `COMPARISON_LT` and `COMPARISON_GT` are supported currently.
Comparison ComparisonType `protobuf:"varint,4,opt,name=comparison,proto3,enum=google.monitoring.v3.ComparisonType" json:"comparison,omitempty"`
// A value against which to compare the time series.
ThresholdValue float64 `protobuf:"fixed64,5,opt,name=threshold_value,json=thresholdValue,proto3" json:"threshold_value,omitempty"`
// The amount of time that a time series must violate the
// threshold to be considered failing. Currently, only values
// that are a multiple of a minute--e.g., 0, 60, 120, or 300
// seconds--are supported. If an invalid value is given, an
// error will be returned. When choosing a duration, it is useful to
// keep in mind the frequency of the underlying time series data
// (which may also be affected by any alignments specified in the
// `aggregations` field); a good duration is long enough so that a single
// outlier does not generate spurious alerts, but short enough that
// unhealthy states are detected and alerted on quickly.
Duration *duration.Duration `protobuf:"bytes,6,opt,name=duration,proto3" json:"duration,omitempty"`
// The number/percent of time series for which the comparison must hold
// in order for the condition to trigger. If unspecified, then the
// condition will trigger if the comparison is true for any of the
// time series that have been identified by `filter` and `aggregations`,
// or by the ratio, if `denominator_filter` and `denominator_aggregations`
// are specified.
Trigger *AlertPolicy_Condition_Trigger `protobuf:"bytes,7,opt,name=trigger,proto3" json:"trigger,omitempty"`
}
func (x *AlertPolicy_Condition_MetricThreshold) Reset() {
*x = AlertPolicy_Condition_MetricThreshold{}
if protoimpl.UnsafeEnabled {
mi := &file_google_monitoring_v3_alert_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AlertPolicy_Condition_MetricThreshold) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AlertPolicy_Condition_MetricThreshold) ProtoMessage() {}
func (x *AlertPolicy_Condition_MetricThreshold) ProtoReflect() protoreflect.Message {
mi := &file_google_monitoring_v3_alert_proto_msgTypes[5]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AlertPolicy_Condition_MetricThreshold.ProtoReflect.Descriptor instead.
func (*AlertPolicy_Condition_MetricThreshold) Descriptor() ([]byte, []int) {
return file_google_monitoring_v3_alert_proto_rawDescGZIP(), []int{0, 1, 1}
}
func (x *AlertPolicy_Condition_MetricThreshold) GetFilter() string {
if x != nil {
return x.Filter
}
return ""
}
func (x *AlertPolicy_Condition_MetricThreshold) GetAggregations() []*Aggregation {
if x != nil {
return x.Aggregations
}
return nil
}
func (x *AlertPolicy_Condition_MetricThreshold) GetDenominatorFilter() string {
if x != nil {
return x.DenominatorFilter
}
return ""
}
func (x *AlertPolicy_Condition_MetricThreshold) GetDenominatorAggregations() []*Aggregation {
if x != nil {
return x.DenominatorAggregations
}
return nil
}
func (x *AlertPolicy_Condition_MetricThreshold) GetComparison() ComparisonType {
if x != nil {
return x.Comparison
}
return ComparisonType_COMPARISON_UNSPECIFIED
}
func (x *AlertPolicy_Condition_MetricThreshold) GetThresholdValue() float64 {
if x != nil {
return x.ThresholdValue
}
return 0
}
func (x *AlertPolicy_Condition_MetricThreshold) GetDuration() *duration.Duration {
if x != nil {
return x.Duration
}
return nil
}
func (x *AlertPolicy_Condition_MetricThreshold) GetTrigger() *AlertPolicy_Condition_Trigger {
if x != nil {
return x.Trigger
}
return nil
}
// A condition type that checks that monitored resources
// are reporting data. The configuration defines a metric and
// a set of monitored resources. The predicate is considered in violation
// when a time series for the specified metric of a monitored
// resource does not include any data in the specified `duration`.
type AlertPolicy_Condition_MetricAbsence struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// A [filter](https://cloud.google.com/monitoring/api/v3/filters) that
// identifies which time series should be compared with the threshold.
//
// The filter is similar to the one that is specified in the
// [`ListTimeSeries`
// request](https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list)
// (that call is useful to verify the time series that will be retrieved /
// processed) and must specify the metric type and optionally may contain
// restrictions on resource type, resource labels, and metric labels.
// This field may not exceed 2048 Unicode characters in length.
Filter string `protobuf:"bytes,1,opt,name=filter,proto3" json:"filter,omitempty"`
// Specifies the alignment of data points in individual time series as
// well as how to combine the retrieved time series together (such as
// when aggregating multiple streams on each resource to a single
// stream for each resource or when aggregating streams across all
// members of a group of resrouces). Multiple aggregations
// are applied in the order specified.
//
// This field is similar to the one in the [`ListTimeSeries`
// request](https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list).
// It is advisable to use the `ListTimeSeries` method when debugging this
// field.
Aggregations []*Aggregation `protobuf:"bytes,5,rep,name=aggregations,proto3" json:"aggregations,omitempty"`
// The amount of time that a time series must fail to report new
// data to be considered failing. Currently, only values that
// are a multiple of a minute--e.g. 60, 120, or 300
// seconds--are supported. If an invalid value is given, an
// error will be returned. The `Duration.nanos` field is
// ignored.
Duration *duration.Duration `protobuf:"bytes,2,opt,name=duration,proto3" json:"duration,omitempty"`
// The number/percent of time series for which the comparison must hold
// in order for the condition to trigger. If unspecified, then the
// condition will trigger if the comparison is true for any of the
// time series that have been identified by `filter` and `aggregations`.
Trigger *AlertPolicy_Condition_Trigger `protobuf:"bytes,3,opt,name=trigger,proto3" json:"trigger,omitempty"`
}
func (x *AlertPolicy_Condition_MetricAbsence) Reset() {
*x = AlertPolicy_Condition_MetricAbsence{}
if protoimpl.UnsafeEnabled {
mi := &file_google_monitoring_v3_alert_proto_msgTypes[6]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AlertPolicy_Condition_MetricAbsence) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AlertPolicy_Condition_MetricAbsence) ProtoMessage() {}
func (x *AlertPolicy_Condition_MetricAbsence) ProtoReflect() protoreflect.Message {
mi := &file_google_monitoring_v3_alert_proto_msgTypes[6]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AlertPolicy_Condition_MetricAbsence.ProtoReflect.Descriptor instead.
func (*AlertPolicy_Condition_MetricAbsence) Descriptor() ([]byte, []int) {
return file_google_monitoring_v3_alert_proto_rawDescGZIP(), []int{0, 1, 2}
}
func (x *AlertPolicy_Condition_MetricAbsence) GetFilter() string {
if x != nil {
return x.Filter
}
return ""
}
func (x *AlertPolicy_Condition_MetricAbsence) GetAggregations() []*Aggregation {
if x != nil {
return x.Aggregations
}
return nil
}
func (x *AlertPolicy_Condition_MetricAbsence) GetDuration() *duration.Duration {
if x != nil {
return x.Duration
}
return nil
}
func (x *AlertPolicy_Condition_MetricAbsence) GetTrigger() *AlertPolicy_Condition_Trigger {
if x != nil {
return x.Trigger
}
return nil
}
var File_google_monitoring_v3_alert_proto protoreflect.FileDescriptor
var file_google_monitoring_v3_alert_proto_rawDesc = []byte{
0x0a, 0x20, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72,
0x69, 0x6e, 0x67, 0x2f, 0x76, 0x33, 0x2f, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x2e, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x12, 0x14, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74,
0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x1a, 0x19, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65,
0x2f, 0x61, 0x70, 0x69, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x1a, 0x21, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x6d, 0x6f, 0x6e, 0x69,
0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2f, 0x76, 0x33, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e,
0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x2a, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x6d,
0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2f, 0x76, 0x33, 0x2f, 0x6d, 0x75, 0x74,
0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x2e, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x62, 0x75, 0x66, 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x1a, 0x17, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x72, 0x70, 0x63, 0x2f, 0x73,
0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xf7, 0x13, 0x0a, 0x0b,
0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x12, 0x12, 0x0a, 0x04, 0x6e,
0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12,
0x21, 0x0a, 0x0c, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18,
0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x4e, 0x61,
0x6d, 0x65, 0x12, 0x55, 0x0a, 0x0d, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74,
0x69, 0x6f, 0x6e, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x67, 0x6f, 0x6f, 0x67,
0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33,
0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x44, 0x6f, 0x63,
0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0d, 0x64, 0x6f, 0x63, 0x75,
0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x52, 0x0a, 0x0b, 0x75, 0x73, 0x65,
0x72, 0x5f, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x73, 0x18, 0x10, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x31,
0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69,
0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63,
0x79, 0x2e, 0x55, 0x73, 0x65, 0x72, 0x4c, 0x61, 0x62, 0x65, 0x6c, 0x73, 0x45, 0x6e, 0x74, 0x72,
0x79, 0x52, 0x0a, 0x75, 0x73, 0x65, 0x72, 0x4c, 0x61, 0x62, 0x65, 0x6c, 0x73, 0x12, 0x4b, 0x0a,
0x0a, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x0c, 0x20, 0x03, 0x28,
0x0b, 0x32, 0x2b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74,
0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f,
0x6c, 0x69, 0x63, 0x79, 0x2e, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0a,
0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x53, 0x0a, 0x08, 0x63, 0x6f,
0x6d, 0x62, 0x69, 0x6e, 0x65, 0x72, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x37, 0x2e, 0x67,
0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67,
0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e,
0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x65,
0x72, 0x54, 0x79, 0x70, 0x65, 0x52, 0x08, 0x63, 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x65, 0x72, 0x12,
0x34, 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x11, 0x20, 0x01, 0x28, 0x0b,
0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62,
0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x07, 0x65, 0x6e,
0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x2e, 0x0a, 0x08, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x69, 0x74,
0x79, 0x18, 0x12, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65,
0x2e, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x08, 0x76, 0x61, 0x6c,
0x69, 0x64, 0x69, 0x74, 0x79, 0x12, 0x33, 0x0a, 0x15, 0x6e, 0x6f, 0x74, 0x69, 0x66, 0x69, 0x63,
0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x73, 0x18, 0x0e,
0x20, 0x03, 0x28, 0x09, 0x52, 0x14, 0x6e, 0x6f, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69,
0x6f, 0x6e, 0x43, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x73, 0x12, 0x4d, 0x0a, 0x0f, 0x63, 0x72,
0x65, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x18, 0x0a, 0x20,
0x01, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e,
0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x4d, 0x75, 0x74, 0x61, 0x74,
0x69, 0x6f, 0x6e, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x52, 0x0e, 0x63, 0x72, 0x65, 0x61, 0x74,
0x69, 0x6f, 0x6e, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x12, 0x4d, 0x0a, 0x0f, 0x6d, 0x75, 0x74,
0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x18, 0x0b, 0x20, 0x01,
0x28, 0x0b, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69,
0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x4d, 0x75, 0x74, 0x61, 0x74, 0x69,
0x6f, 0x6e, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x52, 0x0e, 0x6d, 0x75, 0x74, 0x61, 0x74, 0x69,
0x6f, 0x6e, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x1a, 0x46, 0x0a, 0x0d, 0x44, 0x6f, 0x63, 0x75,
0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x6f, 0x6e,
0x74, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74,
0x65, 0x6e, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x6d, 0x69, 0x6d, 0x65, 0x5f, 0x74, 0x79, 0x70, 0x65,
0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x6d, 0x69, 0x6d, 0x65, 0x54, 0x79, 0x70, 0x65,
0x1a, 0xf4, 0x0a, 0x0a, 0x09, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x12,
0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61,
0x6d, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x5f, 0x6e, 0x61,
0x6d, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61,
0x79, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x6e, 0x0a, 0x13, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69,
0x6f, 0x6e, 0x5f, 0x74, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x18, 0x01, 0x20, 0x01,
0x28, 0x0b, 0x32, 0x3b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69,
0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50,
0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2e,
0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x54, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x48,
0x00, 0x52, 0x12, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x68, 0x72, 0x65,
0x73, 0x68, 0x6f, 0x6c, 0x64, 0x12, 0x66, 0x0a, 0x10, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69,
0x6f, 0x6e, 0x5f, 0x61, 0x62, 0x73, 0x65, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32,
0x39, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72,
0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69,
0x63, 0x79, 0x2e, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x4d, 0x65, 0x74,
0x72, 0x69, 0x63, 0x41, 0x62, 0x73, 0x65, 0x6e, 0x63, 0x65, 0x48, 0x00, 0x52, 0x0f, 0x63, 0x6f,
0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x41, 0x62, 0x73, 0x65, 0x6e, 0x74, 0x1a, 0x45, 0x0a,
0x07, 0x54, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x12, 0x16, 0x0a, 0x05, 0x63, 0x6f, 0x75, 0x6e,
0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x48, 0x00, 0x52, 0x05, 0x63, 0x6f, 0x75, 0x6e, 0x74,
0x12, 0x1a, 0x0a, 0x07, 0x70, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28,
0x01, 0x48, 0x00, 0x52, 0x07, 0x70, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x42, 0x06, 0x0a, 0x04,
0x74, 0x79, 0x70, 0x65, 0x1a, 0xf2, 0x03, 0x0a, 0x0f, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x54,
0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x66, 0x69, 0x6c, 0x74,
0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72,
0x12, 0x45, 0x0a, 0x0c, 0x61, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73,
0x18, 0x08, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e,
0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x67,
0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0c, 0x61, 0x67, 0x67, 0x72, 0x65,
0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x2d, 0x0a, 0x12, 0x64, 0x65, 0x6e, 0x6f, 0x6d,
0x69, 0x6e, 0x61, 0x74, 0x6f, 0x72, 0x5f, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x09, 0x20,
0x01, 0x28, 0x09, 0x52, 0x11, 0x64, 0x65, 0x6e, 0x6f, 0x6d, 0x69, 0x6e, 0x61, 0x74, 0x6f, 0x72,
0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x5c, 0x0a, 0x18, 0x64, 0x65, 0x6e, 0x6f, 0x6d, 0x69,
0x6e, 0x61, 0x74, 0x6f, 0x72, 0x5f, 0x61, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f,
0x6e, 0x73, 0x18, 0x0a, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c,
0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e,
0x41, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x17, 0x64, 0x65, 0x6e,
0x6f, 0x6d, 0x69, 0x6e, 0x61, 0x74, 0x6f, 0x72, 0x41, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74,
0x69, 0x6f, 0x6e, 0x73, 0x12, 0x44, 0x0a, 0x0a, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x72, 0x69, 0x73,
0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c,
0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e,
0x43, 0x6f, 0x6d, 0x70, 0x61, 0x72, 0x69, 0x73, 0x6f, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x52, 0x0a,
0x63, 0x6f, 0x6d, 0x70, 0x61, 0x72, 0x69, 0x73, 0x6f, 0x6e, 0x12, 0x27, 0x0a, 0x0f, 0x74, 0x68,
0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x05, 0x20,
0x01, 0x28, 0x01, 0x52, 0x0e, 0x74, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x56, 0x61,
0x6c, 0x75, 0x65, 0x12, 0x35, 0x0a, 0x08, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18,
0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70,
0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e,
0x52, 0x08, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x4d, 0x0a, 0x07, 0x74, 0x72,
0x69, 0x67, 0x67, 0x65, 0x72, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x33, 0x2e, 0x67, 0x6f,
0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e,
0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x43,
0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x54, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72,
0x52, 0x07, 0x74, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x1a, 0xf4, 0x01, 0x0a, 0x0d, 0x4d, 0x65,
0x74, 0x72, 0x69, 0x63, 0x41, 0x62, 0x73, 0x65, 0x6e, 0x63, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x66,
0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x66, 0x69, 0x6c,
0x74, 0x65, 0x72, 0x12, 0x45, 0x0a, 0x0c, 0x61, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69,
0x6f, 0x6e, 0x73, 0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x67, 0x6f, 0x6f, 0x67,
0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33,
0x2e, 0x41, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0c, 0x61, 0x67,
0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x35, 0x0a, 0x08, 0x64, 0x75,
0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67,
0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44,
0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x08, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f,
0x6e, 0x12, 0x4d, 0x0a, 0x07, 0x74, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x18, 0x03, 0x20, 0x01,
0x28, 0x0b, 0x32, 0x33, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69,
0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50,
0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2e,
0x54, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x52, 0x07, 0x74, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72,
0x3a, 0x97, 0x02, 0xea, 0x41, 0x93, 0x02, 0x0a, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72,
0x69, 0x6e, 0x67, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63,
0x6f, 0x6d, 0x2f, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x43, 0x6f,
0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x46, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74,
0x73, 0x2f, 0x7b, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x7d, 0x2f, 0x61, 0x6c, 0x65, 0x72,
0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x65, 0x73, 0x2f, 0x7b, 0x61, 0x6c, 0x65, 0x72, 0x74,
0x5f, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x7d, 0x2f, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69,
0x6f, 0x6e, 0x73, 0x2f, 0x7b, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x7d, 0x12,
0x50, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x7b,
0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x7d, 0x2f, 0x61, 0x6c,
0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x65, 0x73, 0x2f, 0x7b, 0x61, 0x6c, 0x65,
0x72, 0x74, 0x5f, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x7d, 0x2f, 0x63, 0x6f, 0x6e, 0x64, 0x69,
0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x7b, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e,
0x7d, 0x12, 0x44, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x73, 0x2f, 0x7b, 0x66, 0x6f, 0x6c, 0x64,
0x65, 0x72, 0x7d, 0x2f, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x65,
0x73, 0x2f, 0x7b, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x5f, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x7d,
0x2f, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x7b, 0x63, 0x6f, 0x6e,
0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x7d, 0x12, 0x01, 0x2a, 0x42, 0x0b, 0x0a, 0x09, 0x63, 0x6f,
0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x1a, 0x3d, 0x0a, 0x0f, 0x55, 0x73, 0x65, 0x72, 0x4c,
0x61, 0x62, 0x65, 0x6c, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65,
0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05,
0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c,
0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x61, 0x0a, 0x15, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74,
0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x65, 0x72, 0x54, 0x79, 0x70, 0x65, 0x12,
0x17, 0x0a, 0x13, 0x43, 0x4f, 0x4d, 0x42, 0x49, 0x4e, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45,
0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x07, 0x0a, 0x03, 0x41, 0x4e, 0x44, 0x10,
0x01, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x52, 0x10, 0x02, 0x12, 0x1e, 0x0a, 0x1a, 0x41, 0x4e, 0x44,
0x5f, 0x57, 0x49, 0x54, 0x48, 0x5f, 0x4d, 0x41, 0x54, 0x43, 0x48, 0x49, 0x4e, 0x47, 0x5f, 0x52,
0x45, 0x53, 0x4f, 0x55, 0x52, 0x43, 0x45, 0x10, 0x03, 0x3a, 0xc9, 0x01, 0xea, 0x41, 0xc5, 0x01,
0x0a, 0x25, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x67, 0x6f, 0x6f,
0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x41, 0x6c, 0x65, 0x72,
0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x12, 0x2f, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74,
0x73, 0x2f, 0x7b, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x7d, 0x2f, 0x61, 0x6c, 0x65, 0x72,
0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x65, 0x73, 0x2f, 0x7b, 0x61, 0x6c, 0x65, 0x72, 0x74,
0x5f, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x7d, 0x12, 0x39, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69,
0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x7b, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a,
0x61, 0x74, 0x69, 0x6f, 0x6e, 0x7d, 0x2f, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69,
0x63, 0x69, 0x65, 0x73, 0x2f, 0x7b, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x5f, 0x70, 0x6f, 0x6c, 0x69,
0x63, 0x79, 0x7d, 0x12, 0x2d, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x73, 0x2f, 0x7b, 0x66, 0x6f,
0x6c, 0x64, 0x65, 0x72, 0x7d, 0x2f, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63,
0x69, 0x65, 0x73, 0x2f, 0x7b, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x5f, 0x70, 0x6f, 0x6c, 0x69, 0x63,
0x79, 0x7d, 0x12, 0x01, 0x2a, 0x42, 0xc2, 0x01, 0x0a, 0x18, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f,
0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e,
0x76, 0x33, 0x42, 0x0a, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01,
0x5a, 0x3e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e,
0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f,
0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69,
0x6e, 0x67, 0x2f, 0x76, 0x33, 0x3b, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67,
0xaa, 0x02, 0x1a, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x2e,
0x4d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x56, 0x33, 0xca, 0x02, 0x1a,
0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x5c, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x5c, 0x4d, 0x6f, 0x6e,
0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x5c, 0x56, 0x33, 0xea, 0x02, 0x1d, 0x47, 0x6f, 0x6f,
0x67, 0x6c, 0x65, 0x3a, 0x3a, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x3a, 0x3a, 0x4d, 0x6f, 0x6e, 0x69,
0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x3a, 0x3a, 0x56, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x33,
}
var (
file_google_monitoring_v3_alert_proto_rawDescOnce sync.Once
file_google_monitoring_v3_alert_proto_rawDescData = file_google_monitoring_v3_alert_proto_rawDesc
)
func file_google_monitoring_v3_alert_proto_rawDescGZIP() []byte {
file_google_monitoring_v3_alert_proto_rawDescOnce.Do(func() {
file_google_monitoring_v3_alert_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_monitoring_v3_alert_proto_rawDescData)
})
return file_google_monitoring_v3_alert_proto_rawDescData
}
var file_google_monitoring_v3_alert_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_google_monitoring_v3_alert_proto_msgTypes = make([]protoimpl.MessageInfo, 7)
var file_google_monitoring_v3_alert_proto_goTypes = []interface{}{
(AlertPolicy_ConditionCombinerType)(0), // 0: google.monitoring.v3.AlertPolicy.ConditionCombinerType
(*AlertPolicy)(nil), // 1: google.monitoring.v3.AlertPolicy
(*AlertPolicy_Documentation)(nil), // 2: google.monitoring.v3.AlertPolicy.Documentation
(*AlertPolicy_Condition)(nil), // 3: google.monitoring.v3.AlertPolicy.Condition
nil, // 4: google.monitoring.v3.AlertPolicy.UserLabelsEntry
(*AlertPolicy_Condition_Trigger)(nil), // 5: google.monitoring.v3.AlertPolicy.Condition.Trigger
(*AlertPolicy_Condition_MetricThreshold)(nil), // 6: google.monitoring.v3.AlertPolicy.Condition.MetricThreshold
(*AlertPolicy_Condition_MetricAbsence)(nil), // 7: google.monitoring.v3.AlertPolicy.Condition.MetricAbsence
(*wrappers.BoolValue)(nil), // 8: google.protobuf.BoolValue
(*status.Status)(nil), // 9: google.rpc.Status
(*MutationRecord)(nil), // 10: google.monitoring.v3.MutationRecord
(*Aggregation)(nil), // 11: google.monitoring.v3.Aggregation
(ComparisonType)(0), // 12: google.monitoring.v3.ComparisonType
(*duration.Duration)(nil), // 13: google.protobuf.Duration
}
var file_google_monitoring_v3_alert_proto_depIdxs = []int32{
2, // 0: google.monitoring.v3.AlertPolicy.documentation:type_name -> google.monitoring.v3.AlertPolicy.Documentation
4, // 1: google.monitoring.v3.AlertPolicy.user_labels:type_name -> google.monitoring.v3.AlertPolicy.UserLabelsEntry
3, // 2: google.monitoring.v3.AlertPolicy.conditions:type_name -> google.monitoring.v3.AlertPolicy.Condition
0, // 3: google.monitoring.v3.AlertPolicy.combiner:type_name -> google.monitoring.v3.AlertPolicy.ConditionCombinerType
8, // 4: google.monitoring.v3.AlertPolicy.enabled:type_name -> google.protobuf.BoolValue
9, // 5: google.monitoring.v3.AlertPolicy.validity:type_name -> google.rpc.Status
10, // 6: google.monitoring.v3.AlertPolicy.creation_record:type_name -> google.monitoring.v3.MutationRecord
10, // 7: google.monitoring.v3.AlertPolicy.mutation_record:type_name -> google.monitoring.v3.MutationRecord
6, // 8: google.monitoring.v3.AlertPolicy.Condition.condition_threshold:type_name -> google.monitoring.v3.AlertPolicy.Condition.MetricThreshold
7, // 9: google.monitoring.v3.AlertPolicy.Condition.condition_absent:type_name -> google.monitoring.v3.AlertPolicy.Condition.MetricAbsence
11, // 10: google.monitoring.v3.AlertPolicy.Condition.MetricThreshold.aggregations:type_name -> google.monitoring.v3.Aggregation
11, // 11: google.monitoring.v3.AlertPolicy.Condition.MetricThreshold.denominator_aggregations:type_name -> google.monitoring.v3.Aggregation
12, // 12: google.monitoring.v3.AlertPolicy.Condition.MetricThreshold.comparison:type_name -> google.monitoring.v3.ComparisonType
13, // 13: google.monitoring.v3.AlertPolicy.Condition.MetricThreshold.duration:type_name -> google.protobuf.Duration
5, // 14: google.monitoring.v3.AlertPolicy.Condition.MetricThreshold.trigger:type_name -> google.monitoring.v3.AlertPolicy.Condition.Trigger
11, // 15: google.monitoring.v3.AlertPolicy.Condition.MetricAbsence.aggregations:type_name -> google.monitoring.v3.Aggregation
13, // 16: google.monitoring.v3.AlertPolicy.Condition.MetricAbsence.duration:type_name -> google.protobuf.Duration
5, // 17: google.monitoring.v3.AlertPolicy.Condition.MetricAbsence.trigger:type_name -> google.monitoring.v3.AlertPolicy.Condition.Trigger
18, // [18:18] is the sub-list for method output_type
18, // [18:18] is the sub-list for method input_type
18, // [18:18] is the sub-list for extension type_name
18, // [18:18] is the sub-list for extension extendee
0, // [0:18] is the sub-list for field type_name
}
func init() { file_google_monitoring_v3_alert_proto_init() }
func file_google_monitoring_v3_alert_proto_init() {
if File_google_monitoring_v3_alert_proto != nil {
return
}
file_google_monitoring_v3_common_proto_init()
file_google_monitoring_v3_mutation_record_proto_init()
if !protoimpl.UnsafeEnabled {
file_google_monitoring_v3_alert_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AlertPolicy); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_google_monitoring_v3_alert_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AlertPolicy_Documentation); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_google_monitoring_v3_alert_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AlertPolicy_Condition); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_google_monitoring_v3_alert_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AlertPolicy_Condition_Trigger); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_google_monitoring_v3_alert_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AlertPolicy_Condition_MetricThreshold); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_google_monitoring_v3_alert_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AlertPolicy_Condition_MetricAbsence); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
file_google_monitoring_v3_alert_proto_msgTypes[2].OneofWrappers = []interface{}{
(*AlertPolicy_Condition_ConditionThreshold)(nil),
(*AlertPolicy_Condition_ConditionAbsent)(nil),
}
file_google_monitoring_v3_alert_proto_msgTypes[4].OneofWrappers = []interface{}{
(*AlertPolicy_Condition_Trigger_Count)(nil),
(*AlertPolicy_Condition_Trigger_Percent)(nil),
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_google_monitoring_v3_alert_proto_rawDesc,
NumEnums: 1,
NumMessages: 7,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_google_monitoring_v3_alert_proto_goTypes,
DependencyIndexes: file_google_monitoring_v3_alert_proto_depIdxs,
EnumInfos: file_google_monitoring_v3_alert_proto_enumTypes,
MessageInfos: file_google_monitoring_v3_alert_proto_msgTypes,
}.Build()
File_google_monitoring_v3_alert_proto = out.File
file_google_monitoring_v3_alert_proto_rawDesc = nil
file_google_monitoring_v3_alert_proto_goTypes = nil
file_google_monitoring_v3_alert_proto_depIdxs = nil
}
|
hartsock/vault
|
vendor/google.golang.org/genproto/googleapis/monitoring/v3/alert.pb.go
|
GO
|
mpl-2.0
| 58,646 |
/*
* Copyright (c) 2013-2016, The SeedStack authors <http://seedstack.org>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
define([
'require',
'module',
'jquery',
'{lodash}/lodash',
'{angular}/angular',
'[text]!{w20-business-theme}/templates/topbar.html',
'[text]!{w20-business-theme}/templates/sidebar.html',
'{angular-sanitize}/angular-sanitize',
'{w20-core}/modules/ui',
'{w20-core}/modules/notifications',
'{w20-core}/modules/culture',
'{w20-core}/modules/utils'
], function (require, module, $, _, angular, topbarTemplate, sidebarTemplate) {
'use strict';
var w20BusinessTheme = angular.module('w20BusinessTheme', ['w20CoreCulture', 'w20CoreUtils', 'w20CoreUI', 'w20CoreNotifications', 'ngSanitize']),
_config = module && module.config() || {},
showTopbar = true,
showSidebar = _config.sidebar && typeof _config.sidebar.show === 'boolean' ? _config.show : true,
includes = _.contains || _.includes;
w20BusinessTheme.directive('w20Topbar', ['ApplicationService', 'EventService', 'EnvironmentService', 'DisplayService', 'MenuService', 'NavigationService',
function (applicationService, eventService, environmentService, displayService, menuService, navigationService) {
return {
template: topbarTemplate,
replace: true,
restrict: 'A',
scope: true,
link: function (scope, iElement, iAttrs) {
scope.navActions = menuService.getActions;
scope.navAction = menuService.getAction;
scope.envtype = environmentService.environment;
scope.buildLink = navigationService.buildLink;
scope.title = iAttrs.title || '\'' + applicationService.applicationId + '\'';
scope.description = iAttrs.subtitle || '';
scope.logo = _config.logo;
scope.brandFixedWidth = true;
if (_config.brand) {
scope.brandFixedWidth = _config.brand.fixedWidth === false ? _config.brand.fixedWidth : true;
scope.brandBackgroundColor = _config.brand.backgroundColor ? _config.brand.backgroundColor : undefined;
scope.brandTextColor = _config.brand.textColor ? _config.brand.textColor : undefined;
}
scope.showTopbar = function () {
return showTopbar;
};
scope.toggleSidebar = function () {
eventService.emit('SidebarToggleEvent');
};
displayService.registerContentShiftCallback(function () {
return [showTopbar ? 50 : 0, 0, 0, 0];
});
}
};
}]);
w20BusinessTheme.directive('w20Sidebar', ['EventService', 'DisplayService', 'NavigationService', 'MenuService', '$location', '$window',
function (eventService, displayService, navigationService, menuService, $location, $window) {
return {
template: sidebarTemplate,
replace: true,
restrict: 'A',
scope: true,
link: function (scope) {
var previousSidebarState = showSidebar;
if (_config.sidebar) {
scope.sideBarWidth = _config.sidebar.width ? _config.sidebar.width : undefined;
}
scope.menuSections = menuService.getSections;
scope.menuActiveSectionName = scope.menuSections()[0];
scope.showSidebar = function () {
return showSidebar;
};
scope.menuSection = function (name) {
return name ? menuService.getSection(name) : null;
};
eventService.on('SidebarToggleEvent', function () {
showSidebar = !showSidebar;
previousSidebarState = showSidebar;
displayService.computeContentShift();
});
displayService.registerContentShiftCallback(function () {
return [10, 0, 0, showSidebar ? (scope.sideBarWidth || 270) : 0];
});
angular.element($window).bind('resize', function () {
showSidebar = $(window).width() < 768 ? false : previousSidebarState;
scope.$apply();
displayService.computeContentShift();
});
}
};
}]);
w20BusinessTheme.filter('routeFilter', ['CultureService', 'SecurityExpressionService', function (cultureService, securityExpressionService) {
function isRouteVisible(route) {
return !route.hidden && (typeof route.security === 'undefined' || securityExpressionService.evaluate(route.security));
}
return function (routes, expected) {
if (!expected) {
return;
}
return _.filter(routes, function (route) {
if (isRouteVisible(route) && cultureService.displayName(route).toLowerCase().indexOf(expected.toLowerCase()) !== -1) {
return route;
}
});
};
}]);
w20BusinessTheme.controller('W20btViewsController', ['$scope', 'NavigationService', 'CultureService', '$route', '$location',
function ($scope, navigationService, cultureService, $route, $location) {
var openedCategories = navigationService.expandedRouteCategories();
function recursiveOpen(tree) {
openedCategories.push(tree.categoryName);
for (var key in tree) {
if (tree.hasOwnProperty(key)) {
var subTree = tree[key];
if (subTree instanceof Array) {
recursiveOpen(subTree);
}
}
}
}
$scope.routes = $route.routes;
$scope.filteredRoutes = [];
$scope.menuTree = navigationService.routeTree;
$scope.subMenuTree = navigationService.computeSubTree;
$scope.topLevelCategories = navigationService.topLevelRouteCategories;
$scope.topLevelRoutes = navigationService.topLevelRoutes;
$scope.routesFromCategory = navigationService.routesFromCategory;
$scope.displayName = cultureService.displayName;
$scope.buildLink = navigationService.buildLink;
if (_config.brand) {
$scope.brandColor = _config.brand.backgroundColor ? _config.brand.backgroundColor : undefined;
}
$scope.activeRoutePath = function () {
return $location.path();
};
$scope.localizeCategory = function (categoryName) {
var lastPartIndex = categoryName.lastIndexOf('.');
if (lastPartIndex !== -1) {
return cultureService.localize('application.viewcategory.' + categoryName, undefined, null) || cultureService.localize('application.viewcategory.' + categoryName.substring(lastPartIndex + 1));
} else {
return cultureService.localize('application.viewcategory.' + categoryName);
}
};
$scope.toggleTree = function (tree) {
if ($scope.isOpened(tree.categoryName)) {
openedCategories.splice(openedCategories.indexOf(tree.categoryName), 1);
} else {
openedCategories.push(tree.categoryName);
}
};
$scope.isOpened = function (categoryName) {
return includes(openedCategories, categoryName);
};
$scope.routeSortKey = function (route) {
return route.sortKey || route.path;
};
}]);
w20BusinessTheme.run(['$rootScope', 'EventService', 'DisplayService', 'MenuService', 'CultureService',
function ($rootScope, eventService, displayService, menuService, cultureService) {
$rootScope.$on('$routeChangeSuccess', function (event, routeInfo) {
if (routeInfo && routeInfo.$$route) {
switch (routeInfo.$$route.navigation) {
case 'none':
showSidebar = false;
showTopbar = false;
break;
case 'sidebar':
showSidebar = true;
showTopbar = false;
break;
case 'topbar':
showSidebar = false;
showTopbar = true;
break;
case 'full':
/* falls through */
default:
break;
}
displayService.computeContentShift();
}
});
if (!_config.hideSecurity) {
if (!_config.profileChooser) {
menuService.addAction('login', 'w20-login', {
sortKey: 100
});
} else {
menuService.addAction('profile', 'w20-profile', {
sortKey: 100
});
}
}
if (!_config.hideConnectivity) {
menuService.addAction('connectivity', 'w20-connectivity', {
sortKey: 200
});
}
if (!_config.hideCulture) {
menuService.addAction('culture', 'w20-culture', {
sortKey: 300
});
}
_.each(_config.links, function (link, idx) {
if (idx < 10) {
menuService.addAction('link-' + idx, 'w20-link', _.extend(link, {
sortKey: 400 + idx
}));
}
});
if (!_config.hideSecurity && !_config.profileChooser) {
menuService.addAction('logout', 'w20-logout', {
sortKey: 1000
});
}
menuService.addSection('views', 'w20-views', {
templateUrl: '{w20-business-theme}/templates/sidebar-views.html'
});
eventService.on('w20.security.authenticated', function () {
displayService.computeContentShift();
});
eventService.on('w20.security.deauthenticated', function () {
displayService.computeContentShift();
});
eventService.on('w20.security.refreshed', function () {
displayService.computeContentShift();
});
}]);
return {
angularModules: ['w20BusinessTheme'],
lifecycle: {
pre: function (modules, fragments, callback) {
angular.element('body').addClass('w20-top-shift-padding w20-right-shift-padding w20-bottom-shift-padding w20-left-shift-padding');
callback(module);
}
}
};
});
|
seedstack/w20-business-theme
|
modules/main.js
|
JavaScript
|
mpl-2.0
| 11,739 |
#ifndef RBX_GC_IMMIX_HPP
#define RBX_GC_IMMIX_HPP
#include "memory/address.hpp"
#include "memory/immix_region.hpp"
#include "memory/gc.hpp"
#include "exception.hpp"
#include "object_position.hpp"
namespace rubinius {
class Memory;
namespace memory {
class ImmixGC;
class ImmixMarker;
/**
* ImmixGC uses the immix memory management strategy to perform garbage
* collection on the mature objects in the immix space.
*/
class ImmixGC : public GarbageCollector {
public:
class Diagnostics : public diagnostics::MemoryDiagnostics {
public:
int64_t collections_;
int64_t total_bytes_;
int64_t chunks_;
int64_t holes_;
double percentage_;
Diagnostics();
void update();
};
private:
/**
* Class used as an interface to the Rubinius specific object memory layout
* by the (general purpose) Immix memory manager. By imposing this interface
* between Memory and the utility Immix memory manager, the latter can
* be made reusable.
*
* The Immix memory manager delegates to this class to:
* - determine the size of an object at a particular memory address
* - copy an object
* - return the forwarding pointer for an object
* - set the forwarding pointer for an object that it moves
* - mark an address as visited
* - determine if an object is pinned and cannot be moved
* - walk all root pointers
*
* It will also notify this class when:
* - it adds chunks
* - allocates from the last free block, indicating a collection is needed
*/
class ObjectDescriber {
Memory* memory_;
ImmixGC* gc_;
public:
ObjectDescriber()
: memory_(0)
, gc_(NULL)
{}
void set_object_memory(Memory* om, ImmixGC* gc) {
memory_ = om;
gc_ = gc;
}
void added_chunk(int count);
void last_block() { }
void set_forwarding_pointer(Address from, Address to);
Address forwarding_pointer(Address cur) {
Object* obj = cur.as<Object>();
if(obj->forwarded_p()) return obj->forward();
return Address::null();
}
bool pinned(Address addr) {
return addr.as<Object>()->pinned_p();
}
Address copy(Address original, ImmixAllocator& alloc);
void walk_pointers(Address addr, Marker<ObjectDescriber>& mark) {
Object* obj = addr.as<Object>();
if(obj) gc_->scan_object(obj);
}
Address update_pointer(Address addr);
int size(Address addr);
/**
* Called when the GC object wishes to mark an object.
*
* @returns true if the object is not already marked, and in the Immix
* space; otherwise false.
*/
bool mark_address(Address addr, MarkStack& ms, bool push = true);
};
GC<ObjectDescriber> gc_;
ExpandingAllocator allocator_;
Memory* memory_;
ImmixMarker* marker_;
int chunks_left_;
int chunks_before_collection_;
Diagnostics* diagnostics_;
public:
ImmixGC(Memory* om);
virtual ~ImmixGC();
Object* allocate(size_t bytes, bool& collect_now);
Object* move_object(Object* orig, size_t bytes, bool& collect_now);
virtual Object* saw_object(Object*);
virtual void scanned_object(Object*);
virtual bool mature_gc_in_progress();
void collect(GCData* data);
void collect_start(GCData* data);
void collect_finish(GCData* data);
void sweep();
void walk_finalizers();
ObjectPosition validate_object(Object*);
public: // Inline
Memory* memory() {
return memory_;
}
size_t& bytes_allocated() {
return gc_.bytes_allocated();
}
int dec_chunks_left() {
return --chunks_left_;
}
void reset_chunks_left() {
chunks_left_ = chunks_before_collection_;
}
Diagnostics* diagnostics() {
return diagnostics_;
}
void start_marker(STATE, GCData* data);
bool process_mark_stack();
bool process_mark_stack(bool& exit);
MarkStack& mark_stack();
private:
void collect_scan(GCData* data);
};
}
}
#endif
|
jsyeo/rubinius
|
machine/memory/immix_collector.hpp
|
C++
|
mpl-2.0
| 4,136 |
/*
* Copyright (c) 2012-2016 Arne Schwabe
* Distributed under the GNU GPL v2 with additional terms. For full terms see the file doc/LICENSE.txt
*/
package de.blinkt.openvpn.api;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import java.util.HashSet;
import java.util.Set;
public class ExternalAppDatabase {
private final String PREFERENCES_KEY = "PREFERENCES_KEY";
Context mContext;
public ExternalAppDatabase(Context c) {
mContext = c;
}
boolean isAllowed(String packagename) {
Set<String> allowedapps = getExtAppList();
return allowedapps.contains(packagename);
}
public Set<String> getExtAppList() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
return prefs.getStringSet(PREFERENCES_KEY, new HashSet<String>());
}
void addApp(String packagename) {
Set<String> allowedapps = getExtAppList();
allowedapps.add(packagename);
saveExtAppList(allowedapps);
}
private void saveExtAppList(Set<String> allowedapps) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
Editor prefedit = prefs.edit();
prefedit.putStringSet(PREFERENCES_KEY, allowedapps);
prefedit.apply();
}
public void clearAllApiApps() {
saveExtAppList(new HashSet<String>());
}
public void removeApp(String packagename) {
Set<String> allowedapps = getExtAppList();
allowedapps.remove(packagename);
saveExtAppList(allowedapps);
}
}
|
yonadev/yona-app-android
|
openvpn/src/main/java/de/blinkt/openvpn/api/ExternalAppDatabase.java
|
Java
|
mpl-2.0
| 1,694 |
set :base_url, "https://www.consul.io/"
activate :hashicorp do |h|
h.name = "consul"
h.version = "1.4.0"
h.github_slug = "hashicorp/consul"
end
helpers do
# Returns a segment tracking ID such that local development is not
# tracked to production systems.
def segmentId()
if (ENV['ENV'] == 'production')
'IyzLrqXkox5KJ8XL4fo8vTYNGfiKlTCm'
else
'0EXTgkNx0Ydje2PGXVbRhpKKoe5wtzcE'
end
end
# Returns the FQDN of the image URL.
#
# @param [String] path
#
# @return [String]
def image_url(path)
File.join(base_url, image_path(path))
end
# Get the title for the page.
#
# @param [Middleman::Page] page
#
# @return [String]
def title_for(page)
if page && page.data.page_title
return "#{page.data.page_title} - Consul by HashiCorp"
end
"Consul by HashiCorp"
end
# Get the description for the page
#
# @param [Middleman::Page] page
#
# @return [String]
def description_for(page)
description = (page.data.description || "Consul by HashiCorp")
.gsub('"', '')
.gsub(/\n+/, ' ')
.squeeze(' ')
return escape_html(description)
end
# This helps by setting the "active" class for sidebar nav elements
# if the YAML frontmatter matches the expected value.
def sidebar_current(expected)
current = current_page.data.sidebar_current || ""
if current.start_with?(expected)
return " class=\"active\""
else
return ""
end
end
# Returns the id for this page.
# @return [String]
def body_id_for(page)
if !(name = page.data.sidebar_current).blank?
return "page-#{name.strip}"
end
if page.url == "/" || page.url == "/index.html"
return "page-home"
end
if !(title = page.data.page_title).blank?
return title
.downcase
.gsub('"', '')
.gsub(/[^\w]+/, '-')
.gsub(/_+/, '-')
.squeeze('-')
.squeeze(' ')
end
return ""
end
# Returns the list of classes for this page.
# @return [String]
def body_classes_for(page)
classes = []
if !(layout = page.data.layout).blank?
classes << "layout-#{page.data.layout}"
end
if !(title = page.data.page_title).blank?
title = title
.downcase
.gsub('"', '')
.gsub(/[^\w]+/, '-')
.gsub(/_+/, '-')
.squeeze('-')
.squeeze(' ')
classes << "page-#{title}"
end
return classes.join(" ")
end
end
|
youhong316/consul
|
website/config.rb
|
Ruby
|
mpl-2.0
| 2,474 |
// ----------------------------------------------------------------------------
//
// *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
//
// ----------------------------------------------------------------------------
//
// This file is automatically generated by Magic Modules and manual
// changes will be clobbered when the file is regenerated.
//
// Please read more about how to change this file in
// .github/CONTRIBUTING.md.
//
// ----------------------------------------------------------------------------
package google
import (
"context"
"log"
"strings"
"testing"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
func init() {
resource.AddTestSweepers("ComputeInstanceGroupNamedPort", &resource.Sweeper{
Name: "ComputeInstanceGroupNamedPort",
F: testSweepComputeInstanceGroupNamedPort,
})
}
// At the time of writing, the CI only passes us-central1 as the region
func testSweepComputeInstanceGroupNamedPort(region string) error {
resourceName := "ComputeInstanceGroupNamedPort"
log.Printf("[INFO][SWEEPER_LOG] Starting sweeper for %s", resourceName)
config, err := sharedConfigForRegion(region)
if err != nil {
log.Printf("[INFO][SWEEPER_LOG] error getting shared config for region: %s", err)
return err
}
err = config.LoadAndValidate(context.Background())
if err != nil {
log.Printf("[INFO][SWEEPER_LOG] error loading: %s", err)
return err
}
t := &testing.T{}
billingId := getTestBillingAccountFromEnv(t)
// Setup variables to replace in list template
d := &ResourceDataMock{
FieldsInSchema: map[string]interface{}{
"project": config.Project,
"region": region,
"location": region,
"zone": "-",
"billing_account": billingId,
},
}
listTemplate := strings.Split("https://www.googleapis.com/compute/v1/projects/{{project}}/aggregated/instanceGroups/{{group}}", "?")[0]
listUrl, err := replaceVars(d, config, listTemplate)
if err != nil {
log.Printf("[INFO][SWEEPER_LOG] error preparing sweeper list url: %s", err)
return nil
}
res, err := sendRequest(config, "GET", config.Project, listUrl, nil)
if err != nil {
log.Printf("[INFO][SWEEPER_LOG] Error in response from request %s: %s", listUrl, err)
return nil
}
resourceList, ok := res["namedPorts"]
if !ok {
log.Printf("[INFO][SWEEPER_LOG] Nothing found in response.")
return nil
}
var rl []interface{}
zones := resourceList.(map[string]interface{})
// Loop through every zone in the list response
for _, zonesValue := range zones {
zone := zonesValue.(map[string]interface{})
for k, v := range zone {
// Zone map either has resources or a warning stating there were no resources found in the zone
if k != "warning" {
resourcesInZone := v.([]interface{})
rl = append(rl, resourcesInZone...)
}
}
}
log.Printf("[INFO][SWEEPER_LOG] Found %d items in %s list response.", len(rl), resourceName)
// Keep count of items that aren't sweepable for logging.
nonPrefixCount := 0
for _, ri := range rl {
obj := ri.(map[string]interface{})
if obj["name"] == nil {
log.Printf("[INFO][SWEEPER_LOG] %s resource name was nil", resourceName)
return nil
}
name := GetResourceNameFromSelfLink(obj["name"].(string))
// Skip resources that shouldn't be sweeped
if !isSweepableTestResource(name) {
nonPrefixCount++
continue
}
deleteTemplate := "https://www.googleapis.com/compute/v1/projects/{{project}}/zones/{{zone}}/instanceGroups/{{group}}/setNamedPorts"
if obj["zone"] == nil {
log.Printf("[INFO][SWEEPER_LOG] %s resource zone was nil", resourceName)
return nil
}
zone := GetResourceNameFromSelfLink(obj["zone"].(string))
deleteTemplate = strings.Replace(deleteTemplate, "{{zone}}", zone, -1)
deleteUrl, err := replaceVars(d, config, deleteTemplate)
if err != nil {
log.Printf("[INFO][SWEEPER_LOG] error preparing delete url: %s", err)
return nil
}
deleteUrl = deleteUrl + name
// Don't wait on operations as we may have a lot to delete
_, err = sendRequest(config, "DELETE", config.Project, deleteUrl, nil)
if err != nil {
log.Printf("[INFO][SWEEPER_LOG] Error deleting for url %s : %s", deleteUrl, err)
} else {
log.Printf("[INFO][SWEEPER_LOG] Sent delete request for %s resource: %s", resourceName, name)
}
}
if nonPrefixCount > 0 {
log.Printf("[INFO][SWEEPER_LOG] %d items were non-sweepable and skipped.", nonPrefixCount)
}
return nil
}
|
terraform-providers/terraform-provider-google
|
google/resource_compute_instance_group_named_port_sweeper_test.go
|
GO
|
mpl-2.0
| 4,472 |
/*
* <?xml version="1.0" encoding="utf-8"?><!--
* ~ Copyright (c) 2018 Stichting Yona Foundation
* ~
* ~ This Source Code Form is subject to the terms of the Mozilla Public
* ~ License, v. 2.0. If a copy of the MPL was not distributed with this
* ~ file, You can obtain one at https://mozilla.org/MPL/2.0/.
* -->
*/
package nu.yona.app.enums;
public enum UserStatus
{
ACTIVE,
NUMBER_NOT_CONFIRMED,
NOT_REGISTERED,
BLOCKED
}
|
yonadev/yona-app-android
|
app/src/main/java/nu/yona/app/enums/UserStatus.java
|
Java
|
mpl-2.0
| 448 |
#include <cllogger.h>
#include <stdarg.h>
#ifdef CC_PF_WIN32
# include <process.h>
#endif
cl::ClLogger::ClLogger()
: m_write_interval(CL_INIT_WRITE_INTERVAL),
m_check_interval(CL_INIT_CHECK_INTERVAL),
m_stop_times(CL_INIT_STOP_TIMES),
m_stop_count(CL_INIT_STOP_COUNT),
m_write_flag(false),
m_check_flag(false),
m_msg_queue()
{
m_msg_queue.init();
}
cl::ClLogger::ClLogger(size_t queue_size, int queue_waits)
: m_write_interval(CL_INIT_WRITE_INTERVAL),
m_check_interval(CL_INIT_CHECK_INTERVAL),
m_stop_times(CL_INIT_STOP_TIMES),
m_stop_count(CL_INIT_STOP_COUNT),
m_write_flag(false),
m_check_flag(false),
m_msg_queue(queue_size, queue_waits)
{
m_msg_queue.init();
}
bool
cl::ClLogger::start()
{
bool ret = false;
if (__start()) {
for(std::vector<ClInfoPtr>::iterator it = m_infos_reg.begin();
it != m_infos_reg.end();it ++){
cl::ClInfoPtr& cip = *it;
ret = ret && cip->startWork();
}
}
return ret;
}
void
cl::ClLogger::stop()
{
cc::microSleep(m_stop_times);
m_write_flag = m_check_flag = false;
#if __cplusplus >= 201103L
m_write_thr.detach();
m_check_thr.join();
#else
# if (defined CC_PF_LINUX) || (defined CC_PF_MINGW32)
pthread_detach(m_write_thr);
pthread_join(m_check_thr, 0);
# elif (defined CC_PF_WIN32)
static const int S_WAIT_FOR = 5000;
if (WAIT_TIMEOUT == WaitForSingleObject(m_check_thr, S_WAIT_FOR)){
TerminateThread(m_check_thr, 1);
}
# endif
#endif
}
bool
cl::ClLogger::start(const size_t &id)
{
if(id == 0 || id > m_infos_reg.size()){
return false;
}
if(__start()){
return m_infos_reg[id]->startWork();
}else{
return false;
}
}
bool
cl::ClLogger::start(const string &name)
{
ClInfoPtr curr_info = m_infos_reg[name];
if(curr_info == nullptr){
return false;
}
if(__start()){
return curr_info->startWork();
}else{
return false;
}
}
void
cl::ClLogger::stop(const size_t &id)
{
if(id == 0 || id > m_infos_reg.size()){
return;
}
if(m_write_flag && m_check_flag){
m_infos_reg[id]->stopWork();
}
}
void
cl::ClLogger::stop(const string &name)
{
ClInfoPtr curr_info = m_infos_reg[name];
if(curr_info == nullptr){
return;
}
if(m_write_flag && m_check_flag){
curr_info->stopWork();
}
}
size_t
cl::ClLogger::registerLogInfo(const cl::ClInfoPtr &clinfo)
{
return m_infos_reg.registerInfo(clinfo);
}
size_t
cl::ClLogger::registerLogInfo(const string &name)
{
ClInfoPtr clinfo = new ClInfo(name);
return m_infos_reg.registerInfo(clinfo);
}
size_t
cl::ClLogger::registerLogInfo(const string &name, const string &prefix, const string &postfix)
{
ClInfoPtr clinfo = new ClInfo(name);
clinfo->m_prefix = prefix;
clinfo->m_postfix = postfix;
return m_infos_reg.registerInfo(clinfo);
}
size_t
cl::ClLogger::registerLogInfo(const string &name, const string &path, const string &feed, const cl::log_mode_t &mode)
{
ClInfoPtr clinfo = new ClInfo(name, path, feed, mode);
return m_infos_reg.registerInfo(clinfo);
}
size_t
cl::ClLogger::registerLogInfo(const string &name, const string &prefix, const string &postfix, const string &path, const string &feed, const cl::log_mode_t &mode)
{
ClInfoPtr clinfo = new ClInfo(name, path, feed, mode);
clinfo->m_prefix = prefix;
clinfo->m_postfix = postfix;
return m_infos_reg.registerInfo(clinfo);
}
bool
cl::ClLogger::writef(const size_t &id, const char *format, ...)
{
static const size_t S_BUFF_SIZE = 4096;
if(id == 0 || id > m_infos_reg.size()){
return false;
}
if(!m_infos_reg[id]->isWork()){
return false;
}
va_list argslist;
char buff[S_BUFF_SIZE];
int ret = 0;
va_start(argslist, format);
#if (defined CC_PF_LINUX) || (defined CC_PF_MINGW32)
ret = std::vsnprintf(buff, S_BUFF_SIZE, format, argslist);
#elif (defined CC_PF_WIN32)
ret = _vsnprintf_s(buff, S_BUFF_SIZE, format, argslist);
#endif
va_end(argslist);
if(ret <= 0){
return false;
}
ClMessage message(id, string(buff, ret));
m_msg_queue.push(message);
return true;
}
bool
cl::ClLogger::writef(const string &name, const char *format, ...)
{
static const size_t S_BUFF_SIZE = 4096;
size_t id = m_infos_reg.getLogId(name);
if(id == 0 || !m_infos_reg[id]->isWork()){
return false;
}
va_list argslist;
char buff[S_BUFF_SIZE];
int ret = 0;
va_start(argslist, format);
#if (defined CC_PF_LINUX) || (defined CC_PF_MINGW32)
ret = std::vsnprintf(buff, S_BUFF_SIZE, format, argslist);
#elif (defined CC_PF_WIN32)
ret = _vsnprintf_s(buff, S_BUFF_SIZE, format, argslist);
#endif
va_end(argslist);
if(ret <= 0){
return false;
}
ClMessage message(id, string(buff, ret));
m_msg_queue.push(message);
return true;
}
bool
cl::ClLogger::write(const size_t &id, const string &msg)
{
if(id == 0 || id > m_infos_reg.size()){
return false;
}
if(!m_infos_reg[id]->isWork()){
return false;
}
ClMessage message(id, msg);
m_msg_queue.push(message);
return true;
}
bool
cl::ClLogger::write(const string &name, const string &msg)
{
size_t id = m_infos_reg.getLogId(name);
if(id == 0 || !m_infos_reg[id]->isWork()){
return false;
}
ClMessage message(id, msg);
m_msg_queue.push(message);
return true;
}
bool
cl::ClLogger::__start()
{
if(m_write_flag && m_check_flag){
return true;
}
if(!m_write_flag){
m_write_flag = true;
if(!__startThread(m_write_thr, cl::ClLogger::s_write, static_cast<cc::thread_para_t>(this))){
m_write_flag = false;
return false;
}
}
if(!m_check_flag){
m_check_flag = true;
if(!__startThread(m_check_thr, cl::ClLogger::s_check, static_cast<cc::thread_para_t>(this))){
m_check_flag = false;
return false;
}
}
return true;
}
bool
cl::ClLogger::__startThread(cc::thread_t &thread, cc::thread_func *pfunc, cc::thread_para_t para)
{
#if __cplusplus >= 201103L
cc::thread_t thr(pfunc, para);
thread.swap(thr);
#else
# if (defined CC_PF_LINUX) || (defined CC_PF_MINGW32)
int ret = pthread_create(&thread, 0, pfunc, para);
if(ret != 0){
return false;
}
# elif (defined CC_PF_WIN32)
thread = (cc::thread_t)_beginthreadex(0, 0, pfunc, para, 0, 0);
# endif
#endif
return true;
}
cc::thread_ret_t CC_THREAD cl::ClLogger::s_write(cc::thread_para_t para)
{
cl::ClLogger* logger = static_cast<cl::ClLogger*>(para);
cc::SeqQueue<cl::ClMessage>& msgqueue = logger->m_msg_queue;
cl::ClInfoRegistry& registry = logger->m_infos_reg;
cl::ClMessage message;
bool& is_write = logger->m_write_flag;
int& sleep_tm = logger->m_write_interval;
int quit_wait = logger->m_stop_count;
for(;is_write || quit_wait;is_write ? quit_wait : quit_wait --){
msgqueue.pop(message);
ClInfoPtr curr_info = registry[message.m_id];
curr_info->write(message.m_msg);
message.reset();
cc::microSleep(sleep_tm);
}
return static_cast<cc::thread_ret_t>(0);
}
cc::thread_ret_t CC_THREAD cl::ClLogger::s_check(cc::thread_para_t para)
{
cl::ClLogger* logger = static_cast<cl::ClLogger*>(para);
cl::ClInfoRegistry& registry = logger->m_infos_reg;
bool& is_check = logger->m_check_flag;
int& sleep_tm = logger->m_check_interval;
int quit_wait = logger->m_stop_count;
for(;is_check || quit_wait;is_check ? quit_wait : quit_wait --){
for(std::vector<ClInfoPtr>::iterator it = registry.begin();
it != registry.end();it ++){
cl::ClInfoPtr& cip = *it;
if(cip && cip->isWork()){
cip->check();
}
}
cc::microSleep(sleep_tm);
}
return static_cast<cc::thread_ret_t>(0);
}
|
araraloren/FunctionFind
|
cpplogger/cllogger.cpp
|
C++
|
mpl-2.0
| 8,085 |
var toolURL = {
'application/x-popcorn': 'https://popcorn.webmaker.org',
'application/x-thimble': 'https://thimble.webmaker.org',
'application/x-x-ray-goggles': 'https://goggles.mozilla.org'
};
module.exports = function (options) {
var moment = require('moment');
var MakeClient = require('makeapi-client');
function generateGravatar(hash) {
var DEFAULT_AVATAR = 'https%3A%2F%2Fstuff.webmaker.org%2Favatars%2Fwebmaker-avatar-44x44.png',
DEFAULT_SIZE = 44;
return 'https://secure.gravatar.com/avatar/' + hash + '?s=' + DEFAULT_SIZE + '&d=' + DEFAULT_AVATAR;
}
// Create a make client with or without auth
function createMakeClient(url, hawk) {
var options = {
apiURL: url
};
if (hawk) {
options.hawk = hawk;
}
var makeClient = new MakeClient(options);
// Moment.js default language is 'en'. This function will override
// the default language globally on the coming request for the homepage
makeClient.setLang = function (lang) {
moment.lang(lang);
};
// Given a prefix for an app tag (e.g. "webmaker:p-") sort an array of makes based on that tag
// The tag must be of the format "prefix-1", "prefix-2", etc.
makeClient.sortByPriority = function (prefix, data) {
var sortedData = [],
duplicates = [],
priorityIndex,
regex = new RegExp('^' + prefix + '(\\d+)$');
function extractStickyPriority(tags) {
var res;
for (var i = tags.length - 1; i >= 0; i--) {
res = regex.exec(tags[i]);
if (res) {
return +res[1];
}
}
}
for (var i = 0; i < data.length; i++) {
priorityIndex = extractStickyPriority(data[i].appTags);
data[i].index = priorityIndex;
if (sortedData[priorityIndex - 1]) {
duplicates.push('Duplicate found for ' + prefix + priorityIndex);
} else {
sortedData[priorityIndex - 1] = data[i];
}
}
return {
results: sortedData,
errors: duplicates
};
};
makeClient.process = function (callback, id) {
makeClient.then(function (err, data, totalHits) {
if (err) {
return callback(err);
}
if (!Array.isArray(data)) {
return callback('There was no data returned');
}
data.forEach(function (make) {
// Set the tool
make.tool = make.contentType.replace(/application\/x\-/g, '');
make.toolurl = toolURL[make.contentType];
// Convert tags and set the "make.type"
if (make.taggedWithAny(['guide'])) {
make.type = 'guide';
} else if (make.taggedWithAny(['webmaker:template'])) {
make.type = 'template';
} else if (make.contentType) {
make.type = make.tool;
}
if (make.taggedWithAny(['beginner'])) {
make.level = 'beginner';
} else if (make.taggedWithAny(['intermediate'])) {
make.level = 'intermediate';
} else if (make.taggedWithAny(['advanced'])) {
make.level = 'advanced';
}
// Remove tutorial tags
make.prettyTags = make.rawTags.filter(function (tag) {
return !(tag.match(/^tutorial-/));
});
if (id) {
make.hasBeenLiked = make.likes.some(function (like) {
return like.userId === +id;
});
}
// Convert the created at and updated at to human time
make.updatedAt = moment(make.updatedAt).fromNow();
make.createdAt = moment(make.createdAt).fromNow();
// Set the remix URL
if (make.type !== 'Appmaker') {
make.remixurl = make.url + '/remix';
}
// Create a function for generating the avatar
make.avatar = generateGravatar(make.emailHash);
});
callback(err, data, totalHits);
});
};
return makeClient;
}
module.exports = {
authenticated: createMakeClient(options.authenticatedURL, options.hawk),
readOnly: createMakeClient(options.readOnlyURL)
};
};
|
mozilla/webmaker.org
|
lib/makeapi.js
|
JavaScript
|
mpl-2.0
| 4,168 |
#!/usr/bin/python3
from lxml import etree
import sys
class Word:
def __init__(self):
self.word = ''
self.pos = ''
self.props = []
def __hash__(self):
return (self.word + self.pos).__hash__()
def __cmp__(self, other):
n = cmp(self.word, other.word)
if n != 0:
return n
n = cmp(self.pos, other.pos)
if n != 0:
return n
# FIXME: ์ด๋ ๊ฒ ํ๋ฉด ์์๊ฐ ๋ค๋ฅผํ
๋ฐ. set์์ ๋ญ๊ฐ ๋จผ์ ๋์ฌ์ง ์๊ณ ...
if self.pos == '๋ช
์ฌ':
return 0
for prop in other.props:
if not prop in self.props:
return -1
for prop in self.props:
if not prop in other.props:
return 1
return 0
######################################################################
if len(sys.argv) < 1:
sys.exit(1)
filename = sys.argv[1]
doc = etree.parse(open(filename))
root = doc.getroot()
wordset = set()
for item in root:
w = Word()
for field in item:
if field.tag == 'word':
w.word = field.text
elif field.tag == 'pos':
w.pos = field.text
elif field.tag == 'props' and field.text:
w.props = field.text.split(',')
w.props.sort()
if w in wordset:
sys.stderr.write(('%s (%s)\n' % (w.word, w.pos)).encode('UTF-8'))
else:
wordset.add(w)
|
changwoo/hunspell-dict-ko
|
utils/findduplicates.py
|
Python
|
mpl-2.0
| 1,426 |
<?php
/**
* Jamroom 5 User Accounts module
*
* copyright 2003 - 2015
* by The Jamroom Network
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. Please see the included "license.html" file.
*
* This module may include works that are not developed by
* The Jamroom Network
* and are used under license - any licenses are included and
* can be found in the "contrib" directory within this module.
*
* Jamroom may use modules and skins that are licensed by third party
* developers, and licensed under a different license - please
* reference the individual module or skin license that is included
* with your installation.
*
* This software is provided "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 Jamroom Network 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 from the use of this
* software, even if advised of the possibility of such damage.
* Some jurisdictions may not allow disclaimers of implied warranties
* and certain statements in the above disclaimer may not apply to
* you as regards implied warranties; the other terms and conditions
* remain enforceable notwithstanding. In some jurisdictions it is
* not permitted to limit liability and therefore such limitations
* may not apply to you.
*
* @copyright 2012 Talldude Networks, LLC.
*/
// make sure we are not being called directly
defined('APP_DIR') or exit();
/**
* quota_config
*/
function jrUser_quota_config()
{
// Allow Signups
$_tmp = array(
'name' => 'allow_signups',
'type' => 'checkbox',
'validate' => 'onoff',
'label' => 'allow signups',
'help' => 'If the "Allow Signups" option is <b>checked</b>, then new users signing up for your system will be able to signup directly to this Profile Quota.',
'default' => 'off',
'order' => 1
);
jrProfile_register_quota_setting('jrUser', $_tmp);
// Signup Method
$_als = array(
'instant' => 'Instant Validation',
'email' => 'Email Validation',
'admin' => 'Admin Validation'
);
$_tmp = array(
'name' => 'signup_method',
'type' => 'select',
'options' => $_als,
'default' => 'email',
'required' => 'on',
'label' => 'signup method',
'help' => 'How should users signup for this Quota?<br><br><b>Instant Validation</b> - The new user account and profile are activated on signup.<br><b>Email Validation</b> - An activation email is sent on signup to activate the new account.',
'order' => 2
);
jrProfile_register_quota_setting('jrUser', $_tmp);
// device notice
$_tmp = array(
'name' => 'device_notice',
'type' => 'checkbox',
'default' => 'off',
'validate' => 'onoff',
'label' => 'new device notice',
'help' => 'If this option is checked, when a user logs in for the first time on a new device, they will be sent an email notification letting them know about the login.',
'order' => 3
);
jrProfile_register_quota_setting('jrUser', $_tmp);
// Power User
$_tmp = array(
'name' => 'power_user',
'type' => 'checkbox',
'validate' => 'onoff',
'label' => 'power user enabled',
'help' => 'If this option is checked, User Accounts belonging to profiles in this Quota will be Power Users that can create new profiles.',
'default' => 'off',
'section' => 'power user',
'order' => 10
);
jrProfile_register_quota_setting('jrUser', $_tmp);
// Power User Profiles
$_tmp = array(
'name' => 'power_user_max',
'type' => 'text',
'validate' => 'number_nz',
'label' => 'max profiles',
'help' => 'How many profiles can a Power User in this quota create?',
'default' => 2,
'section' => 'power user',
'order' => 11
);
jrProfile_register_quota_setting('jrUser', $_tmp);
// Power User Quotas
$_tmp = array(
'name' => 'power_user_quotas',
'type' => 'select_multiple',
'label' => 'allowed quotas',
'help' => 'When a Power User in this Quota creates a new Profile, what Quotas can they select for their new profile?',
'options' => 'jrProfile_get_quotas',
'default' => 0,
'section' => 'power user',
'order' => 12
);
jrProfile_register_quota_setting('jrUser', $_tmp);
return true;
}
|
jeffreybrayne/TheBreakContest
|
modules/jrUser/quota.php
|
PHP
|
mpl-2.0
| 5,055 |
/*
* Copyright (C) 2019 DataSwift Ltd - All Rights Reserved
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
* Written by Eleftherios Myteletsis <eleftherios.myteletsis@dataswift.io> 3, 2019
*/
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'rum-settings-page',
templateUrl: './settings-page.component.html',
styleUrls: ['./settings-page.component.scss']
})
export class SettingsPageComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
|
Hub-of-all-Things/Rumpel
|
src/app/settings/settings-page/settings-page.component.ts
|
TypeScript
|
mpl-2.0
| 649 |
/* Created by Blake Gideon. <blake at chicagoan.io>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package io.chicagoan.ctawaittime;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
public class SmsStateListener extends PhoneStateListener {
ServiceState serviceState;
public SmsStateListener () {
serviceState = new ServiceState();
}
@Override
public void onServiceStateChanged(ServiceState serviceState) {
super.onServiceStateChanged(serviceState);
this.serviceState.setState(serviceState.getState());
}
public int getState() {
return serviceState.getState();
}
}
|
ChicagoDev/Android_CTA_Bus_Tracker
|
app/src/main/java/io/chicagoan/ctawaittime/SmsStateListener.java
|
Java
|
mpl-2.0
| 833 |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# Future Modules:
from __future__ import annotations
# Built-in Modules:
import threading
from collections.abc import Callable
from typing import Any, Union
class BaseDelay(threading.Thread):
"""
Implements the base delay class.
"""
_delays: list[threading.Thread] = []
def __init__(
self,
duration: float,
count: Union[int, None],
function: Callable[..., Any],
*args: Any,
**kwargs: Any,
) -> None:
"""
Defines the constructor for the object.
Args:
duration: The amount of time (in seconds) to delay between iterations.
count: The number of iterations to delay, or None to repeat indefinitely.
function: The function to be called at each iteration.
*args: Positional arguments to be passed to the called function.
**kwargs: Key-word only arguments to be passed to the called function.
"""
if count is not None and count < 0:
raise ValueError("count must be a positive number or None.")
super().__init__()
self.daemon: bool = True
self._duration: float = duration
self._count: Union[int, None] = count
self._function: Callable[..., Any] = function
self._args: tuple[Any, ...] = args
self._kwargs: dict[str, Any] = kwargs
self._finished: threading.Event = threading.Event()
def stop(self) -> None:
"""Stops an active delay."""
self._finished.set()
def run(self) -> None:
try:
self._delays.append(self)
while not self._finished.is_set() and self._count != 0:
self._finished.wait(self._duration)
if not self._finished.is_set():
self._function(*self._args, **self._kwargs)
if self._count is not None:
self._count -= 1
finally:
del self._function, self._args, self._kwargs
self._delays.remove(self)
if not self._finished.is_set():
self.stop()
class Delay(BaseDelay):
"""
Implements a delay which automatically starts upon creation.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.start()
class OneShot(Delay):
"""
Implements a delay which is run only once.
"""
def __init__(self, duration: float, function: Callable[..., Any], *args: Any, **kwargs: Any) -> None:
"""
Defines the constructor for the object.
Args:
duration: The amount of time (in seconds) to delay.
function: The function to be called when the delay completes.
*args: Positional arguments to be passed to the called function.
**kwargs: Key-word only arguments to be passed to the called function.
"""
super().__init__(duration, 1, function, *args, **kwargs)
class Repeating(Delay):
"""
Implements a delay which runs indefinitely.
"""
def __init__(self, duration: float, function: Callable[..., Any], *args: Any, **kwargs: Any) -> None:
"""
Defines the constructor for the object.
Args:
duration: The amount of time (in seconds) to delay between iterations.
function: The function to be called at each iteration.
*args: Positional arguments to be passed to the called function.
**kwargs: Key-word only arguments to be passed to the called function.
"""
super().__init__(duration, None, function, *args, **kwargs)
|
nstockton/mapperproxy-mume
|
mapper/delays.py
|
Python
|
mpl-2.0
| 3,316 |