repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
giterio/gitery
internal/views/user.go
package views import ( "context" "net/http" "gitery/internal/prototypes" ) // UserView ... type UserView struct { prototypes.User CreatedAt int64 `json:"createdAt"` UpdatedAt int64 `json:"updatedAt"` } // BuildUserView compose UserView from a User func BuildUserView(user *prototypes.User) UserView { return UserView{ User: *user, CreatedAt: user.CreatedAt.Unix(), UpdatedAt: user.UpdatedAt.Unix(), } } // RenderUser ... func RenderUser(ctx context.Context, w http.ResponseWriter, user *prototypes.User) (err error) { userView := BuildUserView(user) err = Render(ctx, w, userView) return }
kungwahcheung/LeetCode
27_remove_element.cc
<filename>27_remove_element.cc #include <vector> #include "util.h" using namespace std; class Solution { public: int removeElement(vector<int>& nums, int val) { int size = 0; for (int i = 0; i < nums.size(); ++i) { if (nums[i] != val) nums[size++] = nums[i]; } return size; } }; int main() { Solution sol = Solution(); vector<int> nums{0,1,2,2,3,0,4,2}; int val = 2; print_vector(nums); sol.removeElement(nums, val); print_vector(nums); return 0; }
cjh1/molequeue
molequeue/queues/remotessh.cpp
/****************************************************************************** This source file is part of the MoleQueue project. Copyright 2011-2012 Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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. ******************************************************************************/ #include "remotessh.h" #include "../job.h" #include "../jobmanager.h" #include "../logentry.h" #include "../logger.h" #include "../program.h" #include "../remotequeuewidget.h" #include "../server.h" #include "../sshcommandfactory.h" #include <QtCore/QTimer> #include <QtCore/QDebug> #include <QtGui> namespace MoleQueue { QueueRemoteSsh::QueueRemoteSsh(const QString &queueName, QueueManager *parentObject) : QueueRemote(queueName, parentObject), m_sshExecutable(SshCommandFactory::defaultSshCommand()), m_scpExecutable(SshCommandFactory::defaultScpCommand()), m_sshPort(22), m_isCheckingQueue(false) { // Check for jobs to submit every 5 seconds m_checkForPendingJobsTimerId = startTimer(5000); // Always allow m_requestQueueCommand to return 0 m_allowedQueueRequestExitCodes.append(0); } QueueRemoteSsh::~QueueRemoteSsh() { } void QueueRemoteSsh::readSettings(QSettings &settings) { QueueRemote::readSettings(settings); m_submissionCommand = settings.value("submissionCommand").toString(); m_requestQueueCommand = settings.value("requestQueueCommand").toString(); m_killCommand = settings.value("killCommand").toString(); m_sshExecutable = settings.value("sshExecutable", "ssh").toString(); m_scpExecutable = settings.value("scpExecutable", "scp").toString(); m_hostName = settings.value("hostName").toString(); m_userName = settings.value("userName").toString(); m_identityFile = settings.value("identityFile").toString(); m_sshPort = settings.value("sshPort").toInt(); } void QueueRemoteSsh::writeSettings(QSettings &settings) const { QueueRemote::writeSettings(settings); settings.setValue("submissionCommand", m_submissionCommand); settings.setValue("requestQueueCommand", m_requestQueueCommand); settings.setValue("killCommand", m_killCommand); settings.setValue("sshExecutable", m_sshExecutable); settings.setValue("scpExecutable", m_scpExecutable); settings.setValue("hostName", m_hostName); settings.setValue("userName", m_userName); settings.setValue("identityFile", m_identityFile); settings.setValue("sshPort", m_sshPort); } void QueueRemoteSsh::exportConfiguration(QSettings &exporter, bool includePrograms) const { QueueRemote::exportConfiguration(exporter, includePrograms); exporter.setValue("submissionCommand", m_submissionCommand); exporter.setValue("requestQueueCommand", m_requestQueueCommand); exporter.setValue("killCommand", m_killCommand); exporter.setValue("hostName", m_hostName); exporter.setValue("sshPort", m_sshPort); } void QueueRemoteSsh::importConfiguration(QSettings &importer, bool includePrograms) { QueueRemote::importConfiguration(importer, includePrograms); m_submissionCommand = importer.value("submissionCommand").toString(); m_requestQueueCommand = importer.value("requestQueueCommand").toString(); m_killCommand = importer.value("killCommand").toString(); m_hostName = importer.value("hostName").toString(); m_sshPort = importer.value("sshPort").toInt(); } AbstractQueueSettingsWidget* QueueRemoteSsh::settingsWidget() { RemoteQueueWidget *widget = new RemoteQueueWidget (this); return widget; } void QueueRemoteSsh::createRemoteDirectory(Job job) { // Note that this is just the working directory base -- the job folder is // created by scp. QString remoteDir = QString("%1").arg(m_workingDirectoryBase); SshConnection *conn = newSshConnection(); conn->setData(QVariant::fromValue(job)); connect(conn, SIGNAL(requestComplete()), this, SLOT(remoteDirectoryCreated())); if (!conn->execute(QString("mkdir -p %1").arg(remoteDir))) { Logger::logError(tr("Could not initialize ssh resources: user= '%1'\nhost =" " '%2' port = '%3'") .arg(conn->userName()).arg(conn->hostName()) .arg(conn->portNumber()), job.moleQueueId()); job.setJobState(MoleQueue::Error); conn->deleteLater(); return; } } void QueueRemoteSsh::remoteDirectoryCreated() { SshConnection *conn = qobject_cast<SshConnection*>(sender()); if (!conn) { Logger::logError(tr("Internal error: %1\n%2").arg(Q_FUNC_INFO) .arg("Sender is not an SshConnection!")); return; } conn->deleteLater(); Job job = conn->data().value<Job>(); if (!job.isValid()) { Logger::logError(tr("Internal error: %1\n%2").arg(Q_FUNC_INFO) .arg("Sender does not have an associated job!")); return; } if (conn->exitCode() != 0) { Logger::logWarning(tr("Cannot create remote directory '%1@%2:%3'.\n" "Exit code (%4) %5") .arg(conn->userName()).arg(conn->hostName()) .arg(m_workingDirectoryBase).arg(conn->exitCode()) .arg(conn->output()), job.moleQueueId()); // Retry submission: if (addJobFailure(job.moleQueueId())) m_pendingSubmission.append(job.moleQueueId()); job.setJobState(MoleQueue::Error); return; } copyInputFilesToHost(job); } void QueueRemoteSsh::copyInputFilesToHost(Job job) { QString localDir = job.localWorkingDirectory(); QString remoteDir = QDir::cleanPath(QString("%1/%2") .arg(m_workingDirectoryBase) .arg(job.moleQueueId())); SshConnection *conn = newSshConnection(); conn->setData(QVariant::fromValue(job)); connect(conn, SIGNAL(requestComplete()), this, SLOT(inputFilesCopied())); if (!conn->copyDirTo(localDir, remoteDir)) { Logger::logError(tr("Could not initialize ssh resources: user= '%1'\nhost =" " '%2' port = '%3'") .arg(conn->userName()).arg(conn->hostName()) .arg(conn->portNumber()), job.moleQueueId()); job.setJobState(MoleQueue::Error); conn->deleteLater(); return; } } void QueueRemoteSsh::inputFilesCopied() { SshConnection *conn = qobject_cast<SshConnection*>(sender()); if (!conn) { Logger::logError(tr("Internal error: %1\n%2").arg(Q_FUNC_INFO) .arg("Sender is not an SshConnection!")); return; } conn->deleteLater(); Job job = conn->data().value<Job>(); if (!job.isValid()) { Logger::logError(tr("Internal error: %1\n%2").arg(Q_FUNC_INFO) .arg("Sender does not have an associated job!")); return; } if (conn->exitCode() != 0) { // Check if we just need to make the parent directory if (conn->exitCode() == 1 && conn->output().contains("No such file or directory")) { Logger::logDebugMessage(tr("Remote working directory missing on remote " "host. Creating now..."), job.moleQueueId()); createRemoteDirectory(job); return; } Logger::logWarning(tr("Error while copying input files to remote host:\n" "'%1' --> '%2/'\nExit code (%3) %4") .arg(job.localWorkingDirectory()) .arg(m_workingDirectoryBase) .arg(conn->exitCode()).arg(conn->output()), job.moleQueueId()); // Retry submission: if (addJobFailure(job.moleQueueId())) m_pendingSubmission.append(job.moleQueueId()); job.setJobState(MoleQueue::Error); return; } submitJobToRemoteQueue(job); } void QueueRemoteSsh::submitJobToRemoteQueue(Job job) { const QString command = QString("cd %1/%2 && %3 %4") .arg(m_workingDirectoryBase) .arg(job.moleQueueId()) .arg(m_submissionCommand) .arg(m_launchScriptName); SshConnection *conn = newSshConnection(); conn->setData(QVariant::fromValue(job)); connect(conn, SIGNAL(requestComplete()), this, SLOT(jobSubmittedToRemoteQueue())); if (!conn->execute(command)) { Logger::logError(tr("Could not initialize ssh resources: user= '%1'\nhost =" " '%2' port = '%3'") .arg(conn->userName()).arg(conn->hostName()) .arg(conn->portNumber()), job.moleQueueId()); job.setJobState(MoleQueue::Error); conn->deleteLater(); return; } } void QueueRemoteSsh::jobSubmittedToRemoteQueue() { SshConnection *conn = qobject_cast<SshConnection*>(sender()); if (!conn) { Logger::logError(tr("Internal error: %1\n%2").arg(Q_FUNC_INFO) .arg("Sender is not an SshConnection!")); return; } conn->deleteLater(); IdType queueId; parseQueueId(conn->output(), &queueId); Job job = conn->data().value<Job>(); if (!job.isValid()) { Logger::logError(tr("Internal error: %1\n%2").arg(Q_FUNC_INFO) .arg("Sender does not have an associated job!")); return; } if (conn->exitCode() != 0) { Logger::logWarning(tr("Could not submit job to remote queue on %1@%2:%3\n" "%4 %5/%6/%7\nExit code (%8) %9") .arg(conn->userName()).arg(conn->hostName()) .arg(conn->portNumber()).arg(m_submissionCommand) .arg(m_workingDirectoryBase).arg(job.moleQueueId()) .arg(m_launchScriptName).arg(conn->exitCode()) .arg(conn->output()), job.moleQueueId()); // Retry submission: if (addJobFailure(job.moleQueueId())) m_pendingSubmission.append(job.moleQueueId()); job.setJobState(MoleQueue::Error); return; } job.setJobState(MoleQueue::Submitted); clearJobFailures(job.moleQueueId()); job.setQueueId(queueId); m_jobs.insert(queueId, job.moleQueueId()); } void QueueRemoteSsh::requestQueueUpdate() { if (m_isCheckingQueue) return; if (m_jobs.isEmpty()) return; m_isCheckingQueue = true; const QString command = generateQueueRequestCommand(); SshConnection *conn = newSshConnection(); connect(conn, SIGNAL(requestComplete()), this, SLOT(handleQueueUpdate())); if (!conn->execute(command)) { Logger::logError(tr("Could not initialize ssh resources: user= '%1'\nhost =" " '%2' port = '%3'") .arg(conn->userName()).arg(conn->hostName()) .arg(conn->portNumber())); conn->deleteLater(); return; } } void QueueRemoteSsh::handleQueueUpdate() { SshConnection *conn = qobject_cast<SshConnection*>(sender()); if (!conn) { Logger::logError(tr("Internal error: %1\n%2").arg(Q_FUNC_INFO) .arg("Sender is not an SshConnection!")); m_isCheckingQueue = false; return; } conn->deleteLater(); if (!m_allowedQueueRequestExitCodes.contains(conn->exitCode())) { Logger::logWarning(tr("Error requesting queue data (%1 -u %2) on remote " "host %3@%4:%5. Exit code (%6) %7") .arg(m_requestQueueCommand) .arg(m_userName).arg(conn->userName()) .arg(conn->hostName()).arg(conn->portNumber()) .arg(conn->exitCode()).arg(conn->output())); m_isCheckingQueue = false; return; } QStringList output = conn->output().split("\n", QString::SkipEmptyParts); // Get list of submitted queue ids so that we detect when jobs have left // the queue. QList<IdType> queueIds = m_jobs.keys(); MoleQueue::JobState state; foreach (QString line, output) { IdType queueId; if (parseQueueLine(line, &queueId, &state)) { IdType moleQueueId = m_jobs.value(queueId, InvalidId); if (moleQueueId != InvalidId) { queueIds.removeOne(queueId); // Get pointer to jobmanager to lookup job if (!m_server) { Logger::logError(tr("Queue '%1' cannot locate Server instance!") .arg(m_name), moleQueueId); m_isCheckingQueue = false; return; } Job job = m_server->jobManager()->lookupJobByMoleQueueId(moleQueueId); if (!job.isValid()) { Logger::logError(tr("Queue '%1' Cannot update invalid Job reference!") .arg(m_name), moleQueueId); continue; } job.setJobState(state); } } } // Now copy back any jobs that have left the queue foreach (IdType queueId, queueIds) beginFinalizeJob(queueId); m_isCheckingQueue = false; } void QueueRemoteSsh::beginFinalizeJob(IdType queueId) { IdType moleQueueId = m_jobs.value(queueId, InvalidId); if (moleQueueId == InvalidId) return; m_jobs.remove(queueId); // Lookup job if (!m_server) return; Job job = m_server->jobManager()->lookupJobByMoleQueueId(moleQueueId); if (!job.isValid()) return; finalizeJobCopyFromServer(job); } void QueueRemoteSsh::finalizeJobCopyFromServer(Job job) { if (!job.retrieveOutput() || (job.cleanLocalWorkingDirectory() && job.outputDirectory().isEmpty()) ) { // Jump to next step finalizeJobCopyToCustomDestination(job); return; } QString localDir = job.localWorkingDirectory() + "/.."; QString remoteDir = QString("%1/%2").arg(m_workingDirectoryBase).arg(job.moleQueueId()); SshConnection *conn = newSshConnection(); conn->setData(QVariant::fromValue(job)); connect(conn, SIGNAL(requestComplete()), this, SLOT(finalizeJobOutputCopiedFromServer())); if (!conn->copyDirFrom(remoteDir, localDir)) { Logger::logError(tr("Could not initialize ssh resources: user= '%1'\nhost =" " '%2' port = '%3'") .arg(conn->userName()).arg(conn->hostName()) .arg(conn->portNumber()), job.moleQueueId()); job.setJobState(MoleQueue::Error); conn->deleteLater(); return; } } void QueueRemoteSsh::finalizeJobOutputCopiedFromServer() { SshConnection *conn = qobject_cast<SshConnection*>(sender()); if (!conn) { Logger::logError(tr("Internal error: %1\n%2").arg(Q_FUNC_INFO) .arg("Sender is not an SshConnection!")); return; } conn->deleteLater(); Job job = conn->data().value<Job>(); if (!job.isValid()) { Logger::logError(tr("Internal error: %1\n%2").arg(Q_FUNC_INFO) .arg("Sender does not have an associated job!")); return; } if (conn->exitCode() != 0) { Logger::logError(tr("Error while copying job output from remote server:\n" "%1@%2:%3 --> %4\nExit code (%5) %6") .arg(conn->userName()).arg(conn->hostName()) .arg(conn->portNumber()).arg(job.localWorkingDirectory()) .arg(conn->exitCode()).arg(conn->output()), job.moleQueueId()); job.setJobState(MoleQueue::Error); return; } finalizeJobCopyToCustomDestination(job); } void QueueRemoteSsh::finalizeJobCopyToCustomDestination(Job job) { // Skip to next step if needed if (job.outputDirectory().isEmpty() || job.outputDirectory() == job.localWorkingDirectory()) { finalizeJobCleanup(job); return; } // The copy function will throw errors if needed. if (!recursiveCopyDirectory(job.localWorkingDirectory(), job.outputDirectory())) { job.setJobState(MoleQueue::Error); return; } finalizeJobCleanup(job); } void QueueRemoteSsh::finalizeJobCleanup(Job job) { if (job.cleanLocalWorkingDirectory()) cleanLocalDirectory(job); if (job.cleanRemoteFiles()) cleanRemoteDirectory(job); job.setJobState(MoleQueue::Finished); } void QueueRemoteSsh::cleanRemoteDirectory(Job job) { QString remoteDir = QDir::cleanPath( QString("%1/%2").arg(m_workingDirectoryBase).arg(job.moleQueueId())); // Check that the remoteDir is not just "/" due to another bug. if (remoteDir.simplified() == "/") { Logger::logError(tr("Refusing to clean remote directory %1 -- an internal " "error has occurred.").arg(remoteDir), job.moleQueueId()); return; } QString command = QString ("rm -rf %1").arg(remoteDir); SshConnection *conn = newSshConnection(); conn->setData(QVariant::fromValue(job)); connect(conn, SIGNAL(requestComplete()), this, SLOT(remoteDirectoryCleaned())); if (!conn->execute(command)) { Logger::logError(tr("Could not initialize ssh resources: user= '%1'\nhost =" " '%2' port = '%3'") .arg(conn->userName()).arg(conn->hostName()) .arg(conn->portNumber()), job.moleQueueId()); conn->deleteLater(); return; } } void QueueRemoteSsh::remoteDirectoryCleaned() { SshConnection *conn = qobject_cast<SshConnection*>(sender()); if (!conn) { Logger::logError(tr("Internal error: %1\n%2").arg(Q_FUNC_INFO) .arg("Sender is not an SshConnection!")); return; } conn->deleteLater(); Job job = conn->data().value<Job>(); if (!job.isValid()) { Logger::logError(tr("Internal error: %1\n%2").arg(Q_FUNC_INFO) .arg("Sender does not have an associated job!")); return; } if (conn->exitCode() != 0) { Logger::logError(tr("Error clearing remote directory '%1@%2:%3/%4'.\n" "Exit code (%5) %6") .arg(conn->userName()).arg(conn->hostName()) .arg(m_workingDirectoryBase).arg(job.moleQueueId()) .arg(conn->exitCode()).arg(conn->output()), job.moleQueueId()); job.setJobState(MoleQueue::Error); return; } } void QueueRemoteSsh::beginKillJob(Job job) { const QString command = QString("%1 %2") .arg(m_killCommand) .arg(job.queueId()); SshConnection *conn = newSshConnection(); conn->setData(QVariant::fromValue(job)); connect(conn, SIGNAL(requestComplete()), this, SLOT(endKillJob())); if (!conn->execute(command)) { Logger::logError(tr("Could not initialize ssh resources: user= '%1'\nhost =" " '%2' port = '%3'") .arg(conn->userName()).arg(conn->hostName()) .arg(conn->portNumber()), job.moleQueueId()); job.setJobState(MoleQueue::Error); conn->deleteLater(); return; } } void QueueRemoteSsh::endKillJob() { SshConnection *conn = qobject_cast<SshConnection*>(sender()); if (!conn) { Logger::logError(tr("Internal error: %1\n%2").arg(Q_FUNC_INFO) .arg("Sender is not an SshConnection!")); return; } conn->deleteLater(); Job job = conn->data().value<Job>(); if (!job.isValid()) { Logger::logError(tr("Internal error: %1\n%2").arg(Q_FUNC_INFO) .arg("Sender does not have an associated job!")); return; } if (conn->exitCode() != 0) { Logger::logWarning(tr("Error cancelling job (mqid=%1, queueid=%2) on " "%3@%4:%5 (queue=%6)\n(%7) %8") .arg(job.moleQueueId()).arg(job.queueId()) .arg(conn->userName()).arg(conn->hostName()) .arg(conn->portNumber()).arg(m_name) .arg(conn->exitCode()).arg(conn->output())); return; } job.setJobState(MoleQueue::Killed); } SshConnection *QueueRemoteSsh::newSshConnection() { SshCommand *command = SshCommandFactory::instance()->newSshCommand(); command->setSshCommand(m_sshExecutable); command->setScpCommand(m_scpExecutable); command->setHostName(m_hostName); command->setUserName(m_userName); command->setIdentityFile(m_identityFile); command->setPortNumber(m_sshPort); return command; } QString QueueRemoteSsh::generateQueueRequestCommand() { QList<IdType> queueIds = m_jobs.keys(); QString queueIdString; foreach (IdType id, queueIds) { queueIdString += QString::number(id) + " "; } return QString ("%1 %2").arg(m_requestQueueCommand).arg(queueIdString); } } // End namespace
yeshodhan/xsd-to-simplexml
src/test/java/com/vast/DeliveryEnum.java
package com.vast; import org.simpleframework.xml.Namespace; import org.simpleframework.xml.Root; @Root(name = "deliveryEnum") @Namespace(reference = "") public enum DeliveryEnum { streaming, progressive; }
GudangHijrah/e-shop
main/sites/all/libraries/easychart/src/js/components/hot.js
<gh_stars>10-100 (function () { //var _ = require('lodash'); var _ = { forEach: require('lodash.foreach'), isEmpty: require('lodash.isempty'), isUndefined: require('lodash.isundefined') }; var h = require('virtual-dom/h'); var createElement = require('virtual-dom/create-element'); var hot; function constructor(services) { var that = {}; var element; var readOnly; that.load = function (_element_) { element = _element_; var wrapper = createElement(h('div')); readOnly = services.data.getUrl() ? true : false; if (readOnly){ element.appendChild(createElement(h('div.readOnlyBox', h('span', 'A data url was found, the data will be read only')))); } element.appendChild(wrapper); var data = services.data.get(); data = _.isUndefined(data[0]) ? [[]] : data; hot = new Handsontable(wrapper, { minRows: 2, minCols: 2, minSpareRows: 1, //minSpareCols: 1, height: 500, stretchH: 'all', rowHeaders: true, colHeaders: true, contextMenu: true, data: data, afterChange: function () { if(!readOnly){ services.data.set(removeEmptyRows(this)); } }, afterRemoveRow:function () { if(!readOnly){ services.data.set(removeEmptyRows(this)); } }, afterRemoveCol:function (test) { if(!readOnly){ services.data.set(removeEmptyRows(this)); } } }); hot.updateSettings({ cells: function (row, col, prop) { var cellProperties = {}; cellProperties.readOnly = readOnly; return cellProperties; } }); services.mediator.on('dataUpdate', function (_data_) { readOnly = services.data.getUrl() ? true : false; if(_data_.length > 0){ hot.updateSettings({ data: _data_, cells: function (row, col, prop) { var cellProperties = {}; cellProperties.readOnly = readOnly; return cellProperties; } }); } else { hot.clear(); } }, 'hot'); }; var Hook = function () {}; Hook.prototype.hook = function (node) { setTimeout(function () { that.load(node); }); }; that.template = function () { return h('div', { 'afterRender': new Hook() }); }; that.destroy = function () { services.mediator.off(null, null, 'hot'); var data = removeEmptyRows(hot); if (!_.isEmpty(data) && !readOnly) { services.data.set(removeEmptyRows(hot)); } hot.destroy(); element.innerHTML = ''; }; function removeEmptyRows(hot) { var gridData = hot.getData(); var cleanedGridData = []; _.forEach(gridData, function (object, rowKey) { if (!hot.isEmptyRow(rowKey)) cleanedGridData[rowKey] = object; }); return cleanedGridData; } return that; } module.exports = constructor; })();
LaudateCorpus1/BugTrap
source/Examples/BugTrapLogTest/stdafx.h
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #include <windows.h> #include <process.h> #include <stdio.h> #include <tchar.h> #include <shlwapi.h> #include <eh.h> // include set_terminate() declaration // BugTrap includes ////////////////////////////////////////////////////////////// // Include main BugTrap header. #include <BugTrap.h> // Link with one of BugTrap libraries. #if defined _M_IX86 #ifdef _UNICODE #pragma comment(lib, "BugTrapU.lib") #else #pragma comment(lib, "BugTrap.lib") #endif #elif defined _M_X64 #ifdef _UNICODE #pragma comment(lib, "BugTrapU-x64.lib") #else #pragma comment(lib, "BugTrap-x64.lib") #endif #else #error CPU architecture is not supported. #endif // Enable Common Controls support #if defined _M_IX86 #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='<KEY>' language='*'\"") #elif defined _M_IA64 #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='<KEY>' language='*'\"") #elif defined _M_X64 #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='<KEY>' language='*'\"") #else #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='<KEY>' language='*'\"") #endif
importlib/klib
master/core/third/RCF/src/RCF/Token.cpp
<filename>master/core/third/RCF/src/RCF/Token.cpp //***************************************************************************** // RCF - Remote Call Framework // Copyright (c) 2005. All rights reserved. // Developed by <NAME>. // Contact: <EMAIL> . //***************************************************************************** #include <RCF/Token.hpp> #include <iostream> namespace RCF { //***************************************** // Token Token::Token() : id() {} bool operator<(const Token &lhs, const Token &rhs) { return (lhs.getId() < rhs.getId()); } bool operator==(const Token &lhs, const Token &rhs) { return lhs.getId() == rhs.getId(); } bool operator!=(const Token &lhs, const Token &rhs) { return ! (lhs == rhs); } int Token::getId() const { return id; } std::ostream &operator<<(std::ostream &os, const Token &token) { os << "( id = " << token.getId() << " )"; return os; } Token::Token(int id) : id(id) {} } // namespace RCF
rblbank13557/finacle_api
lib/finacle_api/cust_chq_book/response/execute_finacle_script_custom_data.rb
require 'finacle_api/common/serializable_object' module FinacleApi module CustChqBook module ResponseEntity class ExecuteFinacleScriptCustomData < SerializableObject attr_accessor :status, :message, :success_or_failure, :chq_alwd_flg, :error_code, :error_msg, :frez_code, :acct_cls_flg, :acct_status def response_message response_message = @message if @message.present? response_message ||= @acct_status if @acct_status.present? response_message ||= @acct_cls_flg if @acct_cls_flg.present? response_message ||= @frez_code if @frez_code.present? response_message ||= @error_msg if @error_msg.present? response_message ||= @chq_alwd_flg if @chq_alwd_flg.present? response_message end def success? status == 'SUCCESS' || success_or_failure == 'Y' end end end end end
Falvyu/JukeAlert
src/main/java/com/untamedears/jukealert/model/actions/abstr/PlayerAction.java
<filename>src/main/java/com/untamedears/jukealert/model/actions/abstr/PlayerAction.java package com.untamedears.jukealert.model.actions.abstr; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.UUID; import com.untamedears.jukealert.model.Snitch; import vg.civcraft.mc.namelayer.NameAPI; public abstract class PlayerAction extends SnitchAction { private static final DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; protected final UUID player; public PlayerAction(long time, Snitch snitch, UUID player) { super(time, snitch); this.player = player; } /** * @return Player who commited the action */ public UUID getPlayer() { return player; } @Override public boolean hasPlayer() { return true; } protected String getFormattedTime() { return timeFormatter.format(LocalDateTime.ofEpochSecond(time / 1000, 0, ZoneOffset.UTC)); } public String getPlayerName() { return NameAPI.getCurrentName(player); } }
goghtsui/TouchKey
app/src/main/java/com/gogh/floatkey/ui/PayListBrowserFragment.java
package com.gogh.floatkey.ui; import android.Manifest; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.gogh.floatkey.R; import com.gogh.floatkey.model.PayExtra; import com.gogh.floatkey.provider.PayExtraLoader; import java.util.ArrayList; import java.util.List; import github.tornaco.permission.requester.RequiresPermission; import github.tornaco.permission.requester.RuntimePermissions; /** * Created by Tornaco on 2017/7/29. * Licensed with Apache. */ @RuntimePermissions public class PayListBrowserFragment extends Fragment { private RecyclerView recyclerView; private SwipeRefreshLayout swipeRefreshLayout; private Adapter adapter; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View root = inflater.inflate(R.layout.recycler_view_template, container, false); setupView(root); return root; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getActivity().setTitle(R.string.title_pay_list); PayListBrowserFragmentPermissionRequester.startLoadingChecked(this); } public void setupView(View root) { swipeRefreshLayout = (SwipeRefreshLayout) root.findViewById(R.id.swipe); swipeRefreshLayout.setColorSchemeColors(getResources().getIntArray(R.array.polluted_waves)); recyclerView = (RecyclerView) root.findViewById(R.id.recycler_view); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { startLoading(); } }); setupAdapter(); } @RequiresPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}) @RequiresPermission.OnDenied("onPermissionNotGrant") void startLoading() { swipeRefreshLayout.setRefreshing(true); new PayExtraLoader().loadAsync(getString(R.string.pay_list_url), new PayExtraLoader.Callback() { @Override public void onError(final Throwable e) { if (getActivity() == null) return; getActivity().runOnUiThread(new Runnable() { @Override public void run() { swipeRefreshLayout.setRefreshing(false); } }); } @Override public void onSuccess(final List<PayExtra> extras) { if (getActivity() == null) return; getActivity().runOnUiThread(new Runnable() { @Override public void run() { adapter.update(extras); swipeRefreshLayout.setRefreshing(false); } }); } }); } void onPermissionNotGrant() { getActivity().finish(); } protected void setupAdapter() { recyclerView.setHasFixedSize(true); setupLayoutManager(); adapter = new Adapter(); recyclerView.setAdapter(adapter); } protected void setupLayoutManager() { recyclerView.setLayoutManager(getLayoutManager()); } protected RecyclerView.LayoutManager getLayoutManager() { return new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); PayListBrowserFragmentPermissionRequester.onRequestPermissionsResult(requestCode, permissions, grantResults); } class TwoLinesViewHolder extends RecyclerView.ViewHolder { TextView title; TextView description; ImageView thumbnail; TwoLinesViewHolder(final View itemView) { super(itemView); title = (TextView) itemView.findViewById(android.R.id.title); description = (TextView) itemView.findViewById(android.R.id.text1); thumbnail = (ImageView) itemView.findViewById(R.id.avatar); thumbnail.setImageResource(R.drawable.ic_header_avatar); } } private class Adapter extends RecyclerView.Adapter<TwoLinesViewHolder> { private final List<PayExtra> data; public Adapter(List<PayExtra> data) { this.data = data; } public Adapter() { this(new ArrayList<PayExtra>()); } public void update(List<PayExtra> data) { this.data.clear(); this.data.addAll(data); notifyDataSetChanged(); } public void remove(int position) { this.data.remove(position); notifyItemRemoved(position); } public void add(PayExtra PayExtra, int position) { this.data.add(position, PayExtra); notifyItemInserted(position); } @Override public TwoLinesViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) { final View view = LayoutInflater.from(getContext()).inflate(R.layout.simple_card_item, parent, false); return new TwoLinesViewHolder(view); } @Override public void onBindViewHolder(final TwoLinesViewHolder holder, int position) { final PayExtra item = data.get(position); holder.title.setText(item.getNick()); String descriptionText = item.getAd(); holder.description.setText(descriptionText); } @Override public int getItemCount() { return data.size(); } } }
fjdearcos-amplia/oda
oda-operations/update/src/main/java/es/amplia/oda/operation/update/operations/UpgradeDeploymentElementOperation.java
package es.amplia.oda.operation.update.operations; import es.amplia.oda.operation.update.FileManager; import es.amplia.oda.operation.update.OperationConfirmationProcessor; import static es.amplia.oda.operation.api.OperationUpdate.DeploymentElement; import static es.amplia.oda.operation.update.FileManager.FileException; public class UpgradeDeploymentElementOperation extends DeploymentElementOperationBase { private final String localFile; private final String installFolder; private String upgradedFile; UpgradeDeploymentElementOperation(DeploymentElement deploymentElement, String localFile, String installFolder, FileManager fileManager, OperationConfirmationProcessor operationConfirmationProcessor) { super(deploymentElement, fileManager, operationConfirmationProcessor); this.localFile = localFile; this.installFolder = installFolder; } @Override protected void executeSpecificOperation(FileManager fileManager) throws FileException, DeploymentElementOperationException { String installedFile = fileManager.find(installFolder, getName()); if (installedFile == null) { throw new DeploymentElementOperationException("Deployment element file to upgrade is not found"); } fileManager.delete(installedFile); upgradedFile = fileManager.copy(localFile, installFolder); } @Override protected void rollbackSpecificOperation(FileManager fileManager, String backupFile) throws FileException { fileManager.delete(upgradedFile); fileManager.copy(backupFile, installFolder); } }
kelemen/JTrim
subprojects/jtrim-swing-component/src/test/java/org/jtrim2/swing/component/BasicRenderingArgumentsTest.java
package org.jtrim2.swing.component; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.util.Arrays; import org.junit.Test; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class BasicRenderingArgumentsTest { private static Color newColor() { return new Color(20, 30, 40, 50); } private static Font newFont() { return new Font("Arial", Font.ITALIC, 10); } @Test public void testExplicit() { for (Color bckg: Arrays.asList(null, newColor())) { for (Color foreground: Arrays.asList(null, newColor())) { for (Font font: Arrays.asList(null, newFont())) { BasicRenderingArguments args = new BasicRenderingArguments(bckg, foreground, font); assertSame(bckg, args.getBackgroundColor()); assertSame(foreground, args.getForegroundColor()); assertSame(font, args.getFont()); } } } } @Test public void testFromComponent() { for (Color bckg: Arrays.asList(null, newColor())) { for (Color foreground: Arrays.asList(null, newColor())) { for (Font font: Arrays.asList(null, newFont())) { Component component = mock(Component.class); stub(component.getBackground()).toReturn(bckg); stub(component.getForeground()).toReturn(foreground); stub(component.getFont()).toReturn(font); BasicRenderingArguments args = new BasicRenderingArguments(component); assertSame(bckg, args.getBackgroundColor()); assertSame(foreground, args.getForegroundColor()); assertSame(font, args.getFont()); verify(component).getBackground(); verify(component).getForeground(); verify(component).getFont(); verifyNoMoreInteractions(component); } } } } }
hhhhhaaaa/hearthlibrary
appStart/client/src/components/Col/Col.js
import React from "react"; import PropTypes from "prop-types"; /* This Col component offers us the convenience of being able to set a column's "size" prop instead of its className We can also omit the col- at the start of each Bootstrap column class, e.g. size="md-12" instead of className="col-md-12" */ /** * @param props * @param props.size * @param props.children */ function Col({ size, children }) { const sizeCol = size .split(" ") .map((sizeEach) => `col-${sizeEach}`) .join(" "); return <div className={sizeCol}>{children}</div>; } Col.propTypes = { children: PropTypes.any, size: PropTypes.string }; export default Col;
wlbwrx/plushe-jds-admin
src/api/shop.js
<gh_stars>0 import request from '@/utils/request'; // 查询所有的品牌 const platformListData = () =>{ return request({ url: '/gds/shop/conf/all/list', method: 'get', }) } // 品牌配置 const shopListData = (query) =>{ return request({ url: '/gds/shop/page/list', method: 'get', params: query }) } // 新增品牌 const addShopData = (query) => { return request({ url: '/gds/shop/add', method: 'post', data: query }) } // 查询所有的平台和店铺 二级联动数据 const platformShopData = () => { return request({ url: '/gds/shop/all/list', method: 'get' }) } // 启用/禁用 const platformEablepData = (query) => { return request({ url: `/gds/shop/${query.id}/enable`, method: 'put', params:query }) } // 删除品牌 const platformDeleteData = (query) => { return request({ url: `/gds/shop/${query.id}/delete`, method: 'DELETE', params:query }) } // 更新品牌信息 const platformUpdateData = (query) => { return request({ url: `/gds/shop/baseInfo/${query.id}/update`, method: 'put', data:query }) } // 品牌配置排序 const platformSortData = (query) => { return request({ url: `/gds/shop/sort/${query.id}/update`, method: 'put', params:query }) } // 分享人佣金配置 const shopShareAllData = (query) => { return request({ url: '/gds/share/shop/page/list', method: 'get', params: query }) } // 分享佣金配置新增 const shopShareAddData = (query) => { return request({ url: '/gds/share/shop/add', method: 'post', data: query }) } // 分享佣金配置删除 const shopShareDelData = (query) => { return request({ url: `/gds/share/shop/${query.id}/delete`, method: 'DELETE', params: query }) } // 分享佣金配置修改 const shopShareUpdateData = (query) => { return request({ url:`/gds/share/shop/${query.id}/update`, method: 'put', data: query }) } // ------------ // 分享文案配置 // 查询 const shopTextAllData = (query) => { return request({ url:`/gds/share/doc/template/pageQuery`, method: 'get', params: query }) } // 新增 const shopTextAddData = (query) => { return request({ url:`/gds/share/doc/template/batchAdd`, method: 'post', data: query }) } // 编辑 const shopTextUpdateData = (query) => { return request({ url:`/gds/share/doc/template/${query.id}/update`, method: 'put', data: query }) } // 删除 const shopTextDelData = (query) => { return request({ url:`/gds/share/doc/template/${query.id}/delete`, method: 'DELETE', params: query }) } // ---------------------- export default { platformListData, shopListData, addShopData, platformShopData, platformEablepData, platformDeleteData, platformUpdateData, platformSortData, shopShareAllData, shopShareAddData, shopShareDelData, shopShareUpdateData, shopTextAllData, shopTextAddData, shopTextUpdateData, shopTextDelData }
Yoda2798/YodasMod
src/main/java/YodasMod/relics/TwoHeads.java
package YodasMod.relics; import com.megacrit.cardcrawl.actions.common.ApplyPowerAction; import com.megacrit.cardcrawl.actions.common.RelicAboveCreatureAction; import com.megacrit.cardcrawl.actions.utility.UseCardAction; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.cards.CardQueueItem; import com.megacrit.cardcrawl.core.Settings; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.monsters.AbstractMonster; import static YodasMod.YodasMod.makeID; public class TwoHeads extends AbstractEasyRelic { public static final String ID = makeID("TwoHeads"); private static boolean ATTACK_USED = false; private static boolean SKILL_USED = false; private static boolean POWER_USED = false; public TwoHeads() { super(ID, RelicTier.BOSS, LandingSound.FLAT); } public void atBattleStart() { ATTACK_USED = false; SKILL_USED = false; POWER_USED = false; } public void onUseCard(AbstractCard card, UseCardAction action) { if (!card.purgeOnUse) { // check if used up respective type, this could be cleaner somehow but I am bad if (card.type == AbstractCard.CardType.ATTACK) { if (ATTACK_USED) {return;} ATTACK_USED = true; } else if (card.type == AbstractCard.CardType.SKILL) { if (SKILL_USED) {return;} SKILL_USED = true; } else if (card.type == AbstractCard.CardType.POWER) { if (POWER_USED) {return;} POWER_USED = true; } else { return; } this.flash(); this.addToBot(new RelicAboveCreatureAction(AbstractDungeon.player, this)); AbstractMonster m = null; if (action.target != null) { m = (AbstractMonster)action.target; } AbstractCard tmp = card.makeSameInstanceOf(); AbstractDungeon.player.limbo.addToBottom(tmp); tmp.current_x = card.current_x; tmp.current_y = card.current_y; tmp.target_x = (float) Settings.WIDTH / 2.0F - 300.0F * Settings.scale; tmp.target_y = (float)Settings.HEIGHT / 2.0F; if (m != null) { tmp.calculateCardDamage(m); } tmp.purgeOnUse = true; AbstractDungeon.actionManager.addCardQueueItem(new CardQueueItem(tmp, m, card.energyOnUse, true, true), true); } } }
sungloow/PetAdoption
src/main/java/com/sunhongbing/petadoption/forestage/controller/AboutUsController.java
<reponame>sungloow/PetAdoption package com.sunhongbing.petadoption.forestage.controller; import com.sunhongbing.petadoption.backstage.entity.Article; import com.sunhongbing.petadoption.backstage.entity.User; import com.sunhongbing.petadoption.backstage.enums.ArticleType; import com.sunhongbing.petadoption.backstage.result.ResultVO; import com.sunhongbing.petadoption.backstage.service.ArticleService; import com.sunhongbing.petadoption.backstage.service.UserService; import com.sunhongbing.petadoption.forestage.Utils; import com.sunhongbing.petadoption.forestage.entity.AdoptionStatus; import org.apache.shiro.SecurityUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; /** * @className: AboutUsController * @Description: TODO * @author: <NAME> * @date: 2022-02-10 17:43 */ @Controller @RequestMapping("/about_us") public class AboutUsController { @Autowired private ArticleService articleService; @Autowired private UserService userService; // introduction.html @RequestMapping("/introduction") public String index(Model model) { List<Article> articleList = articleService.queryArticles(ArticleType.ABOUT_ORGANIZATION.getCode(), AdoptionStatus.ACCEPT.getCode(), "id", "asc"); Article article = Utils.handlerAboutUsArticle(articleList); model.addAttribute("article", article); return "forestage/about-us/introduction"; } // contact.html @GetMapping("/contact") public String contact() { return "forestage/about-us/contact"; } // contact post @PostMapping("/contact_post") @ResponseBody public ResultVO contactPost(Article article) { ResultVO vo = new ResultVO(); int userId; try { userId = (int) SecurityUtils.getSubject().getPrincipal(); } catch (Exception e) { vo.setCode(500); vo.setMsg("请先登录"); return vo; } User user = userService.getUserById(userId); if (user == null) { vo.setCode(500); vo.setMsg("请先登录"); return vo; } article.setAuthor(user.getEmail()); int i = articleService.addArticle(article); if (i == 1) { vo.setCode(200); vo.setMsg("提交成功"); } else { vo.setCode(500); vo.setMsg("提交失败"); } return vo; } // working-time.html @RequestMapping("/working-time") public String workingTime(Model model) { List<Article> articleList = articleService.queryArticles(ArticleType.ABOUT_TIME_PLACE.getCode(), AdoptionStatus.ACCEPT.getCode(), "id", "asc"); Article article = Utils.handlerAboutUsArticle(articleList); model.addAttribute("article", article); return "forestage/about-us/working-time"; } // faq.html @RequestMapping("/faq") public String faq(Model model) { List<Article> articleList = articleService.queryArticles(ArticleType.ABOUT_QUESTION.getCode(), AdoptionStatus.ACCEPT.getCode(), "id", "asc"); Article article = Utils.handlerAboutUsArticle(articleList); model.addAttribute("article", article); return "forestage/about-us/faq"; } }
MovieCast/moviecast-android
base/src/main/java/io/moviecast/base/providers/response/models/ListResponse.java
/* * Copyright (c) MovieCast and it's contributors. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. */ package io.moviecast.base.providers.response.models; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; import io.moviecast.base.models.Media; public abstract class ListResponse<T extends ResponseItem> { @SerializedName("page") protected int pageNumber; @SerializedName("totalResults") protected int totalResults; @SerializedName("totalPages") protected int totalPages; @SerializedName("results") protected List<T> result = new ArrayList<>(); public int getPageNumber() { return pageNumber; } public List<T> getResult() { return result; } public abstract List<Media> getFormattedResult(); public int getTotalResults() { return totalResults; } public int getTotalPages() { return totalPages; } }
rreusser/rreusser.github.io
src/src/iterative-closest-point/draw-background.js
const glsl = require('glslify'); module.exports = function (regl) { return regl({ vert: ` precision highp float; attribute vec2 aUv; varying vec2 vXy; void main () { vXy = aUv; gl_Position = vec4(aUv, 0, 1); } `, frag: glsl` #extension GL_OES_standard_derivatives : enable precision highp float; varying vec2 vXy; uniform vec3 uEye; uniform float uLineWidth; uniform float uGrid1Strength, uGrid1Density; uniform mat4 uProjectionInv, uViewInv, uProjection, uView; float grid (vec2 parameter, float width, float feather) { float w1 = width - feather * 0.5; vec2 d = fwidth(parameter); vec2 looped = 0.5 - abs(mod(parameter, 1.0) - 0.5); vec2 a2 = smoothstep(d * w1, d * (w1 + feather), looped); return min(a2.x, a2.y); } void main () { vec4 x = uViewInv * vec4((uProjectionInv * vec4(-vXy, 0.0, 1.0)).xy, -1.0, 0.0); vec2 xy = (uEye + x.xyz * uEye.z / x.z).xy; float gridFactor1 = (1.0 - grid(xy * uGrid1Density, uLineWidth, 1.5)); gl_FragColor = vec4(mix( vec3(0.92, 0.94, 0.95) * 0.98, vec3(0.85, 0.86, 0.87) * 0.98, gridFactor1 ), 1); } `, attributes: {aUv: [-4, -4, 0, 4, 4, -4]}, uniforms: { uLineWidth: (ctx, props) => props.lineWidth * ctx.pixelRatio, uGrid1Density: regl.prop('grid1Density'), uGrid1Strength: regl.prop('grid1Strength'), }, depth: {enable: false}, count: 3 }); };
chromium/chromium
chrome/browser/ash/policy/reporting/metrics_reporting/usb/usb_events_observer.cc
<reponame>chromium/chromium // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/policy/reporting/metrics_reporting/usb/usb_events_observer.h" #include "chromeos/services/cros_healthd/public/cpp/service_connection.h" #include "components/reporting/proto/synced/metric_data.pb.h" using UsbEventInfoPtr = chromeos::cros_healthd::mojom::UsbEventInfoPtr; namespace reporting { UsbEventsObserver::UsbEventsObserver() : CrosHealthdEventsObserverBase< chromeos::cros_healthd::mojom::CrosHealthdUsbObserver>(this) {} UsbEventsObserver::~UsbEventsObserver() = default; void UsbEventsObserver::OnAdd(UsbEventInfoPtr info) { MetricData metric_data; metric_data.mutable_event_data()->set_type(MetricEventType::USB_ADDED); FillUsbEventData(metric_data.mutable_event_data()->mutable_usb_event_data(), std::move(info)); OnEventObserved(std::move(metric_data)); } void UsbEventsObserver::OnRemove(UsbEventInfoPtr info) { MetricData metric_data; metric_data.mutable_event_data()->set_type(MetricEventType::USB_REMOVED); FillUsbEventData(metric_data.mutable_event_data()->mutable_usb_event_data(), std::move(info)); OnEventObserved(std::move(metric_data)); } void UsbEventsObserver::AddObserver() { chromeos::cros_healthd::ServiceConnection::GetInstance()->AddUsbObserver( BindNewPipeAndPassRemote()); } void UsbEventsObserver::FillUsbEventData(UsbEventData* data, UsbEventInfoPtr info) { data->set_vendor(info->vendor); data->set_name(info->name); data->set_pid(info->pid); data->set_vid(info->vid); for (auto& category : info->categories) { data->add_categories(category); } } } // namespace reporting
ppadmavilasom/claircore
internal/vulnstore/vulnerability.go
package vulnstore import ( "context" "github.com/quay/claircore" "github.com/quay/claircore/libvuln/driver" ) // GetOpts provides instructions on how to // match your packages to vulnerabilities. type GetOpts struct { // Matchers tells the Get() method to limit the returned vulnerabilities by the provided MatchConstraint // see MatchConstraint type def for more info. Matchers []driver.MatchConstraint // Debug asks the database layer to log exta information Debug bool } type Vulnerability interface { // get finds the vulnerabilities which match each package provided in the packages array // this maybe a one to many relationship. each package is assumed to have an ID. // a map of Package.ID => Vulnerabilities is returned. Get(ctx context.Context, records []*claircore.IndexRecord, opts GetOpts) (map[string][]*claircore.Vulnerability, error) }
lechium/tvOS124Headers
Applications/PineBoard/FBSApplicationDataStoreObserver-Protocol.h
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "NSObject.h" @class FBSApplicationDataStoreMonitor, NSString; @protocol FBSApplicationDataStoreObserver <NSObject> @optional - (void)dataStoreMonitor:(FBSApplicationDataStoreMonitor *)arg1 didInvalidateApplication:(NSString *)arg2; - (void)dataStoreMonitor:(FBSApplicationDataStoreMonitor *)arg1 didUpdateApplication:(NSString *)arg2 forKey:(NSString *)arg3; @end
shisa/kame-shisa
netbsd/sys/arch/i386/i386/db_interface.c
/* $NetBSD: db_interface.c,v 1.35 2002/05/14 02:58:35 matt Exp $ */ /* * Mach Operating System * Copyright (c) 1991,1990 Carnegie Mellon University * All Rights Reserved. * * Permission to use, copy, modify and distribute this software and its * documentation is hereby granted, provided that both the copyright * notice and this permission notice appear in all copies of the * software, derivative works or modified versions, and any portions * thereof, and that both notices appear in supporting documentation. * * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. * * Carnegie Mellon requests users of this software to return to * * Software Distribution Coordinator or <EMAIL> * School of Computer Science * Carnegie Mellon University * Pittsburgh PA 15213-3890 * * any improvements or extensions that they make and grant Carnegie the * rights to redistribute these changes. * * db_interface.c,v 2.4 1991/02/05 17:11:13 mrt (CMU) */ /* * Interface to new debugger. */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: db_interface.c,v 1.35 2002/05/14 02:58:35 matt Exp $"); #include "opt_ddb.h" #include <sys/param.h> #include <sys/proc.h> #include <sys/reboot.h> #include <sys/systm.h> #include <uvm/uvm_extern.h> #include <dev/cons.h> #include <machine/cpufunc.h> #include <machine/db_machdep.h> #include <ddb/db_sym.h> #include <ddb/db_command.h> #include <ddb/db_extern.h> #include <ddb/db_access.h> #include <ddb/db_output.h> #include <ddb/ddbvar.h> extern char *trap_type[]; extern int trap_types; int db_active = 0; db_regs_t ddb_regs; /* register state */ void kdbprinttrap __P((int, int)); /* * Print trap reason. */ void kdbprinttrap(type, code) int type, code; { db_printf("kernel: "); if (type >= trap_types || type < 0) db_printf("type %d", type); else db_printf("%s", trap_type[type]); db_printf(" trap, code=%x\n", code); } /* * kdb_trap - field a TRACE or BPT trap */ int kdb_trap(type, code, regs) int type, code; db_regs_t *regs; { int s; switch (type) { case T_BPTFLT: /* breakpoint */ case T_TRCTRAP: /* single_step */ case T_NMI: /* NMI */ case -1: /* keyboard interrupt */ break; default: if (!db_onpanic && db_recover==0) return (0); kdbprinttrap(type, code); if (db_recover != 0) { db_error("Faulted in DDB; continuing...\n"); /*NOTREACHED*/ } } /* XXX Should switch to kdb`s own stack here. */ ddb_regs = *regs; if (KERNELMODE(regs->tf_cs, regs->tf_eflags)) { /* * Kernel mode - esp and ss not saved */ ddb_regs.tf_esp = (int)&regs->tf_esp; /* kernel stack pointer */ asm("movw %%ss,%w0" : "=r" (ddb_regs.tf_ss)); } ddb_regs.tf_cs &= 0xffff; ddb_regs.tf_ds &= 0xffff; ddb_regs.tf_es &= 0xffff; ddb_regs.tf_fs &= 0xffff; ddb_regs.tf_gs &= 0xffff; ddb_regs.tf_ss &= 0xffff; s = splhigh(); db_active++; cnpollc(TRUE); db_trap(type, code); cnpollc(FALSE); db_active--; splx(s); regs->tf_gs = ddb_regs.tf_gs; regs->tf_fs = ddb_regs.tf_fs; regs->tf_es = ddb_regs.tf_es; regs->tf_ds = ddb_regs.tf_ds; regs->tf_edi = ddb_regs.tf_edi; regs->tf_esi = ddb_regs.tf_esi; regs->tf_ebp = ddb_regs.tf_ebp; regs->tf_ebx = ddb_regs.tf_ebx; regs->tf_edx = ddb_regs.tf_edx; regs->tf_ecx = ddb_regs.tf_ecx; regs->tf_eax = ddb_regs.tf_eax; regs->tf_eip = ddb_regs.tf_eip; regs->tf_cs = ddb_regs.tf_cs; regs->tf_eflags = ddb_regs.tf_eflags; if (!KERNELMODE(regs->tf_cs, regs->tf_eflags)) { /* ring transit - saved esp and ss valid */ regs->tf_esp = ddb_regs.tf_esp; regs->tf_ss = ddb_regs.tf_ss; } return (1); } void cpu_Debugger() { breakpoint(); }
consorzio-rfx/mdsplus
tdishr/TdiGetArgs.c
<filename>tdishr/TdiGetArgs.c /* Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* TdiGetArgs.C Fetches signal, data, and category of each input. Guesses input conversion and output category. Empty XD if not a signal. Empty XD or null units if not with_units. Permits BUILD_UNITS(BUILD_SIGNAL(data),units) or BUILD_SIGNAL(BUILD_UNITS(data,units)) and others. Internal routine called by Tdi1Build Tdi1Same Tdi1Scalar Tdi1Trans Tdi1Trim Tdi1RANGE Tdi1SetRange Tdi1Vector <NAME>, LANL CTR-7 (c)1989,1990 */ #include <STATICdef.h> #include <stdlib.h> #include <mdsdescrip.h> #include <tdishr_messages.h> #include <mdsshr.h> #include "tdirefcat.h" #include "tdireffunction.h" #include "tdirefstandard.h" #include "tdithreadsafe.h" extern int TdiGetData(); extern int TdiData(); extern int TdiUnits(); extern int Tdi2Keep(); extern int Tdi2Long2(); extern int Tdi2Any(); extern int Tdi2Cmplx(); int TdiGetSignalUnitsData(struct descriptor *in_ptr, struct descriptor_xd *signal_ptr, struct descriptor_xd *units_ptr, struct descriptor_xd *data_ptr) { STATIC_CONSTANT unsigned char omitsu[] = { DTYPE_SIGNAL, DTYPE_WITH_UNITS, 0 }; STATIC_CONSTANT unsigned char omits[] = { DTYPE_SIGNAL, 0 }; STATIC_CONSTANT unsigned char omitu[] = { DTYPE_WITH_UNITS, 0 }; struct descriptor_xd tmp, *keep; INIT_STATUS; GET_TDITHREADSTATIC_P; MdsFree1Dx(signal_ptr, NULL); status = TdiGetData(omitsu, in_ptr, data_ptr); if STATUS_OK switch (data_ptr->pointer->dtype) { case DTYPE_SIGNAL: *signal_ptr = *data_ptr; *data_ptr = EMPTY_XD; keep = TdiThreadStatic_p->TdiSELF_PTR; TdiThreadStatic_p->TdiSELF_PTR = (struct descriptor_xd *)signal_ptr->pointer; status = TdiGetData(omitu, ((struct descriptor_signal *)signal_ptr->pointer)->data, data_ptr); if STATUS_OK switch (data_ptr->pointer->dtype) { case DTYPE_WITH_UNITS: tmp = *data_ptr; *data_ptr = EMPTY_XD; status = TdiData(((struct descriptor_with_units *)tmp.pointer)->units, units_ptr MDS_END_ARG); if STATUS_OK status = TdiData(((struct descriptor_with_units *)tmp.pointer)->data, data_ptr MDS_END_ARG); MdsFree1Dx(&tmp, NULL); break; default: MdsFree1Dx(units_ptr, NULL); break; } TdiThreadStatic_p->TdiSELF_PTR = keep; break; case DTYPE_WITH_UNITS: tmp = *data_ptr; *data_ptr = EMPTY_XD; status = TdiUnits(tmp.pointer, units_ptr MDS_END_ARG); if STATUS_OK status = TdiGetData(omits, tmp.pointer, data_ptr); if STATUS_OK switch (data_ptr->pointer->dtype) { case DTYPE_SIGNAL: *signal_ptr = *data_ptr; *data_ptr = EMPTY_XD; status = TdiData(signal_ptr->pointer, data_ptr MDS_END_ARG); break; default: break; } MdsFree1Dx(&tmp, NULL); break; default: MdsFree1Dx(units_ptr, NULL); break; } return status; } void UseNativeFloat(struct TdiCatStruct *cat) { unsigned char k; for (k = 0; k < TdiCAT_MAX; k++) if (((TdiREF_CAT[k].cat & ~(0x800)) == (cat->out_cat & ~(0x800))) && (k == DTYPE_NATIVE_FLOAT || k == DTYPE_NATIVE_DOUBLE || k == DTYPE_FLOAT_COMPLEX || k == DTYPE_DOUBLE_COMPLEX)) { cat->out_dtype = k; cat->out_cat = TdiREF_CAT[k].cat; } } /*-------------------------------------------------------------------*/ int TdiGetArgs(int opcode, int narg, struct descriptor *list[], struct descriptor_xd sig[], struct descriptor_xd uni[], struct descriptor_xd dat[], struct TdiCatStruct cats[]) { INIT_STATUS; struct TdiCatStruct *cptr; struct TdiFunctionStruct *fun_ptr = (struct TdiFunctionStruct *)&TdiRefFunction[opcode]; int nc = 0, j; unsigned short i1 = TdiREF_CAT[fun_ptr->i1].cat, i2 = TdiREF_CAT[fun_ptr->i2].cat, o1 = TdiREF_CAT[fun_ptr->o1].cat, o2 = TdiREF_CAT[fun_ptr->o2].cat; unsigned char nd = 0, jd; int use_native = (fun_ptr->f2 != Tdi2Keep && fun_ptr->f2 != Tdi2Long2 && fun_ptr->f2 != Tdi2Any && fun_ptr->f2 != Tdi2Cmplx); /*************************** Get signal, units, and data. ***************************/ for (j = 0; j < narg; ++j) { sig[j] = uni[j] = dat[j] = EMPTY_XD; if STATUS_OK status = TdiGetSignalUnitsData(list[j], &sig[j], &uni[j], &dat[j]); } /****************************** Find category of data type. Adjust out in f2 routine. Make in into out in CVT_ARGS. ******************************/ if STATUS_OK for (nd = 0, nc = 0, j = 0; j < narg; ++j) { struct descriptor *dat_ptr = dat[j].pointer; cptr = &cats[j]; cptr->out_dtype = cptr->in_dtype = jd = dat_ptr->dtype; if (jd > nd && (nd = jd) >= TdiCAT_MAX) { status = TdiINVDTYDSC; break; } cptr->out_cat = (unsigned short)(((cptr->in_cat = TdiREF_CAT[jd].cat) | i1) & i2); if (jd != DTYPE_MISSING) nc |= cptr->out_cat; if ((cptr->digits = TdiREF_CAT[jd].digits) == 0) cptr->digits = dat_ptr->length; } if STATUS_OK for (j = 0; j < narg; j++) { if (fun_ptr->i1 == fun_ptr->i2) { cats[j].out_dtype = fun_ptr->i2; cats[j].out_cat = i2; } else if (cats[j].out_cat & 0x400 && use_native) UseNativeFloat(&cats[j]); } /*********************************************** Output cat and dtype are guesses, checked later. ***********************************************/ if STATUS_OK { cptr = &cats[narg]; cptr->in_dtype = nd; cptr->out_dtype = nd; cptr->in_cat = TdiREF_CAT[nd].cat; cptr->out_cat = (unsigned short)((nc | o1) & o2); cptr->digits = TdiREF_CAT[nd].digits; if (fun_ptr->o1 == fun_ptr->o2) { cptr->out_dtype = cptr->in_dtype = fun_ptr->o2; cptr->out_cat = cptr->in_cat = o2; } else if (cptr->out_cat & 0x400 && use_native) UseNativeFloat(cptr); } return status; }
kongnir/hig
packages/react/src/adapters/ContainerViewLeftAdapter.js
import React, { Component } from "react"; import PropTypes from "prop-types"; import { ContainerViewLeft as ContainerViewLeftVanilla } from "hig-vanilla"; import HIGAdapter, { MapsPropToMethod, MountsAnyChild } from "./HIGAdapter"; export default class ContainerViewLeftAdapter extends Component { render() { return ( <HIGAdapter {...this.props} displayName="ContainerViewLeft" HIGConstructor={ContainerViewLeftVanilla} > {adapterProps => ( <div> <MapsPropToMethod value={this.props.open} {...adapterProps}> {(instance, value) => value ? instance.open() : instance.close() } </MapsPropToMethod> <MountsAnyChild mounter="addSlot" {...adapterProps}> {this.props.children} </MountsAnyChild> </div> )} </HIGAdapter> ); } } ContainerViewLeftAdapter.propTypes = { /** * Sets whether container is open */ open: PropTypes.bool, /** * Content that is inside the container */ children: PropTypes.node };
hanhansoul/hadoop-with-comments
hadoop-tools/hadoop-streaming/src/main/java/org/apache/hadoop/streaming/io/RawBytesInputWriter.java
<filename>hadoop-tools/hadoop-streaming/src/main/java/org/apache/hadoop/streaming/io/RawBytesInputWriter.java /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.hadoop.streaming.io; import java.io.ByteArrayOutputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.IOException; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.Writable; import org.apache.hadoop.streaming.PipeMapRed; /** * InputWriter that writes the client's input as raw bytes. */ public class RawBytesInputWriter extends InputWriter<Writable, Writable> { private DataOutput clientOut; private ByteArrayOutputStream bufferOut; private DataOutputStream bufferDataOut; @Override public void initialize(PipeMapRed pipeMapRed) throws IOException { super.initialize(pipeMapRed); clientOut = pipeMapRed.getClientOutput(); bufferOut = new ByteArrayOutputStream(); bufferDataOut = new DataOutputStream(bufferOut); } @Override public void writeKey(Writable key) throws IOException { writeRawBytes(key); } @Override public void writeValue(Writable value) throws IOException { writeRawBytes(value); } private void writeRawBytes(Writable writable) throws IOException { if (writable instanceof BytesWritable) { BytesWritable bw = (BytesWritable) writable; byte[] bytes = bw.getBytes(); int length = bw.getLength(); clientOut.writeInt(length); clientOut.write(bytes, 0, length); } else { bufferOut.reset(); writable.write(bufferDataOut); byte[] bytes = bufferOut.toByteArray(); clientOut.writeInt(bytes.length); clientOut.write(bytes); } } }
mip2012/vue-layui
src/components/admin/index.js
<reponame>mip2012/vue-layui<gh_stars>100-1000 /** * kouchao 创建于 */ import LayAdmin from './src/admin'; /* istanbul ignore next */ LayAdmin.install = function (Vue) { Vue.component(LayAdmin.name, LayAdmin); }; export default LayAdmin;
drhaz/VisualFitsBrowser
src/main/java/org/cowjumping/FitsUtils/RadialProfile.java
package org.cowjumping.FitsUtils; import java.awt.Rectangle; public class RadialProfile { public float[] radius = null; public float[] value = null; public float[] error = null; double xcenter = 0; double ycenter = 0; int minx; int maxx; int miny; int maxy; public RadialProfile(double xcenter, double ycenter) { updateCenter(xcenter, ycenter); } private void updateCenter(double xcenter, double ycenter) { if (xcenter == Double.NaN || ycenter == Double.NaN) { System.err.println("Invalid center given!"); this.xcenter = 0; this.ycenter = 0; } else { this.xcenter = xcenter; this.ycenter = ycenter; } } public RadialProfile() { this(0, 0); } public RadialProfile( ImageContainer gs) { this(0, 0); update(gs); } /** * Generate a radial plot of an entire image */ public void update( ImageContainer gs) { updateCenter(gs.getCenterX(), gs.getCenterY()); loadFromImage(gs, new Rectangle(1, 1, gs.getImageDimX() - 2, gs.getImageDimY() - 2), Double.NEGATIVE_INFINITY); } /** * Generate a radial plto of a sub-window only * * @param xcenter * @param ycenter * @param boundary */ public void update(double xcenter, double ycenter, ImageContainer gs, Rectangle boundary) { updateCenter(xcenter, ycenter); loadFromImage(gs, boundary, Double.NEGATIVE_INFINITY); } public void update(double xcenter, double ycenter, ImageContainer gs, Rectangle boundary, double thres) { updateCenter(xcenter, ycenter); loadFromImage(gs, boundary, thres); } public int getNElements() { int retval = 0; if (radius != null) retval = radius.length; return retval; } public float getRadius(int n) { if (n < getNElements()) return radius[n]; else return 0; } public float getValue(int n) { if (n < getNElements()) return value[n]; else return 0; } public void swap(int a, int b) { float temp; if (a >= 0 && b >= 0 && a < this.getNElements() && b < this.getNElements()) { temp = value[a]; value[a] = value[b]; value[b] = temp; temp = radius[a]; radius[a] = radius[b]; radius[b] = temp; if (error != null) { temp = error[a]; error[a] = error[b]; error[b] = temp; } } } public double getMean(int maxGood) { double mean = 0; for (int ii = 0; ii < Math.min(maxGood, this.getNElements()); ii++) { mean += value[ii]; } return mean; } public double getSigma(int maxGood) { double s = 0; double m = getMean(maxGood); for (int ii = 0; ii < Math.min(maxGood, this.getNElements()); ii++) { double v = value[ii] - m; s += v * v; } return Math.sqrt(s); } public float getError(int n) { if (error != null && n < error.length) return error[n]; else return 1f; } private void loadFromImage(ImageContainer gs, Rectangle boundary, double thres) { float[] mradius = new float[boundary.width * boundary.height]; float[] mvalue = new float[boundary.width * boundary.height]; int n = extractRadialProfile(gs, mradius, mvalue, boundary, thres); this.radius = new float[n]; System.arraycopy(mradius, 0, this.radius,0, n); this.value = new float[n]; System.arraycopy(mvalue , 0, this.value ,0, n); } /** * From a given center in the image, extract the radial profile by calculating * distance from the center. The radius is extracted only for a window. * * * center Y position * @param radius * return value: array of radius * @param value * return value: array of values * @param threshold * minimum image value * @return number of elements in the returned array. */ private static int extractRadialProfile(ImageContainer gs, float[] radius, float[] value, Rectangle bounds, double threshold) { int dimX = gs.getImageDimX(); int dimY = gs.getImageDimY(); double cX = gs.getCenterX(); double cY = gs.getCenterY(); // Ensure boundaries are safe! while (bounds.width > 0 && bounds.x + bounds.width >= dimX) bounds.width--; while (bounds.height > 0 && bounds.y + bounds.height >= dimY) bounds.height--; int count = 0; // for (int xx = bounds.x; xx < bounds.x + bounds.width; xx++) { for (int yy = bounds.y; yy < bounds.y + bounds.height; yy++) { float v = gs.rawImageBuffer[yy * dimX + xx] ; if (v >= threshold) { double t1 = (xx - cX) * gs.getBinningX(); double t2 = (yy - cY) * gs.getBinningY(); radius[count] = (float) Math.sqrt(t1 * t1 + t2 * t2); value[count] = v; count++; } } } return count; } }
fabionunesdeparis/Fundamentos-em-python3
exer107/principal.py
# @<NAME> - 30.06.20 from exer107 import moeda while True: valor = str(input('Digite o preço: R$')) if valor.isnumeric(): valor = float(valor) moeda.metade(valor) moeda.dobro(valor) moeda.aumentar(valor) moeda.diminuir(valor) break else: print('Digite um valor numérico! ')
C-Mierez/Web3-Solidity
Web3/Brownie_NFTs/scripts/advanced_collectible/create_collectible.py
<filename>Web3/Brownie_NFTs/scripts/advanced_collectible/create_collectible.py from scripts.utils import ( get_account, OPENSEA_URL, ) from brownie import AdvancedCollectible def create_collectible(): account = get_account() advanced_collectible = AdvancedCollectible[-1] tx = advanced_collectible.createCollectible( {"from": account}, ) tx.wait(1) print( f"AdvancedCollectible created. OpenSea: {OPENSEA_URL.format(advanced_collectible.address, advanced_collectible.tokenCounter())}" ) return tx def main(): return create_collectible()
anyone-oslo/pages
app/views/admin/images/show.json.jbuilder
<reponame>anyone-oslo/pages<filename>app/views/admin/images/show.json.jbuilder # frozen_string_literal: true json.extract!( @image, :id, :filename, :content_type, :content_hash, :content_length, :colorspace, :real_width, :real_height, :crop_width, :crop_height, :crop_start_x, :crop_start_y, :crop_gravity_x, :crop_gravity_y, :alternative, :caption, :created_at, :updated_at )
cyyever/DALI
docs/examples/use_cases/video_superres/common/loss_scaler.py
<gh_stars>1000+ import torch class LossScaler: def __init__(self, scale=1): self.cur_scale = scale # `params` is a list / generator of torch.Variable def has_overflow(self, params): return False # `x` is a torch.Tensor def _has_inf_or_nan(x): return False # `overflow` is boolean indicating whether we overflowed in gradient def update_scale(self, overflow): pass @property def loss_scale(self): return self.cur_scale def scale_gradient(self, module, grad_in, grad_out): return tuple(self.loss_scale * g for g in grad_in) def backward(self, loss): scaled_loss = loss*self.loss_scale scaled_loss.backward() class DynamicLossScaler: def __init__(self, init_scale=2**32, scale_factor=2., scale_window=1000): self.cur_scale = init_scale self.cur_iter = 0 self.last_overflow_iter = -1 self.scale_factor = scale_factor self.scale_window = scale_window # `params` is a list / generator of torch.Variable def has_overflow(self, params): # return False for p in params: if p.grad is not None and DynamicLossScaler._has_inf_or_nan(p.grad.data): return True return False # `x` is a torch.Tensor def _has_inf_or_nan(x): inf_count = torch.sum(x.abs() == float('inf')) if inf_count > 0: return True nan_count = torch.sum(x != x) return nan_count > 0 # `overflow` is boolean indicating whether we overflowed in gradient def update_scale(self, overflow): if overflow: #self.cur_scale /= self.scale_factor self.cur_scale = max(self.cur_scale/self.scale_factor, 1) self.last_overflow_iter = self.cur_iter else: if (self.cur_iter - self.last_overflow_iter) % self.scale_window == 0: self.cur_scale *= self.scale_factor # self.cur_scale = 1 self.cur_iter += 1 @property def loss_scale(self): return self.cur_scale def scale_gradient(self, module, grad_in, grad_out): return tuple(self.loss_scale * g for g in grad_in) def backward(self, loss): scaled_loss = loss*self.loss_scale scaled_loss.backward()
shmilee/gdpy3
src/loaders/tests/test_tarraw.py
# -*- coding: utf-8 -*- # Copyright (c) 2018-2020 shmilee import os import unittest import tempfile import tarfile TARFILE = os.path.join(os.path.dirname(__file__), 'raw.tar.gz') @unittest.skipUnless(tarfile.is_tarfile(TARFILE), "'%s' is not a tar archive!" % TARFILE) class TestTarRawLoader(unittest.TestCase): ''' Test class TarRawLoader ''' def setUp(self): from ..tarraw import TarRawLoader self.tmpfile = tempfile.mktemp(suffix='-test.tar.gz') with open(self.tmpfile, mode='w') as f: f.write('test') self.TarRawLoader = TarRawLoader self.tmptar = TARFILE def tearDown(self): if os.path.isfile(self.tmpfile): os.remove(self.tmpfile) def test_tarloader_init(self): with self.assertRaises(ValueError): loader = self.TarRawLoader(self.tmpfile) loader = self.TarRawLoader(self.tmptar) self.assertSetEqual(set(loader.filenames), {'f1.ignore', 'f1.out', 'd1/f2.out', 'd1/d2/f3.out'}) def test_tarloader_get(self): loader = self.TarRawLoader(self.tmptar) with loader.get('f1.out') as f1: self.assertEqual(f1.readlines(), ['test1']) with loader.get('d1/f2.out') as f2: self.assertEqual(f2.read(), 'test2') with self.assertRaises(ValueError): f2.read()
fengjiachun/byte-buddy
byte-buddy-dep/src/test/java/net/bytebuddy/dynamic/scaffold/FieldRegistryCompiledNoOpTest.java
package net.bytebuddy.dynamic.scaffold; import net.bytebuddy.description.field.FieldDescription; import net.bytebuddy.implementation.attribute.AnnotationAppender; import net.bytebuddy.implementation.attribute.FieldAttributeAppender; import net.bytebuddy.test.utility.MockitoRule; import net.bytebuddy.test.utility.ObjectPropertyAssertion; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import org.mockito.Mock; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; public class FieldRegistryCompiledNoOpTest { @Rule public TestRule mockitoRule = new MockitoRule(this); @Mock private FieldDescription fieldDescription; @Test public void testReturnsNullDefaultValue() throws Exception { TypeWriter.FieldPool.Record record = FieldRegistry.Compiled.NoOp.INSTANCE.target(fieldDescription); assertThat(record.getDefaultValue(), is(FieldDescription.NO_DEFAULT_VALUE)); } @Test public void testReturnsFieldAttributeAppender() throws Exception { TypeWriter.FieldPool.Record record = FieldRegistry.Compiled.NoOp.INSTANCE.target(fieldDescription); assertThat(record.getFieldAppender(), is((FieldAttributeAppender) new FieldAttributeAppender.ForField(fieldDescription, AnnotationAppender.ValueFilter.AppendDefaults.INSTANCE))); } @Test public void testObjectProperties() throws Exception { ObjectPropertyAssertion.of(FieldRegistry.Compiled.NoOp.class).apply(); } }
factcenter/inchworm
src/test/java/org/factcenter/inchworm/ops/dummy/DummyRolOpTest.java
<filename>src/test/java/org/factcenter/inchworm/ops/dummy/DummyRolOpTest.java package org.factcenter.inchworm.ops.dummy; import org.factcenter.inchworm.ops.GenericOpTest; import org.factcenter.inchworm.ops.OpAction; import org.factcenter.inchworm.ops.OpDefaults; import org.factcenter.inchworm.ops.RolOpTest; /** * Created by talm on 09/12/15. */ public class DummyRolOpTest extends RolOpTest { @Override protected OpAction getOp(VM vm) throws Exception { return vm.factory.getOpAction(OpDefaults.Op.OP_ROL.name); } }
allnes/pp_2022_spring
modules/task_1/lakhov_k_trapezoidal_rule/trapezoidal_rule.h
<reponame>allnes/pp_2022_spring // Copyright 2022 <NAME> #ifndef MODULES_TASK_1_LAKHOV_K_TRAPEZOIDAL_RULE_TRAPEZOIDAL_RULE_H_ #define MODULES_TASK_1_LAKHOV_K_TRAPEZOIDAL_RULE_TRAPEZOIDAL_RULE_H_ #include <vector> #include <functional> #include <utility> double _trapezoidalRule(std::function<double(std::vector<double>)> func, const std::vector<double>& args, int position, const std::vector<std::pair<double, double>>& intervals, int interval_count); double trapezoidalRule(std::function<double(std::vector<double>)> func, const std::vector<std::pair<double, double>>& intervals, int interval_count); #endif // MODULES_TASK_1_LAKHOV_K_TRAPEZOIDAL_RULE_TRAPEZOIDAL_RULE_H_
XtakeFinance/website
app/src/Components/HowtoStakeComponent.js
import React from "react"; import {appColor, secondaryTextColor} from "../AppConstants"; import Title from "antd/lib/typography/Title"; import {Link} from "@mui/material"; export const HowtoStakeComponent = () => { return ( <div style={{textAlign: "center", padding:"3% 10% 2% 10%"}}> <h4 style={{color: secondaryTextColor, fontWeight: "bold"}}>HOW TO STAKE WITH XTAKE</h4> <Title style={{color: "white"}}>It's as easy as it sounds</Title> <h3 style={{color: secondaryTextColor, fontWeight: "normal", paddingBottom: "20px"}}>Staking shouldn’t be difficult. And really, it isn’t. Calculate your staking rewards below.</h3> </div> ) }
bengfarrell/material
src/spectrum/components/button/multiStops/dark.js
export default { css() { return ` /* generated from dna-version: 5.3.0 */ /* generated from dna-version: 5.3.0 */ /* Temporary skin variables that need to be moved into origins */ :root { /* Icon Button*/ /* Button */ /* Shell */ /* haha remove this */ /* Custom selection color for placeholders using global blue-500 at 30% opacity. Should be updated in Spectrum-DNA */ } .spectrum--dark .spectrum-Button.focus-ring { box-shadow: 0 0 0 1px rgb(20, 115, 230); } .spectrum--dark .spectrum-Button:active { /* Override focus -- clicking with spacebar should not show outline */ box-shadow: none; } .spectrum--dark .spectrum-ClearButton { background-color: rgba(0, 0, 0, 0); color: rgb(123, 123, 123); } .spectrum--dark .spectrum-ClearButton:hover { background-color: rgba(0, 0, 0, 0); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-ClearButton:active { background-color: rgba(0, 0, 0, 0); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-ClearButton.focus-ring { background-color: rgba(0, 0, 0, 0); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-ClearButton:disabled, .spectrum--dark .spectrum-ClearButton.is-disabled { background-color: rgba(0, 0, 0, 0); color: rgb(92, 92, 92); } /* topdoc {{ button/button-cta.yml }} */ .spectrum--dark .spectrum-Button--cta { background-color: rgb(20, 115, 230); border-color: rgb(20, 115, 230); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-Button--cta:hover { background-color: rgb(13, 102, 208); border-color: rgb(13, 102, 208); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-Button--cta.focus-ring { background-color: rgb(20, 115, 230); border-color: rgb(20, 115, 230); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-Button--cta:active { background-color: rgb(13, 102, 208); border-color: rgb(13, 102, 208); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-Button--cta:disabled, .spectrum--dark .spectrum-Button--cta.is-disabled { background-color: rgb(57, 57, 57); border-color: rgb(57, 57, 57); color: rgb(92, 92, 92); } /* topdoc {{ button/button-primary.yml }} */ .spectrum--dark .spectrum-Button--primary { background-color: rgba(0, 0, 0, 0); border-color: rgb(205, 205, 205); color: rgb(205, 205, 205); } .spectrum--dark .spectrum-Button--primary:hover { background-color: rgb(205, 205, 205); border-color: rgb(205, 205, 205); color: rgb(37, 37, 37); } .spectrum--dark .spectrum-Button--primary.focus-ring { background-color: rgb(20, 115, 230); border-color: rgb(20, 115, 230); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-Button--primary:active { background-color: rgb(255, 255, 255); border-color: rgb(255, 255, 255); color: rgb(37, 37, 37); } .spectrum--dark .spectrum-Button--primary:disabled, .spectrum--dark .spectrum-Button--primary.is-disabled { background-color: rgb(57, 57, 57); border-color: rgb(57, 57, 57); color: rgb(92, 92, 92); } /* topdoc {{ button/button-secondary.yml }} */ .spectrum--dark .spectrum-Button--secondary { background-color: rgba(0, 0, 0, 0); border-color: rgb(157, 157, 157); color: rgb(157, 157, 157); } .spectrum--dark .spectrum-Button--secondary:hover { background-color: rgb(157, 157, 157); border-color: rgb(157, 157, 157); color: rgb(37, 37, 37); } .spectrum--dark .spectrum-Button--secondary.focus-ring { background-color: rgb(20, 115, 230); border-color: rgb(20, 115, 230); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-Button--secondary:active { background-color: rgb(205, 205, 205); border-color: rgb(205, 205, 205); color: rgb(37, 37, 37); } .spectrum--dark .spectrum-Button--secondary:disabled, .spectrum--dark .spectrum-Button--secondary.is-disabled { background-color: rgb(57, 57, 57); border-color: rgb(57, 57, 57); color: rgb(92, 92, 92); } /* topdoc {{ button/button-warning.yml }} */ .spectrum--dark .spectrum-Button--warning { background-color: rgba(0, 0, 0, 0); border-color: rgb(247, 109, 116); color: rgb(247, 109, 116); } .spectrum--dark .spectrum-Button--warning:hover { background-color: rgb(247, 109, 116); border-color: rgb(247, 109, 116); color: rgb(37, 37, 37); } .spectrum--dark .spectrum-Button--warning.focus-ring { background-color: rgb(20, 115, 230); border-color: rgb(20, 115, 230); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-Button--warning:active { background-color: rgb(255, 123, 130); border-color: rgb(255, 123, 130); color: rgb(37, 37, 37); } .spectrum--dark .spectrum-Button--warning:disabled, .spectrum--dark .spectrum-Button--warning.is-disabled { background-color: rgb(57, 57, 57); border-color: rgb(57, 57, 57); color: rgb(92, 92, 92); } /* topdoc {{ button/button-over-background.yml }} */ .spectrum--dark .spectrum-Button--overBackground { background-color: rgba(0, 0, 0, 0); border-color: rgb(255, 255, 255); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-Button--overBackground:hover { background-color: rgb(255, 255, 255); border-color: rgb(255, 255, 255); color: inherit; } .spectrum--dark .spectrum-Button--overBackground.focus-ring { background-color: rgb(255, 255, 255); border-color: rgb(255, 255, 255); color: inherit; box-shadow: 0 0 0 1px rgb(255, 255, 255); } .spectrum--dark .spectrum-Button--overBackground:active { background-color: rgb(255, 255, 255); border-color: rgb(255, 255, 255); color: inherit; box-shadow: none; } .spectrum--dark .spectrum-Button--overBackground:disabled, .spectrum--dark .spectrum-Button--overBackground.is-disabled { background-color: rgba(255,255,255,0.1); border-color: rgba(0, 0, 0, 0); color: rgba(255,255,255,0.35); } /* topdoc {{ button/button-quiet-over-background.yml }} */ .spectrum--dark .spectrum-Button--overBackground.spectrum-Button--quiet, .spectrum--dark .spectrum-ClearButton--overBackground { background-color: rgba(0, 0, 0, 0); border-color: rgba(0, 0, 0, 0); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-Button--overBackground.spectrum-Button--quiet:hover, .spectrum--dark .spectrum-ClearButton--overBackground:hover { background-color: rgba(255,255,255,0.1); border-color: rgba(0, 0, 0, 0); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-Button--overBackground.spectrum-Button--quiet.focus-ring, .spectrum--dark .spectrum-ClearButton--overBackground.focus-ring { background-color: rgb(255, 255, 255); border-color: rgb(255, 255, 255); color: inherit; box-shadow: 0 0 0 1px rgb(255, 255, 255); } .spectrum--dark .spectrum-Button--overBackground.spectrum-Button--quiet:active, .spectrum--dark .spectrum-ClearButton--overBackground:active { background-color: rgba(255,255,255,0.15); border-color: rgba(0, 0, 0, 0); color: rgb(255, 255, 255); box-shadow: none; } .spectrum--dark .spectrum-Button--overBackground.spectrum-Button--quiet:disabled, .spectrum--dark .spectrum-Button--overBackground.spectrum-Button--quiet.is-disabled, .spectrum--dark .spectrum-ClearButton--overBackground:disabled, .spectrum--dark .spectrum-ClearButton--overBackground.is-disabled { background-color: rgba(0, 0, 0, 0); border-color: rgba(0, 0, 0, 0); color: rgba(255,255,255,0.15); } /* topdoc {{ button/button-quiet-primary.yml }} */ .spectrum--dark .spectrum-Button--primary.spectrum-Button--quiet { background-color: rgba(0, 0, 0, 0); border-color: rgba(0, 0, 0, 0); color: rgb(205, 205, 205); } .spectrum--dark .spectrum-Button--primary.spectrum-Button--quiet:hover { background-color: rgb(57, 57, 57); border-color: rgb(57, 57, 57); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-Button--primary.spectrum-Button--quiet.focus-ring { background-color: rgb(20, 115, 230); border-color: rgb(20, 115, 230); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-Button--primary.spectrum-Button--quiet:active { background-color: rgb(62, 62, 62); border-color: rgb(62, 62, 62); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-Button--primary.spectrum-Button--quiet:disabled, .spectrum--dark .spectrum-Button--primary.spectrum-Button--quiet.is-disabled { background-color: rgba(0, 0, 0, 0); border-color: rgba(0, 0, 0, 0); color: rgb(92, 92, 92); } /* topdoc {{ button/button-quiet-secondary.yml }} */ .spectrum--dark .spectrum-Button--secondary.spectrum-Button--quiet { background-color: rgba(0, 0, 0, 0); border-color: rgba(0, 0, 0, 0); color: rgb(157, 157, 157); } .spectrum--dark .spectrum-Button--secondary.spectrum-Button--quiet:hover { background-color: rgb(57, 57, 57); border-color: rgb(57, 57, 57); color: rgb(205, 205, 205); } .spectrum--dark .spectrum-Button--secondary.spectrum-Button--quiet.focus-ring { background-color: rgb(20, 115, 230); border-color: rgb(20, 115, 230); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-Button--secondary.spectrum-Button--quiet:active { background-color: rgb(62, 62, 62); border-color: rgb(62, 62, 62); color: rgb(205, 205, 205); } .spectrum--dark .spectrum-Button--secondary.spectrum-Button--quiet:disabled, .spectrum--dark .spectrum-Button--secondary.spectrum-Button--quiet.is-disabled { background-color: rgba(0, 0, 0, 0); border-color: rgba(0, 0, 0, 0); color: rgb(92, 92, 92); } /* topdoc {{ button/actionbutton.yml }} */ .spectrum--dark .spectrum-ActionButton, .spectrum--dark .spectrum-Tool { background-color: rgb(47, 47, 47); border-color: rgb(62, 62, 62); color: rgb(205, 205, 205); } .spectrum--dark .spectrum-ActionButton .spectrum-Icon, .spectrum--dark .spectrum-Tool .spectrum-Icon { color: rgb(157, 157, 157); } .spectrum--dark .spectrum-ActionButton .spectrum-ActionButton-hold, .spectrum--dark .spectrum-Tool .spectrum-ActionButton-hold { color: rgb(157, 157, 157); } .spectrum--dark .spectrum-ActionButton:hover, .spectrum--dark .spectrum-Tool:hover { background-color: rgb(37, 37, 37); border-color: rgb(77, 77, 77); box-shadow: none; color: rgb(255, 255, 255); } .spectrum--dark .spectrum-ActionButton:hover .spectrum-Icon, .spectrum--dark .spectrum-Tool:hover .spectrum-Icon { color: rgb(255, 255, 255); } .spectrum--dark .spectrum-ActionButton:hover .spectrum-ActionButton-hold, .spectrum--dark .spectrum-Tool:hover .spectrum-ActionButton-hold { color: rgb(255, 255, 255); } .spectrum--dark .spectrum-ActionButton.focus-ring, .spectrum--dark .spectrum-Tool.focus-ring { background-color: rgb(37, 37, 37); border-color: rgb(38, 128, 235); box-shadow: 0 0 0 1px rgb(38, 128, 235); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-ActionButton.focus-ring .spectrum-Icon, .spectrum--dark .spectrum-Tool.focus-ring .spectrum-Icon { color: rgb(255, 255, 255); } .spectrum--dark .spectrum-ActionButton.focus-ring .spectrum-ActionButton-hold, .spectrum--dark .spectrum-Tool.focus-ring .spectrum-ActionButton-hold { color: rgb(255, 255, 255); } .spectrum--dark .spectrum-ActionButton:active, .spectrum--dark .spectrum-Tool:active { background-color: rgb(57, 57, 57); border-color: rgb(77, 77, 77); box-shadow: none; color: rgb(255, 255, 255); } .spectrum--dark .spectrum-ActionButton:active .spectrum-ActionButton-hold, .spectrum--dark .spectrum-Tool:active .spectrum-ActionButton-hold { color: rgb(255, 255, 255); } .spectrum--dark .spectrum-ActionButton:disabled, .spectrum--dark .spectrum-ActionButton.is-disabled, .spectrum--dark .spectrum-Tool:disabled { background-color: rgb(57, 57, 57); border-color: rgb(57, 57, 57); color: rgb(92, 92, 92); } .spectrum--dark .spectrum-ActionButton:disabled .spectrum-Icon, .spectrum--dark .spectrum-ActionButton.is-disabled .spectrum-Icon, .spectrum--dark .spectrum-Tool:disabled .spectrum-Icon { color: rgb(77, 77, 77); } .spectrum--dark .spectrum-ActionButton:disabled .spectrum-ActionButton-hold, .spectrum--dark .spectrum-ActionButton.is-disabled .spectrum-ActionButton-hold, .spectrum--dark .spectrum-Tool:disabled .spectrum-ActionButton-hold { color: rgb(77, 77, 77); } .spectrum--dark .spectrum-ActionButton.is-selected { background-color: rgb(57, 57, 57); border-color: rgb(62, 62, 62); color: rgb(205, 205, 205); } .spectrum--dark .spectrum-ActionButton.is-selected .spectrum-Icon { color: rgb(157, 157, 157); } .spectrum--dark .spectrum-ActionButton.is-selected.focus-ring { background-color: rgb(57, 57, 57); border-color: rgb(38, 128, 235); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-ActionButton.is-selected.focus-ring .spectrum-Icon { color: rgb(255, 255, 255); } .spectrum--dark .spectrum-ActionButton.is-selected:hover { background-color: rgb(57, 57, 57); border-color: rgb(77, 77, 77); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-ActionButton.is-selected:hover .spectrum-Icon { color: rgb(255, 255, 255); } .spectrum--dark .spectrum-ActionButton.is-selected:active { background-color: rgb(57, 57, 57); border-color: rgb(77, 77, 77); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-ActionButton.is-selected:active .spectrum-Icon { color: rgb(255, 255, 255); } .spectrum--dark .spectrum-ActionButton.is-selected:disabled, .spectrum--dark .spectrum-ActionButton.is-selected.is-disabled { background-color: rgb(57, 57, 57); border-color: rgb(57, 57, 57); color: rgb(92, 92, 92); } .spectrum--dark .spectrum-ActionButton.is-selected:disabled .spectrum-Icon, .spectrum--dark .spectrum-ActionButton.is-selected.is-disabled .spectrum-Icon { color: rgb(77, 77, 77); } /* topdoc {{ button/actionbutton-quiet.yml }} */ .spectrum--dark .spectrum-ActionButton--quiet, .spectrum--dark .spectrum-Tool { background-color: rgba(0, 0, 0, 0); border-color: rgba(0, 0, 0, 0); color: rgb(205, 205, 205); } .spectrum--dark .spectrum-ActionButton--quiet:hover, .spectrum--dark .spectrum-Tool:hover { background-color: rgba(0, 0, 0, 0); border-color: rgba(0, 0, 0, 0); color: rgb(255, 255, 255); box-shadow: none; } .spectrum--dark .spectrum-ActionButton--quiet.focus-ring, .spectrum--dark .spectrum-Tool.focus-ring { background-color: rgba(0, 0, 0, 0); box-shadow: 0 0 0 1px rgb(38, 128, 235); border-color: rgb(38, 128, 235); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-ActionButton--quiet:active, .spectrum--dark .spectrum-Tool:active { background-color: rgb(62, 62, 62); border-color: rgb(62, 62, 62); color: rgb(255, 255, 255); box-shadow: none; } .spectrum--dark .spectrum-ActionButton--quiet:disabled, .spectrum--dark .spectrum-ActionButton--quiet.is-disabled, .spectrum--dark .spectrum-Tool:disabled { background-color: rgba(0, 0, 0, 0); border-color: rgba(0, 0, 0, 0); color: rgb(92, 92, 92); } .spectrum--dark .spectrum-ActionButton--quiet.is-selected { background-color: rgb(62, 62, 62); border-color: rgb(62, 62, 62); color: rgb(205, 205, 205); } .spectrum--dark .spectrum-ActionButton--quiet.is-selected.focus-ring { background-color: rgb(62, 62, 62); border-color: rgb(38, 128, 235); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-ActionButton--quiet.is-selected:hover { background-color: rgb(62, 62, 62); border-color: rgb(62, 62, 62); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-ActionButton--quiet.is-selected:active { background-color: rgb(62, 62, 62); border-color: rgb(62, 62, 62); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-ActionButton--quiet.is-selected:disabled, .spectrum--dark .spectrum-ActionButton--quiet.is-selected.is-disabled { background-color: rgb(57, 57, 57); border-color: rgb(57, 57, 57); color: rgb(92, 92, 92); } /* topdoc {{ button/button-quiet-warning.yml }} */ .spectrum--dark .spectrum-Button--warning.spectrum-Button--quiet { background-color: rgba(0, 0, 0, 0); border-color: rgba(0, 0, 0, 0); color: rgb(236, 91, 98); } .spectrum--dark .spectrum-Button--warning.spectrum-Button--quiet:hover { background-color: rgb(57, 57, 57); border-color: rgb(57, 57, 57); color: rgb(247, 109, 116); } .spectrum--dark .spectrum-Button--warning.spectrum-Button--quiet.focus-ring { background-color: rgb(20, 115, 230); border-color: rgb(20, 115, 230); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-Button--warning.spectrum-Button--quiet:active { background-color: rgb(62, 62, 62); border-color: rgb(62, 62, 62); color: rgb(247, 109, 116); } .spectrum--dark .spectrum-Button--warning.spectrum-Button--quiet:disabled, .spectrum--dark .spectrum-Button--warning.spectrum-Button--quiet.is-disabled { background-color: rgba(0, 0, 0, 0); border-color: rgba(0, 0, 0, 0); color: rgb(92, 92, 92); } /* topdoc {{ button/logicbutton.yml }} */ .spectrum--dark .spectrum-LogicButton--and { background-color: rgb(55, 142, 240); border-color: rgb(55, 142, 240); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-LogicButton--and:hover { background-color: rgb(90, 169, 250); border-color: rgb(90, 169, 250); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-LogicButton--and.focus-ring { background-color: rgb(90, 169, 250); border-color: rgb(38, 128, 235); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-LogicButton--and:disabled, .spectrum--dark .spectrum-LogicButton--and.is-disabled { background-color: rgb(57, 57, 57); border-color: rgb(57, 57, 57); color: rgb(92, 92, 92); } .spectrum--dark .spectrum-LogicButton--or { background-color: rgb(226, 73, 157); border-color: rgb(226, 73, 157); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-LogicButton--or:hover { background-color: rgb(245, 107, 183); border-color: rgb(245, 107, 183); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-LogicButton--or.focus-ring { background-color: rgb(245, 107, 183); border-color: rgb(38, 128, 235); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-LogicButton--or:disabled, .spectrum--dark .spectrum-LogicButton--or.is-disabled { background-color: rgb(57, 57, 57); border-color: rgb(57, 57, 57); color: rgb(92, 92, 92); } /* topdoc {{ button/clearbutton-medium.yml }} */ .spectrum--dark .spectrum-FieldButton { color: rgb(205, 205, 205); background-color: rgb(47, 47, 47); border-color: rgb(62, 62, 62); } .spectrum--dark .spectrum-FieldButton:hover { color: rgb(255, 255, 255); background-color: rgb(37, 37, 37); border-color: rgb(77, 77, 77); } .spectrum--dark .spectrum-FieldButton.focus-ring, .spectrum--dark .spectrum-FieldButton.is-focused { background-color: rgb(37, 37, 37); border-color: rgb(38, 128, 235); box-shadow: 0 0 0 1px rgb(38, 128, 235); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-FieldButton.focus-ring.is-placeholder, .spectrum--dark .spectrum-FieldButton.is-focused.is-placeholder { color: rgb(255, 255, 255); } .spectrum--dark .spectrum-FieldButton:active, .spectrum--dark .spectrum-FieldButton.is-selected { background-color: rgb(57, 57, 57); border-color: rgb(77, 77, 77); } .spectrum--dark .spectrum-FieldButton:active.focus-ring, .spectrum--dark .spectrum-FieldButton:active.is-focused, .spectrum--dark .spectrum-FieldButton.is-selected.focus-ring, .spectrum--dark .spectrum-FieldButton.is-selected.is-focused { box-shadow: none; } .spectrum--dark .spectrum-FieldButton.is-invalid { border-color: rgb(236, 91, 98); } .spectrum--dark .spectrum-FieldButton.is-invalid:hover { border-color: rgb(247, 109, 116); } .spectrum--dark .spectrum-FieldButton.is-invalid:active, .spectrum--dark .spectrum-FieldButton.is-invalid.is-selected { border-color: rgb(247, 109, 116); } .spectrum--dark .spectrum-FieldButton.is-invalid.focus-ring, .spectrum--dark .spectrum-FieldButton.is-invalid.is-focused { border-color: rgb(38, 128, 235); box-shadow: 0 0 0 1px rgb(38, 128, 235); } .spectrum--dark .spectrum-FieldButton:disabled, .spectrum--dark .spectrum-FieldButton.is-disabled { background-color: rgb(57, 57, 57); color: rgb(92, 92, 92); } .spectrum--dark .spectrum-FieldButton:disabled.focus-ring, .spectrum--dark .spectrum-FieldButton.is-disabled.focus-ring { box-shadow: none; } .spectrum--dark .spectrum-FieldButton:disabled .spectrum-Icon, .spectrum--dark .spectrum-FieldButton.is-disabled .spectrum-Icon { color: rgb(77, 77, 77); } .spectrum--dark .spectrum-FieldButton--quiet { color: rgb(205, 205, 205); border-color: rgba(0, 0, 0, 0); background-color: rgba(0, 0, 0, 0); } .spectrum--dark .spectrum-FieldButton--quiet:hover { background-color: rgba(0, 0, 0, 0); color: rgb(255, 255, 255); } .spectrum--dark .spectrum-FieldButton--quiet.focus-ring, .spectrum--dark .spectrum-FieldButton--quiet.is-focused { background-color: rgba(0, 0, 0, 0); box-shadow: 0 2px 0 0 rgb(38, 128, 235); } .spectrum--dark .spectrum-FieldButton--quiet.focus-ring.is-placeholder, .spectrum--dark .spectrum-FieldButton--quiet.is-focused.is-placeholder { color: rgb(255, 255, 255); } .spectrum--dark .spectrum-FieldButton--quiet:active, .spectrum--dark .spectrum-FieldButton--quiet.is-selected { background-color: rgba(0, 0, 0, 0); border-color: rgba(0, 0, 0, 0); } .spectrum--dark .spectrum-FieldButton--quiet:active.focus-ring, .spectrum--dark .spectrum-FieldButton--quiet:active.is-focused, .spectrum--dark .spectrum-FieldButton--quiet.is-selected.focus-ring, .spectrum--dark .spectrum-FieldButton--quiet.is-selected.is-focused { background-color: rgba(0, 0, 0, 0); box-shadow: 0 2px 0 0 rgb(38, 128, 235); } .spectrum--dark .spectrum-FieldButton--quiet.is-invalid.focus-ring, .spectrum--dark .spectrum-FieldButton--quiet.is-invalid.is-focused { box-shadow: 0 2px 0 0 rgb(38, 128, 235); } .spectrum--dark .spectrum-FieldButton--quiet:disabled, .spectrum--dark .spectrum-FieldButton--quiet.is-disabled { background-color: rgba(0, 0, 0, 0); color: rgb(92, 92, 92); } .spectrum--dark .spectrum-FieldButton--quiet:disabled.focus-ring, .spectrum--dark .spectrum-FieldButton--quiet.is-disabled.focus-ring { box-shadow: none; } .spectrum--dark .spectrum-Tool.is-selected .spectrum-Icon { color: rgb(55, 142, 240); } .spectrum--dark .spectrum-Tool.is-selected .spectrum-Tool-hold { color: rgb(55, 142, 240); } .spectrum--dark .spectrum-Tool.is-selected:hover .spectrum-Icon { color: rgb(75, 156, 245); } .spectrum--dark .spectrum-Tool.is-selected:hover .spectrum-Tool-hold { color: rgb(75, 156, 245); } .spectrum--dark .spectrum-Tool.is-selected:active .spectrum-Icon { color: rgb(90, 169, 250); } .spectrum--dark .spectrum-Tool.is-selected:active .spectrum-Tool-hold { color: rgb(90, 169, 250); } .spectrum--dark .spectrum-Tool.is-selected.focus-ring .spectrum-Icon { color: rgb(75, 156, 245); } .spectrum--dark .spectrum-Tool.is-selected.focus-ring .spectrum-Tool-hold { color: rgb(75, 156, 245); } .spectrum--dark .spectrum-Tool.is-selected:disabled, .spectrum--dark .spectrum-Tool.is-selected.is-disabled { background-color: rgba(0, 0, 0, 0); border-color: rgba(0, 0, 0, 0); } .spectrum--dark .spectrum-Tool.is-selected:disabled .spectrum-Icon, .spectrum--dark .spectrum-Tool.is-selected.is-disabled .spectrum-Icon { color: rgb(77, 77, 77); } .spectrum--dark .spectrum-Tool.is-selected:disabled .spectrum-Tool-hold, .spectrum--dark .spectrum-Tool.is-selected.is-disabled .spectrum-Tool-hold { color: rgb(77, 77, 77); } .spectrum--dark .spectrum-Tool .spectrum-Tool-hold { color: rgb(157, 157, 157); } .spectrum--dark .spectrum-Tool:hover .spectrum-Tool-hold { color: rgb(255, 255, 255); } .spectrum--dark .spectrum-Tool:active { background-color: rgba(0, 0, 0, 0); border-color: rgba(0, 0, 0, 0); } .spectrum--dark .spectrum-Tool:active .spectrum-Tool-hold { color: rgb(255, 255, 255); } .spectrum--dark .spectrum-Tool.focus-ring .spectrum-Tool-hold { color: rgb(255, 255, 255); } .spectrum--dark .spectrum-Tool.is-disabled .spectrum-Tool-hold, .spectrum--dark .spectrum-Tool:disabled .spectrum-Tool-hold { color: rgb(77, 77, 77); }`; } }
ScoutRFP/ag-grid
enterprise-modules/charts/dist/cjs/charts/util/number.js
<reponame>ScoutRFP/ag-grid<gh_stars>1-10 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function isEqual(a, b, epsilon) { if (epsilon === void 0) { epsilon = 1e-10; } return Math.abs(a - b) < epsilon; } exports.isEqual = isEqual; /** * `Number.toFixed(n)` always formats a number so that it has `n` digits after the decimal point. * For example, `Number(0.00003427).toFixed(2)` returns `0.00`. * That's not very helpful, because all the meaningful information is lost. * In this case we would want the formatted value to have at least two significant digits: `0.000034`, * not two fraction digits. * @param value * @param fractionOrSignificantDigits */ function toFixed(value, fractionOrSignificantDigits) { if (fractionOrSignificantDigits === void 0) { fractionOrSignificantDigits = 2; } var power = Math.floor(Math.log(Math.abs(value)) / Math.LN10); if (power >= 0 || !isFinite(power)) { return value.toFixed(fractionOrSignificantDigits); // fraction digits } return value.toFixed(Math.abs(power) - 1 + fractionOrSignificantDigits); // significant digits } exports.toFixed = toFixed; var numberUnits = ["", "K", "M", "B", "T"]; function toReadableNumber(value, fractionDigits) { if (fractionDigits === void 0) { fractionDigits = 2; } // For example: toReadableNumber(10550000000) yields "10.6B" var prefix = ''; if (value <= 0) { value = -value; prefix = '-'; } var thousands = ~~(Math.log10(value) / Math.log10(1000)); // discard the floating point part return prefix + (value / Math.pow(1000.0, thousands)).toFixed(fractionDigits) + numberUnits[thousands]; } exports.toReadableNumber = toReadableNumber; //# sourceMappingURL=number.js.map
KillianG/R-Type
Client/OptionsMenu/OptionsMenu.hpp
<reponame>KillianG/R-Type // // Created by NANAA on 12/11/18. // #ifndef R_TYPE_OPTIONSMENU_HPP #define R_TYPE_OPTIONSMENU_HPP #include <Client/MainMenu/Settings.hpp> #include "libs/EventManager/Receiver.hpp" #include <unordered_map> #include <Client/MainMenu/Button.hpp> class OptionsMenu : public Receiver<OptionsMenu> { public: OptionsMenu(); ~OptionsMenu() = default; void show(); void hide(); private: std::shared_ptr<Button> getButtonByName(const std::string &name); void setButtons(); std::shared_ptr<gfx::Window> _window; gfx::Manager &_manager = gfx::Singleton<gfx::Manager>::get(); std::unordered_map<std::string, std::shared_ptr<Button>> _buttons; }; #endif //R_TYPE_OPTIONSMENU_HPP
patrickduc/OOP-training
examples/Formes/src/formes/Rectangle.java
<reponame>patrickduc/OOP-training /* * 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 formes; /** * * @author duc */ public class Rectangle extends FormeGeometrique { float longueur, largeur; public Rectangle(float xOrigine, float yOrigine, float longueur, float largeur) { super(xOrigine, yOrigine); this.longueur = longueur; this.largeur = largeur; } @Override public float perimetre() { return (longueur + largeur)* 2; } @Override public float surface() { return longueur * largeur; } @Override public void afficher() { super.afficher(); System.out.println("\tRectangle :\n\t\tlongueur = " + longueur + "\n\t\tlargeur = " + largeur); } }
jwmount/t365
db/migrate/20190301191720_create_engagements.rb
class CreateEngagements < ActiveRecord::Migration[5.2] def change create_table :engagements do |t| t.integer :schedule_id t.integer :person_id t.integer :docket_id t.string :docket_number t.boolean :onsite_now t.boolean :onsite_at t.boolean :breakdown t.boolean :no_show t.integer :OK_tomorrow t.boolean :engagement_declined t.timestamps end end end
ifge-token/Waves
lang/tests/src/test/scala/com/wavesplatform/lang/v1/estimator/CommonScriptEstimatorTest.scala
package com.wavesplatform.lang.v1.estimator import com.wavesplatform.lang.directives.values.V3 import com.wavesplatform.lang.utils.functionCosts import com.wavesplatform.lang.v1.FunctionHeader import com.wavesplatform.lang.v1.FunctionHeader.{Native, User} import com.wavesplatform.lang.v1.compiler.Terms._ import com.wavesplatform.lang.v1.evaluator.FunctionIds.SUM_LONG import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 class CommonScriptEstimatorTest extends ScriptEstimatorTestBase(ScriptEstimatorV1, ScriptEstimatorV2, ScriptEstimatorV3) { property("recursive func block") { val expr = BLOCK( FUNC("x", List.empty, FUNCTION_CALL(FunctionHeader.User("y"), List.empty)), BLOCK(FUNC("y", List.empty, FUNCTION_CALL(FunctionHeader.User("x"), List.empty)), FUNCTION_CALL(FunctionHeader.User("y"), List.empty)) ) estimate(customFunctionCosts, expr) shouldBe 'left } property("context leak") { def script(ref: String) = compile { s""" | func inc($ref: Int) = $ref + 1 | let xxx = 5 | inc(xxx) """.stripMargin } estimateDelta(script("xxx"), script("y")) shouldBe Right(0) } property("overlapped func with recursion") { val expr = BLOCK( FUNC( "f", Nil, BLOCK( FUNC("g", Nil, FUNCTION_CALL(User("f"), Nil)), BLOCK( FUNC( "f", Nil, BLOCK( FUNC("f", Nil, FUNCTION_CALL(User("g"), Nil)), FUNCTION_CALL(User("f"), Nil) ), ), FUNCTION_CALL(User("f"), Nil) ) ) ), FUNCTION_CALL(User("f"), Nil) ) estimate(functionCosts(V3), expr) shouldBe 'left } property("func forward reference") { val expr = BLOCK( FUNC("f", Nil, FUNCTION_CALL(User("g"), Nil)), BLOCK( FUNC("g", Nil, CONST_LONG(1)), CONST_LONG(1) ) ) estimate(functionCosts(V3), expr) shouldBe 'left } property("func decl overlapping inside let") { def expr(outerFunc: String) = BLOCK( FUNC(outerFunc, Nil, FUNCTION_CALL(Native(SUM_LONG), List(CONST_LONG(1), CONST_LONG(1)))), BLOCK( LET( "b", BLOCK( FUNC("f", Nil, CONST_LONG(1)), FUNCTION_CALL(User("f"), Nil) ) ), FUNCTION_CALL(Native(SUM_LONG), List(FUNCTION_CALL(User(outerFunc), Nil), REF("b"))) ) ) /* func f() = 1 + 1 let b = { func f() = 1 1 } f() + b */ estimateDelta(expr("f"), expr("g")) shouldBe Right(0) } property("func decl overlapping inside func") { def expr(outerFunc: String) = BLOCK( FUNC(outerFunc, Nil, FUNCTION_CALL(Native(SUM_LONG), List(CONST_LONG(1), CONST_LONG(1)))), BLOCK( FUNC( "b", Nil, BLOCK( FUNC("f", Nil, CONST_LONG(1)), FUNCTION_CALL(User("f"), Nil) ) ), FUNCTION_CALL( Native(SUM_LONG), List(FUNCTION_CALL(User(outerFunc), Nil), FUNCTION_CALL(User("b"), Nil)) ) ) ) /* func f() = 1 + 1 func b() = { func f() = 1 1 } f() + b() */ estimateDelta(expr("f"), expr("g")) shouldBe Right(0) } property("func decl overlapping inside condition") { def expr(outerFunc: String) = BLOCK( FUNC(outerFunc, Nil, FUNCTION_CALL(Native(SUM_LONG), List(CONST_LONG(1), CONST_LONG(1)))), FUNCTION_CALL( Native(SUM_LONG), List( IF(TRUE, BLOCK( FUNC("f", Nil, CONST_LONG(1)), FUNCTION_CALL(User("f"), Nil) ), CONST_LONG(1) ), FUNCTION_CALL(User(outerFunc), Nil) ) ) ) /* func f() = 1 + 1 ( if (true) then { func f() = 1 1 } else 1 ) + f() */ estimateDelta(expr("f"), expr("g")) shouldBe Right(0) } property("func decl overlapping inside func parameter") { def expr(outerFunc: String) = BLOCK( FUNC(outerFunc, Nil, FUNCTION_CALL(Native(SUM_LONG), List(CONST_LONG(1), CONST_LONG(1)))), BLOCK( FUNC("b", List("a"), REF("a")), FUNCTION_CALL( Native(SUM_LONG), List( FUNCTION_CALL( User("b"), List(BLOCK( FUNC("f", Nil, CONST_LONG(1)), FUNCTION_CALL(User("f"), Nil) )) ), FUNCTION_CALL(User(outerFunc), Nil) ) ) ) ) /* func f() = 1 + 1 func b(a) = a b({func f() = 1; f()}) + f() */ estimateDelta(expr("f"), expr("g")) shouldBe Right(0) } property("let overlapping") { def expr(outerLet: String): EXPR = BLOCK( LET(outerLet, FUNCTION_CALL(Native(SUM_LONG), List(CONST_LONG(1), CONST_LONG(1)))), BLOCK( LET( "b", BLOCK( LET("a", CONST_LONG(1)), CONST_LONG(1) ) ), FUNCTION_CALL(Native(SUM_LONG), List(REF(outerLet), REF("b"))) ) ) /* let a = 1 + 1 let b = { let a = 1 1 } a + b */ estimateDelta(expr("a"), expr("x")) shouldBe Right(0) } }
yeojhenrie/React
src/main/java/com/volmit/react/command/CommandRevoke.java
<filename>src/main/java/com/volmit/react/command/CommandRevoke.java<gh_stars>1-10 package com.volmit.react.command; import java.util.List; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.volmit.react.Config; import com.volmit.react.Gate; import com.volmit.react.Info; import com.volmit.react.api.Permissable; import com.volmit.react.api.ReactCommand; import com.volmit.react.api.SideGate; import com.volmit.react.util.P; import primal.lang.collection.GList; public class CommandRevoke extends ReactCommand { public CommandRevoke() { command = Info.COMMAND_REVOKE; aliases = new String[] {Info.COMMAND_REVOKE_ALIAS_1, Info.COMMAND_REVOKE_ALIAS_2}; permissions = new String[] {Permissable.ACCESS.toString()}; usage = Info.COMMAND_REVOKE_USAGE; description = Info.COMMAND_REVOKE_DESCRIPTION; sideGate = SideGate.ANYTHING; } @Override public List<String> onTabComplete(CommandSender arg0, Command arg1, String arg2, String[] arg3) { GList<String> l = new GList<String>(); return l; } @Override public void fire(CommandSender sender, String[] args) { if(!Config.ALLOW_TEMPACCESS) { Gate.msgError(sender, "Temporary Access is disabled."); return; } if(sender instanceof Player && Permissable.isAccessor((Player) sender)) { if(args.length == 1 && P.findPlayer(args[0]) != null && P.findPlayer(args[0]).equals(sender)) { Permissable.removeAccesssor((Player) sender); Gate.msgSuccess(sender, "Access self revoked. Have a nice day."); return; } Gate.msgError(sender, "Creative, but sorry. You need real access to do this :P"); return; } if(args.length == 1) { Player p = P.findPlayer(args[0]); if(p != null) { if(!Permissable.isAccessor(p)) { Gate.msgError(sender, p.getName() + " does not have temporary access. You can add with /re accept <player>"); return; } Permissable.removeAccesssor(p); Gate.msgSuccess(sender, p.getName() + "'s react privileges revoked."); } else { Gate.msgError(sender, "Cant find '" + args[0] + "'. Make sure your keyboard is plugged in."); } } else { Gate.msgError(sender, "/re revoke <PLAYER>"); } } }
wongmjane/lfi
src/filter.js
<reponame>wongmjane/lfi /** * Copyright 2021 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. */ import { curry } from './curry.js' import { flatMap, flatMapAsync, flatMapConcur } from './flat-map.js' import { asAsync, asConcur } from './as.js' export const filter = curry((fn, iterable) => flatMap(value => (fn(value) === true ? [value] : []), iterable) ) const createAsyncFilter = (flatMap, as) => curry((fn, iterable) => flatMap( async value => as((await fn(value)) === true ? [value] : []), iterable ) ) export const filterAsync = createAsyncFilter(flatMapAsync, asAsync) export const filterConcur = createAsyncFilter(flatMapConcur, asConcur) const createWithout = filter => curry((excluded, iterable) => { const set = new Set(excluded) return filter(value => !set.has(value), iterable) }) export const without = createWithout(filter) export const withoutAsync = createWithout(filterAsync) export const withoutConcur = createWithout(filterConcur)
avidsapp/gatsby-woocommerce-themes
packages/gatsby-woocommerce-theme/src/components/icons/search-icon.js
import React from 'react'; export const SearchIcon = () => ( <svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="15pt" viewBox="0 0 512.005 512.005" className="search-icon" > <g> <g> <path fill="#ccc" d="M505.749,475.587l-145.6-145.6c28.203-34.837,45.184-79.104,45.184-127.317c0-111.744-90.923-202.667-202.667-202.667 S0,90.925,0,202.669s90.923,202.667,202.667,202.667c48.213,0,92.48-16.981,127.317-45.184l145.6,145.6 c4.16,4.16,9.621,6.251,15.083,6.251s10.923-2.091,15.083-6.251C514.091,497.411,514.091,483.928,505.749,475.587z M202.667,362.669c-88.235,0-160-71.765-160-160s71.765-160,160-160s160,71.765,160,160S290.901,362.669,202.667,362.669z"/> </g> </g> </svg> ); export default SearchIcon;
ossimlabs/ossim-gui
src/ossimGui/ProgressDialog.cpp
//--- // // License: See top level LICENSE.txt file. // // Description: Description: Dialog box for ProgressWidget. // //--- // $Id$ #include <ossimGui/ProgressDialog.h> #include <ossimGui/ProgressWidget.h> #include <ossim/base/ossimTrace.h> #include <QVBoxLayout> #include <QWidget> #include <cstring> #include <iomanip> #include <sstream> #include <vector> static ossimTrace traceDebug("ProgressDialog:debug"); ossimGui::ProgressDialog::ProgressDialog(QWidget* parent, Qt::WindowFlags f) : QDialog( parent, f ), m_widget(0) { m_widget = new ossimGui::ProgressWidget(this); m_widget->setValue(0); // setup vertical layout QVBoxLayout* vbox0 = new QVBoxLayout(); vbox0->addWidget( m_widget ); setLayout( vbox0 ); } ossimGui::ProgressDialog::~ProgressDialog() { // m_annotator.removeListener((ossimROIEventListener*)this); // Pretty sure the widget is parented to "this" and will be deleted in the // QT code. Need to verify... // delete m_widget; // m_widget = 0; } ossimGui::ProgressWidget* ossimGui::ProgressDialog::progressWidget() { return m_widget; }
isabella232/parsec-client-go
parsec/keytype.go
<reponame>isabella232/parsec-client-go // Copyright 2021 Contributors to the Parsec project. // SPDX-License-Identifier: Apache-2.0 package parsec import "github.com/parallaxsecond/parsec-client-go/interface/operations/psakeyattributes" type KeyTypeFactory interface { RawData() *KeyType Hmac() *KeyType Derive() *KeyType Aes() *KeyType Des() *KeyType Camellia() *KeyType Arc4() *KeyType Chacha20() *KeyType RsaPublicKey() *KeyType RsaKeyPair() *KeyType EccKeyPair(curveFamily EccFamily) *KeyType EccPublicKey(curveFamily EccFamily) *KeyType DhKeyPair(groupFamily DhFamily) *KeyType DhPublicKey(groupFamily DhFamily) *KeyType } type keyTypeFactory struct{} func NewKeyType() KeyTypeFactory { return &keyTypeFactory{} } func (a *keyTypeFactory) RawData() *KeyType { return &KeyType{ variant: &KeyTypeRawData{}, } } func (a *keyTypeFactory) Hmac() *KeyType { return &KeyType{variant: &KeyTypeHmac{}} } func (a *keyTypeFactory) Derive() *KeyType { return &KeyType{variant: &KeyTypeDerive{}} } func (a *keyTypeFactory) Aes() *KeyType { return &KeyType{variant: &KeyTypeAes{}} } func (a *keyTypeFactory) Des() *KeyType { return &KeyType{variant: &KeyTypeDes{}} } func (a *keyTypeFactory) Camellia() *KeyType { return &KeyType{variant: &KeyTypeCamellia{}} } func (a *keyTypeFactory) Arc4() *KeyType { return &KeyType{variant: &KeyTypeArc4{}} } func (a *keyTypeFactory) Chacha20() *KeyType { return &KeyType{variant: &KeyTypeChacha20{}} } func (a *keyTypeFactory) RsaPublicKey() *KeyType { return &KeyType{variant: &KeyTypeRsaPublicKey{}} } func (a *keyTypeFactory) RsaKeyPair() *KeyType { return &KeyType{variant: &KeyTypeRsaKeyPair{}} } func (a *keyTypeFactory) EccKeyPair(curveFamily EccFamily) *KeyType { return &KeyType{variant: &KeyTypeEccKeyPair{ CurveFamily: curveFamily, }} } func (a *keyTypeFactory) EccPublicKey(curveFamily EccFamily) *KeyType { return &KeyType{variant: &KeyTypeEccPublicKey{ CurveFamily: curveFamily, }} } func (a *keyTypeFactory) DhKeyPair(groupFamily DhFamily) *KeyType { return &KeyType{variant: &KeyTypeDhKeyPair{ GroupFamily: groupFamily, }} } func (a *keyTypeFactory) DhPublicKey(groupFamily DhFamily) *KeyType { return &KeyType{variant: &KeyTypeDhPublicKey{ GroupFamily: groupFamily, }} } type KeyType struct { // Types that are assignable to variant: // *KeyType_RawData // *KeyType_Hmac // *KeyType_Derive // *KeyType_Aes // *KeyType_Des // *KeyType_Camellia // *KeyType_Arc4 // *KeyType_Chacha20 // *KeyType_RsaPublicKey // *KeyType_RsaKeyPair // *KeyType_EccKeyPair // *KeyType_EccPublicKey // *KeyType_DhKeyPair // *KeyType_DhPublicKey variant keyTypeVariant } type keyTypeVariant interface { isKeyTypeVariant() toWireInterface() interface{} } func (k *KeyType) ToWireInterface() interface{} { if k.variant == nil { return nil } return k.variant.toWireInterface() } type EccFamily int32 const ( KeyTypeECCFAMILYNONE EccFamily = 0 // This default variant should not be used. KeyTypeSECPK1 EccFamily = 1 KeyTypeSECPR1 EccFamily = 2 // Deprecated: Do not use. KeyTypeSECPR2 EccFamily = 3 KeyTypeSECTK1 EccFamily = 4 // DEPRECATED for sect163k1 curve KeyTypeSECTR1 EccFamily = 5 // DEPRECATED for sect163r1 curve // Deprecated: Do not use. KeyTypeSECTR2 EccFamily = 6 KeyTypeBRAINPOOLPR1 EccFamily = 7 // DEPRECATED for brainpoolP160r1 curve KeyTypeFRP EccFamily = 8 KeyTypeMONTGOMERY EccFamily = 9 ) type DhFamily int32 const ( KeyTypeRFC7919 DhFamily = 0 ) type KeyTypeRawData struct{} func (k KeyTypeRawData) isKeyTypeVariant() {} func (k *KeyTypeRawData) toWireInterface() interface{} { return &psakeyattributes.KeyType{ Variant: &psakeyattributes.KeyType_RawData_{}, } } type KeyTypeHmac struct{} func (k KeyTypeHmac) isKeyTypeVariant() {} func (k *KeyTypeHmac) toWireInterface() interface{} { return &psakeyattributes.KeyType{ Variant: &psakeyattributes.KeyType_Hmac_{}, } } type KeyTypeDerive struct{} func (k KeyTypeDerive) isKeyTypeVariant() {} func (k *KeyTypeDerive) toWireInterface() interface{} { return &psakeyattributes.KeyType{ Variant: &psakeyattributes.KeyType_Derive_{}, } } type KeyTypeAes struct{} func (k KeyTypeAes) isKeyTypeVariant() {} func (k *KeyTypeAes) toWireInterface() interface{} { return &psakeyattributes.KeyType{ Variant: &psakeyattributes.KeyType_Aes_{}, } } type KeyTypeDes struct{} func (k KeyTypeDes) isKeyTypeVariant() {} func (k *KeyTypeDes) toWireInterface() interface{} { return &psakeyattributes.KeyType{ Variant: &psakeyattributes.KeyType_Des_{}, } } type KeyTypeCamellia struct{} func (k KeyTypeCamellia) isKeyTypeVariant() {} func (k *KeyTypeCamellia) toWireInterface() interface{} { return &psakeyattributes.KeyType{ Variant: &psakeyattributes.KeyType_Camellia_{}, } } type KeyTypeArc4 struct{} func (k KeyTypeArc4) isKeyTypeVariant() {} func (k *KeyTypeArc4) toWireInterface() interface{} { return &psakeyattributes.KeyType{ Variant: &psakeyattributes.KeyType_Arc4_{}, } } type KeyTypeChacha20 struct{} func (k KeyTypeChacha20) isKeyTypeVariant() {} func (k *KeyTypeChacha20) toWireInterface() interface{} { return &psakeyattributes.KeyType{ Variant: &psakeyattributes.KeyType_Chacha20_{}, } } type KeyTypeRsaPublicKey struct{} func (k KeyTypeRsaPublicKey) isKeyTypeVariant() {} func (k *KeyTypeRsaPublicKey) toWireInterface() interface{} { return &psakeyattributes.KeyType{ Variant: &psakeyattributes.KeyType_RsaPublicKey_{}, } } type KeyTypeRsaKeyPair struct{} func (k KeyTypeRsaKeyPair) isKeyTypeVariant() {} func (k *KeyTypeRsaKeyPair) toWireInterface() interface{} { return &psakeyattributes.KeyType{ Variant: &psakeyattributes.KeyType_RsaKeyPair_{}, } } type KeyTypeEccKeyPair struct { CurveFamily EccFamily } func (k KeyTypeEccKeyPair) isKeyTypeVariant() {} func (k *KeyTypeEccKeyPair) toWireInterface() interface{} { return &psakeyattributes.KeyType{ Variant: &psakeyattributes.KeyType_EccKeyPair_{}, } } type KeyTypeEccPublicKey struct { CurveFamily EccFamily } func (k KeyTypeEccPublicKey) isKeyTypeVariant() {} func (k *KeyTypeEccPublicKey) toWireInterface() interface{} { return &psakeyattributes.KeyType{ Variant: &psakeyattributes.KeyType_EccPublicKey_{}, } } type KeyTypeDhKeyPair struct { GroupFamily DhFamily } func (k KeyTypeDhKeyPair) isKeyTypeVariant() {} func (k *KeyTypeDhKeyPair) toWireInterface() interface{} { return &psakeyattributes.KeyType{ Variant: &psakeyattributes.KeyType_DhKeyPair_{}, } } type KeyTypeDhPublicKey struct{ GroupFamily DhFamily } func (k KeyTypeDhPublicKey) isKeyTypeVariant() {} func (k *KeyTypeDhPublicKey) toWireInterface() interface{} { return &psakeyattributes.KeyType{ Variant: &psakeyattributes.KeyType_DhPublicKey_{}, } }
escray/NodeJSPractice
demo/resDemo.js
<gh_stars>0 var express = require('express'); var app = express(); app.get('/', function(req, res) { console.log(res.headersSent); res.send("OK"); console.log(res.headersSent); }); app.get('/file/:name', function(req, res, next) { var options = { root: __dirname + '/public/', dotfiles: 'deny', headers: { 'x-timestamp': Date.now(), 'x-sent': true } }; var filename = req.params.name; res.sendFile(filename, options, function(err) { if (err) { console.log(err); res.status(err.status).end(); } else { console.log('Sent: ', filename); } }); }); app.get('/user/:uid/photos/:file', function(req, res) { var uid = req.params.uid, file = req.params.file; req.user.myViewFilesFrom(uid, function(yes){ if(yes) { res.sendFile('/uploads/' + uid + '/' + file); } else { res.status(403).send('Sorry! you can\'t see that.'); } }) }) app.listen(3000, function(){ console.log("fight!"); });
pm-deepak-dhage/prebid-server-java
src/main/java/org/prebid/server/bidder/Bidder.java
<filename>src/main/java/org/prebid/server/bidder/Bidder.java package org.prebid.server.bidder; import com.fasterxml.jackson.databind.node.ObjectNode; import com.iab.openrtb.request.BidRequest; import org.prebid.server.bidder.model.BidderBid; import org.prebid.server.bidder.model.HttpCall; import org.prebid.server.bidder.model.HttpRequest; import org.prebid.server.bidder.model.Result; import java.util.List; import java.util.Map; /** * Defines the contract needed to participate in an auction. */ public interface Bidder<T> { /** * Makes the HTTP requests which should be made to fetch bids. * <p> * The errors should contain a list of errors which explain why this bidder's bids will be "subpar" in some way. * For example: the request contained ad types which this bidder doesn't support. */ Result<List<HttpRequest<T>>> makeHttpRequests(BidRequest request); /** * Unpacks the server's response into bids. * <p> * The errors should contain a list of errors which explain why this bidder's bids will be * "subpar" in some way. For example: the server response didn't have the expected format. */ Result<List<BidderBid>> makeBids(HttpCall<T> httpCall, BidRequest bidRequest); /** * Extracts targeting from bidder-specific extension. It is safe to assume that {@code ext} is not null. */ Map<String, String> extractTargeting(ObjectNode ext); }
vandreas19/POJ_sol
2161/2185845_AC_15MS_956K.cpp
#include<iostream.h> #include<string.h> struct Node { int iChildNum,iStack,iBegin; Node* pnChild[9]; } nRoot; char cLine[10001]; void Read(Node* pnRoot,int& iPos) { int i,j,iTemp; if(cLine[iPos]=='a') { pnRoot->iChildNum=pnRoot->iBegin=0; pnRoot->iStack=1; } else { pnRoot->iChildNum=cLine[iPos]-'0'; for(i=pnRoot->iChildNum-1;i>=0;i--) { pnRoot->pnChild[i]=new Node; Read(pnRoot->pnChild[i],--iPos); } pnRoot->iStack=100000;pnRoot->iBegin=0; for(i=0;i<pnRoot->iChildNum;i++) { iTemp=0; for(j=0;j<pnRoot->iChildNum;j++) if(pnRoot->pnChild[(i+j)%pnRoot->iChildNum]->iStack+j>iTemp) iTemp=pnRoot->pnChild[(i+j)%pnRoot->iChildNum]->iStack+j; if(iTemp<pnRoot->iStack) { pnRoot->iStack=iTemp; pnRoot->iBegin=i; } } } } void Print(Node* nRoot) { if(nRoot->iChildNum==0) cout<<"a"; else { for(int i=0;i<nRoot->iChildNum;i++) Print(nRoot->pnChild[(nRoot->iBegin+i)%nRoot->iChildNum]); cout<<nRoot->iChildNum; } } void main() { int iPos; cin>>cLine;iPos=strlen(cLine)-1; Read(&nRoot,iPos); cout<<nRoot.iStack<<endl; Print(&nRoot); cout<<endl; }
guillaumewibaux/AER-PGROU
app/controllers/admin/AssignerExpert.java
<reponame>guillaumewibaux/AER-PGROU<filename>app/controllers/admin/AssignerExpert.java /********************************************************************************* * * Copyright 2014 BOUSSEJRA <NAME>, <NAME>, <NAME> * * 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 controllers.admin; import java.util.List; import models.Droits; import models.Groupe; import models.Membre; import models.MembreIsExpertOnGroupe; import play.data.DynamicForm; import play.mvc.Controller; import play.mvc.Result; import views.html.admin.assignerExperts; /** * Gère les fonctions pour assigner les experts * @author malik * */ public class AssignerExpert extends Controller { /** * Affiche la page principale * @return */ public static Result main() { if(Admin.isAdminConnected()){ List<Groupe> groupes = Groupe.find.orderBy("groupe_nom").findList(); return ok(assignerExperts.render(groupes)); }else return Admin.nonAutorise(); } /** * Ajoute l'expert donné dans la form (s'il existe) dans le groupe dont * l'ID est donné en argument. * Si les données entrées sont fausses, retourne juste sur main(). * @param groupe_id * @return */ public static Result ajouter(Integer groupe_id){ if(Admin.isAdminConnected()){ DynamicForm df = DynamicForm.form().bindFromRequest(); Groupe groupe = Groupe.find.byId(groupe_id); Membre expert = Membre.find.where().eq("membre_nom", df.get("membre_nominputGroupe"+groupe_id)).findUnique(); if(expert!=null && groupe!=null && !expert.membre_droits.equals(Droits.ADMIN)){ MembreIsExpertOnGroupe mieog = new MembreIsExpertOnGroupe(expert,groupe); mieog.save(); expert.membre_droits=Droits.EXPERT; expert.save(); } return redirect("/assignerExperts"); }else return Admin.nonAutorise(); } /** * Change l'expert du groupe. DEPRECIEE !!! * @param groupe_id * @return */ public static Result changer(Integer groupe_id){ if(Admin.isAdminConnected()){ DynamicForm df = DynamicForm.form().bindFromRequest(); MembreIsExpertOnGroupe mieog = MembreIsExpertOnGroupe.find.where().eq("groupe.groupe_id",groupe_id).findUnique(); Membre expert = Membre.find.where().eq("membre_nom", df.get("membre_nominputGroupe"+groupe_id)).findUnique(); if(mieog!=null && expert!=null){ if(!mieog.membre.membre_droits.equals(Droits.ADMIN)){ mieog.membre.membre_droits=Droits.TEMOIN; mieog.membre.save(); } mieog.membre=expert; mieog.save(); expert.membre_droits=Droits.EXPERT; expert.save(); } return redirect("/assignerExperts"); }else return Admin.nonAutorise(); } /** * Enlève un expert de son statut d'expert en tel domaine. * @param mieog_id * @return */ public static Result retrograder(Integer mieog_id){ if(Admin.isAdminConnected()){ MembreIsExpertOnGroupe mieog = MembreIsExpertOnGroupe.find.byId(mieog_id); if(mieog!=null){ Membre ex_expert = mieog.membre; mieog.delete(); if(MembreIsExpertOnGroupe.find.where().eq("membre",ex_expert).findList().isEmpty() && !ex_expert.membre_droits.equals(Droits.ADMIN)){ ex_expert.membre_droits=Droits.TEMOIN; ex_expert.update(); } } return redirect("/assignerExperts"); }else return Admin.nonAutorise(); } }
neelimabhukya/readypolicy-ui
src/ToggleSwitch.js
<gh_stars>1-10 /** * ToggleSwitch.js * Copyright: Microsoft 2017 * * A simple toggle control built in ReactXP that allows users to * pick between two values. */ import React from 'react'; import RX from 'reactxp'; const _knobLeftOff = 2; // In pixels const _knobLeftOn = 22; // In pixels const _animationDuration = 250; // In milliseconds const _styles = { container: RX.Styles.createButtonStyle({ flexDirection: 'row', alignItems: 'center' }), toggleSwitch: RX.Styles.createViewStyle({ flexDirection: 'row', borderRadius: 15, marginVertical: 8, height: 30, width: 50, backgroundColor: '#ddd' }), toggleSwitchBackground: RX.Styles.createViewStyle({ position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, borderRadius: 15 }), toggleKnob: RX.Styles.createViewStyle({ top: 2, height: 26, width: 26, borderRadius: 13, backgroundColor: 'white' }) }; export default class ToggleSwitch extends RX.Component { _knobLeftAnimationValue; _knobLeftAnimationStyle; _toggleColorAnimationValue; _toggleColorAnimationStyle; constructor(props){ super(props); // This value controls the left offset of the knob, which we will // animate when the user toggles the control. this._knobLeftAnimationValue = RX.Animated.createValue(this.props.value ? _knobLeftOn : _knobLeftOff); this._knobLeftAnimationStyle = RX.Styles.createAnimatedViewStyle({ left: this._knobLeftAnimationValue }); // This value controls the background color of the control. Here we make // use of the interpolate method to smoothly transition between two colors. this._toggleColorAnimationValue = RX.Animated.createValue(this.props.value ? 1 : 0); this._toggleColorAnimationStyle = RX.Styles.createAnimatedTextInputStyle({ backgroundColor: RX.Animated.interpolate(this._toggleColorAnimationValue, [0, 1], ['#66f', '#ddd']) }); this._handleClick = this._handleClick.bind(this); } componentWillUpdate(newProps) { // If the value of the toggle changes, animate the toggle sliding // from one side to the other. In parallel, animate the opacity change. if (this.props.value !== newProps.value) { RX.Animated.parallel([ RX.Animated.timing(this._knobLeftAnimationValue, { toValue: newProps.value ? _knobLeftOn : _knobLeftOff, duration: _animationDuration, easing: RX.Animated.Easing.InOut() }), RX.Animated.timing(this._toggleColorAnimationValue, { toValue: newProps.value ? 1 : 0, duration: _animationDuration, easing: RX.Animated.Easing.InOut() }) ]) .start(); } } render() { const knobStyles = [_styles.toggleKnob, this._knobLeftAnimationStyle]; const backgroundStyle = [_styles.toggleSwitchBackground, this._toggleColorAnimationStyle]; return ( <RX.Button style={ _styles.container } onPress={ this._handleClick }> <RX.View style={ _styles.toggleSwitch }> <RX.Animated.View style={ backgroundStyle }/> <RX.Animated.View style={ knobStyles }/> </RX.View> </RX.Button> ); } _handleClick(e) { e.stopPropagation(); if (this.props.onChange) { this.props.onChange(!this.props.value); } } }
RabbitPo/TabooLib
src/main/scala/io/izzel/taboolib/util/chat/SelectorComponentSerializer.java
package io.izzel.taboolib.util.chat; import com.google.gson.*; import java.lang.reflect.Type; public class SelectorComponentSerializer extends BaseComponentSerializer implements JsonSerializer<SelectorComponent>, JsonDeserializer<SelectorComponent> { @Override public SelectorComponent deserialize(JsonElement element, Type type, JsonDeserializationContext context) throws JsonParseException { JsonObject object = element.getAsJsonObject(); SelectorComponent component = new SelectorComponent(object.get("selector").getAsString()); deserialize(object, component, context); return component; } @Override public JsonElement serialize(SelectorComponent component, Type type, JsonSerializationContext context) { JsonObject object = new JsonObject(); serialize(object, component, context); object.addProperty("selector", component.getSelector()); return object; } }
ManuelDeLeon/viewmodel-react-docs
src/imports/ReactDocumentation/Bindings/Repeat/ColorPosition/ColorPosition.js
ColorPosition({ position: 0, rgb: '', name: '', render() { <label b="text: position + ':' + name + ' ', style: { color: rgb }"></label> } });
nuxodin/vanilla-cms
m/cms.backend.module/pub/main.js
/* Copyright (c) 2016 <NAME> https://goo.gl/gl0mbf | MIT License https://goo.gl/HgajeK */ cms.initCont('cms.backend.module',function(el) { const pid = cms.el.pid(el); const searchInp = document.getElementById('searchForm'); const search = function(){ const search = this.elements.search.value; const installed = this.elements.installed.checked; $fn('page::loadPart')(pid, 'list', {search, installed}).run( c1.loading.mark(list) ); }.c1Debounce(200); searchInp && searchInp.addEventListener('input', search); searchInp && searchInp.addEventListener('change', search); const list = el.querySelector('[data-part=list]'); list && list.addEventListener('click',e=>{ const tr = e.target.closest('tr'); const module = tr.getAttribute('itemid'); let el = null; if (el = e.target.closest('.-access')) { $fn('page::api')(pid, {module,access:el.checked}); } else if (el = e.target.closest('.updateBtn')) { confirm('wirklich?') && $fn('page::api')(pid, {update:module}).run(done=>{ el.remove(); checkUpdateAll(); }); } else if (el = e.target.closest('.-uninstall')) { if (confirm('Möchten Sie das Modul wirklich löschen?')) { $fn('page::api')(pid, {uninstall:module}).run(()=>tr.remove()); } } else if (el = e.target.closest('.-init')) { $fn('page::api')(pid, {init:module}).run(()=>el.remove()); } else if (el = e.target.closest('.-upload')) { if (!confirm('Achtung! Das Modul wird auf dem Server überschrieben! \nMöchten Sie das Modul wirklich hochladen?')) return false; var notes = prompt('Notes'); $fn('page::api')(pid, {upload:module, incVersion:2, notes}).run(version=>{ if (!version) { alert('hat nicht funktioniert!'); } el.closest('tr').querySelector('.serverVersion').innerHTML = version; el.closest('tr').querySelector('.localVersion').innerHTML = version; el.parentNode.innerHTML = ''; }); } else if (el = e.target.closest('.-remoteDelete')) { if (confirm('Wirklich löschen auf dem Server löschen!?')) { $fn('page::api')(pid, {remoteDelete:module}); } } el && e.stopPropagation(); }) // moduleSetTitle = function(el, module) { // $fn('page::api')(pid, {module, title:el.value}); // }; const updateBtn = el.querySelector('.btnUpdateAll'); updateBtn && updateBtn.addEventListener('click',e=>{ if (e.ctrlKey || confirm('Wirklich Alle updaten?')) { updateBtn.style.opacity = .5; $fn('page::api')(pid, {updateAll:true}).then(()=>{ //$('input[name=search]').trigger('keyup'); // zzz? }); $fn('page::loadPart')(pid, 'list').then(()=>{ checkUpdateAll(); }); } e.preventDefault(); }) function checkUpdateAll(){ updateBtn && !el.querySelector('.updateBtn') && updateBtn.setAttribute('hidden','hidden'); } checkUpdateAll(); });
bilwa496/Placement-Preparation
Leetcode Solution/Tree/Medium/113. Path Sum II.cpp
<filename>Leetcode Solution/Tree/Medium/113. Path Sum II.cpp /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: void helper(TreeNode* root,int sum,vector<vector<int>> &ans,vector<int> temp) { if(!root) return ; temp.push_back(root->val); if(!(root->left) && !(root->right) && sum== root->val) ans.push_back(temp); helper(root->left,sum - root->val,ans,temp); helper(root->right,sum - root->val,ans,temp); temp.pop_back(); } vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> ans; vector<int> temp; helper(root,sum,ans,temp); return ans; } };
Golang-Coach/client
src/components/content/index.js
/** ** Created by <NAME> on 12/18/2017. * */ // @flow import Grid from 'material-ui/Grid'; import { withStyles } from 'material-ui/styles'; import PropTypes from 'prop-types'; import React, { PureComponent } from 'react'; import GitContent from './gitcontent'; import Packages from './packages'; import Overlay from './../common/overlay'; const styles = () => ({ container: { padding: 10, alignSelf: 'center', }, content: { zIndex: 2, position: 'relative', paddingRight: 10, paddingLeft: 20, }, padding0: { padding: '0 !important', }, packages: { overflow: 'auto', height: 'calc(100vh - 85px)', position: 'relative', }, gitContent: { overflow: 'auto', height: 'calc(100vh - 85px)', paddingLeft: 10, position: 'relative', }, }); type Props = { classes : any } class Content extends PureComponent<Props> { static propTypes = { classes: PropTypes.object.isRequired, }; render() { const { classes } = this.props; return ( <Grid className={classes.container} container direction="row" spacing={0} > <Grid className={classes.packages} item xs={5} > <Packages /> <Overlay color={'rbga(0,0,0, 0.4)'} eventEnable visible /> </Grid> <Grid className={classes.gitContent} item xs={7} > <GitContent /> </Grid> </Grid> ); } } export default withStyles(styles)(Content);
mpsitech/idec_public
ideccmbd/CrdIdecUsr/PnlIdecUsr1NSession.h
<gh_stars>0 /** * \file PnlIdecUsr1NSession.h * job handler for job PnlIdecUsr1NSession (declarations) * \author <NAME> * \date created: 30 Dec 2017 * \date modified: 30 Dec 2017 */ #ifndef PNLIDECUSR1NSESSION_H #define PNLIDECUSR1NSESSION_H // IP custInclude --- INSERT #include "QryIdecUsr1NSession.h" #define VecVIdecUsr1NSessionDo PnlIdecUsr1NSession::VecVDo #define ContInfIdecUsr1NSession PnlIdecUsr1NSession::ContInf #define StatAppIdecUsr1NSession PnlIdecUsr1NSession::StatApp #define StatShrIdecUsr1NSession PnlIdecUsr1NSession::StatShr #define StgIacIdecUsr1NSession PnlIdecUsr1NSession::StgIac #define TagIdecUsr1NSession PnlIdecUsr1NSession::Tag #define DpchAppIdecUsr1NSessionData PnlIdecUsr1NSession::DpchAppData #define DpchAppIdecUsr1NSessionDo PnlIdecUsr1NSession::DpchAppDo #define DpchEngIdecUsr1NSessionData PnlIdecUsr1NSession::DpchEngData /** * PnlIdecUsr1NSession */ class PnlIdecUsr1NSession : public JobIdec { public: /** * VecVDo (full: VecVIdecUsr1NSessionDo) */ class VecVDo { public: static const uint BUTDELETECLICK = 1; static const uint BUTREFRESHCLICK = 2; static uint getIx(const string& sref); static string getSref(const uint ix); }; /** * ContInf (full: ContInfIdecUsr1NSession) */ class ContInf : public Block { public: static const uint NUMFCSIQST = 1; public: ContInf(const uint numFCsiQst = 1); public: uint numFCsiQst; public: void writeXML(xmlTextWriter* wr, string difftag = "", bool shorttags = true); set<uint> comm(const ContInf* comp); set<uint> diff(const ContInf* comp); }; /** * StatApp (full: StatAppIdecUsr1NSession) */ class StatApp { public: static void writeXML(xmlTextWriter* wr, string difftag = "", bool shorttags = true, const uint ixIdecVExpstate = VecIdecVExpstate::MIND); }; /** * StatShr (full: StatShrIdecUsr1NSession) */ class StatShr : public Block { public: static const uint BUTDELETEAVAIL = 1; static const uint BUTDELETEACTIVE = 2; public: StatShr(const bool ButDeleteAvail = true, const bool ButDeleteActive = true); public: bool ButDeleteAvail; bool ButDeleteActive; public: void writeXML(xmlTextWriter* wr, string difftag = "", bool shorttags = true); set<uint> comm(const StatShr* comp); set<uint> diff(const StatShr* comp); }; /** * StgIac (full: StgIacIdecUsr1NSession) */ class StgIac : public Block { public: static const uint TCOREFWIDTH = 1; public: StgIac(const uint TcoRefWidth = 100); public: uint TcoRefWidth; public: bool readXML(xmlXPathContext* docctx, string basexpath = "", bool addbasetag = false); void writeXML(xmlTextWriter* wr, string difftag = "", bool shorttags = true); set<uint> comm(const StgIac* comp); set<uint> diff(const StgIac* comp); }; /** * Tag (full: TagIdecUsr1NSession) */ class Tag { public: static void writeXML(const uint ixIdecVLocale, xmlTextWriter* wr, string difftag = "", bool shorttags = true); }; /** * DpchAppData (full: DpchAppIdecUsr1NSessionData) */ class DpchAppData : public DpchAppIdec { public: static const uint JREF = 1; static const uint STGIAC = 2; static const uint STGIACQRY = 3; public: DpchAppData(); public: StgIac stgiac; QryIdecUsr1NSession::StgIac stgiacqry; public: string getSrefsMask(); void readXML(pthread_mutex_t* mScr, map<string,ubigint>& descr, xmlXPathContext* docctx, string basexpath = "", bool addbasetag = false); }; /** * DpchAppDo (full: DpchAppIdecUsr1NSessionDo) */ class DpchAppDo : public DpchAppIdec { public: static const uint JREF = 1; static const uint IXVDO = 2; public: DpchAppDo(); public: uint ixVDo; public: string getSrefsMask(); void readXML(pthread_mutex_t* mScr, map<string,ubigint>& descr, xmlXPathContext* docctx, string basexpath = "", bool addbasetag = false); }; /** * DpchEngData (full: DpchEngIdecUsr1NSessionData) */ class DpchEngData : public DpchEngIdec { public: static const uint JREF = 1; static const uint CONTINF = 2; static const uint FEEDFCSIQST = 3; static const uint STATAPP = 4; static const uint STATSHR = 5; static const uint STGIAC = 6; static const uint TAG = 7; static const uint RST = 8; static const uint STATAPPQRY = 9; static const uint STATSHRQRY = 10; static const uint STGIACQRY = 11; static const uint ALL = 12; public: DpchEngData(const ubigint jref = 0, ContInf* continf = NULL, Feed* feedFCsiQst = NULL, StatShr* statshr = NULL, StgIac* stgiac = NULL, ListIdecQUsr1NSession* rst = NULL, QryIdecUsr1NSession::StatShr* statshrqry = NULL, QryIdecUsr1NSession::StgIac* stgiacqry = NULL, const set<uint>& mask = {NONE}); public: ContInf continf; Feed feedFCsiQst; StatShr statshr; StgIac stgiac; ListIdecQUsr1NSession rst; QryIdecUsr1NSession::StatShr statshrqry; QryIdecUsr1NSession::StgIac stgiacqry; public: string getSrefsMask(); void merge(DpchEngIdec* dpcheng); void writeXML(const uint ixIdecVLocale, pthread_mutex_t* mScr, map<ubigint,string>& scr, map<string,ubigint>& descr, xmlTextWriter* wr); }; bool evalButDeleteAvail(DbsIdec* dbsidec); bool evalButDeleteActive(DbsIdec* dbsidec); public: PnlIdecUsr1NSession(XchgIdec* xchg, DbsIdec* dbsidec, const ubigint jrefSup, const uint ixIdecVLocale); ~PnlIdecUsr1NSession(); public: ContInf continf; StatShr statshr; StgIac stgiac; Feed feedFCsiQst; QryIdecUsr1NSession* qry; IdecMSession recSes; // IP custVar --- INSERT public: // IP cust --- INSERT public: DpchEngIdec* getNewDpchEng(set<uint> items); void refresh(DbsIdec* dbsidec, set<uint>& moditems); void updatePreset(DbsIdec* dbsidec, const uint ixIdecVPreset, const ubigint jrefTrig, const bool notif = false); public: void handleRequest(DbsIdec* dbsidec, ReqIdec* req); void handleDpchAppIdecInit(DbsIdec* dbsidec, DpchAppIdecInit* dpchappidecinit, DpchEngIdec** dpcheng); void handleDpchAppDataStgiac(DbsIdec* dbsidec, StgIac* _stgiac, DpchEngIdec** dpcheng); void handleDpchAppDataStgiacqry(DbsIdec* dbsidec, QryIdecUsr1NSession::StgIac* _stgiacqry, DpchEngIdec** dpcheng); void handleDpchAppDoButDeleteClick(DbsIdec* dbsidec, DpchEngIdec** dpcheng); void handleDpchAppDoButRefreshClick(DbsIdec* dbsidec, DpchEngIdec** dpcheng); void handleCall(DbsIdec* dbsidec, Call* call); bool handleCallIdecStatChg(DbsIdec* dbsidec, const ubigint jrefTrig); }; #endif
ramsrib/javaee7-samples
jaxrs/interceptor/src/main/java/org/javaee7/jaxrs/interceptor/MyClientWriterInterceptor.java
<gh_stars>1-10 package org.javaee7.jaxrs.interceptor; import java.io.ByteArrayOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import javax.ws.rs.WebApplicationException; import javax.ws.rs.ext.WriterInterceptor; import javax.ws.rs.ext.WriterInterceptorContext; /** * @author <NAME> */ public class MyClientWriterInterceptor implements WriterInterceptor { @Override public void aroundWriteTo(WriterInterceptorContext wic) throws IOException, WebApplicationException { System.out.println("MyClientWriterInterceptor"); wic.setOutputStream(new FilterOutputStream(wic.getOutputStream()) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); @Override public void write(int b) throws IOException { baos.write(b); super.write(b); } @Override public void close() throws IOException { System.out.println("MyClientWriterInterceptor --> " + baos.toString()); super.close(); } }); // wic.setOutputStream(new FilterOutputStream(wic.getOutputStream()) { // // @Override // public void write(int b) throws IOException { // System.out.println("**** " + (char)b); // super.write(b); // } // // }); wic.proceed(); } }
difonz/Immunizationtario
Capstone/app/src/main/java/ca/georgebrown/comp2074/capstone2/SchoolProfileActivity.java
package ca.georgebrown.comp2074.capstone2; import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.ViewModelProvider; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; public class SchoolProfileActivity extends AppCompatActivity implements View.OnClickListener{ // to upload image private static final int RESULT_LOAD_IMAGE = 1; ImageView btnSProfileUpload; Button btn_uploadSchool; private AccountViewModel accountViewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile_school); SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE); // String email = sharedPref.getString("email", ""); Intent i = getIntent(); String email = i.getStringExtra("email"); long id = i.getLongExtra("id",0); accountViewModel = new ViewModelProvider(this).get(AccountViewModel.class); SchoolAccount sa = accountViewModel.getSchoolByEmail(email); // To upload image btnSProfileUpload = (ImageView) findViewById(R.id.btnSProfileUpload); btn_uploadSchool = (Button) findViewById(R.id.btn_uploadSchool); // --- EditText txtTitle = findViewById(R.id.txtSProfileTitle); TextView txtName = findViewById(R.id.txtSProfileName); TextView txtSchoolName = findViewById(R.id.txtSProfileSchoolName); TextView txtAddress = findViewById(R.id.txtSProfileAddress); TextView txtPhone = findViewById(R.id.txtSProfilePhone); TextView txtEmail = findViewById(R.id.txtSProfileEmail); if (sa != null) { txtTitle.setText(sa.getName() + "'s Profile"); txtName.setText(sa.getName()); txtSchoolName.setText(sa.getSchoolName()); txtAddress.setText(sa.getAddress()); txtPhone.setText(sa.getPhone()); txtEmail.setText(sa.getEmail()); } Button btnHome = findViewById(R.id.btnSProfileHome); btnHome.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(v.getContext(), home_school.class); i.putExtra("email", email); i.putExtra("id", id); startActivity(i); finish(); } }); // to upload image btnSProfileUpload.setOnClickListener(this); btn_uploadSchool.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.btnSProfileUpload: Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(galleryIntent,RESULT_LOAD_IMAGE); break; case R.id.btn_uploadSchool: break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data){ super.onActivityResult(requestCode,resultCode,data); if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null){ Uri selectedImage = data.getData(); btnSProfileUpload.setImageURI(selectedImage); } } }
NeolithEra/WavesGatewayFramework
waves_gateway/storage/polling_state_storage_proxy.py
<reponame>NeolithEra/WavesGatewayFramework<gh_stars>10-100 """PollingStateStorageProxy""" from abc import ABC, abstractmethod from waves_gateway.model import PollingState class PollingStateStorageProxy(ABC): """Offers access to the current polling_state.""" @abstractmethod def get_polling_state(self) -> PollingState: pass @abstractmethod def set_polling_state(self, state: PollingState) -> None: pass
murgle2/website
server/src/models/db/map-zone.js
<filename>server/src/models/db/map-zone.js 'use strict'; module.exports = (sequelize, type) => { return sequelize.define('mapZone', { zoneNum: type.TINYINT.UNSIGNED, }, { indexes: [ { fields: ['zoneNum'] } ] }) };
fxbin/personal-growth
code-modules/basic-knowledge/src/main/java/cn/fxbin/record/basic/jmh/JMHExample04.java
package cn.fxbin.record.basic.jmh; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import java.util.concurrent.TimeUnit; /** * JMHExample04 * * @author fxbin * @version v1.0 * @since 2020/10/13 14:45 */ @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @State(Scope.Thread) @Measurement(iterations = 5)// 度量5个批次 @Warmup(iterations = 3)// 预热3个批次 public class JMHExample04 { @Benchmark public void testAverageTime() throws InterruptedException { TimeUnit.MILLISECONDS.sleep(1); } @BenchmarkMode(Mode.Throughput) @Benchmark public void testThroughput() throws InterruptedException { TimeUnit.MILLISECONDS.sleep(1); } @BenchmarkMode(Mode.SampleTime) @Benchmark public void testSampleTime() throws InterruptedException { TimeUnit.MILLISECONDS.sleep(1); } @BenchmarkMode(Mode.SingleShotTime) @Benchmark public void testSingleShotTime() throws InterruptedException { TimeUnit.MILLISECONDS.sleep(1); } @BenchmarkMode(Mode.All) @Benchmark public void testAll() throws InterruptedException { TimeUnit.MILLISECONDS.sleep(1); } public static void main(String[] args) throws RunnerException { final Options options = new OptionsBuilder() .include(JMHExample04.class.getSimpleName()) .forks(1) // // 度量执行的批次为5, 也就是说在这5个批次中,对基准方法的执行与调用将会纳入统计 // .measurementIterations(5) // // 在真正的度量之前,首先会对代码进行3个批次的热身,是代码运行达到JVM 已经优化的效果 // .warmupIterations(3) .build(); new Runner(options).run(); } }
DominicWindisch/mqtt-io
mqtt_io/tests/features/steps/module_gpio.py
import asyncio from typing import Any from behave import given, then, when # type: ignore from behave.api.async_step import async_run_until_complete # type: ignore from mqtt_io.modules.gpio import InterruptEdge, PinDirection from mqtt_io.server import MqttIo # pylint: disable=function-redefined,protected-access # TODO: Tasks pending completion -@flyte at 22/02/2021, 16:56:52 # Add a test to go through all of the modules in the gpio dir and test them for compliance def get_coro(task: "asyncio.Task[Any]") -> Any: """ Get a task's coroutine. """ # pylint: disable=protected-access if hasattr(task, "get_coro"): return task.get_coro() # type: ignore[attr-defined] if hasattr(task, "_coro"): return task._coro # type: ignore[attr-defined] raise AttributeError("Unable to get task's coro") @then("GPIO module {module_name} should have a pin config for {pin_name}") def step(context: Any, module_name: str, pin_name: str) -> None: mqttio = context.data["mqttio"] module = mqttio.gpio_modules[module_name] assert pin_name in {x["name"] for x in module.pin_configs.values()} @then("GPIO module {module_name} should have a setup_pin() call for {pin_name}") # type: ignore[no-redef] def step(context: Any, module_name: str, pin_name: str) -> None: mqttio = context.data["mqttio"] module = mqttio.gpio_modules[module_name] call_pin_names = { kwargs["pin_config"]["name"] for _, kwargs in module.setup_pin.call_args_list } assert pin_name in call_pin_names @then("{pin_name} pin should have been set up as an {io_dir}") # type: ignore[no-redef] def step(context: Any, pin_name: str, io_dir: str) -> None: assert io_dir in ("input", "output") mqttio = context.data["mqttio"] io_conf = getattr(mqttio, f"digital_{io_dir}_configs")[pin_name] module = mqttio.gpio_modules[io_conf["module"]] pin_dirs = { kwargs["pin_config"]["name"]: args[1] for args, kwargs in module.setup_pin.call_args_list } if io_dir == "input": assert pin_dirs[pin_name] == PinDirection.INPUT else: assert pin_dirs[pin_name] == PinDirection.OUTPUT @then("GPIO module {module_name} {should_shouldnt} have a {setup_func_name}() call for {pin_name}") # type: ignore[no-redef] def step( context: Any, module_name: str, should_shouldnt: str, setup_func_name: str, pin_name: str, ) -> None: assert should_shouldnt in ("should", "shouldn't") mqttio = context.data["mqttio"] module = mqttio.gpio_modules[module_name] relevant_call_args = None for call_args, _ in getattr(module, setup_func_name).call_args_list: # type: ignore[attr-defined] if call_args[2]["name"] == pin_name: relevant_call_args = call_args if should_shouldnt == "should": assert relevant_call_args is not None else: assert relevant_call_args is None @then("a digital input poller task {is_isnt} added for {pin_name}") # type: ignore[no-redef] def step(context: Any, is_isnt: str, pin_name: str): assert is_isnt in ("is", "isn't") mqttio = context.data["mqttio"] poller_task_pin_names = { get_coro(task).cr_frame.f_locals["in_conf"]["name"] for task in mqttio.transient_tasks if isinstance(task, asyncio.Task) # concurrent.Future doesn't have get_coro() and get_coro(task).__name__ == "digital_input_poller" } if is_isnt == "is": assert ( pin_name in poller_task_pin_names ), "Should have a digital input poller task added to transient_tasks" else: assert ( pin_name not in poller_task_pin_names ), "Shouldn't have a digital input poller task added to transient_tasks" poller_task_pin_names = { get_coro(task).cr_frame.f_locals["in_conf"]["name"] for task in asyncio.Task.all_tasks(loop=mqttio.loop) if get_coro(task).__name__ == "digital_input_poller" } if is_isnt == "is": assert ( pin_name in poller_task_pin_names ), "Should have a digital input poller task added to the event loop" else: assert ( pin_name not in poller_task_pin_names ), "Shouldn't have a digital input poller task added to the event loop" @then("a digital output loop task {is_isnt} added for GPIO module {module_name}") # type: ignore[no-redef] def step(context: Any, is_isnt: str, module_name: str): assert is_isnt in ("is", "isn't") mqttio = context.data["mqttio"] module = mqttio.gpio_modules[module_name] task_modules = { get_coro(task).cr_frame.f_locals["module"] for task in mqttio.transient_tasks if isinstance(task, asyncio.Task) # concurrent.Future doesn't have get_coro() and get_coro(task).__name__ == "digital_output_loop" } if is_isnt == "is": assert ( module in task_modules ), "Should have a digital output loop task added to transient_tasks" else: assert ( module not in task_modules ), "Shouldn't have a digital output loop task added to transient_tasks" task_modules = { get_coro(task).cr_frame.f_locals["module"] for task in asyncio.Task.all_tasks(loop=mqttio.loop) if get_coro(task).__name__ == "digital_output_loop" } if is_isnt == "is": assert ( module in task_modules ), "Should have a digital output loop task added to the event loop" else: assert ( module not in task_modules ), "Shouldn't have a digital output loop task added to the event loop" @then("{pin_name} {should_shouldnt} be configured as a remote interrupt") # type: ignore[no-redef] def step(context: Any, pin_name: str, should_shouldnt: str): assert should_shouldnt in ("should", "shouldn't") mqttio = context.data["mqttio"] in_conf = mqttio.digital_input_configs[pin_name] module = mqttio.gpio_modules[in_conf["module"]] is_remote_interrupt = module.remote_interrupt_for(in_conf["pin"]) if should_shouldnt == "should": assert is_remote_interrupt else: assert not is_remote_interrupt @then("{pin_name} should be configured as a {direction_str} interrupt") # type: ignore[no-redef] def step(context: Any, pin_name: str, direction_str: str): mqttio = context.data["mqttio"] in_conf = mqttio.digital_input_configs[pin_name] module = mqttio.gpio_modules[in_conf["module"]] direction = module.interrupt_edges[in_conf["pin"]] assert direction == getattr(InterruptEdge, direction_str.upper()) @when("{pin_name} reads a value of {value_str} with a last value of {last_value_str}") # type: ignore[no-redef] @async_run_until_complete(loop="loop") async def step(context: Any, pin_name: str, value_str: str, last_value_str: str) -> None: assert value_str in ("true", "false") assert last_value_str in ("null", "true", "false") value_map = dict(true=True, false=False, null=None) mqttio: MqttIo = context.data["mqttio"] in_conf = mqttio.digital_input_configs[pin_name] value = value_map[value_str] last_value = value_map[last_value_str] await mqttio._handle_digital_input_value(in_conf, value, last_value) @when("we set digital output {pin_name} to {on_off}") # type: ignore[no-redef] @async_run_until_complete(loop="loop") async def step(context: Any, pin_name: str, on_off: str) -> None: assert on_off in ("on", "off") mqttio: MqttIo = context.data["mqttio"] out_conf = mqttio.digital_output_configs[pin_name] module = mqttio.gpio_modules[out_conf["module"]] await mqttio.set_digital_output(module, out_conf, on_off == "on")
UnicornRaceEngineering/g5-nodes
nodes/SteeringNode/shiftlight.h
/* The MIT License (MIT) Copyright (c) 2015 UnicornRaceEngineering Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef SHIFTLIGHT_H #define SHIFTLIGHT_H #define SHIFT_LIGHT_PORT PORTE #define SHIFT_LIGHT_R PIN4 // Red rgb light #define SHIFT_LIGHT_B PIN3 // Blue rgb light #define SHIFT_LIGHT_MSK (SHIFT_LIGHT_R|SHIFT_LIGHT_B) void shiftlight_init(void); void shiftlight_off(void); void shiftlight_on(void); void shiftlight_toggle(void); #endif /* SHIFTLIGHT_H */
mukaer/clipss
app/clipss/timediff.rb
# Clipss module Clipss # TimeDiff module TimeDiff attr_accessor :time_hash def now(key) @time_hash ||= Hash.new(0) tm = Time.now @time_hash[key] = milisec(tm) end def df(start, finish) @time_hash[finish] - @time_hash[start] end def milisec(tm) (tm.to_i * 1000) + ( tm.usec / 1000.0).round end module_function :now, :df, :time_hash, :milisec end end
romanha/elasticsearch-status-monitor
src/test/java/app/habitzl/elasticsearch/status/monitor/tool/configuration/DefaultConfigurationLoaderTest.java
package app.habitzl.elasticsearch.status.monitor.tool.configuration; import app.habitzl.elasticsearch.status.monitor.AnalysisStartOption; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledOnOs; import org.junit.jupiter.api.condition.OS; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; class DefaultConfigurationLoaderTest { private DefaultConfigurationLoader sut; private StatusMonitorConfiguration configuration; @BeforeEach void setUp() { configuration = new StatusMonitorConfiguration(); CliOptions cliOptions = new CliOptions(); sut = new DefaultConfigurationLoader(configuration, cliOptions); } @Test void load_oneInvalidOption_returnAnalysisNotPossible() { // Given String[] args = ArgumentBuilder .create() .withShortOption(CliOptions.HOST_OPTION_SHORT, "1.2.3.4") .withLongOption("unknown") .withShortOption(CliOptions.PORT_OPTION_SHORT, "9999") .build(); // When AnalysisStartOption result = sut.load(args); // Then assertThat(result, is(AnalysisStartOption.ANALYSIS_NOT_POSSIBLE)); } @Test void load_noHelpOptions_returnAnalysisPossible() { // Given String[] args = ArgumentBuilder .create() .withShortOption(CliOptions.HOST_OPTION_SHORT, "1.2.3.4") .withShortOption(CliOptions.PORT_OPTION_SHORT, "9999") .build(); // When AnalysisStartOption result = sut.load(args); // Then assertThat(result, is(AnalysisStartOption.ANALYSIS_POSSIBLE)); } @Test void load_containsHelpOption_returnAnalysisNotRequested() { // Given String[] args = ArgumentBuilder .create() .withShortOption(CliOptions.HOST_OPTION_SHORT, "1.2.3.4") .withShortOption(CliOptions.PORT_OPTION_SHORT, "9999") .withLongOption(CliOptions.HELP_OPTION_LONG) .build(); // When AnalysisStartOption result = sut.load(args); // Then assertThat(result, is(AnalysisStartOption.ANALYSIS_NOT_REQUESTED)); } @Test void load_containsVersionOption_returnAnalysisNotRequested() { // Given String[] args = ArgumentBuilder .create() .withShortOption(CliOptions.HOST_OPTION_SHORT, "1.2.3.4") .withShortOption(CliOptions.PORT_OPTION_SHORT, "9999") .withLongOption(CliOptions.VERSION_OPTION_LONG) .build(); // When AnalysisStartOption result = sut.load(args); // Then assertThat(result, is(AnalysisStartOption.ANALYSIS_NOT_REQUESTED)); } @Test void load_validShortOptions_setConfiguration() { // Given String address = "1.2.3.4"; String port = "9999"; String[] args = ArgumentBuilder .create() .withShortOption(CliOptions.HOST_OPTION_SHORT, address) .withShortOption(CliOptions.PORT_OPTION_SHORT, port) .build(); // When sut.load(args); // Then assertThat(configuration.getHost(), equalTo(address)); assertThat(configuration.getPort(), equalTo(port)); } @Test void load_validLongOptions_setConfiguration() { // Given String address = "1.2.3.4"; String port = "9999"; String username = "username"; String password = "password"; String fallbackEndpoint1 = "2.2.2.2:9200"; String fallbackEndpoint2 = "3.3.3.3:9202"; String fallbackEndpoints = fallbackEndpoint1 + "," + fallbackEndpoint2; String reportFilesPath = "reports/custom"; String[] args = ArgumentBuilder .create() .withLongOption(CliOptions.HOST_OPTION_LONG, address) .withLongOption(CliOptions.PORT_OPTION_LONG, port) .withLongOption(CliOptions.USER_OPTION_LONG, username) .withLongOption(CliOptions.PASSWORD_OPTION_LONG, password) .withLongOption(CliOptions.FALLBACK_ENDPOINTS_OPTION_LONG, fallbackEndpoints) .withLongOption(CliOptions.REPORT_FILES_PATH_OPTION_LONG, reportFilesPath) .build(); // When sut.load(args); // Then assertThat(configuration.getHost(), equalTo(address)); assertThat(configuration.getPort(), equalTo(port)); assertThat(configuration.getUsername(), equalTo(username)); assertThat(configuration.getPassword(), equalTo(password)); assertThat(configuration.getFallbackEndpoints(), contains(fallbackEndpoint1, fallbackEndpoint2)); assertThat(configuration.getReportFilesPath(), equalTo(reportFilesPath)); } @Test void load_oneValidOption_setConfigurationForOnlyThisOption() { // Given String address = "1.2.3.4"; String[] args = ArgumentBuilder .create() .withShortOption(CliOptions.HOST_OPTION_SHORT, address) .build(); // When sut.load(args); // Then assertThat(configuration.getHost(), equalTo(address)); assertThat(configuration.getPort(), equalTo(StatusMonitorConfiguration.DEFAULT_PORT)); assertThat(configuration.isUsingHttps(), equalTo(StatusMonitorConfiguration.DEFAULT_USING_HTTPS)); assertThat(configuration.getUsername(), equalTo(StatusMonitorConfiguration.DEFAULT_USERNAME)); assertThat(configuration.getPassword(), equalTo(StatusMonitorConfiguration.DEFAULT_PASSWORD)); assertThat(configuration.getReportFilesPath(), equalTo(StatusMonitorConfiguration.DEFAULT_REPORT_FILES_PATH)); assertThat(configuration.isSkippingArchiveReport(), equalTo(StatusMonitorConfiguration.DEFAULT_SKIP_ARCHIVE_REPORT)); } @Test void load_oneInvalidOption_useDefaultConfiguration() { // Given String[] args = ArgumentBuilder .create() .withShortOption(CliOptions.HOST_OPTION_SHORT, "1.2.3.4") .withLongOption("unknown") .withShortOption(CliOptions.PORT_OPTION_SHORT, "9999") .build(); // When sut.load(args); // Then assertThatConfigurationIsDefault(); } @Test void load_noOptions_useDefaultConfiguration() { // Given String[] args = {}; // When sut.load(args); // Then assertThatConfigurationIsDefault(); } @Test void load_includingBlankFallbackEndpoints_ignoreBlankFallbackEndpoints() { // Given String validEndpoint = "127.0.0.1:9200"; String[] args = ArgumentBuilder .create() .withLongOption(CliOptions.FALLBACK_ENDPOINTS_OPTION_LONG, ",, , " + validEndpoint + " ,,") .build(); // When sut.load(args); // Then assertThat(configuration.getFallbackEndpoints(), contains(validEndpoint)); } @Test void load_noUnsecureOption_enableSecurity() { // Given String[] args = ArgumentBuilder .create() .build(); // When sut.load(args); // Then assertThat(configuration.isUsingHttps(), equalTo(true)); } @Test void load_unsecureOption_disableSecurity() { // Given String[] args = ArgumentBuilder .create() .withLongOption(CliOptions.UNSECURE_OPTION_LONG) .build(); // When sut.load(args); // Then assertThat(configuration.isUsingHttps(), equalTo(false)); } @ParameterizedTest @MethodSource("validRelativeFilePaths") void load_validRelativeReportFilesPath_usePath(final String validPath) { // Given String[] args = ArgumentBuilder .create() .withLongOption(CliOptions.REPORT_FILES_PATH_OPTION_LONG, validPath) .build(); // When sut.load(args); // Then assertThat(configuration.getReportFilesPath(), equalTo(validPath)); } @EnabledOnOs(OS.WINDOWS) @ParameterizedTest @MethodSource("validAbsoluteFilePathsWindows") void load_validAbsoluteReportFilesPathOnWindows_usePath(final String validPath) { // Given String[] args = ArgumentBuilder .create() .withLongOption(CliOptions.REPORT_FILES_PATH_OPTION_LONG, validPath) .build(); // When sut.load(args); // Then assertThat(configuration.getReportFilesPath(), equalTo(validPath)); } @EnabledOnOs(OS.WINDOWS) @ParameterizedTest @MethodSource("invalidFilePathsWindows") void load_invalidReportFilesPathOnWindows_useDefaultPath(final String invalidPath) { // Given String[] args = ArgumentBuilder .create() .withLongOption(CliOptions.REPORT_FILES_PATH_OPTION_LONG, invalidPath) .build(); // When sut.load(args); // Then assertThat(configuration.getReportFilesPath(), equalTo(StatusMonitorConfiguration.DEFAULT_REPORT_FILES_PATH)); } @Test void load_noSkipArchiveReportOption_disableSkippingArchiveReport() { // Given String[] args = ArgumentBuilder .create() .build(); // When sut.load(args); // Then assertThat(configuration.isSkippingArchiveReport(), equalTo(false)); } @Test void load_skipArchiveReportOption_enableSkippingArchiveReport() { // Given String[] args = ArgumentBuilder .create() .withLongOption(CliOptions.SKIP_ARCHIVE_REPORT_LONG) .build(); // When sut.load(args); // Then assertThat(configuration.isSkippingArchiveReport(), equalTo(true)); } private void assertThatConfigurationIsDefault() { assertThat(configuration, equalTo(StatusMonitorConfiguration.defaultConfig())); } private static final class ArgumentBuilder { private final List<String> arguments; private static ArgumentBuilder create() { return new ArgumentBuilder(); } private ArgumentBuilder() { arguments = new ArrayList<>(); } private ArgumentBuilder withShortOption(final String option) { arguments.add("-" + option); return this; } private ArgumentBuilder withShortOption(final String option, final String value) { arguments.add("-" + option); arguments.add(value); return this; } private ArgumentBuilder withLongOption(final String option) { arguments.add("--" + option); return this; } private ArgumentBuilder withLongOption(final String option, final String value) { arguments.add("--" + option); arguments.add(value); return this; } private String[] build() { return arguments.toArray(new String[0]); } } @SuppressWarnings("unused") private static Stream<Arguments> validRelativeFilePaths() { return Stream.of( Arguments.of(""), Arguments.of("reports"), Arguments.of("reports" + File.separator + "valid" + File.separator + "path") ); } @SuppressWarnings("unused") private static Stream<Arguments> validAbsoluteFilePathsWindows() { return Stream.of( Arguments.of("C:\\ProgramData\\Temp") ); } @SuppressWarnings("unused") private static Stream<Arguments> invalidFilePathsWindows() { return Stream.of( Arguments.of("reports:invalid"), Arguments.of("reports?invalid"), Arguments.of("reports\"invalid"), Arguments.of("reports<invalid"), Arguments.of("reports>invalid"), Arguments.of("reports|invalid") ); } }
Amourspirit/ooo_uno_tmpl
ooobuild/lo/ucb/open_command_argument3.py
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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. # # Struct Class # this is a auto generated file generated by Cheetah # Namespace: com.sun.star.ucb # Libre Office Version: 7.3 from ooo.oenv.env_const import UNO_NONE from .open_command_argument2 import OpenCommandArgument2 as OpenCommandArgument2_9210e08 from ..beans.property import Property as Property_8f4e0a76 from ..uno.x_interface import XInterface as XInterface_8f010a43 from .numbered_sorting_info import NumberedSortingInfo as NumberedSortingInfo_fd0e0de6 import typing from ..beans.named_value import NamedValue as NamedValue_a37a0af3 class OpenCommandArgument3(OpenCommandArgument2_9210e08): """ Struct Class Extended argument for commands like \"open\". We're extending OpenCommandArgument even more, to provide some opening flags on to webdav. See Also: `API OpenCommandArgument3 <https://api.libreoffice.org/docs/idl/ref/structcom_1_1sun_1_1star_1_1ucb_1_1OpenCommandArgument3.html>`_ """ __ooo_ns__: str = 'com.sun.star.ucb' __ooo_full_ns__: str = 'com.sun.star.ucb.OpenCommandArgument3' __ooo_type_name__: str = 'struct' typeName: str = 'com.sun.star.ucb.OpenCommandArgument3' """Literal Constant ``com.sun.star.ucb.OpenCommandArgument3``""" def __init__(self, Properties: typing.Optional[typing.Tuple[Property_8f4e0a76, ...]] = UNO_NONE, Mode: typing.Optional[int] = 0, Priority: typing.Optional[int] = 0, Sink: typing.Optional[XInterface_8f010a43] = None, SortingInfo: typing.Optional[typing.Tuple[NumberedSortingInfo_fd0e0de6, ...]] = UNO_NONE, OpeningFlags: typing.Optional[typing.Tuple[NamedValue_a37a0af3, ...]] = UNO_NONE) -> None: """ Constructor Arguments: Properties (typing.Tuple[Property, ...], optional): Properties value. Mode (int, optional): Mode value. Priority (int, optional): Priority value. Sink (XInterface, optional): Sink value. SortingInfo (typing.Tuple[NumberedSortingInfo, ...], optional): SortingInfo value. OpeningFlags (typing.Tuple[NamedValue, ...], optional): OpeningFlags value. """ if isinstance(Properties, OpenCommandArgument3): oth: OpenCommandArgument3 = Properties self.Properties = oth.Properties self.Mode = oth.Mode self.Priority = oth.Priority self.Sink = oth.Sink self.SortingInfo = oth.SortingInfo self.OpeningFlags = oth.OpeningFlags return kargs = { "Properties": Properties, "Mode": Mode, "Priority": Priority, "Sink": Sink, "SortingInfo": SortingInfo, "OpeningFlags": OpeningFlags, } if kargs["Properties"] is UNO_NONE: kargs["Properties"] = None if kargs["SortingInfo"] is UNO_NONE: kargs["SortingInfo"] = None if kargs["OpeningFlags"] is UNO_NONE: kargs["OpeningFlags"] = None self._init(**kargs) def _init(self, **kwargs) -> None: self._opening_flags = kwargs["OpeningFlags"] inst_keys = ('OpeningFlags',) kargs = kwargs.copy() for key in inst_keys: del kargs[key] super()._init(**kargs) @property def OpeningFlags(self) -> typing.Tuple[NamedValue_a37a0af3, ...]: """ Flags to use for opening. WebDav e.g. uses \"KeepAlive\" to enable/disable the respective http feature. """ return self._opening_flags @OpeningFlags.setter def OpeningFlags(self, value: typing.Tuple[NamedValue_a37a0af3, ...]) -> None: self._opening_flags = value __all__ = ['OpenCommandArgument3']
elucash/nextgen
io/codec/src/io/immutables/codec/Resolver.java
package io.immutables.codec; import com.google.common.collect.HashBasedTable; import com.google.common.collect.Ordering; import com.google.common.collect.Table; import com.google.common.reflect.TypeToken; import io.immutables.Nullable; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.annotation.Target; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import static java.lang.annotation.ElementType.TYPE_USE; public interface Resolver { <T> Codec<T> get(TypeToken<T> type, @Nullable Annotation qualifier); default <T> Codec<T> get(TypeToken<T> type) { return get(type, null); } @SuppressWarnings("unchecked") default <T> Codec<T> get(Class<? extends T> type) { return get((TypeToken<T>) TypeToken.of(type), null); } @SuppressWarnings("unchecked") default <T> Codec<T> get(Type type) { return get((TypeToken<T>) TypeToken.of(type), null); } class Compound { // The opposite of order, the bigger - the higher priority. @Target(TYPE_USE) @interface Priority {} static final @Priority int DEFAULT_PRIORITY = 0; static final @Priority int LOWEST_PRIORITY = Integer.MIN_VALUE; private final List<FactoryEntry> factories = new ArrayList<>(); private static class FactoryEntry implements Comparable<FactoryEntry> { Codec.Factory factory; @Nullable Annotation qualifier; @Priority int priority = DEFAULT_PRIORITY; @Override public int compareTo(FactoryEntry o) { return o.priority - priority; } } public Compound add(Codec.Factory factory) { return add(factory, null, DEFAULT_PRIORITY); } public Compound add(Codec.Factory factory, @Nullable Annotation qualifier, @Priority int priority) { FactoryEntry e = new FactoryEntry(); e.factory = factory; e.qualifier = qualifier; e.priority = priority; factories.add(e); Collections.sort(factories); return this; } static Object qualifierKey(@Nullable Annotation qualifier) { return qualifier != null ? qualifier : UNQUALIFIED; } private static final ThreadLocal<Set<TypeToken<?>>> resolveChain = ThreadLocal.withInitial(HashSet::new); private static class DeferredCodec<T> extends Codec<T> { private final TypeToken<T> token; private final Resolver resolver; private @Nullable Codec<T> codec; DeferredCodec(Resolver resolver, TypeToken<T> token) { this.resolver = resolver; this.token = token; } private Codec<T> advance() { return codec != null ? codec : (codec = resolver.get(token)); } @Override public T decode(In in) throws IOException { return advance().decode(in); } @Override public void encode(Out out, T instance) throws IOException { advance().encode(out, instance); } } public Resolver toResolver() { return new Resolver() { private final Table<TypeToken<?>, Object, Codec<?>> memoised = HashBasedTable.create(); private final List<FactoryEntry> factories = Ordering.natural().sortedCopy(Compound.this.factories); @SuppressWarnings("unchecked") @Override public <T> Codec<T> get(TypeToken<T> type, @Nullable Annotation qualifier) { if (resolveChain.get().add(type)) { try { Codec<T> codec = (Codec<T>) memoised.get(type, qualifierKey(qualifier)); if (codec == null) { codec = findBestUncontested(type, qualifier); memoised.put(type, qualifierKey(qualifier), codec); } return codec; } finally { resolveChain.get().remove(type); } } return new DeferredCodec<>(this, type); } @SuppressWarnings("null") // cannot be null, bestEntry assigned with best private <T> Codec<T> findBestUncontested(TypeToken<T> type, @Nullable Annotation qualifier) { @Nullable List<FactoryEntry> contesters = null; @Nullable FactoryEntry bestEntry = null; @Nullable Codec<T> best = null; for (FactoryEntry e : factories) { // short circuit search if we already found something and priority is lower now if (bestEntry != null && bestEntry.priority > e.priority) break; Codec.Factory f = e.factory; if (Objects.equals(qualifier, e.qualifier)) { @Nullable Codec<T> c = f.get(this, type); if (c != null) { if (best != null) { assert bestEntry.priority == e.priority; if (contesters == null) { contesters = new ArrayList<>(2); contesters.add(bestEntry); } contesters.add(e); } else { best = c; bestEntry = e; } } } } if (contesters != null) { throw new RuntimeException( String.format("More than one applicable adapter founds for %s @%s. Factories with priority %s: %s", type, qualifier, bestEntry.priority, contesters)); } return best != null ? best : Codecs.unsupported(type, qualifier); } }; } @Override public String toString() { return "Codec.Compound(" + factories.size() + " factories)"; } private static final Object UNQUALIFIED = new Object(); } }
tydhot/arana
pkg/config/config.go
// // Licensed to Apache Software Foundation (ASF) under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Apache Software Foundation (ASF) licenses this file to you 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 config import ( "bytes" "encoding/json" "fmt" "io/ioutil" "path/filepath" "time" ) import ( "github.com/ghodss/yaml" "github.com/pkg/errors" ) import ( "github.com/dubbogo/arana/pkg/proto" "github.com/dubbogo/arana/pkg/util/log" ) type Configuration struct { Listeners []*Listener `yaml:"listeners" json:"listeners"` Executors []*Executor `yaml:"executors" json:"executors"` Filters []*Filter `yaml:"filters" json:"filters"` DataSources []*DataSource `yaml:"data_source_cluster" json:"data_source_cluster"` } type ( // ProtocolType protocol type enum ProtocolType int32 // SocketAddress specify either a logical or physical address and port, which are // used to tell server where to bind/listen, connect to upstream and find // management servers SocketAddress struct { Address string `default:"0.0.0.0" yaml:"address" json:"address"` Port int `default:"8881" yaml:"port" json:"port"` } Filter struct { Name string `json:"name,omitempty"` Config json.RawMessage `json:"config,omitempty"` } DataSourceGroup struct { Master *Source `yaml:"master" json:"master"` Slaves []*Source `yaml:"slaves,omitempty" json:"slaves,omitempty"` } Executor struct { Name string `yaml:"name" json:"name"` Mode proto.ExecuteMode `yaml:"mode" json:"mode"` DataSources []*DataSourceGroup `yaml:"data_sources" json:"data_sources"` Filters []string `yaml:"filters" json:"filters"` ProcessDistributedTransaction bool `yaml:"process_distributed_transaction,omitempty" json:"process_distributed_transaction,omitempty"` } Source struct { Name string `yaml:"name" json:"name"` Weight *int `yaml:"weight,omitempty" json:"weight,omitempty"` } Listener struct { ProtocolType ProtocolType `yaml:"protocol_type" json:"protocol_type"` SocketAddress SocketAddress `yaml:"socket_address" json:"socket_address"` Filters []string `yaml:"filters" json:"filters"` Config json.RawMessage `yaml:"config" json:"config"` Executor string `yaml:"executor" json:"executor"` } ) const ( Http ProtocolType = iota Mysql ) func (t *ProtocolType) UnmarshalText(text []byte) error { if t == nil { return errors.New("can't unmarshal a nil *ProtocolType") } if !t.unmarshalText(bytes.ToLower(text)) { return fmt.Errorf("unrecognized protocol type: %q", text) } return nil } func (t *ProtocolType) unmarshalText(text []byte) bool { protocolType := string(text) switch protocolType { case "mysql": *t = Mysql case "http": *t = Http default: return false } return true } func parse(path string) *Configuration { log.Infof("load config from : %s", path) content, err := ioutil.ReadFile(path) if err != nil { log.Fatalf("[config] [default load] load config failed, error: %v", err) } cfg := &Configuration{} if yamlFormat(path) { jsonBytes, err := yaml.YAMLToJSON(content) if err != nil { log.Fatalf("[config] [default load] translate yaml to json error: %v", err) } content = jsonBytes } // translate to lower case err = json.Unmarshal(content, cfg) if err != nil { log.Fatalf("[config] [default load] json unmarshal config failed, error: %v", err) } for _, ds := range cfg.DataSources { if ds.IdleTimeoutStr != "" { var err error if ds.IdleTimeout, err = time.ParseDuration(ds.IdleTimeoutStr); err != nil { log.Errorf("[config] [default load] parse idle timeout failed, set to default %s, data source name: %s, error: %v", ds.Name, err) } } } return cfg } func yamlFormat(path string) bool { ext := filepath.Ext(path) if ext == ".yaml" || ext == ".yml" { return true } return false } // Load config file and parse func Load(path string) *Configuration { configPath, _ := filepath.Abs(path) cfg := parse(configPath) return cfg }
mfkiwl/ICE
3rdparty/GPSTk/ext/lib/Vdraw/BasicShape.hpp
<reponame>mfkiwl/ICE //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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.0 of the License, or // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= ///@file BasicShape.hpp Interface for all basic shapes. Manages common objects/calls. #ifndef VDRAW_BASICSHAPE_H #define VDRAW_BASICSHAPE_H #include "StrokeStyle.hpp" namespace vdraw { /// @ingroup BasicVectorGraphics //@{ /** * This is an interface for basic shapes to group them together. * These include circles, rectangles, lines, and polygons. All * of these objects can contain a StrokeStyle. */ class BasicShape { public: /** * Constructors and Destructor */ /** * Default constructor. */ BasicShape(void) : hasLineStyle(false) {} /** * Constructor. Defines a basic shape by a StrokeStyle. * @param istyle appearance of the stroke */ BasicShape(const StrokeStyle& istyle) : lineStyle(istyle), hasLineStyle(true) {} /// Accessor. Does this basic shape have a preferred appearance? inline bool hasOwnStrokeStyle(void) const { return hasLineStyle; } /// Accessor. What is the style associated with this basic shape inline StrokeStyle getStrokeStyle(void) const { return lineStyle; } /// Mutator. Set the stroke style inline void setStrokeStyle(const StrokeStyle& istyle) { lineStyle=istyle;hasLineStyle=true; } /// Mutator. Remove the stroke style...use default inline void removeStrokeStyle(void) { hasLineStyle=false; } protected: /// Default line style StrokeStyle lineStyle; /// A lineStyle has been set? bool hasLineStyle; private: }; // class BasicShape //@} } // namespace vdraw #endif //VDRAW_BASICSHAPE_H
getsproud/react-app
src/components/dashboard/project/ProjectDescriptionForm.js
<gh_stars>0 import { useState } from 'react'; import PropTypes from 'prop-types'; import { Box, Button, Card, FormHelperText, Paper, Typography } from '@material-ui/core'; import QuillEditor from '../../QuillEditor'; const ProjectDescriptionForm = (props) => { const { onBack, onComplete, ...other } = props; const [content, setContent] = useState(''); const [isSubmitting, setIsSubmitting] = useState(false); const [error, setError] = useState(null); const handleChange = (value) => { setContent(value); }; const handleSubmit = async (event) => { event.preventDefault(); try { setIsSubmitting(true); // NOTE: Make API request if (onComplete) { onComplete(); } } catch (err) { console.error(err); setError(err.message); } finally { setIsSubmitting(false); } }; return ( <form onSubmit={handleSubmit} {...other} > <Card sx={{ p: 3 }}> <Typography color="textPrimary" variant="h6" > Please select one option </Typography> <Typography color="textSecondary" variant="body1" > Proin tincidunt lacus sed ante efficitur efficitur. Quisque aliquam fringilla velit sit amet euismod. </Typography> <Paper sx={{ mt: 3 }} variant="outlined" > <QuillEditor handleChange={handleChange} placeholder="Write something" sx={{ height: 400 }} value={content} /> </Paper> {error && ( <Box sx={{ mt: 2 }}> <FormHelperText error> {FormHelperText} </FormHelperText> </Box> )} <Box sx={{ display: 'flex', mt: 6 }} > {onBack && ( <Button color="primary" onClick={onBack} size="large" variant="text" > Previous </Button> )} <Box sx={{ flexGrow: 1 }} /> <Button color="primary" disabled={isSubmitting} type="submit" variant="contained" > Complete </Button> </Box> </Card> </form> ); }; ProjectDescriptionForm.propTypes = { onBack: PropTypes.func, onComplete: PropTypes.func }; export default ProjectDescriptionForm;
aiw-google/openweave-core
src/adaptations/device-layer/include/Weave/DeviceLayer/internal/testing/GroupKeyStoreUnitTest.h
<gh_stars>100-1000 /* * * Copyright (c) 2018 <NAME>, Inc. * All rights reserved. * * 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. */ #ifndef WEAVE_DEVICE_GROUP_KEYSTORE_UNIT_TEST_H #define WEAVE_DEVICE_GROUP_KEYSTORE_UNIT_TEST_H #include <Weave/Core/WeaveCore.h> namespace nl { namespace Weave { namespace DeviceLayer { namespace Internal { template<class GroupKeyStoreClass> void RunGroupKeyStoreUnitTest(GroupKeyStoreClass * groupKeyStore) { WEAVE_ERROR err; Profiles::Security::AppKeys::WeaveGroupKey keyIn, keyOut; // ===== Test 1: Store and retrieve root key // Store service root key keyIn.KeyId = WeaveKeyId::kServiceRootKey; keyIn.KeyLen = Profiles::Security::AppKeys::kWeaveAppRootKeySize; memset(keyIn.Key, 0x34, keyIn.KeyLen); err = groupKeyStore->StoreGroupKey(keyIn); VerifyOrDie(err == WEAVE_NO_ERROR); // Retrieve and validate service root key memset(&keyOut, 0, sizeof(keyOut)); err = groupKeyStore->RetrieveGroupKey(WeaveKeyId::kServiceRootKey, keyOut); VerifyOrDie(err == WEAVE_NO_ERROR); VerifyOrDie(keyOut.KeyId == WeaveKeyId::kServiceRootKey); VerifyOrDie(keyOut.KeyLen == Profiles::Security::AppKeys::kWeaveAppRootKeySize); VerifyOrDie(memcmp(keyOut.Key, keyIn.Key, keyOut.KeyLen) == 0); // ===== Test 2: Store and retrieve fabric secret // Store fabric secret keyIn.KeyId = WeaveKeyId::kFabricSecret; keyIn.KeyLen = Profiles::Security::AppKeys::kWeaveFabricSecretSize; memset(keyIn.Key, 0xAB, keyIn.KeyLen); err = groupKeyStore->StoreGroupKey(keyIn); VerifyOrDie(err == WEAVE_NO_ERROR); // Retrieve and validate fabric secret memset(&keyOut, 0, sizeof(keyOut)); err = groupKeyStore->RetrieveGroupKey(WeaveKeyId::kFabricSecret, keyOut); VerifyOrDie(err == WEAVE_NO_ERROR); VerifyOrDie(keyOut.KeyId == WeaveKeyId::kFabricSecret); VerifyOrDie(keyOut.KeyLen == Profiles::Security::AppKeys::kWeaveFabricSecretSize); VerifyOrDie(memcmp(keyOut.Key, keyIn.Key, keyOut.KeyLen) == 0); // ===== Test 3: Store and retrieve application master key // Store application master key keyIn.KeyId = WeaveKeyId::MakeAppGroupMasterKeyId(0x42); keyIn.KeyLen = Profiles::Security::AppKeys::kWeaveAppGroupMasterKeySize; memset(keyIn.Key, 0x42, keyIn.KeyLen); keyIn.GlobalId = 0x42424242; err = groupKeyStore->StoreGroupKey(keyIn); VerifyOrDie(err == WEAVE_NO_ERROR); // Retrieve and validate application master key memset(&keyOut, 0, sizeof(keyOut)); err = groupKeyStore->RetrieveGroupKey(keyIn.KeyId, keyOut); VerifyOrDie(err == WEAVE_NO_ERROR); VerifyOrDie(keyOut.KeyId == keyIn.KeyId); VerifyOrDie(keyOut.KeyLen == Profiles::Security::AppKeys::kWeaveAppGroupMasterKeySize); VerifyOrDie(memcmp(keyOut.Key, keyIn.Key, keyOut.KeyLen) == 0); // ===== Test 4: Store and retrieve epoch keys // Store first epoch key keyIn.KeyId = WeaveKeyId::MakeEpochKeyId(2); keyIn.KeyLen = Profiles::Security::AppKeys::kWeaveAppEpochKeySize; memset(keyIn.Key, 0x73, keyIn.KeyLen); keyIn.StartTime = 0x74; err = groupKeyStore->StoreGroupKey(keyIn); VerifyOrDie(err == WEAVE_NO_ERROR); // Store second epoch key keyIn.KeyId = WeaveKeyId::MakeEpochKeyId(6); keyIn.KeyLen = Profiles::Security::AppKeys::kWeaveAppEpochKeySize; memset(keyIn.Key, 0x75, keyIn.KeyLen); keyIn.StartTime = 0x76; err = groupKeyStore->StoreGroupKey(keyIn); VerifyOrDie(err == WEAVE_NO_ERROR); // Retrieve and validate first epoch key memset(&keyOut, 0, sizeof(keyOut)); err = groupKeyStore->RetrieveGroupKey(WeaveKeyId::MakeEpochKeyId(2), keyOut); VerifyOrDie(err == WEAVE_NO_ERROR); VerifyOrDie(keyOut.KeyId == WeaveKeyId::MakeEpochKeyId(2)); VerifyOrDie(keyOut.KeyLen == Profiles::Security::AppKeys::kWeaveAppEpochKeySize); memset(keyIn.Key, 0x73, Profiles::Security::AppKeys::kWeaveAppEpochKeySize); VerifyOrDie(memcmp(keyOut.Key, keyIn.Key, Profiles::Security::AppKeys::kWeaveAppEpochKeySize) == 0); VerifyOrDie(keyOut.StartTime == 0x74); // Retrieve and validate second epoch key memset(&keyOut, 0, sizeof(keyOut)); err = groupKeyStore->RetrieveGroupKey(WeaveKeyId::MakeEpochKeyId(6), keyOut); VerifyOrDie(err == WEAVE_NO_ERROR); VerifyOrDie(keyOut.KeyId == WeaveKeyId::MakeEpochKeyId(6)); VerifyOrDie(keyOut.KeyLen == Profiles::Security::AppKeys::kWeaveAppEpochKeySize); memset(keyIn.Key, 0x75, Profiles::Security::AppKeys::kWeaveAppEpochKeySize); VerifyOrDie(memcmp(keyOut.Key, keyIn.Key, Profiles::Security::AppKeys::kWeaveAppEpochKeySize) == 0); VerifyOrDie(keyOut.StartTime == 0x76); // ===== Test 5: Enumerate epoch keys { enum { kKeyIdListSize = 32 }; uint32_t keyIds[kKeyIdListSize]; uint8_t keyCount, i; // Enumerate epoch keys err = groupKeyStore->EnumerateGroupKeys(WeaveKeyId::kType_AppEpochKey, keyIds, kKeyIdListSize, keyCount); VerifyOrDie(err == WEAVE_NO_ERROR); // Verify both epoch keys were returned. VerifyOrDie(keyCount >= 2); for (i = 0; i < keyCount && keyIds[i] != WeaveKeyId::MakeEpochKeyId(2); i++); VerifyOrDie(i < keyCount); for (i = 0; i < keyCount && keyIds[i] != WeaveKeyId::MakeEpochKeyId(6); i++); VerifyOrDie(i < keyCount); } // ===== Test 6: Enumerate all keys { enum { kKeyIdListSize = 32 }; uint32_t keyIds[kKeyIdListSize]; uint8_t keyCount, i; // Enumerate all keys err = groupKeyStore->EnumerateGroupKeys(WeaveKeyId::kType_None, keyIds, kKeyIdListSize, keyCount); VerifyOrDie(err == WEAVE_NO_ERROR); // Verify all keys were returned. VerifyOrDie(keyCount >= 5); for (i = 0; i < keyCount && keyIds[i] != WeaveKeyId::kServiceRootKey; i++); VerifyOrDie(i < keyCount); for (i = 0; i < keyCount && keyIds[i] != WeaveKeyId::kFabricSecret; i++); VerifyOrDie(i < keyCount); for (i = 0; i < keyCount && keyIds[i] != WeaveKeyId::MakeAppGroupMasterKeyId(0x42); i++); VerifyOrDie(i < keyCount); for (i = 0; i < keyCount && keyIds[i] != WeaveKeyId::MakeEpochKeyId(2); i++); VerifyOrDie(i < keyCount); for (i = 0; i < keyCount && keyIds[i] != WeaveKeyId::MakeEpochKeyId(6); i++); VerifyOrDie(i < keyCount); } // ===== Test 7: Overwrite the application master key // Update application master key keyIn.KeyId = WeaveKeyId::MakeAppGroupMasterKeyId(0x42); keyIn.KeyLen = Profiles::Security::AppKeys::kWeaveAppGroupMasterKeySize; memset(keyIn.Key, 0x24, keyIn.KeyLen); keyIn.GlobalId = 0x24242424; err = groupKeyStore->StoreGroupKey(keyIn); VerifyOrDie(err == WEAVE_NO_ERROR); // Retrieve and validate the update application master key memset(&keyOut, 0, sizeof(keyOut)); err = groupKeyStore->RetrieveGroupKey(keyIn.KeyId, keyOut); VerifyOrDie(err == WEAVE_NO_ERROR); VerifyOrDie(keyOut.KeyId == keyIn.KeyId); VerifyOrDie(keyOut.KeyLen == Profiles::Security::AppKeys::kWeaveAppGroupMasterKeySize); VerifyOrDie(memcmp(keyOut.Key, keyIn.Key, keyOut.KeyLen) == 0); LogGroupKeys(groupKeyStore); // ===== Test 8: Clear all keys { enum { kKeyIdListSize = 32 }; uint32_t keyIds[kKeyIdListSize]; uint8_t keyCount; // Clear all keys err = groupKeyStore->Clear(); VerifyOrDie(err == WEAVE_NO_ERROR); // Enumerate all keys err = groupKeyStore->EnumerateGroupKeys(WeaveKeyId::kType_None, keyIds, kKeyIdListSize, keyCount); VerifyOrDie(err == WEAVE_NO_ERROR); // Verify no keys were returned. VerifyOrDie(keyCount == 0); // Attempt to retrieve the fabric secret memset(&keyOut, 0, sizeof(keyOut)); err = groupKeyStore->RetrieveGroupKey(WeaveKeyId::kFabricSecret, keyOut); VerifyOrDie(err == WEAVE_ERROR_KEY_NOT_FOUND); } LogGroupKeys(groupKeyStore); } } // namespace internal } // namespace DeviceLayer } // namespace Weave } // namespace nl #endif // WEAVE_DEVICE_GROUP_KEYSTORE_UNIT_TEST_H
Bhaskers-Blu-Org2/SpectrumDBClient
libs/string-buffer/string_buffer.c
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. */ #include "string_buffer.h" #include <stdlib.h> #include <string.h> StrBuf *strbuf_alloc() { StrBuf *buf = malloc(sizeof(StrBuf)); if (!buf) return NULL; int initial_size = 32; buf->data = malloc(initial_size * sizeof(char)); if (!buf->data) { free(buf); return NULL; } buf->data[0] = '\0'; buf->len = 0; buf->max_len = initial_size; return buf; } void strbuf_free(StrBuf *buf) { free(buf->data); free(buf); } static int strbuf_grow(StrBuf *buf, int minimum_size) { int new_size = (int)(buf->max_len * 1.5); if (new_size < minimum_size) new_size = minimum_size; char *tmp = realloc(buf->data, new_size * sizeof(char)); if (tmp == NULL) return -1; buf->data = tmp; buf->max_len = new_size; return 0; } int strbuf_append(StrBuf *buf, char const *data, int length) { int desired_length = buf->len + length + 1; if (buf->max_len < desired_length) if (strbuf_grow(buf, desired_length) == -1) return -1; memcpy(buf->data + buf->len, data, length); buf->len += length; buf->data[buf->len] = '\0'; return 0; } char *strbuf_to_cstr(StrBuf *buf) { char *result = malloc(buf->len + 1); if (!result) return NULL; memcpy(result, buf->data, buf->len + 1); result[buf->len] = '\0'; return result; }
jackyruslymoonlay/dl-models
src/garment-purchasing/purchase-order-validator.js
require("should"); var validatePurchaseOrderItem = require('./purchase-order-item-validator'); var validateBuyer = require('../master/buyer-validator'); module.exports = function (data) { data.should.not.equal(null); data.should.instanceOf(Object); data.should.have.property('no'); data.no.should.be.String(); data.should.have.property('refNo'); data.refNo.should.be.String(); data.should.have.property('iso'); data.iso.should.be.String(); data.should.have.property('roNo'); data.roNo.should.be.String(); data.should.have.property('buyer'); data.buyer.should.instanceof(Object); data.should.have.property('artikel'); data.artikel.should.be.String(); data.should.have.property('purchaseRequestId'); data.purchaseRequestId.should.instanceof(Object); data.should.have.property('purchaseRequest'); data.purchaseRequest.should.instanceof(Object); // data.should.have.property('buyerId'); // data.buyerId.should.instanceof(Object); // data.should.have.property('buyer'); // data.buyer.should.instanceof(Object); // validateBuyer(data.buyer); data.should.have.property('unitId'); data.unitId.should.instanceof(Object); data.should.have.property('unit'); data.unit.should.instanceof(Object); data.should.have.property('date'); data.date.should.instanceof(Date); data.should.have.property('expectedDeliveryDate'); data.expectedDeliveryDate.should.instanceof(Date); data.should.have.property('shipmentDate'); data.shipmentDate.should.instanceof(Date); data.should.have.property('isPosted'); data.isPosted.should.instanceOf(Boolean); data.should.have.property('isClosed'); data.isClosed.should.instanceOf(Boolean); data.should.have.property('isSplit'); data.isSplit.should.instanceOf(Boolean); data.should.have.property('remark'); data.remark.should.instanceOf(String); data.should.have.property('items'); data.items.should.instanceOf(Array); for (var item of data.items) { validatePurchaseOrderItem(item); } data.should.have.property('status'); data.status.should.instanceof(Object); };
HoussemNasri/Logisim-Dark
src/logisim_src/gui/menu/MenuItem.java
<filename>src/logisim_src/gui/menu/MenuItem.java<gh_stars>1-10 /* Copyright (c) 2010, <NAME>. License information is located in the * logisim_src.Main source code and at www.cburch.com/logisim/. */ package logisim_src.gui.menu; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; interface MenuItem { boolean hasListeners(); public void addActionListener(ActionListener l); public void removeActionListener(ActionListener l); public boolean isEnabled(); public void setEnabled(boolean value); public void actionPerformed(ActionEvent event); }
yuchengs/viennacl-dev
libviennacl/src/blas1_opencl.cpp
/* ========================================================================= Copyright (c) 2010-2014, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. Portions of this software are copyright by UChicago Argonne, LLC. ----------------- ViennaCL - The Vienna Computing Library ----------------- Project Head: <NAME> <EMAIL> (A list of authors and contributors can be found in the PDF manual) License: MIT (X11), see file LICENSE in the base directory ============================================================================= */ // include necessary system headers #include <iostream> #include "viennacl.hpp" #include "viennacl_private.hpp" //include basic scalar and vector types of ViennaCL #include "viennacl/scalar.hpp" #include "viennacl/vector.hpp" //include the generic inner product functions of ViennaCL #include "viennacl/linalg/inner_prod.hpp" //include the generic norm functions of ViennaCL #include "viennacl/linalg/norm_1.hpp" #include "viennacl/linalg/norm_2.hpp" #include "viennacl/linalg/norm_inf.hpp" #ifdef VIENNACL_WITH_OPENCL // IxAMAX VIENNACL_EXPORTED_FUNCTION ViennaCLStatus ViennaCLOpenCLiSamax(ViennaCLBackend backend, ViennaCLInt n, ViennaCLInt *index, cl_mem x, ViennaCLInt offx, ViennaCLInt incx) { typedef viennacl::vector_base<float>::size_type size_type; typedef viennacl::vector_base<float>::size_type difference_type; viennacl::vector_base<float> v1(x, size_type(n), size_type(offx), difference_type(incx), viennacl::ocl::get_context(backend->opencl_backend.context_id)); *index = static_cast<ViennaCLInt>(viennacl::linalg::index_norm_inf(v1)); return ViennaCLSuccess; } VIENNACL_EXPORTED_FUNCTION ViennaCLStatus ViennaCLOpenCLiDamax(ViennaCLBackend backend, ViennaCLInt n, ViennaCLInt *index, cl_mem x, ViennaCLInt offx, ViennaCLInt incx) { typedef viennacl::vector_base<double>::size_type size_type; typedef viennacl::vector_base<double>::size_type difference_type; viennacl::vector_base<double> v1(x, size_type(n), size_type(offx), difference_type(incx), viennacl::ocl::get_context(backend->opencl_backend.context_id)); *index = static_cast<ViennaCLInt>(viennacl::linalg::index_norm_inf(v1)); return ViennaCLSuccess; } // xASUM VIENNACL_EXPORTED_FUNCTION ViennaCLStatus ViennaCLOpenCLSasum(ViennaCLBackend backend, ViennaCLInt n, float *alpha, cl_mem x, ViennaCLInt offx, ViennaCLInt incx) { typedef viennacl::vector_base<float>::size_type size_type; typedef viennacl::vector_base<float>::size_type difference_type; viennacl::vector_base<float> v1(x, size_type(n), size_type(offx), difference_type(incx), viennacl::ocl::get_context(backend->opencl_backend.context_id)); *alpha = viennacl::linalg::norm_1(v1); return ViennaCLSuccess; } VIENNACL_EXPORTED_FUNCTION ViennaCLStatus ViennaCLOpenCLDasum(ViennaCLBackend backend, ViennaCLInt n, double *alpha, cl_mem x, ViennaCLInt offx, ViennaCLInt incx) { typedef viennacl::vector_base<double>::size_type size_type; typedef viennacl::vector_base<double>::size_type difference_type; viennacl::vector_base<double> v1(x, size_type(n), size_type(offx), difference_type(incx), viennacl::ocl::get_context(backend->opencl_backend.context_id)); *alpha = viennacl::linalg::norm_1(v1); return ViennaCLSuccess; } // xAXPY VIENNACL_EXPORTED_FUNCTION ViennaCLStatus ViennaCLOpenCLSaxpy(ViennaCLBackend backend, ViennaCLInt n, float alpha, cl_mem x, ViennaCLInt offx, ViennaCLInt incx, cl_mem y, ViennaCLInt offy, ViennaCLInt incy) { typedef viennacl::vector_base<float>::size_type size_type; typedef viennacl::vector_base<float>::size_type difference_type; viennacl::vector_base<float> v1(x, size_type(n), size_type(offx), difference_type(incx), viennacl::ocl::get_context(backend->opencl_backend.context_id)); viennacl::vector_base<float> v2(y, size_type(n), size_type(offy), difference_type(incy), viennacl::ocl::get_context(backend->opencl_backend.context_id)); v2 += alpha * v1; return ViennaCLSuccess; } VIENNACL_EXPORTED_FUNCTION ViennaCLStatus ViennaCLOpenCLDaxpy(ViennaCLBackend backend, ViennaCLInt n, double alpha, cl_mem x, ViennaCLInt offx, ViennaCLInt incx, cl_mem y, ViennaCLInt offy, ViennaCLInt incy) { typedef viennacl::vector_base<double>::size_type size_type; typedef viennacl::vector_base<double>::size_type difference_type; viennacl::vector_base<double> v1(x, size_type(n), size_type(offx), difference_type(incx), viennacl::ocl::get_context(backend->opencl_backend.context_id)); viennacl::vector_base<double> v2(y, size_type(n), size_type(offy), difference_type(incy), viennacl::ocl::get_context(backend->opencl_backend.context_id)); v2 += alpha * v1; return ViennaCLSuccess; } // xCOPY VIENNACL_EXPORTED_FUNCTION ViennaCLStatus ViennaCLOpenCLScopy(ViennaCLBackend backend, ViennaCLInt n, cl_mem x, ViennaCLInt offx, ViennaCLInt incx, cl_mem y, ViennaCLInt offy, ViennaCLInt incy) { typedef viennacl::vector_base<float>::size_type size_type; typedef viennacl::vector_base<float>::size_type difference_type; viennacl::vector_base<float> v1(x, size_type(n), size_type(offx), difference_type(incx), viennacl::ocl::get_context(backend->opencl_backend.context_id)); viennacl::vector_base<float> v2(y, size_type(n), size_type(offy), difference_type(incy), viennacl::ocl::get_context(backend->opencl_backend.context_id)); v2 = v1; return ViennaCLSuccess; } VIENNACL_EXPORTED_FUNCTION ViennaCLStatus ViennaCLOpenCLDcopy(ViennaCLBackend backend, ViennaCLInt n, cl_mem x, ViennaCLInt offx, ViennaCLInt incx, cl_mem y, ViennaCLInt offy, ViennaCLInt incy) { typedef viennacl::vector_base<double>::size_type size_type; typedef viennacl::vector_base<double>::size_type difference_type; viennacl::vector_base<double> v1(x, size_type(n), size_type(offx), difference_type(incx), viennacl::ocl::get_context(backend->opencl_backend.context_id)); viennacl::vector_base<double> v2(y, size_type(n), size_type(offy), difference_type(incy), viennacl::ocl::get_context(backend->opencl_backend.context_id)); v2 = v1; return ViennaCLSuccess; } // xDOT VIENNACL_EXPORTED_FUNCTION ViennaCLStatus ViennaCLOpenCLSdot(ViennaCLBackend backend, ViennaCLInt n, float *alpha, cl_mem x, ViennaCLInt offx, ViennaCLInt incx, cl_mem y, ViennaCLInt offy, ViennaCLInt incy) { typedef viennacl::vector_base<float>::size_type size_type; typedef viennacl::vector_base<float>::size_type difference_type; viennacl::vector_base<float> v1(x, size_type(n), size_type(offx), difference_type(incx), viennacl::ocl::get_context(backend->opencl_backend.context_id)); viennacl::vector_base<float> v2(y, size_type(n), size_type(offy), difference_type(incy), viennacl::ocl::get_context(backend->opencl_backend.context_id)); *alpha = viennacl::linalg::inner_prod(v1, v2); return ViennaCLSuccess; } VIENNACL_EXPORTED_FUNCTION ViennaCLStatus ViennaCLOpenCLDdot(ViennaCLBackend backend, ViennaCLInt n, double *alpha, cl_mem x, ViennaCLInt offx, ViennaCLInt incx, cl_mem y, ViennaCLInt offy, ViennaCLInt incy) { typedef viennacl::vector_base<double>::size_type size_type; typedef viennacl::vector_base<double>::size_type difference_type; viennacl::vector_base<double> v1(x, size_type(n), size_type(offx), difference_type(incx), viennacl::ocl::get_context(backend->opencl_backend.context_id)); viennacl::vector_base<double> v2(y, size_type(n), size_type(offy), difference_type(incy), viennacl::ocl::get_context(backend->opencl_backend.context_id)); *alpha = viennacl::linalg::inner_prod(v1, v2); return ViennaCLSuccess; } // xNRM2 VIENNACL_EXPORTED_FUNCTION ViennaCLStatus ViennaCLOpenCLSnrm2(ViennaCLBackend backend, ViennaCLInt n, float *alpha, cl_mem x, ViennaCLInt offx, ViennaCLInt incx) { typedef viennacl::vector_base<float>::size_type size_type; typedef viennacl::vector_base<float>::size_type difference_type; viennacl::vector_base<float> v1(x, size_type(n), size_type(offx), difference_type(incx), viennacl::ocl::get_context(backend->opencl_backend.context_id)); *alpha = viennacl::linalg::norm_2(v1); return ViennaCLSuccess; } VIENNACL_EXPORTED_FUNCTION ViennaCLStatus ViennaCLOpenCLDnrm2(ViennaCLBackend backend, ViennaCLInt n, double *alpha, cl_mem x, ViennaCLInt offx, ViennaCLInt incx) { typedef viennacl::vector_base<double>::size_type size_type; typedef viennacl::vector_base<double>::size_type difference_type; viennacl::vector_base<double> v1(x, size_type(n), size_type(offx), difference_type(incx), viennacl::ocl::get_context(backend->opencl_backend.context_id)); *alpha = viennacl::linalg::norm_2(v1); return ViennaCLSuccess; } // xROT VIENNACL_EXPORTED_FUNCTION ViennaCLStatus ViennaCLOpenCLSrot(ViennaCLBackend backend, ViennaCLInt n, cl_mem x, ViennaCLInt offx, ViennaCLInt incx, cl_mem y, ViennaCLInt offy, ViennaCLInt incy, float c, float s) { typedef viennacl::vector_base<float>::size_type size_type; typedef viennacl::vector_base<float>::size_type difference_type; viennacl::vector_base<float> v1(x, size_type(n), size_type(offx), difference_type(incx), viennacl::ocl::get_context(backend->opencl_backend.context_id)); viennacl::vector_base<float> v2(y, size_type(n), size_type(offy), difference_type(incy), viennacl::ocl::get_context(backend->opencl_backend.context_id)); viennacl::linalg::plane_rotation(v1, v2, c, s); return ViennaCLSuccess; } VIENNACL_EXPORTED_FUNCTION ViennaCLStatus ViennaCLOpenCLDrot(ViennaCLBackend backend, ViennaCLInt n, cl_mem x, ViennaCLInt offx, ViennaCLInt incx, cl_mem y, ViennaCLInt offy, ViennaCLInt incy, double c, double s) { typedef viennacl::vector_base<double>::size_type size_type; typedef viennacl::vector_base<double>::size_type difference_type; viennacl::vector_base<double> v1(x, size_type(n), size_type(offx), difference_type(incx), viennacl::ocl::get_context(backend->opencl_backend.context_id)); viennacl::vector_base<double> v2(y, size_type(n), size_type(offy), difference_type(incy), viennacl::ocl::get_context(backend->opencl_backend.context_id)); viennacl::linalg::plane_rotation(v1, v2, c, s); return ViennaCLSuccess; } // xSCAL VIENNACL_EXPORTED_FUNCTION ViennaCLStatus ViennaCLOpenCLSscal(ViennaCLBackend backend, ViennaCLInt n, float alpha, cl_mem x, ViennaCLInt offx, ViennaCLInt incx) { typedef viennacl::vector_base<float>::size_type size_type; typedef viennacl::vector_base<float>::size_type difference_type; viennacl::vector_base<float> v1(x, size_type(n), size_type(offx), difference_type(incx), viennacl::ocl::get_context(backend->opencl_backend.context_id)); v1 *= alpha; return ViennaCLSuccess; } VIENNACL_EXPORTED_FUNCTION ViennaCLStatus ViennaCLOpenCLDscal(ViennaCLBackend backend, ViennaCLInt n, double alpha, cl_mem x, ViennaCLInt offx, ViennaCLInt incx) { typedef viennacl::vector_base<double>::size_type size_type; typedef viennacl::vector_base<double>::size_type difference_type; viennacl::vector_base<double> v1(x, size_type(n), size_type(offx), difference_type(incx), viennacl::ocl::get_context(backend->opencl_backend.context_id)); v1 *= alpha; return ViennaCLSuccess; } // xSWAP VIENNACL_EXPORTED_FUNCTION ViennaCLStatus ViennaCLOpenCLSswap(ViennaCLBackend backend, ViennaCLInt n, cl_mem x, ViennaCLInt offx, ViennaCLInt incx, cl_mem y, ViennaCLInt offy, ViennaCLInt incy) { typedef viennacl::vector_base<float>::size_type size_type; typedef viennacl::vector_base<float>::size_type difference_type; viennacl::vector_base<float> v1(x, size_type(n), size_type(offx), difference_type(incx), viennacl::ocl::get_context(backend->opencl_backend.context_id)); viennacl::vector_base<float> v2(y, size_type(n), size_type(offy), difference_type(incy), viennacl::ocl::get_context(backend->opencl_backend.context_id)); viennacl::swap(v1, v2); return ViennaCLSuccess; } VIENNACL_EXPORTED_FUNCTION ViennaCLStatus ViennaCLOpenCLDswap(ViennaCLBackend backend, ViennaCLInt n, cl_mem x, ViennaCLInt offx, ViennaCLInt incx, cl_mem y, ViennaCLInt offy, ViennaCLInt incy) { typedef viennacl::vector_base<double>::size_type size_type; typedef viennacl::vector_base<double>::size_type difference_type; viennacl::vector_base<double> v1(x, size_type(n), size_type(offx), difference_type(incx), viennacl::ocl::get_context(backend->opencl_backend.context_id)); viennacl::vector_base<double> v2(y, size_type(n), size_type(offy), difference_type(incy), viennacl::ocl::get_context(backend->opencl_backend.context_id)); viennacl::swap(v1, v2); return ViennaCLSuccess; } #endif
rkprajapat/construction-crm
pdi/apps.py
from django.apps import AppConfig class PdiConfig(AppConfig): name = 'pdi'
JoshYaxley/Pineapple
Demo/SpaceRocks/Rock.h
#pragma once #include <Pineapple/Pineapple.h> #include <random> #include "Resource.h" #include "Warp.h" class Rock : public Warp, private pa::EnableChildList<Rock> { public: float m_rotation; Rock(pa::World& world); void onCreate() override; void onStep(pa::Time deltaTime) override; void onDestroy() override; static std::mt19937 gen; }; class SmallRock : public Rock { public: SmallRock(pa::World& world); void onCreate() override; void onDestroy() override; };
du-wei/lemon
src/main/java/com/mossle/user/service/AccountLogService.java
<reponame>du-wei/lemon package com.mossle.user.service; import java.util.List; import javax.annotation.Resource; import com.mossle.api.user.AccountAliasConverter; import com.mossle.api.user.AccountLogDTO; import com.mossle.api.user.AccountStatus; import com.mossle.api.user.ApplicationAliasConverter; import com.mossle.api.user.MockAccountAliasConverter; import com.mossle.api.user.MockApplicationAliasConverter; import com.mossle.core.mapper.BeanMapper; import com.mossle.user.persistence.domain.AccountLog; import com.mossle.user.persistence.manager.AccountLogManager; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class AccountLogService { private static Logger logger = LoggerFactory .getLogger(AccountLogService.class); private BeanMapper beanMapper = new BeanMapper(); private AccountLogManager accountLogManager; private AccountLockService accountLockService; private AccountAliasConverter accountAliasConverter = new MockAccountAliasConverter(); private ApplicationAliasConverter applicationAliasConverter = new MockApplicationAliasConverter(); /** * 批量记录认证日志. */ public void batchLog(List<AccountLogDTO> accountLogDtos) { for (AccountLogDTO accountLogDto : accountLogDtos) { AccountLog accountLog = new AccountLog(); beanMapper.copy(accountLogDto, accountLog); if (accountAliasConverter != null) { String username = accountLog.getUsername(); String realUsername = accountAliasConverter .convertAlias(username); accountLog.setUsername(realUsername); } String username = accountLog.getUsername(); if (StringUtils.isNotBlank(username) && (username.length() > 64)) { logger.info("username : {}", username); username = username.substring(0, 64); accountLog.setUsername(username); } String reason = accountLog.getReason(); if (StringUtils.isNotBlank(reason) && (reason.length() > 200)) { logger.info("reason : {}", reason); reason = reason.substring(0, 200); accountLog.setReason(reason); } this.log(accountLog); } } /** * 记录一条日志. */ public void log(AccountLog accountLog) { try { accountLogManager.save(accountLog); // if ("success".equals(accountLog.getResult())) { // accountLockService.unlock(accountLog.getUsername(), // accountLog.getApplication()); // } else if (AccountStatus.BAD_CREDENTIALS.equals(accountLog.getReason())) { String application = accountLog.getApplication(); if (applicationAliasConverter != null) { application = applicationAliasConverter.convertAlias( application, accountLog.getClient()); } accountLockService.addLockLog(accountLog.getUsername(), application, accountLog.getLogTime()); } } catch (Exception ex) { logger.error(ex.getMessage(), ex); } } @Resource public void setAccountLogManager(AccountLogManager accountLogManager) { this.accountLogManager = accountLogManager; } @Resource public void setAccountLockService(AccountLockService accountLockService) { this.accountLockService = accountLockService; } @Autowired(required = false) public void setAccountAliasConverter( AccountAliasConverter accountAliasConverter) { this.accountAliasConverter = accountAliasConverter; } @Autowired(required = false) public void setApplicationAliasConverter( ApplicationAliasConverter applicationAliasConverter) { this.applicationAliasConverter = applicationAliasConverter; } }
airfranceklm/masherylocal-adapters
ml-sdk-mock/src/main/java/com/airfranceklm/amt/testsupport/MasheryProcessorTestSupport.java
package com.airfranceklm.amt.testsupport; import com.airfranceklm.amt.testsupport.mocks.CacheImpl; import com.airfranceklm.amt.testsupport.mocks.DebugContextImpl; import com.airfranceklm.amt.testsupport.mocks.HTTPServerResponseImpl; import com.airfranceklm.amt.testsupport.mocks.TrafficManagerResponseImpl; import com.fasterxml.jackson.core.type.TypeReference; import com.mashery.http.client.HTTPClientRequest; import com.mashery.http.server.HTTPServerRequest; import com.mashery.trafficmanager.event.processor.model.PostProcessEvent; import com.mashery.trafficmanager.event.processor.model.PreProcessEvent; import com.mashery.trafficmanager.event.processor.model.ProcessorEvent; import com.mashery.trafficmanager.model.core.APICall; import com.mashery.trafficmanager.model.core.ApplicationRequest; import com.mashery.trafficmanager.model.core.TrafficManagerResponse; import lombok.NonNull; import org.easymock.EasyMockSupport; import static com.airfranceklm.amt.testsupport.MasheryProcessorTestCaseAccessor.locateAPIOriginResponse; import static com.airfranceklm.amt.testsupport.MasheryProcessorTestCaseAccessor.synchPayloadLengths; import static org.easymock.EasyMock.expect; public class MasheryProcessorTestSupport<T extends MasheryProcessorTestCase> extends EasyMockSupport { // ----------------------------------------------------- // Methods to be overridden protected PreProcessEvent createPreProcessMock(@NonNull T caseData) { synchPayloadLengths(caseData); TestContext<T> ctx = new TestContext<>(this, caseData); PreProcessEvent retVal = createMock(PreProcessEvent.class); expect(retVal.getType()).andReturn(PreProcessEvent.EVENT_TYPE).anyTimes(); mockCommonEventMethods(ctx, retVal); if (caseData.getClientRequest() != null) { final HTTPServerRequest serverReq = ctx.allocOrGetServerRequest(() -> caseData.getClientRequest().mock(ctx)); final HTTPClientRequest clReq = ctx.allocOrGetAPIOriginRequest(() -> caseData.getClientRequest().mockOriginRequest(ctx)); expect(retVal.getServerRequest()).andReturn(serverReq).anyTimes(); expect(retVal.getClientRequest()).andReturn(clReq).anyTimes(); } return retVal; } protected PostProcessEvent createPostProcessMock(@NonNull T caseData) { synchPayloadLengths(caseData); TestContext<T> ctx = new TestContext<>(this, caseData); PostProcessEvent retVal = createMock(PostProcessEvent.class); expect(retVal.getType()).andReturn(PostProcessEvent.EVENT_TYPE).anyTimes(); mockCommonEventMethods(ctx, retVal); expect(retVal.getServerResponse()).andReturn(ctx.getHttpServerResponse()).anyTimes(); APIOriginResponseModel resp = locateAPIOriginResponse(caseData); if (resp != null) { expect(retVal.getClientResponse()).andReturn(resp.mock(ctx)).anyTimes(); } return retVal; } protected APICall mockAPICallContext(TestContext<T> ctx) { APICall callMock = createMock(APICall.class); if (ctx.getTestCase().getClientRequest() != null) { final ApplicationRequest appReq = ctx.getTestCase().getClientRequest().mockApplicationRequest(ctx); expect(callMock.getRequest()).andReturn(appReq).anyTimes(); } TrafficManagerResponse tmr; if (ctx.getTestCase().getMasheryResponse() != null) { tmr = ctx.getTestCase().getMasheryResponse().mockMasheryResponse(ctx); } else { tmr = new TrafficManagerResponseImpl(); ctx.setHttpServerResponse(tmr.getHTTPResponse()); } expect(callMock.getResponse()).andReturn(tmr).anyTimes(); return callMock; } protected void mockCommonEventMethods(TestContext<T> ctx, ProcessorEvent mock) { expect(mock.getCallContext()).andReturn(mockAPICallContext(ctx)).anyTimes(); final MasheryEndpointModel endp = ctx.getTestCase().getEndpoint(); final APIClientRequestModel clReq = ctx.getTestCase().getClientRequest(); if (endp != null) { expect(mock.getEndpoint()).andReturn(endp.mock(ctx.getOwner())).anyTimes(); } if (clReq != null) { if (clReq.getApplication() != null) { expect(mock.getKey()) .andReturn(clReq.getApplication().mockPackageKey(ctx.getOwner())) .anyTimes(); } else { expect(mock.getKey()).andReturn(null).anyTimes(); } if (clReq.getAuthorizationContext() != null) { expect(mock.getAuthorizationContext()) .andReturn(clReq.getAuthorizationContext().mock(ctx.getOwner())) .anyTimes(); } else { expect(mock.getAuthorizationContext()).andReturn(null).anyTimes(); } } else { // If a client request was not provided, we'll mock the methods anyway, but these // would return null. expect(mock.getAuthorizationContext()) .andReturn(null) .anyTimes(); expect(mock.getKey()) .andReturn(null) .anyTimes(); } // If cache interactions are not defined, then the code should // not be making any use of the caching. if (ctx.getTestCase().getCacheInteraction() != null) { expect(mock.getCache()) .andReturn(ctx.getTestCase().getCacheInteraction().mock(ctx.getOwner())) .anyTimes(); } else { expect(mock.getCache()).andReturn(new CacheImpl(null)).anyTimes(); } // If the debug context interactions are not defined, the code should not be making // any use of the debug context. if (ctx.getTestCase().getDebugContextInteraction() != null) { expect(mock.getDebugContext()) .andReturn(ctx.getTestCase().getDebugContextInteraction().mock(ctx.getOwner())) .anyTimes(); } else { expect(mock.getDebugContext()).andReturn(new DebugContextImpl(null)).anyTimes(); } } }
jeongjoonyoo/CodeXL
CodeXL/Remote/AMDTRemoteAgent/dmnServerThreadConfig.cpp
//================================================================================== // Copyright (c) 2016 , Advanced Micro Devices, Inc. All rights reserved. // /// \author AMD Developer Tools Team /// \file dmnServerThreadConfig.cpp /// //================================================================================== #include <AMDTRemoteAgent/dmnServerThreadConfig.h> #include <AMDTOSWrappers/Include/osChannel.h> dmnServerThreadConfig::dmnServerThreadConfig(unsigned int backlog, unsigned int daemonPortNumber, long readTimeout, long writeTimeout, const gtString& userForcedIpStr) : m_backlog(backlog), m_portNumber(daemonPortNumber), m_readTimeout(readTimeout), m_writeTimeout(writeTimeout), m_userForcedIpStr(userForcedIpStr) { } dmnServerThreadConfig::~dmnServerThreadConfig(void) { } static bool isTimeoutRequired(long timeoutValue) { return (timeoutValue >= DMN_MAX_TIMEOUT_VAL); } bool dmnServerThreadConfig::isReadTimeout() const { return isTimeoutRequired(m_readTimeout); } bool dmnServerThreadConfig::isWriteTimeout() const { return isTimeoutRequired(m_writeTimeout); } static long CalculateTimeout(long timeoutValue) { long ret = timeoutValue; if (timeoutValue == DMN_MAX_TIMEOUT_VAL) { ret = LONG_MAX; } else if (timeoutValue <= DMN_MAX_TIMEOUT_VAL) { // Indicates a programmer error. dmnUtils::LogMessage(L"Warning: Calculated timeout for negative value.", OS_DEBUG_LOG_ERROR); } return ret; } long dmnServerThreadConfig::getReadTimeout() const { return CalculateTimeout(m_readTimeout); } long dmnServerThreadConfig::getWriteTimeout() const { return CalculateTimeout(m_writeTimeout); } gtString dmnServerThreadConfig::getUserForcedIpString() const { return m_userForcedIpStr; } bool dmnServerThreadConfig::isUserForcedIp() const { return (!m_userForcedIpStr.isEmpty()); }
mihaitodor/SeComLib
private_recommendations_data_packing/secure_comparison_server.cpp
/* SeComLib Copyright 2012-2013 TU Delft, Information Security & Privacy Lab (http://isplab.tudelft.nl/) Contributors: <NAME> (<EMAIL>) <NAME> (<EMAIL>) <NAME> (<EMAIL>) <NAME> (<EMAIL>) 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. */ /** @file private_recommendations_data_packing/secure_comparison_server.cpp @brief Implementation of class SecureComparisonServer. @author <NAME> (<EMAIL>) */ #include "secure_comparison_server.h" //avoid circular includes #include "secure_comparison_client.h" namespace SeComLib { namespace PrivateRecommendationsDataPacking { /** @param paillierCryptoProvider the Paillier crypto provider @param dgkCryptoProvider the DGK crypto provider @param similarityTreshold the threshold to which similarity values will be compared @param l @f$ l = 2k + \lceil log_2(R) \rceil @f$ @param bucketSize the size of the data buckets (in bits) @param maxPackedBuckets the maximum number of buckets that fit in one encryption @param emptyBuckets pre-computed empty buckets @param configurationPath the configuration path for parameters */ SecureComparisonServer::SecureComparisonServer (const Paillier &paillierCryptoProvider, const Dgk &dgkCryptoProvider, const BigInteger &similarityTreshold, const size_t l, const size_t bucketSize, const size_t maxPackedBuckets, const std::deque<BigInteger> &emptyBuckets, const std::string &configurationPath) : paillierCryptoProvider(paillierCryptoProvider), dgkCryptoProvider(dgkCryptoProvider), blindingFactorCache(paillierCryptoProvider, ComparisonBlindingFactorCacheParameters(configurationPath + ".BlindingFactorCache", bucketSize * maxPackedBuckets, emptyBuckets)), l(l), emptyBuckets(emptyBuckets), maxPackedBuckets(maxPackedBuckets), //the dgkComparisonServer operates on l + 1 bit values (due to the empty bit at the beginning of each bucket) dgkComparisonServer(std::make_shared<DgkComparisonServer>(paillierCryptoProvider, dgkCryptoProvider, l + 1)) { /// Precompute @f$ \left[ \displaystyle\sum_{i = 0}^{N - 1}{(2^{l + 2})^i 2(2^l - \delta) } \right] @f$, where N is the maximum number of packed buckets that fit in one encryption BigInteger twoTimestwoPowLMinusDelta = (BigInteger(2).GetPow(static_cast<unsigned long>(this->l)) - similarityTreshold) * 2; BigInteger one(1); BigInteger partialD = twoTimestwoPowLMinusDelta; for (size_t i = 1; i < maxPackedBuckets; ++i) { partialD += (one << (static_cast<unsigned long>(bucketSize * i))) * twoTimestwoPowLMinusDelta;//bucketSize = l + 2 } this->encryptedPartialD = this->paillierCryptoProvider.EncryptIntegerNonrandom(partialD); } /** @param packedSimilarityValues packed similariy values @param similarityValueCountInLastEncryption number of packed similarity values in the last element of the packedSimilarityValues encryptions vector @return The encrypted similarity comparison results, @f$ [\gamma_i] @f$, for the current user */ SecureComparisonServer::EncryptedUserData SecureComparisonServer::Compare (const PackedData &packedSimilarityValues, const size_t similarityValueCountInLastEncryption) { EncryptedUserData gammaVector; /// Iterate over the @f$ [SIM_{user}^{Packed}] @f$ encryptions (if there are enough users, multiple encryptions will be required to pack all @f$ sim_{(user, j)} @f$ values) for (size_t encryptionIndex = 0; encryptionIndex < packedSimilarityValues.size(); ++encryptionIndex) { /** Compute @f$ [D] = \left[ \displaystyle\sum_{i = 0}^{N - 1}{(2^{l + 2})^i 2 \tilde{d}^{(i)}} \right] = [SIM_A^{Packed}] \left[ \displaystyle\sum_{i = 0}^{N - 1}{(2^{l + 2})^i 2(2^l - \delta) } \right] @f$ where @f$ [\tilde{d}^{(i)}] = [2^l + sim_{(A, i)} - \delta] @f$ */ Paillier::Ciphertext D = packedSimilarityValues[encryptionIndex] + this->encryptedPartialD; const BlindingFactorContainer &blindingFactorContainer = this->blindingFactorCache.Pop(); /// @f$ [z] = [D] \cdot [r] @f$ Paillier::Ciphertext z = D + blindingFactorContainer.encryptedR; //the last element of the packedSimilarityValues vector may contain fewer packed buckets size_t encryptedBucketsCount = encryptionIndex < packedSimilarityValues.size() - 1 ? this->maxPackedBuckets : similarityValueCountInLastEncryption; /// Ask the client to unpack @f$ [z] @f$ this->secureComparisonClient.lock()->UnpackZ(z, this->emptyBuckets, encryptedBucketsCount); /// Compute @f$ [\gamma_{(user, i)}] @f$ for (size_t i = 0; i < encryptedBucketsCount; ++i) { this->secureComparisonClient.lock()->SetZi(i); //std::cout << "r_i: " << blindingFactorContainer.ri[i].ToString() << std::endl; gammaVector.emplace_back(this->dgkComparisonServer->ComputeDi(blindingFactorContainer.ri[i])); //this->secureComparisonClient.lock()->DebugPaillierEncryption(gammaVector.back()); } } return gammaVector; } /** @param index The index of the bucket @return a reference to the requested empty bucket */ const BigInteger &SecureComparisonServer::GetEmptyBucket (const size_t index) const { return this->emptyBuckets.at(index); } /** @param secureComparisonClient a SecureComparisonClient instance */ void SecureComparisonServer::SetClient (const std::shared_ptr<SecureComparisonClient> &secureComparisonClient) { this->secureComparisonClient = secureComparisonClient; this->dgkComparisonServer->SetClient(secureComparisonClient->GetDgkComparisonClient()); } /** @return The DgkComparisonServer instance. */ const std::shared_ptr<DgkComparisonServer> &SecureComparisonServer::GetDgkComparisonServer () const { return this->dgkComparisonServer; } }//namespace PrivateRecommendationsDataPacking }//namespace SeComLib
skrobul/salt
salt/modules/lxc.py
<filename>salt/modules/lxc.py<gh_stars>0 # -*- coding: utf-8 -*- ''' Control Linux Containers via Salt :depends: lxc package for distribution lxc >= 1.0 (even beta alpha) is required ''' # Import python libs from __future__ import print_function import traceback import datetime import pipes import logging import tempfile import os import shutil import re # Import salt libs import salt import salt.utils import salt.utils.cloud import salt.config import salt._compat # Set up logging log = logging.getLogger(__name__) # Don't shadow built-in's. __func_alias__ = { 'list_': 'list' } DEFAULT_NIC_PROFILE = {'eth0': {'link': 'br0', 'type': 'veth'}} def _ip_sort(ip): '''Ip sorting''' idx = '001' if ip == '127.0.0.1': idx = '200' if ip == '::1': idx = '201' elif '::' in ip: idx = '100' return '{0}___{1}'.format(idx, ip) def __virtual__(): if salt.utils.which('lxc-start'): return True # To speed up the whole thing, we decided to not use the # subshell way and assume things are in place for lxc # Discussion made by @kiorky and @thatch45 # lxc-version presence is not sufficient, in lxc1.0 alpha # (precise backports), we have it and it is sufficient # for the module to execute. # elif salt.utils.which('lxc-version'): # passed = False # try: # passed = subprocess.check_output( # 'lxc-version').split(':')[1].strip() >= '1.0' # except Exception: # pass # if not passed: # log.warning('Support for lxc < 1.0 may be incomplete.') # return 'lxc' # return False # return False def _lxc_profile(profile): ''' Gather the lxc profile from the config or apply the default (empty). Profiles can be defined in the config or pillar, e.g.: .. code-block:: yaml lxc.profile: ubuntu: template: ubuntu backing: lvm vgname: lxc size: 1G ''' return __salt__['config.option']('lxc.profile', {}).get(profile, {}) def _config_list(**kwargs): ''' Return a list of dicts from the salt level configurations ''' ret = [] memory = kwargs.pop('memory', None) if memory: memory = memory * 1024 * 1024 ret.append({'lxc.cgroup.memory.limit_in_bytes': memory}) cpuset = kwargs.pop('cpuset', None) if cpuset: ret.append({'lxc.cgroup.cpuset.cpus': cpuset}) cpushare = kwargs.pop('cpushare', None) if cpushare: ret.append({'lxc.cgroup.cpu.shares': cpushare}) nic = kwargs.pop('nic') if nic: nicp = __salt__['config.option']('lxc.nic', {}).get( nic, DEFAULT_NIC_PROFILE ) nic_opts = kwargs.pop('nic_opts', None) for dev, args in nicp.items(): ret.append({'lxc.network.type': args.pop('type', 'veth')}) ret.append({'lxc.network.name': dev}) ret.append({'lxc.network.flags': args.pop('flags', 'up')}) opts = nic_opts.get(dev) if nic_opts else None if opts: mac = opts.get('mac') ipv4 = opts.get('ipv4') ipv6 = opts.get('ipv6') else: ipv4, ipv6 = None, None mac = salt.utils.gen_mac() ret.append({'lxc.network.hwaddr': mac}) if ipv4: ret.append({'lxc.network.ipv4': ipv4}) if ipv6: ret.append({'lxc.network.ipv6': ipv6}) for k, v in args.items(): ret.append({'lxc.network.{0}'.format(k): v}) return ret class _LXCConfig(object): ''' LXC configuration data ''' pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)') def __init__(self, **kwargs): self.name = kwargs.pop('name', None) self.data = [] if self.name: self.path = '/var/lib/lxc/{0}/config'.format(self.name) if os.path.isfile(self.path): with open(self.path) as f: for l in f.readlines(): match = self.pattern.findall((l.strip())) if match: self.data.append((match[0][0], match[0][-1])) else: self.path = None def _replace(k, v): if v: self._filter_data(k) self.data.append((k, v)) memory = kwargs.pop('memory', None) if memory: memory = memory * 1024 * 1024 _replace('lxc.cgroup.memory.limit_in_bytes', memory) cpuset = kwargs.pop('cpuset', None) _replace('lxc.cgroup.cpuset.cpus', cpuset) cpushare = kwargs.pop('cpushare', None) _replace('lxc.cgroup.cpu.shares', cpushare) nic = kwargs.pop('nic') if nic: self._filter_data('lxc.network') nicp = __salt__['config.option']('lxc.nic', {}).get( nic, DEFAULT_NIC_PROFILE ) nic_opts = kwargs.pop('nic_opts', None) for dev, args in nicp.items(): self.data.append(('lxc.network.type', args.pop('type', 'veth'))) self.data.append(('lxc.network.name', dev)) self.data.append(('lxc.network.flags', args.pop('flags', 'up'))) opts = nic_opts.get(dev) if nic_opts else None if opts: mac = opts.get('mac') ipv4 = opts.get('ipv4') ipv6 = opts.get('ipv6') else: ipv4, ipv6 = None, None mac = salt.utils.gen_mac() self.data.append(('lxc.network.hwaddr', mac)) if ipv4: self.data.append(('lxc.network.ipv4', ipv4)) if ipv6: self.data.append(('lxc.network.ipv6', ipv6)) for k, v in args.items(): self.data.append(('lxc.network.{0}'.format(k), v)) def as_string(self): return '\n'.join( ['{0} = {1}'.format(k, v) for k, v in self.data]) + '\n' def write(self): if self.path: salt.utils.fopen(self.path, 'w').write(self.as_string()) def tempfile(self): # this might look like the function name is shadowing the # module, but it's not since the method belongs to the class f = tempfile.NamedTemporaryFile() f.write(self.as_string()) f.flush() return f def _filter_data(self, pat): x = [] for i in self.data: if not re.match('^' + pat, i[0]): x.append(i) self.data = x def get_base(**kwargs): ''' If the needed base does not exist, then create it, if it does exist create nothing and return the name of the base lxc container so it can be cloned. CLI Example: .. code-block:: bash salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\ [nic=nic_profile] [profile=lxc_profile] \\ [nic_opts=nic_opts] [image=network image path]\\ [seed=(True|False)] [install=(True|False)] \\ [config=minion_config] ''' cntrs = ls() if kwargs.get('image'): image = kwargs.get('image') proto = salt._compat.urlparse(image).scheme img_tar = __salt__['cp.cache_file'](image) img_name = os.path.basename(img_tar) hash_ = salt.utils.get_hash( img_tar, __salt__['config.option']('hash_type')) name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_) if name not in cntrs: create(name, **kwargs) if kwargs.get('vgname'): rootfs = os.path.join('/dev', kwargs['vgname'], name) lxc_info = info(name) edit_conf(lxc_info['config'], **{'lxc.rootfs': rootfs}) return name elif kwargs.get('template'): name = '__base_{0}'.format(kwargs['template']) if name not in cntrs: create(name, **kwargs) if kwargs.get('vgname'): rootfs = os.path.join('/dev', kwargs['vgname'], name) lxc_info = info(name) edit_conf(lxc_info['config'], **{'lxc.rootfs': rootfs}) return name return '' def init(name, cpuset=None, cpushare=None, memory=None, nic='default', profile=None, nic_opts=None, **kwargs): ''' Initialize a new container. CLI Example: .. code-block:: bash salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\ [cpushare=cgroups_cpushare] [memory=cgroups_memory] \\ [nic=nic_profile] [profile=lxc_profile] \\ [nic_opts=nic_opts] [start=(True|False)] \\ [seed=(True|False)] [install=(True|False)] \\ [config=minion_config] [approve_key=(True|False) \\ [clone=original] name Name of the container. cpuset cgroups cpuset. cpushare cgroups cpu shares. memory cgroups memory limit, in MB. nic Network interfaces profile (defined in config or pillar). profile A LXC profile (defined in config or pillar). nic_opts Extra options for network interfaces. E.g: {"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}} start Start the newly created container. seed Seed the container with the minion config. Default: ``True`` install If salt-minion is not already installed, install it. Default: ``True`` config Optional config parameters. By default, the id is set to the name of the container. approve_key Attempt to request key approval from the master. Default: ``True`` clone Original from which to use a clone operation to create the container. Default: ``None`` ''' profile = _lxc_profile(profile) def select(k, default=None): kw = kwargs.pop(k, None) p = profile.pop(k, default) return kw or p tvg = select('vgname') vgname = tvg if tvg else __salt__['config.option']('lxc.vgname') start_ = select('start', True) seed = select('seed', True) install = select('install', True) seed_cmd = select('seed_cmd') salt_config = select('config') approve_key = select('approve_key', True) clone_from = select('clone') # If using a volume group then set up to make snapshot cow clones if vgname and not clone_from: clone_from = get_base(vgname=vgname, **kwargs) if not kwargs.get('snapshot') is False: kwargs['snapshot'] = True if clone_from: ret = __salt__['lxc.clone'](name, clone_from, profile=profile, **kwargs) if not ret.get('cloned', False): return ret cfg = _LXCConfig(name=name, nic=nic, nic_opts=nic_opts, cpuset=cpuset, cpushare=cpushare, memory=memory) cfg.write() else: cfg = _LXCConfig(nic=nic, nic_opts=nic_opts, cpuset=cpuset, cpushare=cpushare, memory=memory) with cfg.tempfile() as cfile: ret = __salt__['lxc.create'](name, config=cfile.name, profile=profile, **kwargs) if not ret.get('created', False): return ret path = '/var/lib/lxc/{0}/config'.format(name) for comp in _config_list(nic=nic, nic_opts=nic_opts, cpuset=cpuset, cpushare=cpushare, memory=memory): edit_conf(path, **comp) lxc_info = info(name) rootfs = lxc_info['rootfs'] #lxc_config = lxc_info['config'] if seed: ret['seeded'] = __salt__['lxc.bootstrap']( name, config=salt_config, approve_key=approve_key, install=install) elif seed_cmd: ret['seeded'] = __salt__[seed_cmd](rootfs, name, salt_config) if start_: ret['state'] = start(name)['state'] else: ret['state'] = state(name) return ret def create(name, config=None, profile=None, options=None, **kwargs): ''' Create a new container. CLI Example: .. code-block:: bash salt 'minion' lxc.create name [config=config_file] \\ [profile=profile] [template=template_name] \\ [backing=backing_store] [vgname=volume_group] \\ [size=filesystem_size] [options=template_options] name Name of the container. config The config file to use for the container. Defaults to system-wide config (usually in /etc/lxc/lxc.conf). profile A LXC profile (defined in config or pillar). template The template to use. E.g., 'ubuntu' or 'fedora'. backing The type of storage to use. Set to 'lvm' to use an LVM group. Defaults to filesystem within /var/lib/lxc/. vgname Name of the LVM volume group in which to create the volume for this container. Only applicable if backing=lvm. Defaults to 'lxc'. fstype fstype to use on LVM lv. size Size of the volume to create. Only applicable if backing=lvm. Defaults to 1G. options Template specific options to pass to the lxc-create command. ''' if exists(name): return {'created': False, 'error': 'container already exists'} cmd = 'lxc-create -n {0}'.format(name) if not isinstance(profile, dict): profile = _lxc_profile(profile) def select(k, default=None): kw = kwargs.pop(k, None) p = profile.pop(k, default) return kw or p tvg = select('vgname') vgname = tvg if tvg else __salt__['config.option']('lxc.vgname') template = select('template') backing = select('backing') if vgname and not backing: backing = 'lvm' lvname = select('lvname') fstype = select('fstype') size = select('size', '1G') image = select('image') if image: img_tar = __salt__['cp.cache_file'](image) template = os.path.join( os.path.dirname(salt.__file__), 'templates', 'lxc', 'salt_tarball') profile['imgtar'] = img_tar if config: cmd += ' -f {0}'.format(config) if template: cmd += ' -t {0}'.format(template) if backing: backing = backing.lower() cmd += ' -B {0}'.format(backing) if backing in ['lvm']: if lvname: cmd += ' --lvname {0}'.format(vgname) if vgname: cmd += ' --vgname {0}'.format(vgname) if backing not in ['dir', 'overlayfs']: if fstype: cmd += ' --fstype {0}'.format(fstype) if size: cmd += ' --fssize {0}'.format(size) if profile: cmd += ' --' options = profile for k, v in options.items(): cmd += ' --{0} {1}'.format(k, v) ret = __salt__['cmd.run_all'](cmd) if ret['retcode'] == 0 and exists(name): return {'created': True} else: if exists(name): # destroy the container if it was partially created cmd = 'lxc-destroy -n {0}'.format(name) __salt__['cmd.retcode'](cmd) log.warn('lxc-create failed to create container') return {'created': False, 'error': 'container could not be created with cmd "{0}": {1}'.format(cmd, ret['stderr'])} def clone(name, orig, snapshot=False, profile=None, **kwargs): ''' Create a new container. CLI Example: .. code-block:: bash salt 'minion' lxc.clone name orig [snapshot=(True|False)] \\ [size=filesystem_size] [vgname=volume_group] \\ [profile=profile_name] name Name of the container. orig Name of the cloned original container snapshot Do we use Copy On Write snapshots (LVM) size Size of the container vgname LVM volume group(lxc) profile A LXC profile (defined in config or pillar). CLI Example: .. code-block:: bash salt '*' lxc.clone myclone ubuntu "snapshot=True" ''' if exists(name): return {'cloned': False, 'error': 'container already exists'} orig_state = state(orig) if orig_state is None: return {'cloned': False, 'error': 'original container \'{0}\' does not exist'.format(orig)} elif orig_state != 'stopped': return {'cloned': False, 'error': 'original container \'{0}\' is running'.format(orig)} if not snapshot: snapshot = '' else: snapshot = '-s' cmd = 'lxc-clone {2} -o {0} -n {1}'.format(orig, name, snapshot) if not isinstance(profile, dict): profile = _lxc_profile(profile) def select(k, default=None): kw = kwargs.pop(k, None) p = profile.pop(k, default) return kw or p backing = select('backing') size = select('size', '1G') if size: cmd += ' -L {0}'.format(size) if backing: cmd += ' -B {0}'.format(backing) ret = __salt__['cmd.run_all'](cmd) if ret['retcode'] == 0 and exists(name): return {'cloned': True} else: if exists(name): # destroy the container if it was partially created cmd = 'lxc-destroy -n {0}'.format(name) __salt__['cmd.retcode'](cmd) log.warn('lxc-clone failed to create container') return {'cloned': False, 'error': 'container could not be created with cmd "{0}": {1}'.format(cmd, ret['stderr'])} def ls(): ''' Return just a list of the containers available CLI Example: .. code-block:: bash salt '*' lxc.ls ''' return __salt__['cmd.run']('lxc-ls | sort -u').splitlines() def list_(extra=False): ''' List defined containers classified by status. Status can be running, stopped, and frozen. extra Also get per container specific info at once. Warning: it will not return a collection of list but a collection of mappings by status and then per container name:: {'running': ['foo']} # normal mode {'running': {'foo': {'info1': 'bar'}} # extra mode CLI Example: .. code-block:: bash salt '*' lxc.list salt '*' lxc.list extra=True ''' ctnrs = __salt__['cmd.run']('lxc-ls | sort -u').splitlines() if extra: stopped = {} frozen = {} running = {} else: stopped = [] frozen = [] running = [] ret = {'running': running, 'stopped': stopped, 'frozen': frozen} for container in ctnrs: c_infos = __salt__['cmd.run']( 'lxc-info -n {0}'.format(container)).splitlines() log.debug(c_infos) c_state = None for c_info in c_infos: log.debug(c_info) stat = c_info.split(':') if stat[0] in ('State', 'state'): c_state = stat[1].strip() break if extra: try: infos = __salt__['lxc.info'](container) except Exception: trace = traceback.format_exc() infos = {'error': 'Error while getting extra infos', 'comment': trace} method = 'update' value = {container: infos} else: method = 'append' value = container if not c_state: continue if c_state == 'STOPPED': getattr(stopped, method)(value) continue if c_state == 'FROZEN': getattr(frozen, method)(value) continue if c_state == 'RUNNING': getattr(running, method)(value) continue return ret def _change_state(cmd, name, expected): s1 = state(name) if s1 is None: return {'state': None, 'change': False} elif s1 == expected: return {'state': expected, 'change': False} cmd = '{0} -n {1}'.format(cmd, name) err = __salt__['cmd.run_stderr'](cmd) if err: s2 = state(name) r = {'state': s2, 'change': s1 != s2, 'error': err} else: if expected is not None: # some commands do not wait, so we will cmd = 'lxc-wait -n {0} -s {1}'.format(name, expected.upper()) __salt__['cmd.run'](cmd, timeout=30) s2 = state(name) r = {'state': s2, 'change': s1 != s2} return r def _ensure_running(name, no_start=False): prior_state = __salt__['lxc.state'](name) if not prior_state: return None res = {} if prior_state == 'stopped': if no_start: return False res = __salt__['lxc.start'](name) elif prior_state == 'frozen': if no_start: return False res = __salt__['lxc.unfreeze'](name) if res.get('error'): log.warn('Failed to run command: {0}'.format(res['error'])) return False return prior_state def start(name, restart=False): ''' Start the named container. CLI Example: .. code-block:: bash salt '*' lxc.start name ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Started'} try: does_exist = __salt__['lxc.exists'](name) if not does_exist: return {'name': name, 'result': False, 'comment': 'Container does not exist'} if restart: __salt__['lxc.stop'](name) ret.update(_change_state('lxc-start -d', name, 'running')) infos = __salt__['lxc.info'](name) ret['result'] = infos['state'] == 'running' if ret['change']: ret['changes']['started'] = 'started' except Exception, ex: trace = traceback.format_exc() ret['result'] = False ret['comment'] = 'Error in starting container' ret['comment'] += '{0}\n{1}\n'.format(ex, trace) return ret def stop(name, kill=True): ''' Stop the named container. CLI Example: .. code-block:: bash salt '*' lxc.stop name ''' cmd = 'lxc-stop' if kill: cmd += ' -k' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Stopped'} try: does_exist = __salt__['lxc.exists'](name) if not does_exist: return {'name': name, 'result': False, 'changes': {}, 'comment': 'Container does not exist'} ret.update(_change_state('lxc-stop', name, 'stopped')) infos = __salt__['lxc.info'](name) ret['result'] = infos['state'] == 'stopped' if ret['change']: ret['changes']['stopped'] = 'stopped' except Exception, ex: trace = traceback.format_exc() ret['result'] = False ret['comment'] = 'Error in stopping container' ret['comment'] += '{0}\n{1}\n'.format(ex, trace) return ret def freeze(name): ''' Freeze the named container. CLI Example: .. code-block:: bash salt '*' lxc.freeze name ''' return _change_state('lxc-freeze', name, 'frozen') def unfreeze(name): ''' Unfreeze the named container. CLI Example: .. code-block:: bash salt '*' lxc.unfreeze name ''' return _change_state('lxc-unfreeze', name, 'running') def destroy(name, stop=True): ''' Destroy the named container. WARNING: Destroys all data associated with the container. CLI Example: .. code-block:: bash salt '*' lxc.destroy name [stop=(True|False)] ''' if stop: _change_state('lxc-stop -k', name, 'stopped') return _change_state('lxc-destroy', name, None) def exists(name): ''' Returns whether the named container exists. CLI Example: .. code-block:: bash salt '*' lxc.exists name ''' l = list_() return name in l['running'] + l['stopped'] + l['frozen'] def state(name): ''' Returns the state of a container. CLI Example: .. code-block:: bash salt '*' lxc.state name ''' if not exists(name): return None cmd = 'lxc-info -n {0}'.format(name) ret = __salt__['cmd.run_all'](cmd) if ret['retcode'] != 0: return False else: c_infos = ret['stdout'].splitlines() c_state = None for c_info in c_infos: stat = c_info.split(':') if stat[0] in ('State', 'state'): c_state = stat[1].strip().lower() break return c_state def get_parameter(name, parameter): ''' Returns the value of a cgroup parameter for a container. CLI Example: .. code-block:: bash salt '*' lxc.get_parameter name parameter ''' if not exists(name): return None cmd = 'lxc-cgroup -n {0} {1}'.format(name, parameter) ret = __salt__['cmd.run_all'](cmd) if ret['retcode'] != 0: return False else: return {parameter: ret['stdout'].strip()} def set_parameter(name, parameter, value): ''' Set the value of a cgroup parameter for a container. CLI Example: .. code-block:: bash salt '*' lxc.set_parameter name parameter value ''' if not exists(name): return None cmd = 'lxc-cgroup -n {0} {1} {2}'.format(name, parameter, value) ret = __salt__['cmd.run_all'](cmd) if ret['retcode'] != 0: return False else: return True def templates(templates_dir='/usr/share/lxc/templates'): ''' Returns a list of existing templates CLI Example: .. code-block:: bash salt '*' lxc.templates ''' templates_list = [] san = re.compile('^lxc-') if os.path.isdir(templates_dir): templates_list.extend( [san.sub('', a) for a in os.listdir(templates_dir)] ) templates_list.sort() return templates_list def info(name): ''' Returns information about a container. CLI Example: .. code-block:: bash salt '*' lxc.info name ''' f = '/var/lib/lxc/{0}/config'.format(name) if not os.path.isfile(f): return None ret = {} config = [(v[0].strip(), v[1].strip()) for v in [l.split('#', 1)[0].strip().split('=', 1) for l in open(f).readlines()] if len(v) == 2] ifaces = [] current = None for k, v in config: if k == 'lxc.network.type': current = {'type': v} ifaces.append(current) elif not current: continue elif k.startswith('lxc.network.'): current[k.replace('lxc.network.', '', 1)] = v if ifaces: ret['nics'] = ifaces ret['rootfs'] = next((i[1] for i in config if i[0] == 'lxc.rootfs'), None) ret['state'] = state(name) ret['_ips'] = [] ret['public_ips'] = [] ret['private_ips'] = [] ret['public_ipv4_ips'] = [] ret['public_ipv6_ips'] = [] ret['private_ipv4_ips'] = [] ret['private_ipv6_ips'] = [] ret['ipv4_ips'] = [] ret['ipv6_ips'] = [] ret['size'] = None ret['config'] = f if ret['state'] == 'running': limit = int(get_parameter(name, 'memory.limit_in_bytes').get( 'memory.limit_in_bytes')) usage = int(get_parameter(name, 'memory.usage_in_bytes').get( 'memory.usage_in_bytes')) free = limit - usage ret['memory_limit'] = limit ret['memory_free'] = free ret['size'] = __salt__['cmd.run']( ('lxc-attach -n \'{0}\' -- ' 'df /|tail -n1|awk \'{{print $2}}\'').format(name)) ipaddr = __salt__['cmd.run']( 'lxc-attach -n \'{0}\' -- ip addr show'.format(name)) for line in ipaddr.splitlines(): if 'inet' in line: line = line.split() ip_address = line[1].split('/')[0] if not ip_address in ret['_ips']: ret['_ips'].append(ip_address) if '::' in ip_address: ret['ipv6_ips'].append(ip_address) if ( ip_address == '::1' or ip_address.startswith('fe80') ): ret['private_ips'].append(ip_address) ret['private_ipv6_ips'].append(ip_address) else: ret['public_ips'].append(ip_address) ret['public_ipv6_ips'].append(ip_address) else: ret['ipv4_ips'].append(ip_address) if ip_address == '127.0.0.1': ret['private_ips'].append(ip_address) ret['private_ipv4_ips'].append(ip_address) elif salt.utils.cloud.is_public_ip(ip_address): ret['public_ips'].append(ip_address) ret['public_ipv4_ips'].append(ip_address) else: ret['private_ips'].append(ip_address) ret['private_ipv4_ips'].append(ip_address) for k in [l for l in ret if l.endswith('_ips')]: ret[k].sort(key=_ip_sort) return ret def set_pass(name, users, password): '''Set the password of one or more system users inside containers CLI Example: .. code-block:: bash salt '*' lxc.set_pass root foo ''' ret = {'result': True, 'comment': ''} if not isinstance(users, list): users = [users] ret['comment'] = '' if users: try: cmd = ( "lxc-attach -n \"{0}\" -- " " /bin/sh -c \"" "").format(name) for i in users: cmd += "echo {0}:{1}|chpasswd && ".format( pipes.quote(i), pipes.quote(password), ) cmd += " /bin/true\"" cret = __salt__['cmd.run_all'](cmd) if cret['retcode'] != 0: raise ValueError('Can\'t change passwords') ret['comment'] = 'Password updated for {0}'.format(users) except ValueError, ex: trace = traceback.format_exc() ret['result'] = False ret['comment'] = 'Error in setting base password\n' ret['comment'] += '{0}\n{1}\n'.format(ex, trace) else: ret['result'] = False ret['comment'] = 'No user selected' return ret def update_lxc_conf(name, lxc_conf, lxc_conf_unset): '''Edit LXC configuration options CLI Example: .. code-block:: bash salt-call -lall lxc.update_lxc_conf ubuntu \ lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \ lxc_conf_unset="['lxc.utsname']" ''' changes = {'edited': [], 'added': [], 'removed': []} ret = {'changes': changes, 'result': True, 'comment': ''} lxc_conf_p = '/var/lib/lxc/{0}/config'.format(name) if not __salt__['lxc.exists'](name): ret['result'] = False ret['comment'] = 'Container does not exist: {0}'.format(name) elif not os.path.exists(lxc_conf_p): ret['result'] = False ret['comment'] = ( 'Configuration does not exist: {0}'.format(lxc_conf_p)) else: with open(lxc_conf_p, 'r') as fic: filtered_lxc_conf = [] for row in lxc_conf: if not row: continue for conf in row: filtered_lxc_conf.append((conf.strip(), row[conf].strip())) ret['comment'] = 'lxc.conf is up to date' lines = [] orig_config = fic.read() for line in orig_config.splitlines(): if line.startswith('#') or not line.strip(): lines.append([line, '']) else: line = line.split('=') index = line.pop(0) val = (index.strip(), '='.join(line).strip()) if not val in lines: lines.append(val) for k, item in filtered_lxc_conf: matched = False for idx, line in enumerate(lines[:]): if line[0] == k: matched = True lines[idx] = (k, item) if '='.join(line[1:]).strip() != item.strip(): changes['edited'].append( ({line[0]: line[1:]}, {k: item})) break if not matched: if not (k, item) in lines: lines.append((k, item)) changes['added'].append({k: item}) dest_lxc_conf = [] # filter unset if lxc_conf_unset: for line in lines: for opt in lxc_conf_unset: if ( not line[0].startswith(opt) and not line in dest_lxc_conf ): dest_lxc_conf.append(line) else: changes['removed'].append(opt) else: dest_lxc_conf = lines conf = '' for k, val in dest_lxc_conf: if not val: conf += '{0}\n'.format(k) else: conf += '{0} = {1}\n'.format(k.strip(), val.strip()) conf_changed = conf != orig_config chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') if conf_changed: wfic = open('{0}.{1}'.format(lxc_conf_p, chrono), 'w') wfic.write(conf) wfic.close() wfic = open(lxc_conf_p, 'w') wfic.write(conf) wfic.close() ret['comment'] = 'Updated' ret['result'] = True if ( not changes['added'] and not changes['edited'] and not changes['removed'] ): ret['changes'] = {} return ret def set_dns(name, dnsservers=None, searchdomains=None): '''Update container DNS configuration and possibly also resolvonf one. CLI Example: .. code-block:: bash salt-call -lall lxc.set_dns ubuntu ['8.8.8.8', '192.168.127.12'] ''' ret = {'result': False} if not dnsservers: dnsservers = ['8.8.8.8', '192.168.127.12'] if not searchdomains: searchdomains = [] dns = ['nameserver {0}'.format(d) for d in dnsservers] dns.extend(['search {0}'.format(d) for d in searchdomains]) dns = "\n".join(dns) has_resolvconf = not int( __salt__['cmd.run'](('lxc-attach -n \'{0}\' -- ' '/usr/bin/test -e /etc/resolvconf/resolv.conf.d/base;' 'echo ${{?}}').format(name))) if has_resolvconf: cret = __salt__['cmd.run_all'](( 'lxc-attach -n \'{0}\' -- ' 'rm /etc/resolvconf/resolv.conf.d/base &&' 'echo \'{1}\'|lxc-attach -n \'{0}\' -- ' 'tee /etc/resolvconf/resolv.conf.d/base' ).format(name, dns)) if not cret['retcode']: ret['result'] = True cret = __salt__['cmd.run_all'](( 'lxc-attach -n \'{0}\' -- rm /etc/resolv.conf &&' 'echo \'{1}\'|lxc-attach -n \'{0}\' -- ' 'tee /etc/resolv.conf' ).format(name, dns)) if not cret['retcode']: ret['result'] = True return ret def bootstrap(name, config=None, approve_key=True, install=True): ''' Install and configure salt in a container. .. code-block:: bash salt 'minion' lxc.bootstrap name [config=config_data] \\ [approve_key=(True|False)] [install=(True|False)] config Minion configuration options. By default, the ``master`` option is set to the target host's master. approve_key Request a pre-approval of the generated minion key. Requires that the salt-master be configured to either auto-accept all keys or expect a signing request from the target host. Default: ``True`` install Whether to attempt a full installation of salt-minion if needed. CLI Example: .. code-block:: bash salt '*' lxc.bootstrap ubuntu ''' infos = __salt__['lxc.info'](name) if not infos: return None prior_state = _ensure_running(name) if not prior_state: return prior_state cmd = 'bash -c "if type salt-minion; then ' \ 'salt-call --local service.stop salt-minion; exit 0; ' \ 'else exit 1; fi"' needs_install = bool(__salt__['lxc.run_cmd'](name, cmd, stdout=False)) tmp = tempfile.mkdtemp() cfg_files = __salt__['seed.mkconfig'](config, tmp=tmp, id_=name, approve_key=approve_key) if needs_install: if install: rstr = __salt__['test.rand_str']() configdir = '/tmp/.c_{0}'.format(rstr) keydir = '/tmp/.k_{0}'.format(rstr) run_cmd(name, 'install -m 0700 -d {0}'.format(configdir)) run_cmd(name, 'install -m 0700 -d {0}'.format(keydir)) bs_ = __salt__['config.gather_bootstrap_script']() cp(name, bs_, '/tmp/bootstrap.sh') cp(name, cfg_files['config'], configdir) cp(name, cfg_files['privkey'], keydir) cp(name, cfg_files['pubkey'], keydir) cmd = 'sh /tmp/bootstrap.sh -c {0} -k {1}'.format(configdir, keydir) res = not __salt__['lxc.run_cmd'](name, cmd, stdout=False) else: res = False else: minion_config = salt.config.minion_config(cfg_files['config']) pki_dir = os.path.join(minion_config['pki_dir'], 'minion') cp(name, cfg_files['config'], '/etc/salt/minion') cp(name, cfg_files['privkey'], pki_dir) cp(name, cfg_files['pubkey'], pki_dir) run_cmd(name, 'salt-call --local service.start salt-minion', stdout=False) res = True shutil.rmtree(tmp) if prior_state == 'stopped': __salt__['lxc.stop'](name) elif prior_state == 'frozen': __salt__['lxc.freeze'](name) return res def run_cmd(name, cmd, no_start=False, preserve_state=True, stdout=True, stderr=False): ''' Run a command inside the container. CLI Example: .. code-block:: bash salt 'minion' name command [no_start=(True|False)] \\ [preserve_state=(True|False)] [stdout=(True|False)] \\ [stderr=(True|False)] name Name of the container on which to operate. cmd Command to run no_start If the container is not running, don't start it. Default: ``False`` preserve_state After running the command, return the container to its previous state. Default: ``True`` stdout: Return stdout. Default: ``True`` stderr: Return stderr. Default: ``False`` .. note:: If stderr and stdout are both ``False``, the return code is returned. If stderr and stdout are both ``True``, the pid and return code are also returned. ''' prior_state = _ensure_running(name, no_start=no_start) if not prior_state: return prior_state res = __salt__['cmd.run_all']( 'lxc-attach -n \'{0}\' -- {1}'.format(name, cmd)) if preserve_state: if prior_state == 'stopped': __salt__['lxc.stop'](name) elif prior_state == 'frozen': __salt__['lxc.freeze'](name) if stdout and stderr: return res elif stdout: return res['stdout'] elif stderr: return res['stderr'] else: return res['retcode'] def cp(name, src, dest): ''' Copy a file or directory from the host into a container CLI Example: .. code-block:: bash salt 'minion' lxc.cp /tmp/foo /root/ ''' if state(name) != 'running': return {'error': 'container is not running'} if not os.path.exists(src): return {'error': 'src does not exist'} if not os.path.isfile(src): return {'error': 'src must be a regular file'} src_dir, src_name = os.path.split(src) dest_dir, dest_name = os.path.split(dest) if run_cmd(name, 'test -d {0}'.format(dest_dir), stdout=False): return {'error': '{0} is not a directory on the container'.format(dest_dir)} if not dest_name: dest_name = src_name cmd = 'cat {0} | lxc-attach -n {1} -- tee {2} > /dev/null'.format( src, name, os.path.join(dest_dir, dest_name)) log.info(cmd) ret = __salt__['cmd.run_all'](cmd) return ret def read_conf(conf_file, out_format='simple'): ''' Read in an LXC configuration file. By default returns a simple, unsorted dict, but can also return a more detailed structure including blank lines and comments. CLI Examples: .. code-block:: bash salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf \ out_format=commented ''' ret_commented = [] ret_simple = {} with salt.utils.fopen(conf_file, 'r') as fp_: for line in fp_.readlines(): if not '=' in line: ret_commented.append(line) continue comps = line.split('=') value = '='.join(comps[1:]).strip() comment = None if '#' in value: vcomps = value.split('#') value = vcomps[1].strip() comment = '#'.join(vcomps[1:]).strip() ret_commented.append({comps[0].strip(): { 'value': value, 'comment': comment, }}) else: ret_commented.append({comps[0].strip(): value}) ret_simple[comps[0].strip()] = value if out_format == 'simple': return ret_simple return ret_commented def write_conf(conf_file, conf): ''' Write out an LXC configuration file This is normally only used internally. The format of the data structure must match that which is returned from ``lxc.read_conf()``, with ``out_format`` set to ``commented``. An example might look like:: [ {'lxc.utsname': '$CONTAINER_NAME'}, '# This is a commented line\\n', '\\n', {'lxc.mount': '$CONTAINER_FSTAB'}, {'lxc.rootfs': {'comment': 'This is another test', 'value': 'This is another test'}}, '\\n', {'lxc.network.type': 'veth'}, {'lxc.network.flags': 'up'}, {'lxc.network.link': 'br0'}, {'lxc.network.hwaddr': '$CONTAINER_MACADDR'}, {'lxc.network.ipv4': '$CONTAINER_IPADDR'}, {'lxc.network.name': '$CONTAINER_DEVICENAME'}, ] CLI Examples: .. code-block:: bash salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\ out_format=commented ''' if type(conf) is not list: return {'Error': 'conf must be passed in as a list'} with salt.utils.fopen(conf_file, 'w') as fp_: for line in conf: if type(line) is str: fp_.write(line) elif type(line) is dict: key = line.keys()[0] if type(line[key]) is str: out_line = ' = '.join((key, line[key])) elif type(line[key]) is dict: out_line = ' = '.join((key, line[key]['value'])) if 'comment' in line[key]: out_line = ' # '.join((out_line, line[key]['comment'])) fp_.write(out_line) fp_.write('\n') return {} def edit_conf(conf_file, out_format='simple', **kwargs): ''' Edit an LXC configuration file. If a setting is already present inside the file, its value will be replaced. If it does not exist, it will be appended to the end of the file. Comments and blank lines will be kept in-tact if they already exist in the file. After the file is edited, its contents will be returned. By default, it will be returned in ``simple`` format, meaning an unordered dict (which may not represent the actual file order). Passing in an ``out_format`` of ``commented`` will return a data structure which accurately represents the order and content of the file. CLI Examples: .. code-block:: bash salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \ out_format=commented lxc.network.type=veth ''' data = [] try: conf = read_conf(conf_file, out_format='commented') except Exception: conf = [] for line in conf: if type(line) is not dict: data.append(line) continue else: key = line.keys()[0] if not key in kwargs: data.append(line) continue data.append({ key: kwargs[key] }) del kwargs[key] for kwarg in kwargs: if kwarg.startswith('__'): continue data.append({kwarg: kwargs[kwarg]}) write_conf(conf_file, data) return read_conf(conf_file, out_format)
liquicode/lib-mrpc
src/ServiceClient.js
'use strict'; //--------------------------------------------------------------------- function ServiceClient() { return { //--------------------------------------------------------------------- Services: {}, //--------------------------------------------------------------------- ConnectService: function ConnectService( Service ) { let service_name = Service.ServiceName; // Validate that the service does not already exist. if ( typeof this.Services[ service_name ] !== 'undefined' ) { throw new Error( `The service [${service_name}] already exists.` ); } this.Services[ service_name ] = Service; return; }, //--------------------------------------------------------------------- DisconnectService: function DisconnectService( ServiceName ) { // Validate that the service does exist. if ( typeof this.Services[ ServiceName ] !== 'undefined' ) { delete this.Services[ ServiceName ]; } return; }, //--------------------------------------------------------------------- CallEndpoint: async function CallEndpoint( ServiceName, EndpointName, CommandParameters, CommandCallback ) { // Validate that the service exists. if ( typeof this.Services[ ServiceName ] === 'undefined' ) { throw new Error( `The service [${ServiceName}] does not exist.` ); } // Invoke the endpoint. await this.Services[ ServiceName ].CallEndpoint( EndpointName, CommandParameters, CommandCallback ); // Return, OK. return; }, }; } //--------------------------------------------------------------------- exports.ServiceClient = ServiceClient;
typemeta/funcj
codec2/core/src/main/java/org/typemeta/funcj/codec2/core/CodecCore.java
<filename>codec2/core/src/main/java/org/typemeta/funcj/codec2/core/CodecCore.java package org.typemeta.funcj.codec2.core; public interface CodecCore<IN, OUT> extends EncoderCore<OUT>, DecoderCore<IN> { CodecFormat<IN, OUT> format(); CodecConfig config(); <T> Codec<T, IN, OUT> getCodec(Class<T> type); }
smunir/pack-backend-jpa
src/main/resources/celerio/pack-backend-jpa/src/main/java/jaxio/commons/ByRangeUtil.p.vm.java
<reponame>smunir/pack-backend-jpa $output.java($JaxioCommons, "ByRangeUtil")## $output.require("javax.inject.Inject")## $output.require("javax.inject.Named")## $output.require("javax.inject.Singleton")## $output.require("javax.persistence.criteria.CriteriaBuilder")## $output.require("javax.persistence.criteria.Path")## $output.require("javax.persistence.criteria.Predicate")## $output.require("javax.persistence.criteria.Root")## $output.require("java.util.List")## $output.requireStatic("com.google.common.collect.Lists.newArrayList")## $output.requireStatic("java.lang.Boolean.FALSE")## $output.requireStatic("java.lang.Boolean.TRUE")## /** * Helper to create a predicate out of {@link Range}s. */ @SuppressWarnings("unchecked") @Named @Singleton public class $output.currentClass { @Inject private JpaUtil jpaUtil; public <E> Predicate byRanges(Root<E> root, CriteriaBuilder builder, SearchParameters sp, Class<E> type) { List<Range<?, ?>> ranges = sp.getRanges(); List<Predicate> predicates = newArrayList(); for (Range<?, ?> r : ranges) { Range<E, ?> range = (Range<E, ?>) r; if (range.isSet()) { Predicate rangePredicate = buildRangePredicate(range, root, builder); if (rangePredicate != null) { predicates.add(rangePredicate); } } } return jpaUtil.concatPredicate(sp, builder, predicates); } private static <D extends Comparable<? super D>, E> Predicate buildRangePredicate(Range<E, D> range, Root<E> root, CriteriaBuilder builder) { Predicate rangePredicate = null; Path<D> path = JpaUtil.getInstance().getPath(root, range.getAttributes()); if (range.isBetween()) { rangePredicate = builder.between(path, range.getFrom(), range.getTo()); } else if (range.isFromSet()) { rangePredicate = builder.greaterThanOrEqualTo(path, range.getFrom()); } else if (range.isToSet()) { rangePredicate = builder.lessThanOrEqualTo(path, range.getTo()); } if (rangePredicate != null) { if (!range.isIncludeNullSet() || range.getIncludeNull() == FALSE) { return rangePredicate; } else { return builder.or(rangePredicate, builder.isNull(path)); } } else { // no from/to is set, but include null or not could be: if (TRUE == range.getIncludeNull()) { return builder.isNull(path); } else if (FALSE == range.getIncludeNull()) { return builder.isNotNull(path); } } return null; } }
containers/podman-tui
pdcs/images/save.go
<reponame>containers/podman-tui package images import ( "os" "github.com/containers/podman-tui/pdcs/registry" "github.com/containers/podman/v4/pkg/bindings/images" "github.com/containers/podman/v4/pkg/channel" "github.com/containers/podman/v4/pkg/errorhandling" "github.com/pkg/errors" "github.com/rs/zerolog/log" ) // ImageSaveOptions image save options type ImageSaveOptions struct { Output string Compressed bool OciAcceptUncompressedLayers bool Format string } // Save saves an image on the local machine func Save(imageID string, opts ImageSaveOptions) error { log.Debug().Msgf("pdcs: podman image save %v", opts) conn, err := registry.GetConnection() if err != nil { return err } info, err := os.Stat(opts.Output) if err == nil { if info.Mode().IsRegular() { return errors.Errorf("%q already exists as a regular file", opts.Output) } } // performing basic check for output var outputErrors []error outputFile, err := os.Create(opts.Output) if err != nil { log.Info().Msgf("%v", err) return err } defer outputFile.Close() cancelChan := make(chan bool, 1) writerChan := make(chan []byte, 1024) outputWriter := channel.NewWriter(writerChan) writeOutputFunc := func() { log.Debug().Msgf("pdcs: podman image save starting writer") for { select { case <-cancelChan: close(writerChan) close(cancelChan) log.Debug().Msgf("pdcs: podman image save writer stopped") return case data := <-writerChan: if _, err := outputFile.Write(data); err != nil { outputErrors = append(outputErrors, err) } } } } go writeOutputFunc() var saveOpts images.ExportOptions saveOpts.WithCompress(opts.Compressed) saveOpts.WithFormat(opts.Format) saveOpts.WithOciAcceptUncompressedLayers(opts.OciAcceptUncompressedLayers) err = images.Export(conn, []string{imageID}, outputWriter, &saveOpts) cancelChan <- true if err != nil { return err } if len(outputErrors) > 0 { return errorhandling.JoinErrors(outputErrors) } return nil }
lucaskurata/FIAP_Full_Stack_Java_Xpert
Modulo_Integracao_Web/webshift/src/main/java/br/com/fiap/webshift/controller/MarcaController.java
<gh_stars>0 package br.com.fiap.webshift.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import br.com.fiap.webshift.model.MarcaModel; import br.com.fiap.webshift.model.filter.mixin.ProdutosIgnoreMixin; import br.com.fiap.webshift.repository.MarcaRepository; @RestController @CrossOrigin("*") @RequestMapping("/marca") public class MarcaController { @Autowired private MarcaRepository marcaRepository; @CrossOrigin @GetMapping("/{id}") public ResponseEntity<MarcaModel> findById(@PathVariable("id") int id){ if ( marcaRepository.existsById(id) ) { MarcaModel model = marcaRepository.findById(id).get(); return ResponseEntity.ok(model); } else { return ResponseEntity.notFound().build(); } } @GetMapping public ResponseEntity<JsonNode> findAll() throws JsonProcessingException{ List<MarcaModel> lista = marcaRepository.findAll(); ObjectMapper mapper = new ObjectMapper().addMixIn(MarcaModel.class, ProdutosIgnoreMixin.class); return ResponseEntity.ok( mapper.readTree( mapper.writeValueAsString(lista) ) ); } }
kinow83/soso
wifimon/docs/html/search/functions_2.js
<gh_stars>1-10 var searchData= [ ['component80211_2240',['Component80211',['../classsoso_1_1Component80211.html#a829b03457e6f0d9fe42cf4c86f0339ad',1,'soso::Component80211']]], ['componentsession_2241',['ComponentSession',['../classsoso_1_1ComponentSession.html#a67b2860ae7521b44cb09dce245d748ef',1,'soso::ComponentSession']]] ];
yokwe/yokwe-root
yokwe-stock-jp/src/main/java/yokwe/stock/jp/Storage.java
<reponame>yokwe/yokwe-root package yokwe.stock.jp; public final class Storage { public static final String PATH_BASE = "/mnt/stock/jp"; public static String getPath(String path) { return String.format("%s/%s", PATH_BASE, path); } public static String getPath(String prefix, String path) { return getPath(String.format("%s/%s", prefix, path)); } }
darylnak/ucdavis-work
UCD/ecs60_40/ecs60/p2/p2-me/LeafNode.cpp
#include <iostream> #include <cmath> #include "LeafNode.h" #include "InternalNode.h" #include "QueueAr.h" using namespace std; LeafNode::LeafNode(int LSize, InternalNode *p, BTreeNode *left, BTreeNode *right) : BTreeNode(LSize, p, left, right) { values = new int[LSize]; } // LeafNode() void LeafNode::adopt(BTreeNode* sibling, int value) { int max = getMax(value); if(max < sibling->getMinimum()) // right sibling transfer { if(value == max) sibling->insert(max); else { --count; insert(value); sibling->insert(max); } } else // we goin left boys { if(value < getMinimum()) sibling->insert(value); else { sibling->insert(getMinimum()); for(int i = 1; i < count; i++) // shift everything up values[i - 1] = values[i]; --count; insert(value); } } if(parent) // update THIS parent with new minimums parent->resetMinimum(); } void LeafNode::connectSibs(BTreeNode* newSib) { if(rightSibling) rightSibling->setLeftSibling(newSib); newSib->setRightSibling(rightSibling); // right of new sibling is right of old newSib->setLeftSibling(this); // left of new sibling is old setRightSibling(newSib); // set right of old to new } int LeafNode::getMax(int value) { if(values[count - 1] > value) return values[count - 1]; else return value; } int LeafNode::getMinimum()const { if(count > 0) // should always be the case return values[0]; else return 0; } // LeafNode::getMinimum() LeafNode* LeafNode::insert(int value) { if(count != leafSize) { sort(value); // insert value in order if not full return NULL; // no split } else { if(leftSibling && !isFull(leftSibling)) { adopt(leftSibling, value); return NULL; } else if(rightSibling && !isFull(rightSibling)) { adopt(rightSibling, value); return NULL; } else return split(value); // split and insert } } // LeafNode::insert() bool LeafNode::isFull(BTreeNode *lfnode) { return lfnode->getCount() == leafSize; } void LeafNode::print(Queue <BTreeNode*> &queue) { cout << "Leaf: "; for (int i = 0; i < count; i++) cout << values[i] << ' '; cout << endl; } // LeafNode::print() void LeafNode::sort(int value) // insert value in order. Guaranteed to have space { if(count == 0) // insert if empty values[0] = value; else // not empty { for (int i = 0; i <= count; i++) { if (i == count) // insert at end { values[i] = value; break; } if (value > values[i]) // keep moving while value is greater than value in array continue; else // move everything down and insert. Array guaranteed to have space. { for (int j = count - 1; j >= i; j--) values[j + 1] = values[j]; values[i] = value; // insert break; } } } if(parent) // update parent minimums parent->resetMinimum(); ++count; // increment count } LeafNode* LeafNode::split(int value) // split and insert { LeafNode* newLfNode = new LeafNode(leafSize, parent, this, rightSibling); int start = 0; // starting position if(leafSize % 2 != 0) // create offset if size odd ++start; // give all elements starting 1 past the middle. for (start += (leafSize / 2); start < leafSize; start++) newLfNode->sort(values[--count]); if (value > values[count - 1]) // give new sibling value and keep middle newLfNode->sort(value); else // give middle to new sibling and keep value { newLfNode->insert(values[--count]); sort(value); } connectSibs(newLfNode); return newLfNode; }
msldxy/LeetCodePractice
problem/Easy/485.MaxConsecutiveOnes/Solution.java
<filename>problem/Easy/485.MaxConsecutiveOnes/Solution.java<gh_stars>0 /* 创建一个新数组,遍历原数组,判断是1还是0 */ class Solution { public int findMaxConsecutiveOnes(int[] nums) { int index = 0; int[] res = new int[nums.length]; for(int i = 0; i < nums.length; i++){ //如果是1,对应index数加一 if(nums[i] == 1){ res[index]++; } else{ index++; //如果不是那么index加一,并且res[index]=0 res[index] = 0; } } Arrays.sort(res); return res[res.length - 1]; } } /* result:Runtime Error Runtime Error Message: Line 12: java.lang.ArrayIndexOutOfBoundsException: 1 Last executed input: [0] 这里如果数组元素全为0,那么index就应该是nums.length,res[index]索引越界了 */
trifonnt/jhipster--great-big-example-application
src/test/java/org/exampleapps/greatbig/web/rest/MessageResourceIntTest.java
<reponame>trifonnt/jhipster--great-big-example-application<filename>src/test/java/org/exampleapps/greatbig/web/rest/MessageResourceIntTest.java package org.exampleapps.greatbig.web.rest; import org.exampleapps.greatbig.GreatBigExampleApplicationApp; import org.exampleapps.greatbig.domain.Message; import org.exampleapps.greatbig.repository.MessageRepository; import org.exampleapps.greatbig.repository.search.MessageSearchRepository; import org.exampleapps.greatbig.web.rest.errors.ExceptionTranslator; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.time.Instant; import java.time.ZonedDateTime; import java.time.ZoneOffset; import java.time.ZoneId; import java.util.List; import static org.exampleapps.greatbig.web.rest.TestUtil.sameInstant; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the MessageResource REST controller. * * @see MessageResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = GreatBigExampleApplicationApp.class) public class MessageResourceIntTest { private static final String DEFAULT_USER_LOGIN = "AAAAAAAAAA"; private static final String UPDATED_USER_LOGIN = "BBBBBBBBBB"; private static final String DEFAULT_MESSAGE = "AAAAAAAAAA"; private static final String UPDATED_MESSAGE = "BBBBBBBBBB"; private static final ZonedDateTime DEFAULT_CREATED_AT = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC); private static final ZonedDateTime UPDATED_CREATED_AT = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0); private static final ZonedDateTime DEFAULT_UPDATED_AT = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC); private static final ZonedDateTime UPDATED_UPDATED_AT = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0); @Autowired private MessageRepository messageRepository; @Autowired private MessageSearchRepository messageSearchRepository; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Autowired private PageableHandlerMethodArgumentResolver pageableArgumentResolver; @Autowired private ExceptionTranslator exceptionTranslator; @Autowired private EntityManager em; private MockMvc restMessageMockMvc; private Message message; @Before public void setup() { MockitoAnnotations.initMocks(this); MessageResource messageResource = new MessageResource(messageRepository, messageSearchRepository); this.restMessageMockMvc = MockMvcBuilders.standaloneSetup(messageResource) .setCustomArgumentResolvers(pageableArgumentResolver) .setControllerAdvice(exceptionTranslator) .setMessageConverters(jacksonMessageConverter).build(); } /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static Message createEntity(EntityManager em) { Message message = new Message() .userLogin(DEFAULT_USER_LOGIN) .message(DEFAULT_MESSAGE) .createdAt(DEFAULT_CREATED_AT) .updatedAt(DEFAULT_UPDATED_AT); return message; } @Before public void initTest() { messageSearchRepository.deleteAll(); message = createEntity(em); } @Test @Transactional public void createMessage() throws Exception { int databaseSizeBeforeCreate = messageRepository.findAll().size(); // Create the Message restMessageMockMvc.perform(post("/api/messages") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(message))) .andExpect(status().isCreated()); // Validate the Message in the database List<Message> messageList = messageRepository.findAll(); assertThat(messageList).hasSize(databaseSizeBeforeCreate + 1); Message testMessage = messageList.get(messageList.size() - 1); assertThat(testMessage.getUserLogin()).isEqualTo(DEFAULT_USER_LOGIN); assertThat(testMessage.getMessage()).isEqualTo(DEFAULT_MESSAGE); assertThat(testMessage.getCreatedAt()).isEqualTo(DEFAULT_CREATED_AT); assertThat(testMessage.getUpdatedAt()).isEqualTo(DEFAULT_UPDATED_AT); // Validate the Message in Elasticsearch Message messageEs = messageSearchRepository.findOne(testMessage.getId()); assertThat(messageEs).isEqualToComparingFieldByField(testMessage); } @Test @Transactional public void createMessageWithExistingId() throws Exception { int databaseSizeBeforeCreate = messageRepository.findAll().size(); // Create the Message with an existing ID message.setId(1L); // An entity with an existing ID cannot be created, so this API call must fail restMessageMockMvc.perform(post("/api/messages") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(message))) .andExpect(status().isBadRequest()); // Validate the Alice in the database List<Message> messageList = messageRepository.findAll(); assertThat(messageList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional public void checkMessageIsRequired() throws Exception { int databaseSizeBeforeTest = messageRepository.findAll().size(); // set the field null message.setMessage(null); // Create the Message, which fails. restMessageMockMvc.perform(post("/api/messages") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(message))) .andExpect(status().isBadRequest()); List<Message> messageList = messageRepository.findAll(); assertThat(messageList).hasSize(databaseSizeBeforeTest); } @Test @Transactional public void getAllMessages() throws Exception { // Initialize the database messageRepository.saveAndFlush(message); // Get all the messageList restMessageMockMvc.perform(get("/api/messages?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(message.getId().intValue()))) .andExpect(jsonPath("$.[*].userLogin").value(hasItem(DEFAULT_USER_LOGIN.toString()))) .andExpect(jsonPath("$.[*].message").value(hasItem(DEFAULT_MESSAGE.toString()))) .andExpect(jsonPath("$.[*].createdAt").value(hasItem(sameInstant(DEFAULT_CREATED_AT)))) .andExpect(jsonPath("$.[*].updatedAt").value(hasItem(sameInstant(DEFAULT_UPDATED_AT)))); } @Test @Transactional public void getMessage() throws Exception { // Initialize the database messageRepository.saveAndFlush(message); // Get the message restMessageMockMvc.perform(get("/api/messages/{id}", message.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id").value(message.getId().intValue())) .andExpect(jsonPath("$.userLogin").value(DEFAULT_USER_LOGIN.toString())) .andExpect(jsonPath("$.message").value(DEFAULT_MESSAGE.toString())) .andExpect(jsonPath("$.createdAt").value(sameInstant(DEFAULT_CREATED_AT))) .andExpect(jsonPath("$.updatedAt").value(sameInstant(DEFAULT_UPDATED_AT))); } @Test @Transactional public void getNonExistingMessage() throws Exception { // Get the message restMessageMockMvc.perform(get("/api/messages/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test @Transactional public void updateMessage() throws Exception { // Initialize the database messageRepository.saveAndFlush(message); messageSearchRepository.save(message); int databaseSizeBeforeUpdate = messageRepository.findAll().size(); // Update the message Message updatedMessage = messageRepository.findOne(message.getId()); updatedMessage .userLogin(UPDATED_USER_LOGIN) .message(UPDATED_MESSAGE) .createdAt(UPDATED_CREATED_AT) .updatedAt(UPDATED_UPDATED_AT); restMessageMockMvc.perform(put("/api/messages") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(updatedMessage))) .andExpect(status().isOk()); // Validate the Message in the database List<Message> messageList = messageRepository.findAll(); assertThat(messageList).hasSize(databaseSizeBeforeUpdate); Message testMessage = messageList.get(messageList.size() - 1); assertThat(testMessage.getUserLogin()).isEqualTo(UPDATED_USER_LOGIN); assertThat(testMessage.getMessage()).isEqualTo(UPDATED_MESSAGE); assertThat(testMessage.getCreatedAt()).isEqualTo(UPDATED_CREATED_AT); assertThat(testMessage.getUpdatedAt()).isEqualTo(UPDATED_UPDATED_AT); // Validate the Message in Elasticsearch Message messageEs = messageSearchRepository.findOne(testMessage.getId()); assertThat(messageEs).isEqualToComparingFieldByField(testMessage); } @Test @Transactional public void updateNonExistingMessage() throws Exception { int databaseSizeBeforeUpdate = messageRepository.findAll().size(); // Create the Message // If the entity doesn't have an ID, it will be created instead of just being updated restMessageMockMvc.perform(put("/api/messages") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(message))) .andExpect(status().isCreated()); // Validate the Message in the database List<Message> messageList = messageRepository.findAll(); assertThat(messageList).hasSize(databaseSizeBeforeUpdate + 1); } @Test @Transactional public void deleteMessage() throws Exception { // Initialize the database messageRepository.saveAndFlush(message); messageSearchRepository.save(message); int databaseSizeBeforeDelete = messageRepository.findAll().size(); // Get the message restMessageMockMvc.perform(delete("/api/messages/{id}", message.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); // Validate Elasticsearch is empty boolean messageExistsInEs = messageSearchRepository.exists(message.getId()); assertThat(messageExistsInEs).isFalse(); // Validate the database is empty List<Message> messageList = messageRepository.findAll(); assertThat(messageList).hasSize(databaseSizeBeforeDelete - 1); } @Test @Transactional public void searchMessage() throws Exception { // Initialize the database messageRepository.saveAndFlush(message); messageSearchRepository.save(message); // Search the message restMessageMockMvc.perform(get("/api/_search/messages?query=id:" + message.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(message.getId().intValue()))) .andExpect(jsonPath("$.[*].userLogin").value(hasItem(DEFAULT_USER_LOGIN.toString()))) .andExpect(jsonPath("$.[*].message").value(hasItem(DEFAULT_MESSAGE.toString()))) .andExpect(jsonPath("$.[*].createdAt").value(hasItem(sameInstant(DEFAULT_CREATED_AT)))) .andExpect(jsonPath("$.[*].updatedAt").value(hasItem(sameInstant(DEFAULT_UPDATED_AT)))); } @Test @Transactional public void equalsVerifier() throws Exception { TestUtil.equalsVerifier(Message.class); Message message1 = new Message(); message1.setId(1L); Message message2 = new Message(); message2.setId(message1.getId()); assertThat(message1).isEqualTo(message2); message2.setId(2L); assertThat(message1).isNotEqualTo(message2); message1.setId(null); assertThat(message1).isNotEqualTo(message2); } }
ReyderOlarte/Fintech_AutoStock
src/com/autoStock/quote/QuoteEntry.java
/** * */ package com.autoStock.quote; import java.util.Date; /** * @author <NAME> * */ public class QuoteEntry { public long id; public String symbol; public float priceOpen; public float priceHigh; public float priceLow; public float priceClose; public int sizeVolume; public Date dateTime; public QuoteEntry(long id, String symbol, float priceOpen, float priceHigh, float priceLow, float priceClose, int sizeVolume, Date dateTime) { this.id = id; this.symbol = symbol; this.priceOpen = priceOpen; this.priceHigh = priceHigh; this.priceLow = priceLow; this.priceClose = priceClose; this.sizeVolume = sizeVolume; this.dateTime = dateTime; } }
Worthington-Robotics/2020RobotCode
RobotCode/src/main/java/frc/robot/actions/colorwheelactions/LightsStateTest.java
<filename>RobotCode/src/main/java/frc/robot/actions/colorwheelactions/LightsStateTest.java package frc.robot.actions.colorwheelactions; import frc.lib.statemachine.Action; import frc.robot.subsystems.Lights; public class LightsStateTest extends Action { private int state = 0; public LightsStateTest(int state) { this.state = state; } @Override public void onStart() { Lights.getInstance().testLights(state); } @Override public void onLoop() { } @Override public boolean isFinished() { return true; } @Override public void onStop() { } }
hfsugar/hetu-core
presto-orc/src/main/java/io/prestosql/orc/OrcCacheStore.java
<filename>presto-orc/src/main/java/io/prestosql/orc/OrcCacheStore.java /* * Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved. * 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 io.prestosql.orc; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.Weigher; import io.airlift.units.DataSize; import io.prestosql.orc.metadata.RowGroupIndex; import io.prestosql.orc.metadata.StripeFooter; import io.prestosql.orc.metadata.statistics.HashableBloomFilter; import io.prestosql.spi.block.Block; import java.time.Duration; import java.util.List; public class OrcCacheStore { public static final OrcCacheStore CACHE_NOTHING = new OrcCacheStore(null, null, null, null, null); private Cache<OrcFileTailCacheKey, OrcFileTail> fileTailCache; private Cache<OrcStripeFooterCacheKey, StripeFooter> stripeFooterCache; private Cache<OrcRowIndexCacheKey, List<RowGroupIndex>> rowIndexCache; private Cache<OrcBloomFilterCacheKey, List<HashableBloomFilter>> bloomFiltersCache; private Cache<OrcRowDataCacheKey, Block> rowDataCache; private OrcCacheStore() { //do nothing } private OrcCacheStore(Cache<OrcFileTailCacheKey, OrcFileTail> fileTailCache, Cache<OrcStripeFooterCacheKey, StripeFooter> stripeFooterCache, Cache<OrcRowIndexCacheKey, List<RowGroupIndex>> rowIndexCache, Cache<OrcBloomFilterCacheKey, List<HashableBloomFilter>> bloomFiltersCache, Cache<OrcRowDataCacheKey, Block> rowDataCache) { this.fileTailCache = fileTailCache; this.stripeFooterCache = stripeFooterCache; this.rowIndexCache = rowIndexCache; this.bloomFiltersCache = bloomFiltersCache; this.rowDataCache = rowDataCache; } public Cache<OrcFileTailCacheKey, OrcFileTail> getFileTailCache() { return fileTailCache; } public Cache<OrcStripeFooterCacheKey, StripeFooter> getStripeFooterCache() { return stripeFooterCache; } public Cache<OrcRowIndexCacheKey, List<RowGroupIndex>> getRowIndexCache() { return rowIndexCache; } public Cache<OrcBloomFilterCacheKey, List<HashableBloomFilter>> getBloomFiltersCache() { return bloomFiltersCache; } public Cache<OrcRowDataCacheKey, Block> getRowDataCache() { return rowDataCache; } public static Builder builder() { return new Builder(); } public static class Builder { private Builder() { //default constructor } public OrcCacheStore newCacheStore(long fileTailMaximumSize, Duration fileTailTtl, long stripeFooterMaximumSize, Duration stripeFooterTtl, long rowIndexMaximumSize, Duration rowIndexTtl, long bloomFiltersMaximumSize, Duration bloomFiltersTtl, DataSize rowDataMaximumWeight, Duration rowDataTtl, boolean isOrcCacheStatsMetricCollectionEnabled) { OrcCacheStore store = new OrcCacheStore(); store.fileTailCache = buildOrcFileTailCache(fileTailMaximumSize, fileTailTtl, isOrcCacheStatsMetricCollectionEnabled); store.stripeFooterCache = buildOrcStripeFooterCache(stripeFooterMaximumSize, stripeFooterTtl, isOrcCacheStatsMetricCollectionEnabled); store.rowIndexCache = buildOrcRowGroupIndexCache(rowIndexMaximumSize, rowIndexTtl, isOrcCacheStatsMetricCollectionEnabled); store.bloomFiltersCache = buildOrcBloomFilterCache(bloomFiltersMaximumSize, bloomFiltersTtl, isOrcCacheStatsMetricCollectionEnabled); store.rowDataCache = buildOrcRowDataCache(rowDataMaximumWeight, rowDataTtl, isOrcCacheStatsMetricCollectionEnabled); return store; } private Cache<OrcFileTailCacheKey, OrcFileTail> buildOrcFileTailCache(long maximumSize, Duration ttl, boolean isOrcCacheStatsMetricCollectionEnabled) { CacheBuilder cacheBuilder = CacheBuilder.newBuilder().maximumSize(maximumSize).expireAfterAccess(ttl); if (isOrcCacheStatsMetricCollectionEnabled) { cacheBuilder.recordStats(); } return cacheBuilder.build(); } private Cache<OrcStripeFooterCacheKey, StripeFooter> buildOrcStripeFooterCache(long maximumSize, Duration ttl, boolean isOrcCacheStatsMetricCollectionEnabled) { CacheBuilder cacheBuilder = CacheBuilder.newBuilder().maximumSize(maximumSize).expireAfterAccess(ttl); if (isOrcCacheStatsMetricCollectionEnabled) { cacheBuilder.recordStats(); } return cacheBuilder.build(); } private Cache<OrcRowIndexCacheKey, List<RowGroupIndex>> buildOrcRowGroupIndexCache(long maximumSize, Duration ttl, boolean isOrcCacheStatsMetricCollectionEnabled) { CacheBuilder cacheBuilder = CacheBuilder.newBuilder().maximumSize(maximumSize).expireAfterAccess(ttl); if (isOrcCacheStatsMetricCollectionEnabled) { cacheBuilder.recordStats(); } return cacheBuilder.build(); } private Cache<OrcBloomFilterCacheKey, List<HashableBloomFilter>> buildOrcBloomFilterCache(long maximumSize, Duration ttl, boolean isOrcCacheStatsMetricCollectionEnabled) { CacheBuilder cacheBuilder = CacheBuilder.newBuilder().maximumSize(maximumSize).expireAfterAccess(ttl); if (isOrcCacheStatsMetricCollectionEnabled) { cacheBuilder.recordStats(); } return cacheBuilder.build(); } private Cache<OrcRowDataCacheKey, Block> buildOrcRowDataCache(DataSize maximumWeight, Duration ttl, boolean isOrcCacheStatsMetricCollectionEnabled) { CacheBuilder cacheBuilder = CacheBuilder.newBuilder() .maximumWeight(maximumWeight.toBytes()) .weigher( (Weigher<OrcRowDataCacheKey, Block>) (orcRowDataCacheKey, block) -> (int) block.getSizeInBytes()) .expireAfterAccess(ttl); if (isOrcCacheStatsMetricCollectionEnabled) { cacheBuilder.recordStats(); } return cacheBuilder.build(); } } }
junkhp/esuites_database_modification
esuits/samples/newsapi_sample/views.py
from esuits.esuits_utils.newsapi import newsapi from django.shortcuts import render from .forms import NewsAPIForm from django.http.response import JsonResponse def newsapi_sample(request): name = request.GET.get('name','') if name: news_list = newsapi.get_news(name) return JsonResponse({"news":news_list}) form = NewsAPIForm() return render(request,'samples/newsapi_sample.html', {'form':form})
xinyufei/Quantum-Control-qutip
tools/circuitutil.py
<reponame>xinyufei/Quantum-Control-qutip<gh_stars>1-10 """ circuitutil.py - A module for extending Qiskit circuit functionality. """ import numpy as np import pickle from qiskit import Aer, BasicAer, QuantumCircuit, QuantumRegister, execute, assemble from qiskit.extensions import * from qiskit.compiler import transpile from qiskit.transpiler import PassManager from qiskit.transpiler.passes import BasicSwap, CXCancellation from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE from qiskit.aqua import QuantumInstance from qiskit.chemistry.algorithms.ground_state_solvers.minimum_eigensolver_factories import VQEUCCSDFactory from qiskit.chemistry.algorithms.ground_state_solvers import GroundStateEigensolver from qiskit.chemistry.transformations import FermionicTransformation, FermionicQubitMappingType from qiskit.aqua.components.optimizers import COBYLA, SPSA, SLSQP ### CONSTANTS ### # NOTICE: GATE_TO_PULSE_TIME is kept here for dependency reasons, but all # future references to this dict and any other experimental constants # should be kept in fqc/data/data.py. # See Gate_Times.ipynb or Realistic_Pulses.ipynb for determination of these pulse times GATE_TO_PULSE_TIME = {'h': 1.4, 'cx': 3.8, 'rz': 0.4, 'rx': 2.5, 'x': 2.5, 'swap': 7.4, 'id': 0.0} GATE_TO_PULSE_TIME_REALISTIC = {'h': 20, 'cx': 45, 'rz': 1, 'rx': 31, 'x': 31, 'swap': 59, 'id': 0.0} NUM_SHOTS = 1000 unitary_backend = BasicAer.get_backend('unitary_simulator') state_backend = BasicAer.get_backend('statevector_simulator') ### FUNCTIONS ### def get_unitary(circuit): """Given a qiskit circuit, produce a unitary matrix to represent it. Args: circuit :: qiskit.QuantumCircuit - an arbitrary quantum circuit Returns: matrix :: np.matrix - the unitary representing the circuit """ job = execute(circuit, unitary_backend) unitary = job.result().get_unitary(circuit, decimals=10) return np.matrix(unitary) def get_nearest_neighbor_coupling_list(width, height, directed=True): """Returns a coupling list for nearest neighbor (rectilinear grid) architecture. Qubits are numbered in row-major order with 0 at the top left and (width*height - 1) at the bottom right. If directed is True, the coupling list includes both [a, b] and [b, a] for each edge. """ coupling_list = [] def _qubit_number(row, col): return row * width + col # horizontal edges for row in range(height): for col in range(width - 1): coupling_list.append((_qubit_number(row, col), _qubit_number(row, col + 1))) if directed: coupling_list.append((_qubit_number(row, col + 1), _qubit_number(row, col))) # vertical edges for col in range(width): for row in range(height - 1): coupling_list.append((_qubit_number(row, col), _qubit_number(row + 1, col))) if directed: coupling_list.append((_qubit_number(row + 1, col), _qubit_number(row, col))) return coupling_list def _tests(): """A function to run tests on the module""" pass if __name__ == "__main__": _tests()
a1russell/rethink-scala
core/src/main/scala/com/rethinkscala/reflect/RethinkDateTimeSerializer.scala
package com.rethinkscala.reflect import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.databind.SerializerProvider import com.fasterxml.jackson.databind.ser.std.StdSerializer import com.rethinkscala.ast.Expr import org.joda.time.{ReadableInstant, DateTime} import org.joda.time.format.ISODateTimeFormat /** * Created by IntelliJ IDEA. * User: Keyston * Date: 12/23/13 * Time: 2:57 PM */ object RethinkDateTimeSerializer extends StdSerializer[ReadableInstant](classOf[ReadableInstant]) { override def serialize(date: ReadableInstant, jgen: JsonGenerator, provider: SerializerProvider) = { val value = Expr(date) jgen.writeString(value.serialize) } } /* class RethinkDateTimeSerializer extends StdSerializer[DateTime](classOf[DateTime]) { def serialize(value: DateTime, jgen: JsonGenerator, provider: SerializerProvider) { if (provider.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)) { jgen.writeNumber(value.getMillis) } else { jgen.writeString(value.toString) } } override def serializeWithType(value: DateTime, jgen: JsonGenerator, provider: SerializerProvider, typeSer: TypeSerializer) { typeSer.writeTypePrefixForScalar(value, jgen) serialize(value, jgen, provider) typeSer.writeTypeSuffixForScalar(value, jgen) } override def getSchema(provider: SerializerProvider, typeHint: Type): JsonNode = { createSchemaNode(if (provider.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)) "number" else "string", true) } } */